home-hosted 0.13.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/chunks/{backup-CZcVca2a.js → backup-DeAJ3pbO.js} +6 -6
  2. package/dist/chunks/{backup-CZcVca2a.js.map → backup-DeAJ3pbO.js.map} +1 -1
  3. package/dist/chunks/{backups-CFRaWe_m.js → backups-twva7x2n.js} +3 -3
  4. package/dist/chunks/{backups-CFRaWe_m.js.map → backups-twva7x2n.js.map} +1 -1
  5. package/dist/chunks/{daemon-qKVECISl.js → daemon-CofN9k6Q.js} +3 -3
  6. package/dist/chunks/{daemon-qKVECISl.js.map → daemon-CofN9k6Q.js.map} +1 -1
  7. package/dist/chunks/{down-pKbGCW9d.js → down-C59ne5aM.js} +5 -5
  8. package/dist/chunks/{down-pKbGCW9d.js.map → down-C59ne5aM.js.map} +1 -1
  9. package/dist/chunks/{nanny-BtWfy0QH.js → nanny-COyCJXj9.js} +10 -5
  10. package/dist/chunks/nanny-COyCJXj9.js.map +1 -0
  11. package/dist/chunks/{nanny-ChMtq1Zl.js → nanny-Dnun3hVB.js} +3 -3
  12. package/dist/chunks/{nanny-ChMtq1Zl.js.map → nanny-Dnun3hVB.js.map} +1 -1
  13. package/dist/chunks/{nanny-B-Eu0sFW.js → nanny-rewguyXg.js} +2 -2
  14. package/dist/chunks/{nanny-B-Eu0sFW.js.map → nanny-rewguyXg.js.map} +1 -1
  15. package/dist/chunks/{nanny-sweep-DErnlPY1.js → nanny-sweep-ClVuNJRo.js} +3 -3
  16. package/dist/chunks/{nanny-sweep-DErnlPY1.js.map → nanny-sweep-ClVuNJRo.js.map} +1 -1
  17. package/dist/chunks/{port-B8WBTRMk.js → port-k5VBw8t9.js} +5 -2
  18. package/dist/chunks/{port-B8WBTRMk.js.map → port-k5VBw8t9.js.map} +1 -1
  19. package/dist/chunks/{restart-Des4DrAN.js → restart-BYu_E7x5.js} +5 -5
  20. package/dist/chunks/{restart-Des4DrAN.js.map → restart-BYu_E7x5.js.map} +1 -1
  21. package/dist/chunks/{server-Bge2r2qQ.js → server-By-zktjx.js} +3 -3
  22. package/dist/chunks/{server-Bge2r2qQ.js.map → server-By-zktjx.js.map} +1 -1
  23. package/dist/chunks/{set-token-obPiEJYk.js → set-token-xJkA1IZp.js} +2 -2
  24. package/dist/chunks/{set-token-obPiEJYk.js.map → set-token-xJkA1IZp.js.map} +1 -1
  25. package/dist/chunks/{src-BtWMFmzZ.js → src-BOBh9MBf.js} +9 -6
  26. package/dist/chunks/src-BOBh9MBf.js.map +1 -0
  27. package/dist/chunks/{status-DT1EsA-B.js → status-B6f2-qhs.js} +2 -2
  28. package/dist/chunks/{status-DT1EsA-B.js.map → status-B6f2-qhs.js.map} +1 -1
  29. package/dist/chunks/{up-Pdz-l6IH.js → up-DNZuTi2q.js} +4 -4
  30. package/dist/chunks/{up-Pdz-l6IH.js.map → up-DNZuTi2q.js.map} +1 -1
  31. package/dist/chunks/{usage-DFrCVXpT.js → usage-BrnDARNM.js} +2 -2
  32. package/dist/chunks/{usage-DFrCVXpT.js.map → usage-BrnDARNM.js.map} +1 -1
  33. package/dist/cli.js +11 -11
  34. package/package.json +1 -1
  35. package/uis/stock/dist/ui.json +2 -2
  36. package/dist/chunks/nanny-BtWfy0QH.js.map +0 -1
  37. package/dist/chunks/src-BtWMFmzZ.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import { S as runtimePath } from "./paths-CGlGDrOU.js";
2
2
  import { t as writeFileAtomic } from "./atomic-C1PfJpE7.js";
3
3
  import { t as lazy } from "./lazy-Ce5zEAq1.js";
4
- import { c as processLiveness, r as isProcessAlive } from "./port-B8WBTRMk.js";
4
+ import { c as processLiveness, r as isProcessAlive } from "./port-k5VBw8t9.js";
5
5
  import fs from "node:fs";
6
6
  import { type } from "arktype";
7
7
  import { randomBytes } from "node:crypto";
@@ -136,7 +136,7 @@ function readServerCounts(body) {
136
136
  async function configuredPanelAddress() {
137
137
  const { readStateFile } = await import("./config-text-DifCHhnz.js").then((n) => n.t);
138
138
  const { globalSettingsPath, homeFingerprint } = await import("./paths-CGlGDrOU.js").then((n) => n.d);
139
- const { probePort } = await import("./port-B8WBTRMk.js").then((n) => n.o);
139
+ const { probePort } = await import("./port-k5VBw8t9.js").then((n) => n.o);
140
140
  const { globalSettingsSchema } = await import("./schema-B240VXcV.js").then((n) => n.s);
141
141
  let port;
142
142
  try {
@@ -244,4 +244,4 @@ function localCall(base, path, method, token, timeoutMs) {
244
244
  //#endregion
245
245
  export { clearRuntime, configuredPanelAddress, isLiveLiveness, isProcessAlive, newToken, probeRuntime, readRuntime, requestControl, requestShutdown, runtimeIsAlive, runtimeIsGone, runtimeLiveness, writeRuntime };
246
246
 
247
- //# sourceMappingURL=daemon-qKVECISl.js.map
247
+ //# sourceMappingURL=daemon-CofN9k6Q.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"daemon-qKVECISl.js","names":[],"sources":["../../src/helpers/daemon.ts"],"sourcesContent":["import type { ProcessLiveness } from '#src/providers/port'\nimport { randomBytes } from 'node:crypto'\nimport fs from 'node:fs'\nimport http from 'node:http'\nimport https from 'node:https'\nimport { type } from 'arktype'\nimport { writeFileAtomic } from '#src/helpers/atomic'\nimport { runtimePath } from '#src/helpers/paths'\nimport { processLiveness } from '#src/providers/port'\nimport { lazy } from '#src/shared/lazy'\n\n/**\n * `run.json` is how `status`/`down` find the live control plane and how they are\n * allowed to stop it without a password: the file is mode 0600, and the token in\n * it is what `POST /_hh/shutdown` checks.\n */\nexport const runtimeSchema = lazy(() => type({\n version: 'string',\n pid: 'number.integer >= 1',\n /** The address that was actually bound, for humans. */\n url: 'string',\n /** Always a reachable loopback address, for probes (`lan` binds to 0.0.0.0). */\n probeUrl: 'string',\n protocol: 'string',\n port: '1 <= number.integer <= 65535',\n bindHost: 'string',\n startedAt: 'number',\n projectDir: 'string',\n dataRoot: 'string',\n configPath: 'string',\n logFile: 'string',\n token: 'string >= 1',\n}).onUndeclaredKey('reject'))\nexport type Runtime = typeof runtimeSchema.infer\n\nexport function readRuntime(): Runtime | null {\n try {\n const parsed = runtimeSchema(JSON.parse(fs.readFileSync(runtimePath, 'utf8')))\n return parsed instanceof type.errors ? null : parsed\n }\n catch {\n return null\n }\n}\n\nexport function writeRuntime(runtime: Runtime): void {\n writeFileAtomic(runtimePath, `${JSON.stringify(runtime, null, 2)}\\n`, { mode: 0o600 })\n}\n\nexport function clearRuntime(): void {\n fs.rmSync(runtimePath, { force: true })\n}\n\nexport function newToken(): string {\n return randomBytes(32).toString('base64url')\n}\n\n/**\n * Re-exported from `providers/port.ts` so the two cannot drift on `EPERM` again.\n *\n * They already had: this copy treated a process owned by another user as alive (correct) while the\n * port one treated it as gone, which made a live nanny look absent. One definition, one answer.\n */\nexport { isProcessAlive } from '#src/providers/port'\n\n/**\n * What became of the daemon this record describes: the verdict `run.json`'s pid cannot give on\n * its own. See `processLiveness` in `providers/port.ts` for why the pid is not an identity.\n */\nexport async function runtimeLiveness(runtime: Runtime): Promise<ProcessLiveness> {\n return await processLiveness(runtime.pid, runtime.startedAt)\n}\n\n/**\n * Is the daemon this record describes still the one running?\n *\n * `readRuntime()` answers \"does a record exist\", never \"is the panel behind it alive\" — and a pid\n * alone cannot answer that either. The OS reuses pids, and a zombie still answers signal 0, so a\n * bare `isProcessAlive(runtime.pid)` reported a stale `run.json` as a live panel: `up` refused with\n * \"already running\", `status` said \"running, but not answering\", and `down` signalled whatever\n * unrelated process had since inherited the pid.\n *\n * Every caller must read this one predicate, because a caller that re-derives it slightly differently\n * is how a `down` comes to signal a stranger.\n */\nexport async function runtimeIsAlive(runtime: Runtime): Promise<boolean> {\n return isLiveLiveness(await runtimeLiveness(runtime))\n}\n\n/**\n * Only `'live'` and `'unknown'` count as alive. `'unknown'` means the platform could not read a start\n * time, so the live pid is all there is — dismissing it would clear a record the running panel still\n * owns. `'recycled'` is emphatically **not** alive: the pid belongs to somebody else now.\n */\nexport function isLiveLiveness(liveness: ProcessLiveness): boolean {\n return liveness === 'live' || liveness === 'unknown'\n}\n\n/**\n * Is the record positively pointing at nothing at all — no process behind the pid?\n *\n * This is the **only** condition under which deleting `run.json` is safe, so it is deliberately\n * narrower than `!runtimeIsAlive`. The start-time check can be wrong in one direction: Linux derives\n * a process's birth epoch from `btime`, which the kernel computes from the wall clock\n * (`getboottime64`: \"calls to settimeofday will affect the value returned\"), so a forward clock step\n * — common when a laptop or a WSL host wakes from sleep — makes a *live* panel look recycled. Deleting\n * its record over that would orphan a running panel: still supervising servers, no longer stoppable by\n * `down`. A record that some process may still own is left alone and simply overwritten when a new\n * panel finishes booting.\n */\nexport async function runtimeIsGone(runtime: Runtime): Promise<boolean> {\n return await runtimeLiveness(runtime) === 'gone'\n}\n\nexport interface RuntimeProbe {\n /** The panel answered on its own port — stronger than \"the pid exists\". */\n reachable: boolean\n /** It answered, but reports a crashed autostart server (`/healthz` is 503). */\n degraded: boolean\n /**\n * How many entries it supervises, and how many are up — `null` when the panel answered without\n * a count (an older panel, or one that did not accept the token).\n */\n servers: { total: number, running: number } | null\n}\n\n/** A degraded panel is still answering: a 503 must not read as \"not running\". */\nexport async function probeRuntime(runtime: Runtime, timeoutMs = 2500): Promise<RuntimeProbe> {\n // The token is what makes `/healthz` include the per-server counts instead of only the public\n // status line. `usage` was already reading the same numbers over `/_hh`; `status` not doing so was\n // this call passing no token, not the data being unavailable.\n const answer = await localCall(runtime.probeUrl, '/healthz', 'GET', runtime.token, timeoutMs)\n return { reachable: answer !== null, degraded: answer?.status === 503, servers: readServerCounts(answer?.body) }\n}\n\n/** The `servers` block of a `/healthz` answer, or `null` when it did not carry one. */\nfunction readServerCounts(body: string | undefined): RuntimeProbe['servers'] {\n if (body === undefined)\n return null\n try {\n const parsed = JSON.parse(body) as { servers?: { total?: unknown, running?: unknown } }\n const { total, running } = parsed.servers ?? {}\n return typeof total === 'number' && typeof running === 'number' ? { total, running } : null\n }\n catch {\n return null\n }\n}\n\n/** What holds the configured control port when no `run.json` names a panel. */\nexport type ConfiguredListener\n = | { kind: 'panel', url: string }\n | { kind: 'other', port: number }\n\n/**\n * What is listening on this home's configured port, when no `run.json` says a panel should be — or\n * `null` when nothing is.\n *\n * Every command that answers \"is it running\" has to consult this, not the record alone: with\n * `run.json` deleted, `status` printed \"home-hosted is not running\" while `GET /healthz` on the\n * same port answered `200`, and `down` refuses instead of letting `down && up` start a second panel\n * over a live one. The port comes from the state root's own `settings.json`, because that is the\n * only record left once `run.json` is gone.\n *\n * **A listener is only this home's panel when it says so.** Two homes may share a port (one stopped,\n * one running), and treating any listener as \"ours\" broke `status` and `down` in the stopped one —\n * `down` refused over another home's panel. `/healthz` tells a loopback caller which home it serves\n * (`homeFingerprint`), so anything else — another home, an older panel, a stranger — is `other`.\n *\n * It **probes, and never signals**: without a record there is no pid this process can prove it\n * owns. A settings file that is missing or does not parse is not evidence either way, so this\n * reports nothing rather than inventing a port to test.\n */\nexport async function configuredPanelAddress(): Promise<ConfiguredListener | null> {\n const { readStateFile } = await import('#src/helpers/config-text')\n const { globalSettingsPath, homeFingerprint } = await import('#src/helpers/paths')\n const { probePort } = await import('#src/providers/port')\n const { globalSettingsSchema } = await import('#src/config/schema')\n\n let port: number\n try {\n const parsed = globalSettingsSchema(JSON.parse(readStateFile(globalSettingsPath)) as unknown)\n // `instanceof type.errors` is the only honest test — ArkType's errors are not `Error`s, so\n // `instanceof Error` is false for a valid *and* an invalid payload.\n if (parsed instanceof type.errors)\n return null\n port = parsed.control.port\n }\n catch {\n // No settings file, or one that does not parse: there is nothing to probe.\n return null\n }\n\n if (!await probePort('127.0.0.1', port))\n return null\n // https only when plain http got no answer at all: the panel may serve TLS on its own port.\n for (const protocol of ['http', 'https']) {\n const base = `${protocol}://127.0.0.1:${port}`\n const answer = await localCall(base, '/healthz', 'GET', undefined, 2500)\n if (answer === null)\n continue\n return answeredHome(answer.body) === homeFingerprint() ? { kind: 'panel', url: base } : { kind: 'other', port }\n }\n return { kind: 'other', port }\n}\n\n/** The `home` a `/healthz` answer names, or `null`. */\nfunction answeredHome(body: string): string | null {\n try {\n const home = (JSON.parse(body) as { home?: unknown }).home\n return typeof home === 'string' ? home : null\n }\n catch {\n return null\n }\n}\n\n/**\n * Asks the daemon to stop through its own endpoint, so supervised servers are\n * shut down cleanly on every platform (a bare signal is not graceful on Windows).\n */\nexport async function requestShutdown(runtime: Runtime, timeoutMs = 4000, options: { withPersistent?: boolean } = {}): Promise<boolean> {\n // `withPersistent` rides the same query channel `workspace` already uses: the request helper\n // sends no body, and this is what lets `down --with-persistent` have the panel end the entries\n // while it is still alive to record the stop.\n const query = options.withPersistent === true ? '?withPersistent=true' : ''\n const answer = await localCall(runtime.probeUrl, `/_hh/shutdown${query}`, 'POST', runtime.token, timeoutMs)\n return answer !== null && answer.status >= 200 && answer.status < 300\n}\n\n/** A `/_hh` answer: the status, plus the body when it was JSON. */\nexport interface ControlAnswer {\n status: number\n body: unknown\n}\n\n/**\n * Drives a supervised server from this machine (`home-hosted start`/`stop`). The\n * token comes from run.json, so it needs no session, no password and no API token —\n * only the owner of that 0600 file, talking over loopback.\n *\n * The wait is generous on purpose: a start may have to run a bootstrap, which has a\n * 120s default timeout of its own. Past this it is a wedged panel, not a slow one.\n */\nexport async function requestControl(runtime: Runtime, path: string, timeoutMs = 150000, method: 'GET' | 'POST' = 'POST'): Promise<ControlAnswer | null> {\n const answer = await localCall(runtime.probeUrl, path, method, runtime.token, timeoutMs)\n if (answer === null)\n return null\n\n let body: unknown = null\n try {\n body = JSON.parse(answer.body)\n }\n catch {\n // Not JSON: an empty body or a proxy's error page. The status still means something.\n }\n return { status: answer.status, body }\n}\n\n/**\n * Talks to the panel over loopback. Node's `fetch` cannot be told to accept the\n * self-signed certificate an uploaded TLS pair usually is, which would break\n * `status`, the graceful `down` and the local start/stop — so this speaks\n * http/https directly.\n */\nfunction localCall(base: string, path: string, method: 'GET' | 'POST', token: string | undefined, timeoutMs: number): Promise<{ status: number, body: string } | null> {\n return new Promise((resolve) => {\n const url = new URL(`${base}${path}`)\n const secure = url.protocol === 'https:'\n const request = (secure ? https : http).request({\n hostname: url.hostname,\n port: url.port,\n // The query travels too: a workspace-scoped local call names its workspace there.\n path: `${url.pathname}${url.search}`,\n method,\n // Only ever pointed at our own listener on this machine.\n ...(secure ? { rejectUnauthorized: false } : {}),\n headers: token === undefined ? {} : { 'x-home-hosted-token': token },\n timeout: timeoutMs,\n }, (response) => {\n let body = ''\n response.setEncoding('utf8')\n response.on('data', (chunk: string) => {\n body += chunk\n })\n response.once('end', () => resolve({ status: response.statusCode ?? 0, body }))\n // The `timeout` below is on the *request*, so it stops covering the call once the\n // headers are in. A socket that dies mid-body — the panel rebinding its listener is\n // the documented case — otherwise leaves this promise unsettled for ever, and\n // `down`/`start`/`stop` hang with it.\n response.once('aborted', () => resolve(null))\n response.once('error', () => resolve(null))\n })\n\n request.once('error', () => resolve(null))\n request.once('timeout', () => {\n request.destroy()\n resolve(null)\n })\n request.end()\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,IAAa,gBAAgB,WAAW,KAAK;CAC3C,SAAS;CACT,KAAK;;CAEL,KAAK;;CAEL,UAAU;CACV,UAAU;CACV,MAAM;CACN,UAAU;CACV,WAAW;CACX,YAAY;CACZ,UAAU;CACV,YAAY;CACZ,SAAS;CACT,OAAO;AACT,CAAC,CAAC,CAAC,gBAAgB,QAAQ,CAAC;AAG5B,SAAgB,cAA8B;CAC5C,IAAI;EACF,MAAM,SAAS,cAAc,KAAK,MAAM,GAAG,aAAa,aAAa,MAAM,CAAC,CAAC;EAC7E,OAAO,kBAAkB,KAAK,SAAS,OAAO;CAChD,QACM;EACJ,OAAO;CACT;AACF;AAEA,SAAgB,aAAa,SAAwB;CACnD,gBAAgB,aAAa,GAAG,KAAK,UAAU,SAAS,MAAM,CAAC,EAAE,KAAK,EAAE,MAAM,IAAM,CAAC;AACvF;AAEA,SAAgB,eAAqB;CACnC,GAAG,OAAO,aAAa,EAAE,OAAO,KAAK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AAK,MAAM,OAAO,IAAI;CAC/B,QACM,CAEN;CACA,OAAO;EAAE,QAAQ,OAAO;EAAQ;CAAK;AACvC;;;;;;;AAQA,SAAS,UAAU,MAAc,MAAc,QAAwB,OAA2B,WAAqE;CACrK,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,MAAM,IAAI,IAAI,GAAG,OAAO,MAAM;EACpC,MAAM,SAAS,IAAI,aAAa;EAChC,MAAM,WAAW,SAAS,QAAQ,KAAA,CAAM,QAAQ;GAC9C,UAAU,IAAI;GACd,MAAM,IAAI;GAEV,MAAM,GAAG,IAAI,WAAW,IAAI;GAC5B;GAEA,GAAI,SAAS,EAAE,oBAAoB,MAAM,IAAI,CAAC;GAC9C,SAAS,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,uBAAuB,MAAM;GACnE,SAAS;EACX,IAAI,aAAa;GACf,IAAI,OAAO;GACX,SAAS,YAAY,MAAM;GAC3B,SAAS,GAAG,SAAS,UAAkB;IACrC,QAAQ;GACV,CAAC;GACD,SAAS,KAAK,aAAa,QAAQ;IAAE,QAAQ,SAAS,cAAc;IAAG;GAAK,CAAC,CAAC;GAK9E,SAAS,KAAK,iBAAiB,QAAQ,IAAI,CAAC;GAC5C,SAAS,KAAK,eAAe,QAAQ,IAAI,CAAC;EAC5C,CAAC;EAED,QAAQ,KAAK,eAAe,QAAQ,IAAI,CAAC;EACzC,QAAQ,KAAK,iBAAiB;GAC5B,QAAQ,QAAQ;GAChB,QAAQ,IAAI;EACd,CAAC;EACD,QAAQ,IAAI;CACd,CAAC;AACH"}
1
+ {"version":3,"file":"daemon-CofN9k6Q.js","names":[],"sources":["../../src/helpers/daemon.ts"],"sourcesContent":["import type { ProcessLiveness } from '#src/providers/port'\nimport { randomBytes } from 'node:crypto'\nimport fs from 'node:fs'\nimport http from 'node:http'\nimport https from 'node:https'\nimport { type } from 'arktype'\nimport { writeFileAtomic } from '#src/helpers/atomic'\nimport { runtimePath } from '#src/helpers/paths'\nimport { processLiveness } from '#src/providers/port'\nimport { lazy } from '#src/shared/lazy'\n\n/**\n * `run.json` is how `status`/`down` find the live control plane and how they are\n * allowed to stop it without a password: the file is mode 0600, and the token in\n * it is what `POST /_hh/shutdown` checks.\n */\nexport const runtimeSchema = lazy(() => type({\n version: 'string',\n pid: 'number.integer >= 1',\n /** The address that was actually bound, for humans. */\n url: 'string',\n /** Always a reachable loopback address, for probes (`lan` binds to 0.0.0.0). */\n probeUrl: 'string',\n protocol: 'string',\n port: '1 <= number.integer <= 65535',\n bindHost: 'string',\n startedAt: 'number',\n projectDir: 'string',\n dataRoot: 'string',\n configPath: 'string',\n logFile: 'string',\n token: 'string >= 1',\n}).onUndeclaredKey('reject'))\nexport type Runtime = typeof runtimeSchema.infer\n\nexport function readRuntime(): Runtime | null {\n try {\n const parsed = runtimeSchema(JSON.parse(fs.readFileSync(runtimePath, 'utf8')))\n return parsed instanceof type.errors ? null : parsed\n }\n catch {\n return null\n }\n}\n\nexport function writeRuntime(runtime: Runtime): void {\n writeFileAtomic(runtimePath, `${JSON.stringify(runtime, null, 2)}\\n`, { mode: 0o600 })\n}\n\nexport function clearRuntime(): void {\n fs.rmSync(runtimePath, { force: true })\n}\n\nexport function newToken(): string {\n return randomBytes(32).toString('base64url')\n}\n\n/**\n * Re-exported from `providers/port.ts` so the two cannot drift on `EPERM` again.\n *\n * They already had: this copy treated a process owned by another user as alive (correct) while the\n * port one treated it as gone, which made a live nanny look absent. One definition, one answer.\n */\nexport { isProcessAlive } from '#src/providers/port'\n\n/**\n * What became of the daemon this record describes: the verdict `run.json`'s pid cannot give on\n * its own. See `processLiveness` in `providers/port.ts` for why the pid is not an identity.\n */\nexport async function runtimeLiveness(runtime: Runtime): Promise<ProcessLiveness> {\n return await processLiveness(runtime.pid, runtime.startedAt)\n}\n\n/**\n * Is the daemon this record describes still the one running?\n *\n * `readRuntime()` answers \"does a record exist\", never \"is the panel behind it alive\" — and a pid\n * alone cannot answer that either. The OS reuses pids, and a zombie still answers signal 0, so a\n * bare `isProcessAlive(runtime.pid)` reported a stale `run.json` as a live panel: `up` refused with\n * \"already running\", `status` said \"running, but not answering\", and `down` signalled whatever\n * unrelated process had since inherited the pid.\n *\n * Every caller must read this one predicate, because a caller that re-derives it slightly differently\n * is how a `down` comes to signal a stranger.\n */\nexport async function runtimeIsAlive(runtime: Runtime): Promise<boolean> {\n return isLiveLiveness(await runtimeLiveness(runtime))\n}\n\n/**\n * Only `'live'` and `'unknown'` count as alive. `'unknown'` means the platform could not read a start\n * time, so the live pid is all there is — dismissing it would clear a record the running panel still\n * owns. `'recycled'` is emphatically **not** alive: the pid belongs to somebody else now.\n */\nexport function isLiveLiveness(liveness: ProcessLiveness): boolean {\n return liveness === 'live' || liveness === 'unknown'\n}\n\n/**\n * Is the record positively pointing at nothing at all — no process behind the pid?\n *\n * This is the **only** condition under which deleting `run.json` is safe, so it is deliberately\n * narrower than `!runtimeIsAlive`. The start-time check can be wrong in one direction: Linux derives\n * a process's birth epoch from `btime`, which the kernel computes from the wall clock\n * (`getboottime64`: \"calls to settimeofday will affect the value returned\"), so a forward clock step\n * — common when a laptop or a WSL host wakes from sleep — makes a *live* panel look recycled. Deleting\n * its record over that would orphan a running panel: still supervising servers, no longer stoppable by\n * `down`. A record that some process may still own is left alone and simply overwritten when a new\n * panel finishes booting.\n */\nexport async function runtimeIsGone(runtime: Runtime): Promise<boolean> {\n return await runtimeLiveness(runtime) === 'gone'\n}\n\nexport interface RuntimeProbe {\n /** The panel answered on its own port — stronger than \"the pid exists\". */\n reachable: boolean\n /** It answered, but reports a crashed autostart server (`/healthz` is 503). */\n degraded: boolean\n /**\n * How many entries it supervises, and how many are up — `null` when the panel answered without\n * a count (an older panel, or one that did not accept the token).\n */\n servers: { total: number, running: number } | null\n}\n\n/** A degraded panel is still answering: a 503 must not read as \"not running\". */\nexport async function probeRuntime(runtime: Runtime, timeoutMs = 2500): Promise<RuntimeProbe> {\n // The token is what makes `/healthz` include the per-server counts instead of only the public\n // status line. `usage` was already reading the same numbers over `/_hh`; `status` not doing so was\n // this call passing no token, not the data being unavailable.\n const answer = await localCall(runtime.probeUrl, '/healthz', 'GET', runtime.token, timeoutMs)\n return { reachable: answer !== null, degraded: answer?.status === 503, servers: readServerCounts(answer?.body) }\n}\n\n/** The `servers` block of a `/healthz` answer, or `null` when it did not carry one. */\nfunction readServerCounts(body: string | undefined): RuntimeProbe['servers'] {\n if (body === undefined)\n return null\n try {\n const parsed = JSON.parse(body) as { servers?: { total?: unknown, running?: unknown } }\n const { total, running } = parsed.servers ?? {}\n return typeof total === 'number' && typeof running === 'number' ? { total, running } : null\n }\n catch {\n return null\n }\n}\n\n/** What holds the configured control port when no `run.json` names a panel. */\nexport type ConfiguredListener\n = | { kind: 'panel', url: string }\n | { kind: 'other', port: number }\n\n/**\n * What is listening on this home's configured port, when no `run.json` says a panel should be — or\n * `null` when nothing is.\n *\n * Every command that answers \"is it running\" has to consult this, not the record alone: with\n * `run.json` deleted, `status` printed \"home-hosted is not running\" while `GET /healthz` on the\n * same port answered `200`, and `down` refuses instead of letting `down && up` start a second panel\n * over a live one. The port comes from the state root's own `settings.json`, because that is the\n * only record left once `run.json` is gone.\n *\n * **A listener is only this home's panel when it says so.** Two homes may share a port (one stopped,\n * one running), and treating any listener as \"ours\" broke `status` and `down` in the stopped one —\n * `down` refused over another home's panel. `/healthz` tells a loopback caller which home it serves\n * (`homeFingerprint`), so anything else — another home, an older panel, a stranger — is `other`.\n *\n * It **probes, and never signals**: without a record there is no pid this process can prove it\n * owns. A settings file that is missing or does not parse is not evidence either way, so this\n * reports nothing rather than inventing a port to test.\n */\nexport async function configuredPanelAddress(): Promise<ConfiguredListener | null> {\n const { readStateFile } = await import('#src/helpers/config-text')\n const { globalSettingsPath, homeFingerprint } = await import('#src/helpers/paths')\n const { probePort } = await import('#src/providers/port')\n const { globalSettingsSchema } = await import('#src/config/schema')\n\n let port: number\n try {\n const parsed = globalSettingsSchema(JSON.parse(readStateFile(globalSettingsPath)) as unknown)\n // `instanceof type.errors` is the only honest test — ArkType's errors are not `Error`s, so\n // `instanceof Error` is false for a valid *and* an invalid payload.\n if (parsed instanceof type.errors)\n return null\n port = parsed.control.port\n }\n catch {\n // No settings file, or one that does not parse: there is nothing to probe.\n return null\n }\n\n if (!await probePort('127.0.0.1', port))\n return null\n // https only when plain http got no answer at all: the panel may serve TLS on its own port.\n for (const protocol of ['http', 'https']) {\n const base = `${protocol}://127.0.0.1:${port}`\n const answer = await localCall(base, '/healthz', 'GET', undefined, 2500)\n if (answer === null)\n continue\n return answeredHome(answer.body) === homeFingerprint() ? { kind: 'panel', url: base } : { kind: 'other', port }\n }\n return { kind: 'other', port }\n}\n\n/** The `home` a `/healthz` answer names, or `null`. */\nfunction answeredHome(body: string): string | null {\n try {\n const home = (JSON.parse(body) as { home?: unknown }).home\n return typeof home === 'string' ? home : null\n }\n catch {\n return null\n }\n}\n\n/**\n * Asks the daemon to stop through its own endpoint, so supervised servers are\n * shut down cleanly on every platform (a bare signal is not graceful on Windows).\n */\nexport async function requestShutdown(runtime: Runtime, timeoutMs = 4000, options: { withPersistent?: boolean } = {}): Promise<boolean> {\n // `withPersistent` rides the same query channel `workspace` already uses: the request helper\n // sends no body, and this is what lets `down --with-persistent` have the panel end the entries\n // while it is still alive to record the stop.\n const query = options.withPersistent === true ? '?withPersistent=true' : ''\n const answer = await localCall(runtime.probeUrl, `/_hh/shutdown${query}`, 'POST', runtime.token, timeoutMs)\n return answer !== null && answer.status >= 200 && answer.status < 300\n}\n\n/** A `/_hh` answer: the status, plus the body when it was JSON. */\nexport interface ControlAnswer {\n status: number\n body: unknown\n}\n\n/**\n * Drives a supervised server from this machine (`home-hosted start`/`stop`). The\n * token comes from run.json, so it needs no session, no password and no API token —\n * only the owner of that 0600 file, talking over loopback.\n *\n * The wait is generous on purpose: a start may have to run a bootstrap, which has a\n * 120s default timeout of its own. Past this it is a wedged panel, not a slow one.\n */\nexport async function requestControl(runtime: Runtime, path: string, timeoutMs = 150000, method: 'GET' | 'POST' = 'POST'): Promise<ControlAnswer | null> {\n const answer = await localCall(runtime.probeUrl, path, method, runtime.token, timeoutMs)\n if (answer === null)\n return null\n\n let body: unknown = null\n try {\n body = JSON.parse(answer.body)\n }\n catch {\n // Not JSON: an empty body or a proxy's error page. The status still means something.\n }\n return { status: answer.status, body }\n}\n\n/**\n * Talks to the panel over loopback. Node's `fetch` cannot be told to accept the\n * self-signed certificate an uploaded TLS pair usually is, which would break\n * `status`, the graceful `down` and the local start/stop — so this speaks\n * http/https directly.\n */\nfunction localCall(base: string, path: string, method: 'GET' | 'POST', token: string | undefined, timeoutMs: number): Promise<{ status: number, body: string } | null> {\n return new Promise((resolve) => {\n const url = new URL(`${base}${path}`)\n const secure = url.protocol === 'https:'\n const request = (secure ? https : http).request({\n hostname: url.hostname,\n port: url.port,\n // The query travels too: a workspace-scoped local call names its workspace there.\n path: `${url.pathname}${url.search}`,\n method,\n // Only ever pointed at our own listener on this machine.\n ...(secure ? { rejectUnauthorized: false } : {}),\n headers: token === undefined ? {} : { 'x-home-hosted-token': token },\n timeout: timeoutMs,\n }, (response) => {\n let body = ''\n response.setEncoding('utf8')\n response.on('data', (chunk: string) => {\n body += chunk\n })\n response.once('end', () => resolve({ status: response.statusCode ?? 0, body }))\n // The `timeout` below is on the *request*, so it stops covering the call once the\n // headers are in. A socket that dies mid-body — the panel rebinding its listener is\n // the documented case — otherwise leaves this promise unsettled for ever, and\n // `down`/`start`/`stop` hang with it.\n response.once('aborted', () => resolve(null))\n response.once('error', () => resolve(null))\n })\n\n request.once('error', () => resolve(null))\n request.once('timeout', () => {\n request.destroy()\n resolve(null)\n })\n request.end()\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,IAAa,gBAAgB,WAAW,KAAK;CAC3C,SAAS;CACT,KAAK;;CAEL,KAAK;;CAEL,UAAU;CACV,UAAU;CACV,MAAM;CACN,UAAU;CACV,WAAW;CACX,YAAY;CACZ,UAAU;CACV,YAAY;CACZ,SAAS;CACT,OAAO;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,KAAK,eAAe,QAAQ,IAAI,CAAC;EACzC,QAAQ,KAAK,iBAAiB;GAC5B,QAAQ,QAAQ;GAChB,QAAQ,IAAI;EACd,CAAC;EACD,QAAQ,IAAI;CACd,CAAC;AACH"}
@@ -7,7 +7,7 @@ import fs from "node:fs";
7
7
  import { spawnSync } from "node:child_process";
8
8
  //#region src/cli/down.ts
9
9
  async function runDown(options = {}) {
10
- const { clearRuntime, configuredPanelAddress, isLiveLiveness, readRuntime, requestShutdown, runtimeLiveness } = await import("./daemon-qKVECISl.js");
10
+ const { clearRuntime, configuredPanelAddress, isLiveLiveness, readRuntime, requestShutdown, runtimeLiveness } = await import("./daemon-CofN9k6Q.js");
11
11
  const result = {
12
12
  ok: true,
13
13
  stoppedPersistent: []
@@ -85,7 +85,7 @@ async function runDown(options = {}) {
85
85
  * `down` reads them itself — after a crash there is nobody left to ask.
86
86
  */
87
87
  async function livePersistents() {
88
- const { livePersistentEntries } = await import("./nanny-sweep-DErnlPY1.js");
88
+ const { livePersistentEntries } = await import("./nanny-sweep-ClVuNJRo.js");
89
89
  const { hhDir } = await import("./paths-CGlGDrOU.js").then((n) => n.d);
90
90
  return livePersistentEntries(hhDir);
91
91
  }
@@ -107,7 +107,7 @@ async function stopPersistents(before) {
107
107
  done,
108
108
  survived
109
109
  };
110
- const { stopPersistentEntries } = await import("./nanny-sweep-DErnlPY1.js");
110
+ const { stopPersistentEntries } = await import("./nanny-sweep-ClVuNJRo.js");
111
111
  const results = await stopPersistentEntries(handles, { stopFor: await stopPolicyLookup() });
112
112
  for (const result of results) {
113
113
  const label = persistentLabel(result.handle);
@@ -331,7 +331,7 @@ async function reportPersistent(options, before = []) {
331
331
  return stopped;
332
332
  }
333
333
  async function waitForExit(pid, timeoutMs) {
334
- const { isProcessAlive } = await import("./daemon-qKVECISl.js");
334
+ const { isProcessAlive } = await import("./daemon-CofN9k6Q.js");
335
335
  const deadline = Date.now() + timeoutMs;
336
336
  while (Date.now() < deadline) {
337
337
  if (!isProcessAlive(pid)) return true;
@@ -380,4 +380,4 @@ var downCommand = defineCommand({
380
380
  //#endregion
381
381
  export { downCommand, runDown };
382
382
 
383
- //# sourceMappingURL=down-pKbGCW9d.js.map
383
+ //# sourceMappingURL=down-C59ne5aM.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"down-pKbGCW9d.js","names":[],"sources":["../../src/cli/down.ts"],"sourcesContent":["import type { PersistentHandle } from '#src/providers/nanny-sweep'\nimport type { ServerConfig, StopConfig } from '#src/shared/contracts'\nimport { spawnSync } from 'node:child_process'\nimport fs from 'node:fs'\nimport process from 'node:process'\nimport { defineCommand } from 'citty'\nimport { delay, dim, green, invocation, paint, refusal } from '#src/cli/io'\nimport { recordCleanStop } from '#src/helpers/last-stop'\nimport { versionMismatchNote } from '#src/helpers/version'\nimport { isComposeCommand } from '#src/providers/docker'\n\n/**\n * `down` stops the panel and everything it supervises.\n *\n * A `persistent: true` entry is the one thing it deliberately leaves running, which is what\n * `--with-persistent` changes: the same stop, extended to those entries. While the panel is\n * up they are stopped through it, so the stop is recorded like a click in the UI; once it is\n * gone their nannies are signalled directly, because the state files are then the only record.\n */\n\nexport interface DownOptions {\n /** Also stop every persistent entry, in every workspace. */\n withPersistent?: boolean\n}\n\n/** Which persistent entries this stop ended, as `(workspace, id)` — what `restart` starts back. */\nexport interface DownResult {\n /**\n * False when a panel of this home may still be running: it could not be stopped, or it answers\n * without a `run.json` to stop it by. `restart` must not go on to `up` over it.\n */\n ok: boolean\n stoppedPersistent: Array<{ workspaceId: string, serverId: string }>\n}\n\nexport async function runDown(options: DownOptions = {}): Promise<DownResult> {\n const { clearRuntime, configuredPanelAddress, isLiveLiveness, readRuntime, requestShutdown, runtimeLiveness } = await import('#src/helpers/daemon')\n\n const result: DownResult = { ok: true, stoppedPersistent: [] }\n // What was running before this command did anything. The panel ends the entries itself when\n // asked, so afterwards they are simply gone — and the difference between \"was running\" and\n // \"still running\" is the only account of what was stopped. `restart` starts exactly that list.\n const before = options.withPersistent === true ? await livePersistents() : []\n // Filled by whichever path got here, so one place decides what was stopped and what survived.\n const finish = async (): Promise<DownResult> => {\n result.stoppedPersistent.push(...await reportPersistent(options, before))\n return result\n }\n\n const runtime = readRuntime()\n if (runtime === null) {\n // \"Nothing is running\" is a claim about the machine, not just about the record — and the record\n // is what `run.json` holds. A panel whose `run.json` is gone still listens, and saying \"not\n // running\" over it made `down && up` in a deploy script proceed against a live panel that then\n // held its port. Nothing here can *prove* ownership of a pid, so this only reports: it never\n // signals what it cannot identify.\n const leftover = await configuredPanelAddress()\n if (leftover?.kind === 'panel') {\n // Refused, not a success line: a deploy chain that continues here starts a second panel\n // against a live one. It says where and what to do, and signals nothing.\n refusal(`this home's panel is answering on ${leftover.url}, but no run.json records which process owns it — stop it yourself, or free that port, then run \\`${invocation()} up\\``)\n process.exitCode = 1\n result.ok = false\n // Persistent entries are still the thing easiest to forget, so their report still runs.\n return finish()\n }\n // Another home's panel (or anything else) on the same port is not ours to stop: nothing of this\n // home is running, which is what `down` was asked to make true.\n process.stdout.write(leftover?.kind === 'other'\n ? `home-hosted is not running (port ${leftover.port} is taken by another process — nothing of this home to stop)\\n`\n : 'home-hosted is not running\\n')\n // The panel's absence is exactly when a persistent entry is easiest to forget: it outlives\n // the panel by design, so \"nothing is running\" must not be said by omission here.\n return finish()\n }\n\n const liveness = await runtimeLiveness(runtime)\n // Nothing at all is behind the pid, so the record is simply stale: delete it, and do not touch the\n // network — a port this record names may now belong to an unrelated service.\n if (liveness === 'gone') {\n clearRuntime()\n process.stdout.write(`home-hosted is not running (removed a stale run.json from home-hosted ${runtime.version})\\n`)\n return finish()\n }\n\n /** What was stopped, and whether this CLI is a different release than it was. */\n const reportStopped = (forced: boolean): void => {\n process.stdout.write(`${green('stopped')}${forced ? ' (forced)' : ''} ${dim(`— was home-hosted ${runtime.version}`)}\\n`)\n const note = versionMismatchNote(runtime.version)\n if (note !== null)\n process.stdout.write(`${dim(note)}\\n`)\n }\n\n let answered = false\n // A graceful stop is under way only when the panel accepted the request or received SIGTERM.\n let stopping = true\n if (isLiveLiveness(liveness)) {\n process.stdout.write(`stopping pid ${runtime.pid}…\\n`)\n // The panel's own endpoint stops supervised servers cleanly on every platform; a signal is the\n // fallback for a wedged or unreachable process. Only a pid whose identity is confirmed is ever\n // signalled, and this branch is the only one that signals at all.\n // The panel ends the persistent entries itself when asked: it is the only one that can\n // record the stop (log line, history, health) and consume the state file in order.\n answered = await requestShutdown(runtime, 4000, { withPersistent: options.withPersistent === true })\n if (!answered)\n stopping = signal(runtime.pid, 'SIGTERM')\n }\n else {\n /**\n * The pid is alive but was born **after** this record was written, so it is some other process\n * that inherited the number — and it must never be signalled.\n *\n * The graceful stop is still offered, because it authenticates itself: `/_hh/shutdown` answers\n * only to the token in this `run.json`, which only the panel that wrote it knows. A reply is\n * therefore proof the panel *is* ours, which keeps it stoppable in the one case the birth time\n * can be wrong about — a forward wall-clock step, where the kernel's `btime` moves and a live\n * panel looks recycled. Either way this returns: `runtime.pid` is not the answering process, so\n * it is not signalled and the record is left for that panel to overwrite.\n */\n const answeredByPanel = await requestShutdown(runtime, 4000, { withPersistent: options.withPersistent === true })\n if (!answeredByPanel) {\n process.stdout.write(`home-hosted is not running (the pid in run.json, ${runtime.pid}, belongs to another process — it was not signalled)\\n`)\n return finish()\n }\n process.stdout.write(`stopped the panel on ${runtime.url} (its pid in run.json, ${runtime.pid}, was another process and was left alone)\\n`)\n clearRuntime()\n recordCleanStop()\n return finish()\n }\n\n // Nothing told the process to stop, so there is nothing to wait out; go straight to the forced stop.\n const budget = stopping ? await shutdownBudget(options.withPersistent === true) : 0\n if (await waitForExit(runtime.pid, budget)) {\n clearRuntime()\n recordCleanStop()\n reportStopped(false)\n return finish()\n }\n\n process.stdout.write(`${dim('it did not stop in time — forcing')}\\n`)\n forceStop(runtime.pid)\n // The forced stop's outcome decides the report, the exit code **and** whether the record may go.\n //\n // `forceStop` cannot report its own failure: `signal` swallows every error and `taskkill`'s exit\n // status is never read. This line used to discard `waitForExit`'s answer, `clearRuntime()` ran\n // regardless, and the command printed \"stopped (forced)\" and exited 0 — for a panel that was\n // still alive and still holding its port. Deleting run.json then destroyed the only record of it,\n // so `down && up` in a deploy script proceeded against a live panel. The graceful branch above\n // already asks this question before it clears; the forced branch is the one path that skipped it.\n if (!await waitForExit(runtime.pid, 5000)) {\n // Both lines are the refusal, and a refusal is one message on one stream (stderr): the remedy\n // is part of the reason. Printed to stdout it read as the command's answer, so a `down` in a\n // script — where stdout is the record — showed the failure in the same place success goes.\n refusal(`could not stop pid ${runtime.pid} — it is still running, and its record was kept`)\n process.stderr.write(`${dim(`stop it yourself with \\`kill -9 ${runtime.pid}\\` (Windows: \\`taskkill /PID ${runtime.pid} /F\\`), then run \\`down\\` again`)}\\n`)\n process.exitCode = 1\n result.ok = false\n return finish()\n }\n clearRuntime()\n recordCleanStop()\n reportStopped(true)\n return finish()\n}\n\n/**\n * The persistent entries this host has running, as their state files describe them.\n *\n * Every workspace keeps its own `.state`, and only the panel normally sees all of them, so\n * `down` reads them itself — after a crash there is nobody left to ask.\n */\nexport async function livePersistents(): Promise<PersistentHandle[]> {\n const { livePersistentEntries } = await import('#src/providers/nanny-sweep')\n const { hhDir } = await import('#src/helpers/paths')\n return livePersistentEntries(hhDir)\n}\n\n/** `workspace/id`, because a server id is only unique inside its workspace. */\nexport function persistentLabel(handle: Readonly<PersistentHandle>): string {\n return `${handle.workspaceId}/${handle.serverId}`\n}\n\n/**\n * Stops what is left of the snapshot: with the panel gone each nanny is signalled directly, and\n * its state file consumed once it is really gone. Returns which were ended here and which\n * survived, so the caller can account for the rest as the panel's work.\n */\nasync function stopPersistents(before: PersistentHandle[]): Promise<{ done: Set<string>, survived: Set<string> }> {\n const done = new Set<string>()\n const survived = new Set<string>()\n // Read again rather than trusting the snapshot: the panel's shutdown has been happening in\n // the meantime, and a nanny it already ended must not be signalled a second time.\n const live = new Set((await livePersistents()).map(persistentLabel))\n const handles = before.filter(handle => live.has(persistentLabel(handle)))\n if (handles.length === 0)\n return { done, survived }\n\n const { stopPersistentEntries } = await import('#src/providers/nanny-sweep')\n const results = await stopPersistentEntries(handles, { stopFor: await stopPolicyLookup() })\n\n for (const result of results) {\n const label = persistentLabel(result.handle)\n if (result.stopped) {\n done.add(label)\n process.stdout.write(`${green('stopped')} persistent ${label}\\n`)\n continue\n }\n survived.add(label)\n process.stderr.write(`${paint('31', 'error')} persistent ${label}: ${result.error}\\n`)\n }\n // A stop that left a server running is a failed stop, never a quiet success.\n const code = exitCodeForStops(results)\n if (code !== 0)\n process.exitCode = code\n return { done, survived }\n}\n\n/**\n * The exit code these stops earn: any survivor is a failure, because the command was asked to\n * stop them and the host is still running one. Separated from the printing so the rule is\n * pinned where it can be read, not inferred from a process's status.\n */\nexport function exitCodeForStops(results: ReadonlyArray<Readonly<{ stopped: boolean }>>): 0 | 1 {\n return results.some(result => !result.stopped) ? 1 : 0\n}\n\n/**\n * Each entry's own `stop` policy, read from the workspace that declares it.\n *\n * The grace period is the entry's, not a constant: the nanny forwards it to the child it\n * owns, so a shorter one here would escalate to `SIGKILL` while a shutdown the config asked\n * to allow more time for was still running. A workspace whose config cannot be read falls\n * back to the defaults — the host is being brought down either way.\n */\nasync function stopPolicyLookup(): Promise<(handle: PersistentHandle) => StopConfig> {\n const { stopSchema } = await import('#src/shared/contracts')\n const read = await serversReader()\n const policies = new Map<string, Map<string, StopConfig>>()\n\n return (handle) => {\n let byId = policies.get(handle.workspaceId)\n if (byId === undefined) {\n byId = new Map(read(handle.workspaceId).servers.map(server => [server.id, server.stop]))\n policies.set(handle.workspaceId, byId)\n }\n return byId.get(handle.serverId) ?? stopSchema.assert({})\n }\n}\n\n/**\n * Every workspace's entries, and whether that answer is **complete**.\n *\n * Read without writing: `WorkspaceStore.load()` seeds a missing config, so a `down` that only needs a\n * stop budget would create a workspace directory and two files on the way. Parsing the file directly\n * leaves that to the panel.\n *\n * `complete` is what the budget rests on. A workspace whose config cannot be read yields no entries,\n * and a budget computed from \"no entries\" is the 20 s floor — the exact failure a fixed 20 s wait was\n * replaced to avoid, so an unreadable config widens the wait instead of shortening it.\n */\nasync function configuredServers(): Promise<{ servers: ServerConfig[], complete: boolean }> {\n const { WorkspaceRegistry } = await import('#src/config/workspaces')\n const { DEFAULT_WORKSPACE_ID, workspacesPath } = await import('#src/helpers/paths')\n let ids = [DEFAULT_WORKSPACE_ID]\n let complete = true\n if (fs.existsSync(workspacesPath)) {\n const registry = new WorkspaceRegistry(workspacesPath)\n registry.load()\n if (registry.configError === null) {\n ids = registry.all().map(workspace => workspace.id)\n }\n else {\n // The registry names no workspace, so neither does this budget; the listed default is a guess.\n complete = false\n }\n }\n\n const read = await serversReader()\n const servers: ServerConfig[] = []\n for (const id of ids) {\n const workspace = read(id)\n if (!workspace.complete)\n complete = false\n servers.push(...workspace.servers)\n }\n return { servers, complete }\n}\n\n/**\n * One workspace's entries, parsed read-only: a config this CLI cannot read reports itself.\n *\n * The workspace's `defaults` block is resolved exactly as the panel resolves it, because a `stop`\n * grace that lives there is part of what the budget must cover. Passing `{}` read only each entry's\n * own `stop`: a workspace declaring `defaults.stop.graceMs: 120000` with an entry that spells none\n * measured a 20 s budget against the 132 s the panel actually needed, and `down` then SIGKILLed it\n * mid-grace — the same defect the widening above exists to avoid, reached through a valid config\n * rather than a broken one.\n */\nexport async function serversReader(): Promise<(workspaceId: string) => { servers: ServerConfig[], complete: boolean }> {\n const { readStateFile } = await import('#src/helpers/config-text')\n const { parseServersFile, parseWorkspaceSettings } = await import('#src/config/parse')\n const { workspaceServersPath, workspaceSettingsPath } = await import('#src/helpers/paths')\n return (workspaceId) => {\n const file = workspaceServersPath(workspaceId)\n if (!fs.existsSync(file)) {\n // Nothing declared is a real answer: a workspace with no entries stops nothing.\n return { servers: [], complete: true }\n }\n const resolved = workspaceDefaults(workspaceId, readStateFile, workspaceSettingsPath, parseWorkspaceSettings)\n try {\n const parsed = parseServersFile(JSON.parse(readStateFile(file)), resolved.defaults)\n // A settings file this CLI could not turn into defaults is as unknowable as a broken servers\n // file: the grace it declares is invisible, and the budget computed without it is the 20 s floor\n // — which SIGKILLs a panel still inside a grace the person configured.\n return { servers: parsed.servers, complete: parsed.errors.length === 0 && resolved.complete }\n }\n catch {\n return { servers: [], complete: false }\n }\n }\n}\n\n/**\n * The `defaults` group a workspace's settings file declares, and whether that answer is trustworthy.\n *\n * An **absent** file is a real answer — `{}`, `complete: true` — because a workspace with no settings\n * has no `defaults` to miss and the seed declares none. A file that is there but cannot be read, or\n * carries a `defaults` value this release rejects, is a different fact: the grace it declares is\n * invisible to the budget, and a budget computed without it is the 20 s floor. Reporting that as\n * `complete: false` widens the wait to the ceiling, which is the safe direction — too long costs a\n * slower `down`, too short kills a panel inside a grace the person configured.\n */\nfunction workspaceDefaults(\n workspaceId: string,\n readStateFile: (file: string) => string,\n workspaceSettingsPath: (id: string) => string,\n parseWorkspaceSettings: (raw: unknown) => { config: { defaults?: Record<string, unknown> } | null, errors: string[] },\n): { defaults: Record<string, unknown>, complete: boolean } {\n const file = workspaceSettingsPath(workspaceId)\n if (!fs.existsSync(file))\n return { defaults: {}, complete: true }\n try {\n const parsed = parseWorkspaceSettings(JSON.parse(readStateFile(file)))\n if (parsed.errors.length > 0)\n return { defaults: {}, complete: false }\n return { defaults: (parsed.config?.defaults ?? {}) as Record<string, unknown>, complete: true }\n }\n catch {\n return { defaults: {}, complete: false }\n }\n}\n\nconst SHUTDOWN_FLOOR_MS = 20_000\nconst SHUTDOWN_CEILING_MS = 10 * 60_000\n/** `stopComposeContainers`' own `docker stop` timeout, plus its two listings. */\nconst COMPOSE_STOP_MS = 130_000\n\n/**\n * How long to give the panel, from whatever this CLI could read of its config.\n *\n * A config it could not read makes the answer unknowable rather than empty, and an unknowable config\n * means an entry with a long grace may be one the read never showed. Widening to the ceiling there is\n * the safe direction: waiting too long costs a slower `down`, waiting too little SIGKILLs a panel\n * still inside a grace the person configured.\n */\nasync function shutdownBudget(withPersistent: boolean): Promise<number> {\n const { servers, complete } = await configuredServers()\n if (!complete) {\n process.stderr.write(`${dim('could not read every server config — allowing the panel the full stop budget')}\\n`)\n return SHUTDOWN_CEILING_MS\n }\n return shutdownBudgetMs(servers, withPersistent)\n}\n\n/**\n * How long the panel may take to stop what it supervises before `down` forces it.\n *\n * This is the slowest entry's stop, because the path `down` takes — `/_hh/shutdown` → `PanelService\n * .dispose` — stops every workspace's entries through `Promise.all`. (`stopAll`, behind the panel's\n * own stop-all route, is sequential; a caller budgeting for *that* would need the sum, not the max.)\n *\n * The slowest entry is its grace, the SIGKILL wait after it, a second round for a persistent child\n * signalled alone, and a compose stack's `docker stop` — plus a margin.\n */\nexport function shutdownBudgetMs(servers: ReadonlyArray<Pick<ServerConfig, 'command' | 'args' | 'persistent' | 'stop'>>, withPersistent: boolean): number {\n let slowest = 0\n for (const server of servers) {\n if (server.persistent && !withPersistent)\n continue\n const round = server.stop.graceMs + 2000\n let ms = round\n if (server.persistent && !server.stop.killGroup)\n ms += round\n if (server.stop.killPortHolders)\n ms += round\n if (isComposeCommand(server.command, server.args))\n ms += COMPOSE_STOP_MS\n slowest = Math.max(slowest, ms)\n }\n return Math.min(SHUTDOWN_CEILING_MS, Math.max(SHUTDOWN_FLOOR_MS, slowest + 10_000))\n}\n\n/**\n * The last step: name what the flag left running, or stop what the panel could not and account\n * for every entry that was running when this command started.\n *\n * The panel does the stopping whenever it is reachable — it is the only process that can record\n * it — so what is left of the snapshot is what still needs a signal here. Anything else in the\n * snapshot was ended by the panel, and is reported as stopped; a survivor is never reported as\n * stopped, or `restart` would treat a failed stop as a successful one.\n */\nasync function reportPersistent(options: DownOptions, before: PersistentHandle[] = []): Promise<DownResult['stoppedPersistent']> {\n if (options.withPersistent !== true) {\n const running = await livePersistents()\n if (running.length === 0)\n return []\n process.stdout.write(`${dim(`${running.length} persistent server(s) left running: ${running.map(persistentLabel).join(', ')}\\n`)}`)\n process.stdout.write(`${dim('stop one from the panel, or pass --with-persistent')}\\n`)\n return []\n }\n\n const ended = await stopPersistents(before)\n const stopped: DownResult['stoppedPersistent'] = []\n for (const handle of before) {\n const label = persistentLabel(handle)\n // A survivor is never reported as stopped, or `restart` would treat a failed stop as one.\n if (ended.survived.has(label))\n continue\n // Not ended here, so the panel did it on the way out: either way it is stopped, and the\n // caller cannot tell the two apart — nor should it have to.\n if (!ended.done.has(label))\n process.stdout.write(`${green('stopped')} persistent ${label}\\n`)\n stopped.push({ workspaceId: handle.workspaceId, serverId: handle.serverId })\n }\n return stopped\n}\n\nasync function waitForExit(pid: number, timeoutMs: number): Promise<boolean> {\n const { isProcessAlive } = await import('#src/helpers/daemon')\n const deadline = Date.now() + timeoutMs\n\n while (Date.now() < deadline) {\n if (!isProcessAlive(pid))\n return true\n await delay(200)\n }\n return !isProcessAlive(pid)\n}\n\n/** Whether the signal was delivered; `false` for a pid that is gone or not ours to signal (EPERM). */\nfunction signal(pid: number, name: NodeJS.Signals): boolean {\n try {\n process.kill(pid, name)\n return true\n }\n catch {\n return false\n }\n}\n\n/**\n * Only the panel's own pid, as SIGKILL is on POSIX: `taskkill /T` follows parent pids, which a\n * detached spawn keeps on Windows, so it also killed every persistent entry's nanny.\n */\nexport function forceStopCommand(pid: number, platform: NodeJS.Platform = process.platform): [string, string[]] | null {\n return platform === 'win32' ? ['taskkill', ['/PID', String(pid), '/F']] : null\n}\n\nfunction forceStop(pid: number): void {\n const command = forceStopCommand(pid)\n if (command !== null) {\n spawnSync(command[0], command[1], { windowsHide: true })\n return\n }\n signal(pid, 'SIGKILL')\n}\n\nexport const downCommand = defineCommand({\n meta: { name: 'down' },\n args: {\n withPersistent: { type: 'boolean', description: 'also stop every persistent entry, in every workspace' },\n },\n run: async ({ args }) => {\n await runDown({ withPersistent: args.withPersistent === true })\n },\n})\n"],"mappings":";;;;;;;;AAmCA,eAAsB,QAAQ,UAAuB,CAAC,GAAwB;CAC5E,MAAM,EAAE,cAAc,wBAAwB,gBAAgB,aAAa,iBAAiB,oBAAoB,MAAM,OAAO;CAE7H,MAAM,SAAqB;EAA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CACA,OAAO,CAAC,eAAe,GAAG;AAC5B;;AAGA,SAAS,OAAO,KAAa,MAA+B;CAC1D,IAAI;EACF,QAAQ,KAAK,KAAK,IAAI;EACtB,OAAO;CACT,QACM;EACJ,OAAO;CACT;AACF;;;;;AAMA,SAAgB,iBAAiB,KAAa,WAA4B,QAAQ,UAAqC;CACrH,OAAO,aAAa,UAAU,CAAC,YAAY;EAAC;EAAQ,OAAO,GAAG;EAAG;CAAI,CAAC,IAAI;AAC5E;AAEA,SAAS,UAAU,KAAmB;CACpC,MAAM,UAAU,iBAAiB,GAAG;CACpC,IAAI,YAAY,MAAM;EACpB,UAAU,QAAQ,IAAI,QAAQ,IAAI,EAAE,aAAa,KAAK,CAAC;EACvD;CACF;CACA,OAAO,KAAK,SAAS;AACvB;AAEA,IAAa,cAAc,cAAc;CACvC,MAAM,EAAE,MAAM,OAAO;CACrB,MAAM,EACJ,gBAAgB;EAAE,MAAM;EAAW,aAAa;CAAuD,EACzG;CACA,KAAK,OAAO,EAAE,WAAW;EACvB,MAAM,QAAQ,EAAE,gBAAgB,KAAK,mBAAmB,KAAK,CAAC;CAChE;AACF,CAAC"}
1
+ {"version":3,"file":"down-C59ne5aM.js","names":[],"sources":["../../src/cli/down.ts"],"sourcesContent":["import type { PersistentHandle } from '#src/providers/nanny-sweep'\nimport type { ServerConfig, StopConfig } from '#src/shared/contracts'\nimport { spawnSync } from 'node:child_process'\nimport fs from 'node:fs'\nimport process from 'node:process'\nimport { defineCommand } from 'citty'\nimport { delay, dim, green, invocation, paint, refusal } from '#src/cli/io'\nimport { recordCleanStop } from '#src/helpers/last-stop'\nimport { versionMismatchNote } from '#src/helpers/version'\nimport { isComposeCommand } from '#src/providers/docker'\n\n/**\n * `down` stops the panel and everything it supervises.\n *\n * A `persistent: true` entry is the one thing it deliberately leaves running, which is what\n * `--with-persistent` changes: the same stop, extended to those entries. While the panel is\n * up they are stopped through it, so the stop is recorded like a click in the UI; once it is\n * gone their nannies are signalled directly, because the state files are then the only record.\n */\n\nexport interface DownOptions {\n /** Also stop every persistent entry, in every workspace. */\n withPersistent?: boolean\n}\n\n/** Which persistent entries this stop ended, as `(workspace, id)` — what `restart` starts back. */\nexport interface DownResult {\n /**\n * False when a panel of this home may still be running: it could not be stopped, or it answers\n * without a `run.json` to stop it by. `restart` must not go on to `up` over it.\n */\n ok: boolean\n stoppedPersistent: Array<{ workspaceId: string, serverId: string }>\n}\n\nexport async function runDown(options: DownOptions = {}): Promise<DownResult> {\n const { clearRuntime, configuredPanelAddress, isLiveLiveness, readRuntime, requestShutdown, runtimeLiveness } = await import('#src/helpers/daemon')\n\n const result: DownResult = { ok: true, stoppedPersistent: [] }\n // What was running before this command did anything. The panel ends the entries itself when\n // asked, so afterwards they are simply gone — and the difference between \"was running\" and\n // \"still running\" is the only account of what was stopped. `restart` starts exactly that list.\n const before = options.withPersistent === true ? await livePersistents() : []\n // Filled by whichever path got here, so one place decides what was stopped and what survived.\n const finish = async (): Promise<DownResult> => {\n result.stoppedPersistent.push(...await reportPersistent(options, before))\n return result\n }\n\n const runtime = readRuntime()\n if (runtime === null) {\n // \"Nothing is running\" is a claim about the machine, not just about the record — and the record\n // is what `run.json` holds. A panel whose `run.json` is gone still listens, and saying \"not\n // running\" over it made `down && up` in a deploy script proceed against a live panel that then\n // held its port. Nothing here can *prove* ownership of a pid, so this only reports: it never\n // signals what it cannot identify.\n const leftover = await configuredPanelAddress()\n if (leftover?.kind === 'panel') {\n // Refused, not a success line: a deploy chain that continues here starts a second panel\n // against a live one. It says where and what to do, and signals nothing.\n refusal(`this home's panel is answering on ${leftover.url}, but no run.json records which process owns it — stop it yourself, or free that port, then run \\`${invocation()} up\\``)\n process.exitCode = 1\n result.ok = false\n // Persistent entries are still the thing easiest to forget, so their report still runs.\n return finish()\n }\n // Another home's panel (or anything else) on the same port is not ours to stop: nothing of this\n // home is running, which is what `down` was asked to make true.\n process.stdout.write(leftover?.kind === 'other'\n ? `home-hosted is not running (port ${leftover.port} is taken by another process — nothing of this home to stop)\\n`\n : 'home-hosted is not running\\n')\n // The panel's absence is exactly when a persistent entry is easiest to forget: it outlives\n // the panel by design, so \"nothing is running\" must not be said by omission here.\n return finish()\n }\n\n const liveness = await runtimeLiveness(runtime)\n // Nothing at all is behind the pid, so the record is simply stale: delete it, and do not touch the\n // network — a port this record names may now belong to an unrelated service.\n if (liveness === 'gone') {\n clearRuntime()\n process.stdout.write(`home-hosted is not running (removed a stale run.json from home-hosted ${runtime.version})\\n`)\n return finish()\n }\n\n /** What was stopped, and whether this CLI is a different release than it was. */\n const reportStopped = (forced: boolean): void => {\n process.stdout.write(`${green('stopped')}${forced ? ' (forced)' : ''} ${dim(`— was home-hosted ${runtime.version}`)}\\n`)\n const note = versionMismatchNote(runtime.version)\n if (note !== null)\n process.stdout.write(`${dim(note)}\\n`)\n }\n\n let answered = false\n // A graceful stop is under way only when the panel accepted the request or received SIGTERM.\n let stopping = true\n if (isLiveLiveness(liveness)) {\n process.stdout.write(`stopping pid ${runtime.pid}…\\n`)\n // The panel's own endpoint stops supervised servers cleanly on every platform; a signal is the\n // fallback for a wedged or unreachable process. Only a pid whose identity is confirmed is ever\n // signalled, and this branch is the only one that signals at all.\n // The panel ends the persistent entries itself when asked: it is the only one that can\n // record the stop (log line, history, health) and consume the state file in order.\n answered = await requestShutdown(runtime, 4000, { withPersistent: options.withPersistent === true })\n if (!answered)\n stopping = signal(runtime.pid, 'SIGTERM')\n }\n else {\n /**\n * The pid is alive but was born **after** this record was written, so it is some other process\n * that inherited the number — and it must never be signalled.\n *\n * The graceful stop is still offered, because it authenticates itself: `/_hh/shutdown` answers\n * only to the token in this `run.json`, which only the panel that wrote it knows. A reply is\n * therefore proof the panel *is* ours, which keeps it stoppable in the one case the birth time\n * can be wrong about — a forward wall-clock step, where the kernel's `btime` moves and a live\n * panel looks recycled. Either way this returns: `runtime.pid` is not the answering process, so\n * it is not signalled and the record is left for that panel to overwrite.\n */\n const answeredByPanel = await requestShutdown(runtime, 4000, { withPersistent: options.withPersistent === true })\n if (!answeredByPanel) {\n process.stdout.write(`home-hosted is not running (the pid in run.json, ${runtime.pid}, belongs to another process — it was not signalled)\\n`)\n return finish()\n }\n process.stdout.write(`stopped the panel on ${runtime.url} (its pid in run.json, ${runtime.pid}, was another process and was left alone)\\n`)\n clearRuntime()\n recordCleanStop()\n return finish()\n }\n\n // Nothing told the process to stop, so there is nothing to wait out; go straight to the forced stop.\n const budget = stopping ? await shutdownBudget(options.withPersistent === true) : 0\n if (await waitForExit(runtime.pid, budget)) {\n clearRuntime()\n recordCleanStop()\n reportStopped(false)\n return finish()\n }\n\n process.stdout.write(`${dim('it did not stop in time — forcing')}\\n`)\n forceStop(runtime.pid)\n // The forced stop's outcome decides the report, the exit code **and** whether the record may go.\n //\n // `forceStop` cannot report its own failure: `signal` swallows every error and `taskkill`'s exit\n // status is never read. This line used to discard `waitForExit`'s answer, `clearRuntime()` ran\n // regardless, and the command printed \"stopped (forced)\" and exited 0 — for a panel that was\n // still alive and still holding its port. Deleting run.json then destroyed the only record of it,\n // so `down && up` in a deploy script proceeded against a live panel. The graceful branch above\n // already asks this question before it clears; the forced branch is the one path that skipped it.\n if (!await waitForExit(runtime.pid, 5000)) {\n // Both lines are the refusal, and a refusal is one message on one stream (stderr): the remedy\n // is part of the reason. Printed to stdout it read as the command's answer, so a `down` in a\n // script — where stdout is the record — showed the failure in the same place success goes.\n refusal(`could not stop pid ${runtime.pid} — it is still running, and its record was kept`)\n process.stderr.write(`${dim(`stop it yourself with \\`kill -9 ${runtime.pid}\\` (Windows: \\`taskkill /PID ${runtime.pid} /F\\`), then run \\`down\\` again`)}\\n`)\n process.exitCode = 1\n result.ok = false\n return finish()\n }\n clearRuntime()\n recordCleanStop()\n reportStopped(true)\n return finish()\n}\n\n/**\n * The persistent entries this host has running, as their state files describe them.\n *\n * Every workspace keeps its own `.state`, and only the panel normally sees all of them, so\n * `down` reads them itself — after a crash there is nobody left to ask.\n */\nexport async function livePersistents(): Promise<PersistentHandle[]> {\n const { livePersistentEntries } = await import('#src/providers/nanny-sweep')\n const { hhDir } = await import('#src/helpers/paths')\n return livePersistentEntries(hhDir)\n}\n\n/** `workspace/id`, because a server id is only unique inside its workspace. */\nexport function persistentLabel(handle: Readonly<PersistentHandle>): string {\n return `${handle.workspaceId}/${handle.serverId}`\n}\n\n/**\n * Stops what is left of the snapshot: with the panel gone each nanny is signalled directly, and\n * its state file consumed once it is really gone. Returns which were ended here and which\n * survived, so the caller can account for the rest as the panel's work.\n */\nasync function stopPersistents(before: PersistentHandle[]): Promise<{ done: Set<string>, survived: Set<string> }> {\n const done = new Set<string>()\n const survived = new Set<string>()\n // Read again rather than trusting the snapshot: the panel's shutdown has been happening in\n // the meantime, and a nanny it already ended must not be signalled a second time.\n const live = new Set((await livePersistents()).map(persistentLabel))\n const handles = before.filter(handle => live.has(persistentLabel(handle)))\n if (handles.length === 0)\n return { done, survived }\n\n const { stopPersistentEntries } = await import('#src/providers/nanny-sweep')\n const results = await stopPersistentEntries(handles, { stopFor: await stopPolicyLookup() })\n\n for (const result of results) {\n const label = persistentLabel(result.handle)\n if (result.stopped) {\n done.add(label)\n process.stdout.write(`${green('stopped')} persistent ${label}\\n`)\n continue\n }\n survived.add(label)\n process.stderr.write(`${paint('31', 'error')} persistent ${label}: ${result.error}\\n`)\n }\n // A stop that left a server running is a failed stop, never a quiet success.\n const code = exitCodeForStops(results)\n if (code !== 0)\n process.exitCode = code\n return { done, survived }\n}\n\n/**\n * The exit code these stops earn: any survivor is a failure, because the command was asked to\n * stop them and the host is still running one. Separated from the printing so the rule is\n * pinned where it can be read, not inferred from a process's status.\n */\nexport function exitCodeForStops(results: ReadonlyArray<Readonly<{ stopped: boolean }>>): 0 | 1 {\n return results.some(result => !result.stopped) ? 1 : 0\n}\n\n/**\n * Each entry's own `stop` policy, read from the workspace that declares it.\n *\n * The grace period is the entry's, not a constant: the nanny forwards it to the child it\n * owns, so a shorter one here would escalate to `SIGKILL` while a shutdown the config asked\n * to allow more time for was still running. A workspace whose config cannot be read falls\n * back to the defaults — the host is being brought down either way.\n */\nasync function stopPolicyLookup(): Promise<(handle: PersistentHandle) => StopConfig> {\n const { stopSchema } = await import('#src/shared/contracts')\n const read = await serversReader()\n const policies = new Map<string, Map<string, StopConfig>>()\n\n return (handle) => {\n let byId = policies.get(handle.workspaceId)\n if (byId === undefined) {\n byId = new Map(read(handle.workspaceId).servers.map(server => [server.id, server.stop]))\n policies.set(handle.workspaceId, byId)\n }\n return byId.get(handle.serverId) ?? stopSchema.assert({})\n }\n}\n\n/**\n * Every workspace's entries, and whether that answer is **complete**.\n *\n * Read without writing: `WorkspaceStore.load()` seeds a missing config, so a `down` that only needs a\n * stop budget would create a workspace directory and two files on the way. Parsing the file directly\n * leaves that to the panel.\n *\n * `complete` is what the budget rests on. A workspace whose config cannot be read yields no entries,\n * and a budget computed from \"no entries\" is the 20 s floor — the exact failure a fixed 20 s wait was\n * replaced to avoid, so an unreadable config widens the wait instead of shortening it.\n */\nasync function configuredServers(): Promise<{ servers: ServerConfig[], complete: boolean }> {\n const { WorkspaceRegistry } = await import('#src/config/workspaces')\n const { DEFAULT_WORKSPACE_ID, workspacesPath } = await import('#src/helpers/paths')\n let ids = [DEFAULT_WORKSPACE_ID]\n let complete = true\n if (fs.existsSync(workspacesPath)) {\n const registry = new WorkspaceRegistry(workspacesPath)\n registry.load()\n if (registry.configError === null) {\n ids = registry.all().map(workspace => workspace.id)\n }\n else {\n // The registry names no workspace, so neither does this budget; the listed default is a guess.\n complete = false\n }\n }\n\n const read = await serversReader()\n const servers: ServerConfig[] = []\n for (const id of ids) {\n const workspace = read(id)\n if (!workspace.complete)\n complete = false\n servers.push(...workspace.servers)\n }\n return { servers, complete }\n}\n\n/**\n * One workspace's entries, parsed read-only: a config this CLI cannot read reports itself.\n *\n * The workspace's `defaults` block is resolved exactly as the panel resolves it, because a `stop`\n * grace that lives there is part of what the budget must cover. Passing `{}` read only each entry's\n * own `stop`: a workspace declaring `defaults.stop.graceMs: 120000` with an entry that spells none\n * measured a 20 s budget against the 132 s the panel actually needed, and `down` then SIGKILLed it\n * mid-grace — the same defect the widening above exists to avoid, reached through a valid config\n * rather than a broken one.\n */\nexport async function serversReader(): Promise<(workspaceId: string) => { servers: ServerConfig[], complete: boolean }> {\n const { readStateFile } = await import('#src/helpers/config-text')\n const { parseServersFile, parseWorkspaceSettings } = await import('#src/config/parse')\n const { workspaceServersPath, workspaceSettingsPath } = await import('#src/helpers/paths')\n return (workspaceId) => {\n const file = workspaceServersPath(workspaceId)\n if (!fs.existsSync(file)) {\n // Nothing declared is a real answer: a workspace with no entries stops nothing.\n return { servers: [], complete: true }\n }\n const resolved = workspaceDefaults(workspaceId, readStateFile, workspaceSettingsPath, parseWorkspaceSettings)\n try {\n const parsed = parseServersFile(JSON.parse(readStateFile(file)), resolved.defaults)\n // A settings file this CLI could not turn into defaults is as unknowable as a broken servers\n // file: the grace it declares is invisible, and the budget computed without it is the 20 s floor\n // — which SIGKILLs a panel still inside a grace the person configured.\n return { servers: parsed.servers, complete: parsed.errors.length === 0 && resolved.complete }\n }\n catch {\n return { servers: [], complete: false }\n }\n }\n}\n\n/**\n * The `defaults` group a workspace's settings file declares, and whether that answer is trustworthy.\n *\n * An **absent** file is a real answer — `{}`, `complete: true` — because a workspace with no settings\n * has no `defaults` to miss and the seed declares none. A file that is there but cannot be read, or\n * carries a `defaults` value this release rejects, is a different fact: the grace it declares is\n * invisible to the budget, and a budget computed without it is the 20 s floor. Reporting that as\n * `complete: false` widens the wait to the ceiling, which is the safe direction — too long costs a\n * slower `down`, too short kills a panel inside a grace the person configured.\n */\nfunction workspaceDefaults(\n workspaceId: string,\n readStateFile: (file: string) => string,\n workspaceSettingsPath: (id: string) => string,\n parseWorkspaceSettings: (raw: unknown) => { config: { defaults?: Record<string, unknown> } | null, errors: string[] },\n): { defaults: Record<string, unknown>, complete: boolean } {\n const file = workspaceSettingsPath(workspaceId)\n if (!fs.existsSync(file))\n return { defaults: {}, complete: true }\n try {\n const parsed = parseWorkspaceSettings(JSON.parse(readStateFile(file)))\n if (parsed.errors.length > 0)\n return { defaults: {}, complete: false }\n return { defaults: (parsed.config?.defaults ?? {}) as Record<string, unknown>, complete: true }\n }\n catch {\n return { defaults: {}, complete: false }\n }\n}\n\nconst SHUTDOWN_FLOOR_MS = 20_000\nconst SHUTDOWN_CEILING_MS = 10 * 60_000\n/** `stopComposeContainers`' own `docker stop` timeout, plus its two listings. */\nconst COMPOSE_STOP_MS = 130_000\n\n/**\n * How long to give the panel, from whatever this CLI could read of its config.\n *\n * A config it could not read makes the answer unknowable rather than empty, and an unknowable config\n * means an entry with a long grace may be one the read never showed. Widening to the ceiling there is\n * the safe direction: waiting too long costs a slower `down`, waiting too little SIGKILLs a panel\n * still inside a grace the person configured.\n */\nasync function shutdownBudget(withPersistent: boolean): Promise<number> {\n const { servers, complete } = await configuredServers()\n if (!complete) {\n process.stderr.write(`${dim('could not read every server config — allowing the panel the full stop budget')}\\n`)\n return SHUTDOWN_CEILING_MS\n }\n return shutdownBudgetMs(servers, withPersistent)\n}\n\n/**\n * How long the panel may take to stop what it supervises before `down` forces it.\n *\n * This is the slowest entry's stop, because the path `down` takes — `/_hh/shutdown` → `PanelService\n * .dispose` — stops every workspace's entries through `Promise.all`. (`stopAll`, behind the panel's\n * own stop-all route, is sequential; a caller budgeting for *that* would need the sum, not the max.)\n *\n * The slowest entry is its grace, the SIGKILL wait after it, a second round for a persistent child\n * signalled alone, and a compose stack's `docker stop` — plus a margin.\n */\nexport function shutdownBudgetMs(servers: ReadonlyArray<Pick<ServerConfig, 'command' | 'args' | 'persistent' | 'stop'>>, withPersistent: boolean): number {\n let slowest = 0\n for (const server of servers) {\n if (server.persistent && !withPersistent)\n continue\n const round = server.stop.graceMs + 2000\n let ms = round\n if (server.persistent && !server.stop.killGroup)\n ms += round\n if (server.stop.killPortHolders)\n ms += round\n if (isComposeCommand(server.command, server.args))\n ms += COMPOSE_STOP_MS\n slowest = Math.max(slowest, ms)\n }\n return Math.min(SHUTDOWN_CEILING_MS, Math.max(SHUTDOWN_FLOOR_MS, slowest + 10_000))\n}\n\n/**\n * The last step: name what the flag left running, or stop what the panel could not and account\n * for every entry that was running when this command started.\n *\n * The panel does the stopping whenever it is reachable — it is the only process that can record\n * it — so what is left of the snapshot is what still needs a signal here. Anything else in the\n * snapshot was ended by the panel, and is reported as stopped; a survivor is never reported as\n * stopped, or `restart` would treat a failed stop as a successful one.\n */\nasync function reportPersistent(options: DownOptions, before: PersistentHandle[] = []): Promise<DownResult['stoppedPersistent']> {\n if (options.withPersistent !== true) {\n const running = await livePersistents()\n if (running.length === 0)\n return []\n process.stdout.write(`${dim(`${running.length} persistent server(s) left running: ${running.map(persistentLabel).join(', ')}\\n`)}`)\n process.stdout.write(`${dim('stop one from the panel, or pass --with-persistent')}\\n`)\n return []\n }\n\n const ended = await stopPersistents(before)\n const stopped: DownResult['stoppedPersistent'] = []\n for (const handle of before) {\n const label = persistentLabel(handle)\n // A survivor is never reported as stopped, or `restart` would treat a failed stop as one.\n if (ended.survived.has(label))\n continue\n // Not ended here, so the panel did it on the way out: either way it is stopped, and the\n // caller cannot tell the two apart — nor should it have to.\n if (!ended.done.has(label))\n process.stdout.write(`${green('stopped')} persistent ${label}\\n`)\n stopped.push({ workspaceId: handle.workspaceId, serverId: handle.serverId })\n }\n return stopped\n}\n\nasync function waitForExit(pid: number, timeoutMs: number): Promise<boolean> {\n const { isProcessAlive } = await import('#src/helpers/daemon')\n const deadline = Date.now() + timeoutMs\n\n while (Date.now() < deadline) {\n if (!isProcessAlive(pid))\n return true\n await delay(200)\n }\n return !isProcessAlive(pid)\n}\n\n/** Whether the signal was delivered; `false` for a pid that is gone or not ours to signal (EPERM). */\nfunction signal(pid: number, name: NodeJS.Signals): boolean {\n try {\n process.kill(pid, name)\n return true\n }\n catch {\n return false\n }\n}\n\n/**\n * Only the panel's own pid, as SIGKILL is on POSIX: `taskkill /T` follows parent pids, which a\n * detached spawn keeps on Windows, so it also killed every persistent entry's nanny.\n */\nexport function forceStopCommand(pid: number, platform: NodeJS.Platform = process.platform): [string, string[]] | null {\n return platform === 'win32' ? ['taskkill', ['/PID', String(pid), '/F']] : null\n}\n\nfunction forceStop(pid: number): void {\n const command = forceStopCommand(pid)\n if (command !== null) {\n spawnSync(command[0], command[1], { windowsHide: true })\n return\n }\n signal(pid, 'SIGKILL')\n}\n\nexport const downCommand = defineCommand({\n meta: { name: 'down' },\n args: {\n withPersistent: { type: 'boolean', description: 'also stop every persistent entry, in every workspace' },\n },\n run: async ({ args }) => {\n await runDown({ withPersistent: args.withPersistent === true })\n },\n})\n"],"mappings":";;;;;;;;AAmCA,eAAsB,QAAQ,UAAuB,CAAC,GAAwB;CAC5E,MAAM,EAAE,cAAc,wBAAwB,gBAAgB,aAAa,iBAAiB,oBAAoB,MAAM,OAAO;CAE7H,MAAM,SAAqB;EAAE,IAAI;EAAM,mBAAmB,CAAC;CAAE;CAI7D,MAAM,SAAS,QAAQ,mBAAmB,OAAO,MAAM,gBAAgB,IAAI,CAAC;CAE5E,MAAM,SAAS,YAAiC;EAC9C,OAAO,kBAAkB,KAAK,GAAG,MAAM,iBAAiB,SAAS,MAAM,CAAC;EACxE,OAAO;CACT;CAEA,MAAM,UAAU,YAAY;CAC5B,IAAI,YAAY,MAAM;EAMpB,MAAM,WAAW,MAAM,uBAAuB;EAC9C,IAAI,UAAU,SAAS,SAAS;GAG9B,QAAQ,qCAAqC,SAAS,IAAI,oGAAoG,WAAW,EAAE,MAAM;GACjL,QAAQ,WAAW;GACnB,OAAO,KAAK;GAEZ,OAAO,OAAO;EAChB;EAGA,QAAQ,OAAO,MAAM,UAAU,SAAS,UACpC,oCAAoC,SAAS,KAAK,kEAClD,8BAA8B;EAGlC,OAAO,OAAO;CAChB;CAEA,MAAM,WAAW,MAAM,gBAAgB,OAAO;CAG9C,IAAI,aAAa,QAAQ;EACvB,aAAa;EACb,QAAQ,OAAO,MAAM,yEAAyE,QAAQ,QAAQ,IAAI;EAClH,OAAO,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E;AACF,CAAC"}
@@ -3,7 +3,7 @@ import "../cli.js";
3
3
  import { f as projectDir } from "./paths-CGlGDrOU.js";
4
4
  import { t as writeFileAtomic } from "./atomic-C1PfJpE7.js";
5
5
  import { M as nannySpecSchema, N as nannyStateSchema } from "./contracts-CMBD1TF9.js";
6
- import { c as processLiveness, r as isProcessAlive } from "./port-B8WBTRMk.js";
6
+ import { c as processLiveness, r as isProcessAlive } from "./port-k5VBw8t9.js";
7
7
  import process from "node:process";
8
8
  import path from "node:path";
9
9
  import fs from "node:fs";
@@ -144,7 +144,8 @@ async function readWindows() {
144
144
  script
145
145
  ], {
146
146
  timeout: 8e3,
147
- maxBuffer: 16777216
147
+ maxBuffer: 16777216,
148
+ windowsHide: true
148
149
  });
149
150
  return parseWindowsCsv(stdout);
150
151
  } catch {
@@ -156,7 +157,8 @@ async function readWindows() {
156
157
  "/format:csv"
157
158
  ], {
158
159
  timeout: 8e3,
159
- maxBuffer: 16777216
160
+ maxBuffer: 16777216,
161
+ windowsHide: true
160
162
  });
161
163
  return parseWindowsCsv(stdout);
162
164
  } catch {
@@ -829,7 +831,10 @@ async function killTreeWindows(pid) {
829
831
  String(pid),
830
832
  "/T",
831
833
  "/F"
832
- ], { timeout: 5e3 });
834
+ ], {
835
+ timeout: 5e3,
836
+ windowsHide: true
837
+ });
833
838
  } catch {}
834
839
  }
835
840
  /** SIGKILL to a `spawnManaged` child and everything it started: its group, or its tree on Windows. */
@@ -1164,4 +1169,4 @@ async function nannyChildPid(state, options = {}) {
1164
1169
  //#endregion
1165
1170
  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 };
1166
1171
 
1167
- //# sourceMappingURL=nanny-BtWfy0QH.js.map
1172
+ //# sourceMappingURL=nanny-COyCJXj9.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nanny-COyCJXj9.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 windowsHide: true,\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, windowsHide: true })\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, windowsHide: true })\n }\n catch {\n // Already gone, or taskkill is unavailable.\n }\n}\n\n/** SIGKILL to a `spawnManaged` child and everything it started: its group, or its tree on Windows. */\nexport function forceKillTree(child: ChildProcess): void {\n if (child.exitCode === null && child.signalCode === null)\n signalChild(child, 'SIGKILL', true)\n}\n\nfunction signalChild(child: ChildProcess, signal: NodeJS.Signals, killGroup: boolean): void {\n const pid = child.pid\n if (pid === undefined)\n return\n signalPid(pid, signal, killGroup)\n}\n\nfunction signalPid(pid: number, signal: NodeJS.Signals, killGroup: boolean): void {\n if (process.platform === 'win32') {\n if (killGroup) {\n void killTreeWindows(pid)\n }\n else {\n try {\n process.kill(pid, signal)\n }\n catch {\n // already exited\n }\n }\n return\n }\n\n if (killGroup) {\n try {\n process.kill(-pid, signal)\n return\n }\n catch {\n // group already gone, fall through to the single pid\n }\n }\n\n try {\n process.kill(pid, signal)\n }\n catch {\n // already exited\n }\n}\n\n/**\n * The same shutdown a supervised child gets, for a process we adopted instead of\n * spawned: a detached successor is not our child, so it is signalled by pid (and\n * by process group when asked) and its exit is polled rather than awaited.\n *\n * Liveness comes from `isProcessAlive`, never a local signal-0 copy: a second definition returned\n * `false` for `EPERM`, so a process that was there but not ours to signal read as \"exited\" and\n * `'force-killed'` was returned for one still running. One predicate, one answer.\n */\nexport async function terminatePid(pid: number, options: TerminateOptions): Promise<'exited' | 'force-killed'> {\n if (!isProcessAlive(pid))\n return 'exited'\n\n signalPid(pid, options.signal, options.killGroup)\n\n const deadline = Date.now() + Math.max(0, options.graceMs)\n while (Date.now() < deadline && isProcessAlive(pid))\n await delay(50)\n if (!isProcessAlive(pid))\n return 'exited'\n\n signalPid(pid, 'SIGKILL', options.escalateGroup ?? options.killGroup)\n const hardDeadline = Date.now() + 2000\n while (Date.now() < hardDeadline && isProcessAlive(pid))\n await delay(50)\n return 'force-killed'\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n\nfunction waitForExit(child: ChildProcess, timeoutMs: number): Promise<boolean> {\n if (child.exitCode !== null || child.signalCode !== null)\n return Promise.resolve(true)\n if (timeoutMs <= 0)\n return Promise.resolve(false)\n\n return new Promise((resolve) => {\n const timer = setTimeout(() => {\n child.removeListener('exit', onExit)\n resolve(false)\n }, timeoutMs)\n\n function onExit(): void {\n clearTimeout(timer)\n resolve(true)\n }\n\n child.once('exit', onExit)\n })\n}\n","import type { ProcessBirth } from '#src/providers/port'\nimport type { TerminateOptions } from '#src/providers/process'\nimport type { NannyExit, NannySpec, NannyState, StopConfig } from '#src/shared/contracts'\nimport fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { type } from 'arktype'\nimport { writeFileAtomic } from '#src/helpers/atomic'\nimport { NANNY_COMMAND } from '#src/helpers/runtime'\nimport { processArgv } from '#src/providers/identity'\nimport { processLiveness } from '#src/providers/port'\nimport { processCarriesServerId } from '#src/providers/proc'\nimport { findProgram } from '#src/providers/process'\nimport { nannySpecSchema, nannyStateSchema } from '#src/shared/contracts'\n\n/**\n * A persistent entry is not run by the panel: the panel spawns a *nanny* that owns\n * the child's pipes, writes its output to the entry's JSONL log and keeps a small\n * state file. That is what lets the entry survive a panel stop, restart or kill\n * without losing its log or its identity — the pipes belong to a process that stays.\n *\n * These are the files and the liveness rules behind that arrangement; the nanny\n * itself is `src/services/nanny.ts`.\n */\n\n/** The spec carries expanded `env`, so it lives only from spawn to read. */\nconst SPEC_MODE = 0o600\n\n/** Suffix of a spawn spec, so a sweep and the state reader can tell them apart. */\nexport const SPEC_SUFFIX = '.spec.json'\n\n/**\n * The signals a nanny traps and forwards to its child. Any other signal ends the nanny outright,\n * so nothing was forwarded — see `stopPersistentEntries`, which then signals the child directly.\n */\nexport const NANNY_TRAPPED_SIGNALS: ReadonlySet<NodeJS.Signals> = new Set(['SIGTERM', 'SIGINT'])\n\n/**\n * How a nanny is stopped. A trapped signal goes to the nanny's pid alone and the nanny signals its\n * own group once (`killGroup` is honoured there): signalling the group from here as well delivered\n * the stop to the child twice. The SIGKILL escalation still covers the whole group. Windows has no\n * signal a nanny can trap, so its stop is unchanged.\n */\nexport function nannyStopOptions(stop: StopConfig, platform: NodeJS.Platform = process.platform): TerminateOptions {\n if (platform === 'win32' || !stop.killGroup || !NANNY_TRAPPED_SIGNALS.has(stop.signal))\n return stop\n return { ...stop, killGroup: false, escalateGroup: true }\n}\n\n/** How often a nanny rewrites its state file. */\nexport const NANNY_HEARTBEAT_MS = 5000\n\n/** A heartbeat older than this is not evidence of anything. */\nexport const HEARTBEAT_STALE_MS = 30_000\n\n/**\n * The state directory is passed in rather than read from a global: the panel injects\n * `$HHOSTED_HOME/.state`, and a test injects its own temp directory.\n */\nexport function nannySpecPath(dir: string, id: string): string {\n return path.join(dir, `${id}${SPEC_SUFFIX}`)\n}\n\nexport function nannyStatePath(dir: string, id: string): string {\n return path.join(dir, `${id}.json`)\n}\n\n/** The file a nanny writes and the panel tails; one derivation, so they cannot drift. */\nexport function nannyLogFile(logDir: string, id: string): string {\n return path.join(logDir, `${id}.log`)\n}\n\n/**\n * How to run this CLI again as a nanny. The panel was itself launched through this\n * entry point (`up` re-spawns itself with it), so `process.argv[1]` is the one path\n * that works under tsx, from `dist/cli.js` and through the published bin alike.\n */\nexport function nannyEntryPoint(): string {\n return process.argv[1] ?? ''\n}\n\n/** Written before the spawn, consumed by the nanny, never left behind. */\nexport function writeNannySpec(file: string, spec: NannySpec): void {\n writeFileAtomic(file, JSON.stringify(spec), { mode: SPEC_MODE })\n}\n\nexport function clearNannySpec(file: string): void {\n fs.rmSync(file, { force: true })\n}\n\n/**\n * Reads and unlinks in one step: the spec holds expanded secrets, and a spec left\n * behind — a nanny that died before reading it, a panel killed mid-spawn — is a\n * secret file with no owner. It is consumed even when it cannot be parsed.\n */\nexport function takeNannySpec(file: string): NannySpec {\n const raw = fs.readFileSync(file, 'utf8')\n fs.rmSync(file, { force: true })\n\n const parsed = nannySpecSchema(JSON.parse(raw))\n if (parsed instanceof type.errors)\n throw new Error(`invalid nanny spec: ${parsed.summary}`)\n return parsed\n}\n\n/**\n * Nothing can be waiting on a spec before this panel has spawned a nanny, so every\n * one still on disk at boot belongs to a nanny that never read it.\n */\nexport function sweepNannySpecs(dir: string): number {\n let swept = 0\n for (const name of readSpecNames(dir)) {\n fs.rmSync(path.join(dir, name), { force: true })\n swept += 1\n }\n return swept\n}\n\nfunction readSpecNames(dir: string): string[] {\n try {\n return fs.readdirSync(dir).filter(name => name.endsWith(SPEC_SUFFIX))\n }\n catch {\n return []\n }\n}\n\n/** A stale or foreign file reads as \"no state\", never as a throw. */\nexport function readNannyState(file: string): NannyState | null {\n try {\n const parsed = nannyStateSchema(JSON.parse(fs.readFileSync(file, 'utf8')))\n return parsed instanceof type.errors ? null : parsed\n }\n catch {\n return null\n }\n}\n\nexport function writeNannyState(file: string, state: NannyState): void {\n writeFileAtomic(file, JSON.stringify(state))\n}\n\nexport function clearNannyState(file: string): void {\n fs.rmSync(file, { force: true })\n}\n\n/**\n * The same wording the supervisor uses for a child's exit, so history reads alike — plus a hint\n * when the code has a conventional meaning, because `code 137` alone tells an operator nothing and\n * that is the one they most want explained (a container limit or the kernel OOM killer).\n *\n * The hint is worded as a possibility, never a claim: 128+N is a shell convention, and a program\n * is free to exit 137 for its own reasons — a JVM reports OOM that way itself. 126 and 127 are\n * firmer, since the shell sets those when it cannot run the command at all.\n */\nexport function describeNannyExit(exit: NannyExit): string {\n if (exit.signal !== null)\n return `signal ${exit.signal}`\n const hint = exitCodeHint(exit.code)\n return hint === null ? `code ${exit.code}` : `code ${exit.code} (${hint})`\n}\n\n/** What a conventional exit code usually means, or null when there is nothing to add. */\nfunction exitCodeHint(code: number | null): string | null {\n if (code === null || code === 0)\n return null\n if (code === 126)\n return 'the command is not executable'\n if (code === 127)\n return 'the command was not found'\n if (code <= 128 || code > 128 + 64)\n return null\n const signal = signalName(code - 128)\n if (signal === null)\n return null\n return code === 137\n ? `${signal} — which the kernel sends when memory runs out`\n : `${signal}, if the shell reported the kill`\n}\n\n/**\n * A spawn failure in words a person can act on.\n *\n * Node reports a missing program as `spawn <cmd> ENOENT` — the same errno as a missing *file*, and\n * the same wording whichever of the two it is. A user who pasted `java -jar server.jar` into\n * `command` saw exactly that and had nothing to go on: the message names the whole line, so it\n * reads as \"the program is missing\" even when the program is fine and only the argument is wrong.\n *\n * `command` is the configured program, so the two cases can be told apart: if a bare name has no\n * path separator, the shell would have searched `PATH` and this one did not.\n *\n * A **missing working directory** is the third cause of the same errno, and it is the one a\n * deployment hits: `spawn` resolves `cwd` before it looks for the program, so an entry whose `cwd`\n * does not exist *under this launch directory* fails exactly like an uninstalled program. That read\n * sent a person to `which node` while `node` was fine and only the relative path was wrong (a unit\n * file with no `WorkingDirectory=`, a container started from `/`). `cwd` is therefore checked first:\n * if it is not an existing directory, nothing else about the spawn could have worked.\n */\nexport function describeSpawnError(error: NodeJS.ErrnoException, command: string, cwd?: string): string {\n const missingDir = cwd === undefined ? null : describeMissingDir(cwd)\n if (missingDir !== null && (error.code === 'ENOENT' || error.code === 'ENOTDIR'))\n return missingDir\n\n if (error.code === 'ENOENT') {\n const pasted = describePastedCommandLine(command, cwd)\n if (pasted !== null)\n return pasted\n return command.includes('/') || command.includes('\\\\')\n // A path was given, so the path is what is missing — the file, or a directory on the way.\n ? `\\`${command}\\` does not exist — check the path, and any directory on the way to it`\n // A bare name: spawn does not search a shell's PATH aliases, and the program may simply\n // not be installed. Naming the program is the whole value here.\n : `\\`${command}\\` was not found — is it installed, and is it on PATH for the user running the panel?`\n }\n if (error.code === 'EACCES')\n return `\\`${command}\\` exists but is not executable — ${notExecutableHint()}`\n return `${error.message} (while running \\`${command}\\`)`\n}\n\n/**\n * What to do about `EACCES`, in the shell of the platform the panel is running on.\n *\n * `chmod +x` is not a Windows program: `cmd.exe` answers `'chmod' is not recognized…`, so the one\n * line that exists to offer a way out sent the reader to a second dead end. The platform is the\n * only signal available, exactly as it is for `shellQuote` (`helpers/shell.ts`); one function so a\n * second `EACCES` message cannot be written with the POSIX half alone.\n */\nfunction notExecutableHint(): string {\n return process.platform === 'win32'\n // Windows has no executable bit: `EACCES` there means an ACL or a blocked file, not a mode.\n ? 'check its permissions (Windows has no executable bit — look at the file\\'s Security tab for a denied account)'\n : 'check its permissions (chmod +x)'\n}\n\n/**\n * The first mistake the Add-server form invites: a whole command line typed into `Command`.\n *\n * `Command` is spawned **without a shell** and `Arguments` is a separate field, so `node server.js`\n * names a program called `node server.js`. The fix is to split it — and the sentence has to say so,\n * because the alternative reading (\"node is not installed\") is what sends someone to `which node`\n * while `node` is right there.\n *\n * Only claimed when the evidence is unambiguous: the field has whitespace, and the program it opens\n * with **does** resolve. So a genuinely missing program keeps the message about PATH, and a path with\n * a space in it is never split (it has no bare first word that resolves). See `findProgram`.\n */\nfunction describePastedCommandLine(command: string, cwd?: string): string | null {\n const words = command.trim().split(/\\s+/)\n if (words.length < 2)\n return null\n const program = words[0]!\n if (findProgram(program, cwd) === null)\n return null\n return `\\`${command}\\` is a whole command line, but \\`Command\\` is spawned without a shell — this release looks for a program named \\`${command}\\`. Put \\`${program}\\` in \\`Command\\` and the rest in \\`Arguments\\`, one argument per line`\n}\n\n/** Why a working directory cannot be used, in one sentence, or null when it can. */\nfunction describeMissingDir(cwd: string): string | null {\n try {\n if (fs.statSync(cwd).isDirectory())\n return null\n return `the working directory \\`${cwd}\\` is not a directory — a relative \\`cwd\\` resolves against the directory the panel was started from`\n }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return `the working directory \\`${cwd}\\` does not exist — a relative \\`cwd\\` resolves against the directory the panel was started from, so a service started from elsewhere (systemd, docker, a login shell) looks in a different place`\n }\n return `the working directory \\`${cwd}\\` cannot be read — check its permissions`\n }\n}\n\n/** `SIGKILL` for 9, or null when the number names nothing. */\nfunction signalName(number: number): string | null {\n for (const [name, value] of Object.entries(os.constants.signals)) {\n if (value === number)\n return name\n }\n return null\n}\n\n/**\n * Is the nanny this state describes still ours? A live pid proves nothing on its\n * own — pids are reused, and the heartbeat is written *into the file*, not by the\n * process the file names, so a recycled pid with a recent write reads as running.\n * `startedAt` settles that first (`processLiveness`), exactly as `run.json` uses it:\n * the nanny stamps its record during its own boot, so its process is always born\n * before the stamp. The environment marker (Linux, macOS) or the argv we spawned it\n * with answers the rest, Windows included.\n */\nexport async function nannyIsAlive(state: NannyState, id: string, options: { readBirth?: (pid: number) => Promise<ProcessBirth | null> } = {}): Promise<boolean> {\n if (state.nannyPid <= 0)\n return false\n // `'recycled'` is decisive and needs no threshold: a pid born after the record cannot be the\n // nanny that wrote it. `'gone'` is the plain dead pid. `'live'` and `'unknown'` both carry on —\n // a platform that cannot report a birth time must not have its running nanny dismissed.\n const liveness = await processLiveness(state.nannyPid, state.startedAt, options)\n if (liveness === 'gone' || liveness === 'recycled')\n return false\n if (Date.now() - state.heartbeatAt <= HEARTBEAT_STALE_MS)\n return true\n if (await processCarriesServerId(state.nannyPid, id))\n return true\n\n const words = await processArgv(state.nannyPid)\n return words !== null\n && words.includes(NANNY_COMMAND)\n && words.some(word => word.endsWith(`${id}.spec.json`))\n}\n\n/**\n * The nanny's child, when that pid is still the process it spawned — `null` otherwise. Used to stop a\n * child the nanny could not pass a stop on to, which happens *after* the nanny is gone, so a pid alone\n * could be anybody's by then. The nanny stamps `startedAt` just before it spawns the child, so the\n * child is born within the stamp's tolerance and a pid born later is a recycled one. Where the\n * platform reports no birth, the environment marker decides.\n */\nexport async function nannyChildPid(state: NannyState, options: { readBirth?: (pid: number) => Promise<ProcessBirth | null> } = {}): Promise<number | null> {\n const pid = state.childPid\n if (pid === null || pid <= 0)\n return null\n const liveness = await processLiveness(pid, state.startedAt, options)\n if (liveness === 'live')\n return pid\n if (liveness === 'unknown' && await processCarriesServerId(pid, state.serverId))\n return pid\n return null\n}\n"],"mappings":";;;;;;;;;;;;;;AAMA,IAAMA,kBAAgB,UAAU,QAAQ;AAYxC,SAAgB,cAAc,MAAyB;CACrD,MAAM,OAAkB,CAAC;CACzB,KAAK,MAAM,QAAQ,KAAK,MAAM,IAAI,GAAG;EACnC,MAAM,QAAQ,KAAK,KAAK,CAAC,CAAC,MAAM,KAAK;EACrC,IAAI,MAAM,SAAS,GACjB;EACF,MAAM,CAAC,KAAK,MAAM,KAAK,OAAO,MAAM,KAAI,UAAS,OAAO,WAAW,KAAK,CAAC;EACzE,IAAI,QAAQ,KAAA,KAAa,SAAS,KAAA,KAAa,QAAQ,KAAA,KAAa,CAAC,OAAO,SAAS,GAAG,GACtF;EACF,KAAK,KAAK;GAAE;GAAK;GAAM,OAAO;GAAK,YAAY,OAAO,SAAS,GAAG,IAAI,MAAM,KAAA;EAAU,CAAC;CACzF;CACA,OAAO;AACT;;AAGA,SAAgB,gBAAgB,MAAyB;CACvD,MAAM,OAAkB,CAAC;CACzB,MAAM,QAAQ,KAAK,MAAM,OAAO,CAAC,CAAC,QAAO,SAAQ,KAAK,KAAK,CAAC,CAAC,SAAS,CAAC;CACvE,MAAM,SAAS,MAAM,MAAM;CAC3B,IAAI,WAAW,KAAA,GACb,OAAO;CAET,MAAM,UAAU,OAAO,MAAM,GAAG,CAAC,CAAC,KAAI,UAAS,MAAM,QAAQ,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,YAAY,CAAC;CAC3F,MAAM,SAAS,SAAyB,QAAQ,QAAQ,KAAK,YAAY,CAAC;CAC1E,MAAM,QAAQ,MAAM,WAAW;CAC/B,MAAM,SAAS,MAAM,iBAAiB;CACtC,MAAM,QAAQ,MAAM,gBAAgB;CACpC,MAAM,WAA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AK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,GAAG,UAAU,OAAO,GAC7D,IAAI,UAAU,QACZ,OAAO;CAEX,OAAO;AACT;;;;;;;;;;AAWA,eAAsB,aAAa,OAAmB,IAAY,UAAyE,CAAC,GAAqB;CAC/J,IAAI,MAAM,YAAY,GACpB,OAAO;CAIT,MAAM,WAAW,MAAM,gBAAgB,MAAM,UAAU,MAAM,WAAW,OAAO;CAC/E,IAAI,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-BtWfy0QH.js").then((n) => n.g);
30
- const { runNanny } = await import("./nanny-B-Eu0sFW.js");
29
+ const { takeNannySpec } = await import("./nanny-COyCJXj9.js").then((n) => n.g);
30
+ const { runNanny } = await import("./nanny-rewguyXg.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-ChMtq1Zl.js.map
39
+ //# sourceMappingURL=nanny-Dnun3hVB.js.map
@@ -1 +1 @@
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
+ {"version":3,"file":"nanny-Dnun3hVB.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,4 +1,4 @@
1
- import { T as terminate, b as writeNannyState, c as describeSpawnError, f as nannyLogFile, n as NANNY_HEARTBEAT_MS, r as NANNY_TRAPPED_SIGNALS, s as describeNannyExit, w as spawnManaged } from "./nanny-BtWfy0QH.js";
1
+ import { T as terminate, b as writeNannyState, c as describeSpawnError, f as nannyLogFile, n as NANNY_HEARTBEAT_MS, r as NANNY_TRAPPED_SIGNALS, s as describeNannyExit, w as spawnManaged } from "./nanny-COyCJXj9.js";
2
2
  import { i as LogFiles, t as LineSplitter } from "./log-buffer-Dy9HHDMD.js";
3
3
  import process from "node:process";
4
4
  //#region src/services/nanny.ts
@@ -129,4 +129,4 @@ async function runNanny(spec, statePath) {
129
129
  //#endregion
130
130
  export { runNanny };
131
131
 
132
- //# sourceMappingURL=nanny-B-Eu0sFW.js.map
132
+ //# sourceMappingURL=nanny-rewguyXg.js.map