home-hosted 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/README.md +95 -49
  2. package/dist/chunks/{archive-DpCwA8Nf.js → archive-DP-XQR8X.js} +15 -2
  3. package/dist/chunks/archive-DP-XQR8X.js.map +1 -0
  4. package/dist/chunks/{atomic-CEfCUfkQ.js → atomic-C1PfJpE7.js} +3 -2
  5. package/dist/chunks/atomic-C1PfJpE7.js.map +1 -0
  6. package/dist/chunks/{backup-CPrJVPJI.js → backup-CZcVca2a.js} +101 -76
  7. package/dist/chunks/backup-CZcVca2a.js.map +1 -0
  8. package/dist/chunks/{backups-Bd2SF2qd.js → backups-CFRaWe_m.js} +881 -536
  9. package/dist/chunks/backups-CFRaWe_m.js.map +1 -0
  10. package/dist/chunks/{contracts-ku5ypHXJ.js → contracts-CMBD1TF9.js} +381 -407
  11. package/dist/chunks/contracts-CMBD1TF9.js.map +1 -0
  12. package/dist/chunks/{daemon-TwXk5vb8.js → daemon-qKVECISl.js} +52 -20
  13. package/dist/chunks/daemon-qKVECISl.js.map +1 -0
  14. package/dist/chunks/{docker-CGv4Uv7w.js → docker-Cy9Lyvda.js} +4 -3
  15. package/dist/chunks/docker-Cy9Lyvda.js.map +1 -0
  16. package/dist/chunks/{down-BlX5X3bm.js → down-pKbGCW9d.js} +22 -17
  17. package/dist/chunks/down-pKbGCW9d.js.map +1 -0
  18. package/dist/chunks/{init-DdmqHVra.js → init-BZ7hK9Vf.js} +19 -6
  19. package/dist/chunks/init-BZ7hK9Vf.js.map +1 -0
  20. package/dist/chunks/{last-stop-BZ08Z89-.js → last-stop-C-BXz_XI.js} +6 -5
  21. package/dist/chunks/last-stop-C-BXz_XI.js.map +1 -0
  22. package/dist/chunks/{layout-D74TGUnr.js → layout-DwTtmund.js} +2 -2
  23. package/dist/chunks/{layout-D74TGUnr.js.map → layout-DwTtmund.js.map} +1 -1
  24. package/dist/chunks/lazy-Ce5zEAq1.js +66 -0
  25. package/dist/chunks/lazy-Ce5zEAq1.js.map +1 -0
  26. package/dist/chunks/{log-buffer-HnP0jKhZ.js → log-buffer-Dy9HHDMD.js} +114 -50
  27. package/dist/chunks/log-buffer-Dy9HHDMD.js.map +1 -0
  28. package/dist/chunks/{logs-gI_69Q1P.js → logs---TI_bxM.js} +23 -21
  29. package/dist/chunks/logs---TI_bxM.js.map +1 -0
  30. package/dist/chunks/{migrate-BTlsibvF.js → migrate-Cfoq-Vgh.js} +5 -5
  31. package/dist/chunks/{migrate-BTlsibvF.js.map → migrate-Cfoq-Vgh.js.map} +1 -1
  32. package/dist/chunks/{nanny-CjnnrIpm.js → nanny-B-Eu0sFW.js} +3 -3
  33. package/dist/chunks/{nanny-CjnnrIpm.js.map → nanny-B-Eu0sFW.js.map} +1 -1
  34. package/dist/chunks/{nanny-20aBXL1o.js → nanny-BtWfy0QH.js} +121 -23
  35. package/dist/chunks/nanny-BtWfy0QH.js.map +1 -0
  36. package/dist/chunks/{nanny-DUaAfCV-.js → nanny-ChMtq1Zl.js} +3 -3
  37. package/dist/chunks/{nanny-DUaAfCV-.js.map → nanny-ChMtq1Zl.js.map} +1 -1
  38. package/dist/chunks/{nanny-sweep-Ca9kPAVi.js → nanny-sweep-DErnlPY1.js} +5 -4
  39. package/dist/chunks/nanny-sweep-DErnlPY1.js.map +1 -0
  40. package/dist/chunks/{parse-B9owE47G.js → parse-DhmG26fI.js} +4 -4
  41. package/dist/chunks/{parse-B9owE47G.js.map → parse-DhmG26fI.js.map} +1 -1
  42. package/dist/chunks/{paths-BT94q6-w.js → paths-CGlGDrOU.js} +36 -2
  43. package/dist/chunks/paths-CGlGDrOU.js.map +1 -0
  44. package/dist/chunks/{restart-UZgeDukG.js → restart-Des4DrAN.js} +25 -59
  45. package/dist/chunks/restart-Des4DrAN.js.map +1 -0
  46. package/dist/chunks/{schema-o7Lgk0V1.js → schema-B240VXcV.js} +11 -10
  47. package/dist/chunks/schema-B240VXcV.js.map +1 -0
  48. package/dist/chunks/{secrets-D7PdYh71.js → secrets-BieELnZh.js} +22 -4
  49. package/dist/chunks/secrets-BieELnZh.js.map +1 -0
  50. package/dist/chunks/{server-BuIeSsRu.js → server-Bge2r2qQ.js} +3 -3
  51. package/dist/chunks/{server-BuIeSsRu.js.map → server-Bge2r2qQ.js.map} +1 -1
  52. package/dist/chunks/{set-password-DegMumPh.js → set-password-D5vZqqSX.js} +7 -7
  53. package/dist/chunks/set-password-D5vZqqSX.js.map +1 -0
  54. package/dist/chunks/{set-token-21d1FTDC.js → set-token-obPiEJYk.js} +7 -7
  55. package/dist/chunks/set-token-obPiEJYk.js.map +1 -0
  56. package/dist/chunks/{settings-BVSBnIwJ.js → settings-xu-XTfWg.js} +126 -35
  57. package/dist/chunks/settings-xu-XTfWg.js.map +1 -0
  58. package/dist/chunks/{setup-temp-XiuAtiW2.js → setup-temp-CAN4_bA-.js} +6 -6
  59. package/dist/chunks/setup-temp-CAN4_bA-.js.map +1 -0
  60. package/dist/chunks/{src-BL97vLVb.js → src-BtWMFmzZ.js} +2246 -1061
  61. package/dist/chunks/src-BtWMFmzZ.js.map +1 -0
  62. package/dist/chunks/{status-EuWdRq8Q.js → status-DT1EsA-B.js} +12 -8
  63. package/dist/chunks/status-DT1EsA-B.js.map +1 -0
  64. package/dist/chunks/{ui-DbPuwddJ.js → ui-D562aqw5.js} +9 -7
  65. package/dist/chunks/ui-D562aqw5.js.map +1 -0
  66. package/dist/chunks/{ui-revert-BhqOAhmM.js → ui-revert-EkBBwRTt.js} +3 -3
  67. package/dist/chunks/{ui-revert-BhqOAhmM.js.map → ui-revert-EkBBwRTt.js.map} +1 -1
  68. package/dist/chunks/{ui-switch-CMoslPO2.js → ui-switch-BnZTdMDd.js} +3 -3
  69. package/dist/chunks/{ui-switch-CMoslPO2.js.map → ui-switch-BnZTdMDd.js.map} +1 -1
  70. package/dist/chunks/{ui-update-TTBBoDik.js → ui-update-_xryLYxw.js} +5 -5
  71. package/dist/chunks/{ui-update-TTBBoDik.js.map → ui-update-_xryLYxw.js.map} +1 -1
  72. package/dist/chunks/{up-C4H13hBw.js → up-Pdz-l6IH.js} +25 -11
  73. package/dist/chunks/up-Pdz-l6IH.js.map +1 -0
  74. package/dist/chunks/{usage-CSBgLRN5.js → usage-DFrCVXpT.js} +29 -3
  75. package/dist/chunks/usage-DFrCVXpT.js.map +1 -0
  76. package/dist/chunks/{workspaces-CAln2sQ7.js → workspaces-DYcfvKV_.js} +16 -8
  77. package/dist/chunks/workspaces-DYcfvKV_.js.map +1 -0
  78. package/dist/chunks/wsl-temperature-BiCI4iK6.js.map +1 -1
  79. package/dist/cli.js +80 -70
  80. package/dist/cli.js.map +1 -1
  81. package/dist/client.js +25 -1
  82. package/dist/client.js.map +1 -1
  83. package/dist/types/api/backups.d.ts +8 -3
  84. package/dist/types/api/control.d.ts +4 -3
  85. package/dist/types/api/events.d.ts +2 -1
  86. package/dist/types/api/health.d.ts +1 -0
  87. package/dist/types/api/metrics.d.ts +3 -1
  88. package/dist/types/api/settings.d.ts +2 -2
  89. package/dist/types/api/state.d.ts +8 -2
  90. package/dist/types/app.d.ts +26 -11
  91. package/dist/types/cli/backup.d.ts +7 -0
  92. package/dist/types/cli/down.d.ts +5 -0
  93. package/dist/types/cli/logs.d.ts +14 -2
  94. package/dist/types/cli/restart.d.ts +0 -1
  95. package/dist/types/cli/set-password.d.ts +2 -2
  96. package/dist/types/cli/up.d.ts +8 -2
  97. package/dist/types/client.d.ts +5618 -11
  98. package/dist/types/config/secrets.d.ts +2 -0
  99. package/dist/types/config/settings.d.ts +54 -8
  100. package/dist/types/config/store.d.ts +16 -3
  101. package/dist/types/config/workspaces.d.ts +4 -1
  102. package/dist/types/helpers/copy-tree.d.ts +5 -0
  103. package/dist/types/helpers/daemon.d.ts +20 -7
  104. package/dist/types/helpers/error.d.ts +8 -0
  105. package/dist/types/helpers/event-stream.d.ts +21 -0
  106. package/dist/types/helpers/openapi.d.ts +12 -24
  107. package/dist/types/helpers/paths.d.ts +18 -0
  108. package/dist/types/helpers/utf8-chunks.d.ts +15 -0
  109. package/dist/types/middleware/auth.d.ts +19 -3
  110. package/dist/types/providers/host.d.ts +1 -1
  111. package/dist/types/providers/log-tail.d.ts +27 -0
  112. package/dist/types/providers/nanny-sweep.d.ts +3 -0
  113. package/dist/types/providers/nanny.d.ts +10 -0
  114. package/dist/types/providers/proc.d.ts +9 -0
  115. package/dist/types/providers/process.d.ts +17 -0
  116. package/dist/types/providers/telegram.d.ts +45 -3
  117. package/dist/types/providers/wsl-temperature.d.ts +0 -4
  118. package/dist/types/services/auth.d.ts +36 -4
  119. package/dist/types/services/backups.d.ts +125 -1
  120. package/dist/types/services/ddns.d.ts +5 -0
  121. package/dist/types/services/exposure.d.ts +54 -1
  122. package/dist/types/services/history.d.ts +1 -0
  123. package/dist/types/services/host-monitor.d.ts +1 -0
  124. package/dist/types/services/log-buffer.d.ts +11 -0
  125. package/dist/types/services/log-files.d.ts +1 -11
  126. package/dist/types/services/log-relay.d.ts +0 -1
  127. package/dist/types/services/panel.d.ts +19 -0
  128. package/dist/types/services/proxy-certificates/certificates.d.ts +116 -0
  129. package/dist/types/services/proxy.d.ts +46 -69
  130. package/dist/types/services/state.d.ts +0 -3
  131. package/dist/types/services/supervisor/entry.d.ts +10 -0
  132. package/dist/types/services/supervisor/health.d.ts +3 -2
  133. package/dist/types/services/supervisor/output.d.ts +126 -0
  134. package/dist/types/services/supervisor/persistent.d.ts +4 -1
  135. package/dist/types/services/supervisor/records.d.ts +81 -1
  136. package/dist/types/services/supervisor.d.ts +32 -0
  137. package/dist/types/shared/action-outcome.d.ts +25 -0
  138. package/dist/types/shared/api-client.d.ts +218 -4
  139. package/dist/types/shared/backup-scope.d.ts +58 -0
  140. package/dist/types/shared/contracts.d.ts +142 -200
  141. package/dist/types/shared/ddns-form.d.ts +13 -0
  142. package/dist/types/shared/form-repair.d.ts +6 -0
  143. package/dist/types/shared/lazy.d.ts +4 -0
  144. package/dist/types/shared/live-frames.d.ts +22 -0
  145. package/dist/types/shared/live-series.d.ts +21 -0
  146. package/dist/types/shared/live-store.d.ts +72 -0
  147. package/dist/types/shared/patch-diff.d.ts +13 -2
  148. package/dist/types/shared/proxy-form.d.ts +2 -0
  149. package/dist/types/shared/server-form.d.ts +121 -0
  150. package/dist/types/shared/stream-access.d.ts +20 -0
  151. package/docs/API.md +45 -16
  152. package/docs/BACKUPS.md +31 -11
  153. package/docs/CLI.md +34 -61
  154. package/docs/DDNS.md +3 -1
  155. package/docs/NOTIFICATIONS.md +7 -1
  156. package/docs/REVERSE_PROXY.md +7 -1
  157. package/docs/SECURITY.md +21 -10
  158. package/docs/SERVERS.md +102 -23
  159. package/docs/UI_CREATION.md +10 -1
  160. package/docs/demo/blank-host-restore.sh +4 -3
  161. package/package.json +5 -7
  162. package/uis/stock/dist/assets/CopyButton-BUBKRJyY.js +1 -0
  163. package/uis/stock/dist/assets/GlobalSettingsView-yYMcRWvt.js +1 -0
  164. package/uis/stock/dist/assets/LogViewer-DIliXy62.js +1 -0
  165. package/uis/stock/dist/assets/LogsView-B7Z-7RNg.js +1 -0
  166. package/uis/stock/dist/assets/Modal-DmKa5Qpp.js +39 -0
  167. package/uis/stock/dist/assets/ProxyView-DvZiNkwb.js +1 -0
  168. package/uis/stock/dist/assets/ServerDetailView-6idGT_EX.js +2 -0
  169. package/uis/stock/dist/assets/SettingsShell-CeGtleYI.js +1 -0
  170. package/uis/stock/dist/assets/SettingsView-BrhJIrmk.js +2 -0
  171. package/uis/stock/dist/assets/de-BRITeb0H.js +1 -0
  172. package/uis/stock/dist/assets/es-B2zIEssV.js +1 -0
  173. package/uis/stock/dist/assets/fr-s0ZOBEqh.js +1 -0
  174. package/uis/stock/dist/assets/index-C1MehbKy.css +2 -0
  175. package/uis/stock/dist/assets/index-CnBN54wF.js +15 -0
  176. package/uis/stock/dist/assets/ja-CU7MR85V.js +1 -0
  177. package/uis/stock/dist/assets/ko-tL5Me6d-.js +1 -0
  178. package/uis/stock/dist/assets/ru-92yrvkNJ.js +1 -0
  179. package/uis/stock/dist/assets/vi-CzvY16k2.js +1 -0
  180. package/uis/stock/dist/assets/zh-CN-DDwFW_uW.js +1 -0
  181. package/uis/stock/dist/index.html +3 -2
  182. package/uis/stock/dist/ui.json +3 -3
  183. package/dist/chunks/archive-DpCwA8Nf.js.map +0 -1
  184. package/dist/chunks/atomic-CEfCUfkQ.js.map +0 -1
  185. package/dist/chunks/backup-CPrJVPJI.js.map +0 -1
  186. package/dist/chunks/backups-Bd2SF2qd.js.map +0 -1
  187. package/dist/chunks/contracts-ku5ypHXJ.js.map +0 -1
  188. package/dist/chunks/daemon-TwXk5vb8.js.map +0 -1
  189. package/dist/chunks/docker-CGv4Uv7w.js.map +0 -1
  190. package/dist/chunks/down-BlX5X3bm.js.map +0 -1
  191. package/dist/chunks/init-DdmqHVra.js.map +0 -1
  192. package/dist/chunks/last-stop-BZ08Z89-.js.map +0 -1
  193. package/dist/chunks/log-buffer-HnP0jKhZ.js.map +0 -1
  194. package/dist/chunks/logs-gI_69Q1P.js.map +0 -1
  195. package/dist/chunks/nanny-20aBXL1o.js.map +0 -1
  196. package/dist/chunks/nanny-sweep-Ca9kPAVi.js.map +0 -1
  197. package/dist/chunks/paths-BT94q6-w.js.map +0 -1
  198. package/dist/chunks/restart-UZgeDukG.js.map +0 -1
  199. package/dist/chunks/schema-o7Lgk0V1.js.map +0 -1
  200. package/dist/chunks/secrets-D7PdYh71.js.map +0 -1
  201. package/dist/chunks/set-password-DegMumPh.js.map +0 -1
  202. package/dist/chunks/set-token-21d1FTDC.js.map +0 -1
  203. package/dist/chunks/settings-BVSBnIwJ.js.map +0 -1
  204. package/dist/chunks/setup-temp-XiuAtiW2.js.map +0 -1
  205. package/dist/chunks/src-BL97vLVb.js.map +0 -1
  206. package/dist/chunks/status-EuWdRq8Q.js.map +0 -1
  207. package/dist/chunks/ui-DbPuwddJ.js.map +0 -1
  208. package/dist/chunks/up-C4H13hBw.js.map +0 -1
  209. package/dist/chunks/usage-CSBgLRN5.js.map +0 -1
  210. package/dist/chunks/workspaces-CAln2sQ7.js.map +0 -1
  211. package/docs/RESTORE_DEMO.md +0 -306
  212. package/uis/stock/dist/assets/de-DyGrM1KK.js +0 -1
  213. package/uis/stock/dist/assets/es-BebHdc0E.js +0 -1
  214. package/uis/stock/dist/assets/fr-DsDTrxhI.js +0 -1
  215. package/uis/stock/dist/assets/index-6LANO2Ua.css +0 -2
  216. package/uis/stock/dist/assets/index-D06cUZbM.js +0 -56
  217. package/uis/stock/dist/assets/ja-D3RARJjW.js +0 -1
  218. package/uis/stock/dist/assets/ko-CKI3dFoD.js +0 -1
  219. package/uis/stock/dist/assets/ru-DEU5ujXt.js +0 -1
  220. package/uis/stock/dist/assets/vi-ULKPnasj.js +0 -1
  221. package/uis/stock/dist/assets/zh-CN-tCvnOxWy.js +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"contracts-ku5ypHXJ.js","names":[],"sources":["../../src/shared/host-readings.ts","../../src/shared/contracts.ts"],"sourcesContent":["/**\n * The host's measurements, and the one place that decides a sample exists.\n *\n * `emptyHostView()` is what `HostMonitor` starts from, and it is also the frame a panel keeps for\n * ever when host vitals are switched off: `sampledAt: null`, with **every value zero** because the\n * wire type says `number`. `/api/metrics` refuses to publish those zeros — a scrape has no page to\n * qualify a number, so a `0` it invents silences the alert rule that exists to catch a full disk.\n * The panel's own pages read the same frame and printed it: `0.0%` memory, `0.0%` swap, `0.00`\n * load, under a head that says \"sampling off\". On a homelab box being told memory is at 0% is the\n * same lie as a dashboard being told it, told to the person instead.\n *\n * So `sampledAt === null` means \"nothing has been measured\" and every reading here is `null`.\n * The zeros stay on the wire: an older overridden UI under `.hh/.ui` reads `memoryUsedPercent` as a\n * `number` and calls `.toFixed()` on it, so a nullable field would crash it — the absence is decided\n * where it is rendered, once, instead.\n *\n * `cpus` and `uptimeMs` are **not** readings: they describe the machine, not a sample, and the\n * empty frame already reports them truthfully.\n *\n * `loadAlertPerCpu` is not a reading either: it is the threshold the panel *notifies* on, and it\n * travels with the frame so a surface can band the load against the number a person actually\n * chose. `AGENTS.md` names the rule — a verdict is measured against the configured threshold, and\n * one module decides it — after two surfaces hardcoded the default and kept calling a box a person\n * had raised the threshold on `danger`, for a notification that stayed silent.\n */\n\n/**\n * The load per cpu a panel notifies on when nothing else is configured.\n *\n * One home: `hostSchema` defaults to it, and a surface reading a frame from a panel that predates\n * the field bands its load against the same number the older panel alerted on.\n */\nexport const LOAD_ALERT_PER_CPU_DEFAULT = 2\n\n/**\n * The alert thresholds a percentage reading is banded against, when the frame carries none.\n *\n * One home, the same rule as `LOAD_ALERT_PER_CPU_DEFAULT`: `hostSchema` defaults to these, and a\n * surface reading a frame from a panel that predates the fields bands against the numbers that\n * panel alerted on.\n */\nexport const HOST_ALERT_DEFAULTS = { diskUsedPercent: 90, memoryUsedPercent: 90, swapUsedPercent: 50, tempCelsius: 85 } as const\n\n/** A configurable alert threshold, as it travels on the frame. */\nexport interface HostAlertThresholds {\n /** `host.diskUsedPercent` — the threshold the panel notifies on, `0` disabling it. */\n diskUsedPercentAlert?: number\n /** `host.memoryUsedPercent` — the threshold the panel notifies on, `0` disabling it. */\n memoryUsedPercentAlert?: number\n swapUsedPercentAlert?: number\n tempCelsiusAlert?: number\n}\n\n/** One configured filesystem, with the band its own usage is painted in. */\nexport interface HostDiskReading {\n path: string\n totalBytes: number\n freeBytes: number\n usedPercent: number\n /**\n * How urgent that filesystem's usage is, against `host.diskUsedPercent` — the threshold the panel\n * **notifies** on — else `null` when nothing was measured.\n *\n * It rides on the disk rather than beside the frame because the threshold is per-path usage and a\n * frame can carry several paths; a single `diskBand` next to `memoryBand` would answer for one of\n * them. The band was the last literal: `Gauge`/`Meter` defaulted to `75`/`90` and both\n * noc-console surfaces restated the same pair, which is `hostSchema`'s *default*, so lowering\n * `host.diskUsedPercent` to 80 made the panel notify at 82% while every surface called it `warn`.\n */\n band: HostBand\n}\n\n/** What the predicate needs: the sample's stamp and the numbers the frame carries. */\nexport interface HostReadingSource extends HostAlertThresholds {\n sampledAt: number | null\n cpus: number\n /** The alert thresholds from the panel's own config; absent on a panel that predates the fields. */\n loadAlertPerCpu?: number\n cpuUsedPercent?: number | null\n memoryUsedPercent: number\n swapUsedPercent: number\n loadAvg: number[]\n tempCelsius: number | null\n disks: Array<{ path: string, totalBytes: number, freeBytes: number, usedPercent: number }>\n}\n\n/** One host sample, with every measurement absent until the host has been sampled. */\nexport interface HostReadings {\n /** Whether the frame carries a sample at all. */\n sampled: boolean\n cpuUsedPercent: number | null\n memoryUsedPercent: number | null\n swapUsedPercent: number | null\n load1m: number | null\n load5m: number | null\n load15m: number | null\n /**\n * The 1-minute load as a share of one core. Load is a **count of runnable tasks**, so this is a\n * count per core, never a percentage — `1.00` is one core's worth of work.\n */\n loadPerCpu: number | null\n tempCelsius: number | null\n /** Each configured filesystem, carrying its own band. Empty when nothing was sampled. */\n disks: HostDiskReading[]\n /**\n * How urgent that per-cpu load is: `null` when nothing was measured (an absent reading has no\n * band of its own, or a zero would read as healthy), else the alert threshold it crossed.\n */\n loadBand: HostBand\n /**\n * The same verdict for the three percentage readings, each against the threshold the panel\n * **notifies** on — `null` when nothing was measured. A surface paints `thresholdBand`, never a\n * literal: the swap bar used to call 50% `warn` while the alert fired there, and a raised\n * `tempCelsius` left a box painted `danger` for a notification that never arrives.\n */\n memoryBand: HostBand\n swapBand: HostBand\n tempBand: HostBand\n}\n\n/** A reading's urgency, or `null` when there is no reading to judge. */\nexport type HostBand = 'ok' | 'warn' | 'danger' | null\n\nconst NOTHING_SAMPLED: HostReadings = {\n sampled: false,\n cpuUsedPercent: null,\n memoryUsedPercent: null,\n swapUsedPercent: null,\n load1m: null,\n load5m: null,\n load15m: null,\n loadPerCpu: null,\n tempCelsius: null,\n disks: [],\n loadBand: null,\n memoryBand: null,\n swapBand: null,\n tempBand: null,\n}\n\n/** A number the frame carries, or null when it carries none. */\nfunction present(value: number | null | undefined): number | null {\n return typeof value === 'number' && Number.isFinite(value) ? value : null\n}\n\n/**\n * How a per-cpu load sits against the threshold the panel notifies on.\n *\n * The ratio is what a person configures: `host.loadPerCpu` is the count the alert fires at, so\n * `danger` is that number itself and `warn` is the approach to it. `0` disables the alert in\n * `sampleHost`, so nothing can breach it and the band is `ok` — painting a box red for a\n * notification that will never arrive is the same defect as inventing a reading. It lives here\n * rather than in a component so both UIs share one band, the mistake that produced two hardcoded\n * copies of the default.\n */\nexport function loadBand(loadPerCpu: number | null, alertPerCpu: number | undefined): HostBand {\n return thresholdBand(loadPerCpu, alertPerCpu, LOAD_ALERT_PER_CPU_DEFAULT)\n}\n\n/**\n * The band for the host's own CPU share, which has no configurable alert.\n *\n * `host.cpuUsedPercent` is a share of the whole machine, and `hostSchema` has no threshold for it —\n * so there is nothing a person chose for a surface to follow, and a fixed band is a decision. The\n * decision is *this one*: the two UIs disagreed (noc-console painted 70/90, every stock dial 80/95),\n * so one 75% reading came back `warn` on one page and `ok` on the other — `AGENTS.md`'s \"UIs move\n * together\" broken by two literal pairs. A real alert would make this a `…Alert` field on the frame\n * like its neighbours; until then it is a constant here, not a pair at each call site.\n */\nexport const HOST_CPU_BAND = { warnAt: 80, dangerAt: 95 } as const\n\n/** The band for a host cpu share, against {@link HOST_CPU_BAND}. */\nexport function hostCpuBand(percent: number | null): HostBand {\n if (percent === null || !Number.isFinite(percent))\n return null\n // An explicit pair, not `thresholdBand`'s 70%-of-the-alert: these are two chosen numbers, and\n // deriving one from the other moved the warn line to 66.5 for a band written as 80/95.\n if (percent >= HOST_CPU_BAND.dangerAt)\n return 'danger'\n if (percent >= HOST_CPU_BAND.warnAt)\n return 'warn'\n return 'ok'\n}\n\n/**\n * How a reading sits against the threshold the panel notifies on.\n *\n * `danger` at the threshold is the whole point: the alert fires there, so a bar that stays `warn`\n * while a notification goes out disagrees with the panel's own verdict. `0` disables that alert in\n * `sampleHost`, so nothing can breach it and the band is `ok`. One rule for the per-cpu load, the\n * three percentages and each disk — they differ only in what the number means, and the mistake this\n * replaced was four surfaces each deciding a band for itself.\n */\nexport function percentageBand(value: number | null, alertAt: number | undefined, fallback: number): HostBand {\n return thresholdBand(value, alertAt, fallback)\n}\n\n/**\n * The full scale of a temperature dial: the threshold the panel **notifies** on.\n *\n * There is no natural `100 °C`, so unlike a percentage a temperature has no scale of its own —\n * the alert is the only number a person configured for it, and it is what the dial is drawn\n * against. `0` disables the alert and leaves no scale to draw, so the default the older panels\n * alerted on is kept rather than dividing by zero.\n *\n * This exists because the *band* was moved onto the frame and the *scale* was not: one stock\n * surface scaled by `tempCelsiusAlert` while the other kept `(tempCelsius / 85) * 100`, so one\n * frame at 60 °C against an alert of 95 drew arcs of `101.19` and `113.10` — the same number\n * fuller on one page than the other. A tone test cannot see that; only the arc can.\n */\nexport function tempScale(alertAt: number | undefined): number {\n return alertAt === undefined || !Number.isFinite(alertAt) || alertAt <= 0 ? HOST_ALERT_DEFAULTS.tempCelsius : alertAt\n}\n\n/**\n * How full a temperature dial is, as the percentage a `Gauge`/bar draws: a share of `tempScale`.\n *\n * `null` when nothing was measured — an absent reading has no dial, the same rule every other\n * reading on the frame follows.\n */\nexport function tempDialPercent(temp: number | null | undefined, alertAt: number | undefined): number | null {\n const value = present(temp)\n if (value === null)\n return null\n return (value / tempScale(alertAt)) * 100\n}\n\nfunction thresholdBand(value: number | null, alertAt: number | undefined, fallback: number): HostBand {\n if (value === null || !Number.isFinite(value))\n return null\n // An older panel sends no threshold, and it alerted on the default — so that is the band to draw.\n const threshold = alertAt === undefined || !Number.isFinite(alertAt) ? fallback : alertAt\n if (threshold <= 0)\n return 'ok'\n if (value >= threshold)\n return 'danger'\n if (value >= threshold * 0.7)\n return 'warn'\n return 'ok'\n}\n\n/** The readings of one host frame; a missing frame is the same as an unsampled one. */\nexport function hostReadings(host: HostReadingSource | null | undefined): HostReadings {\n if (host === null || host === undefined)\n return NOTHING_SAMPLED\n const sampled = host.sampledAt !== null\n if (!sampled)\n return { ...NOTHING_SAMPLED, disks: [] }\n // A truthy `sampledAt` is the only thing that makes a zero a reading: an honestly idle box\n // reports 0%, and that must survive as 0 rather than becoming an absence of its own.\n const load1m = present(host.loadAvg[0])\n const cpus = present(host.cpus)\n const loadPerCpu = load1m === null ? null : load1m / Math.max(1, cpus ?? 1)\n return {\n sampled: true,\n cpuUsedPercent: present(host.cpuUsedPercent),\n memoryUsedPercent: present(host.memoryUsedPercent),\n swapUsedPercent: present(host.swapUsedPercent),\n load1m,\n load5m: present(host.loadAvg[1]),\n load15m: present(host.loadAvg[2]),\n loadPerCpu,\n loadBand: loadBand(loadPerCpu, host.loadAlertPerCpu),\n memoryBand: percentageBand(present(host.memoryUsedPercent), host.memoryUsedPercentAlert, HOST_ALERT_DEFAULTS.memoryUsedPercent),\n swapBand: percentageBand(present(host.swapUsedPercent), host.swapUsedPercentAlert, HOST_ALERT_DEFAULTS.swapUsedPercent),\n tempBand: percentageBand(present(host.tempCelsius), host.tempCelsiusAlert, HOST_ALERT_DEFAULTS.tempCelsius),\n tempCelsius: present(host.tempCelsius),\n // Each disk is banded against the same configured alert, on its own usage.\n disks: host.disks.map(disk => ({\n ...disk,\n band: percentageBand(present(disk.usedPercent), host.diskUsedPercentAlert, HOST_ALERT_DEFAULTS.diskUsedPercent),\n })),\n }\n}\n","import { type } from 'arktype'\nimport { HOST_ALERT_DEFAULTS, LOAD_ALERT_PER_CPU_DEFAULT } from './host-readings'\n\n/**\n * Schemas shared by the control plane and the SPA: the server entry shape, the\n * control panel's own settings, API DTOs and SSE frames. Nothing here knows\n * about a particular server — an entry carries its own command, args, env and\n * bootstrap.\n */\n\n/** `local` -> 127.0.0.1, `lan` -> 0.0.0.0, or an explicit IPv4 to bind. */\nexport const bindSchema = type('\"local\" | \"lan\" | /^\\\\d{1,3}(?:\\\\.\\\\d{1,3}){3}$/')\nexport type Bind = typeof bindSchema.infer\n\n/**\n * A top-level unit: its own settings, servers, secrets, logs and nanny state\n * under `$HHOSTED_HOME/.hh/<id>/`. The id is the directory name and never\n * changes; the label is what a person reads and may rename at will.\n */\nexport const workspaceIdSchema = type('/^[a-z0-9][a-z0-9_-]*$/')\nexport const workspaceSchema = type({\n id: workspaceIdSchema,\n label: '1 <= string <= 60',\n}).onUndeclaredKey('reject')\nexport type Workspace = typeof workspaceSchema.infer\n\n/** `id` is optional; when omitted it is derived from the label. */\nexport const workspaceCreateSchema = type({\n 'id?': workspaceIdSchema,\n 'label?': '1 <= string <= 60',\n}).onUndeclaredKey('reject')\nexport type WorkspaceCreate = typeof workspaceCreateSchema.infer\n\nexport const workspaceRenameSchema = type({\n label: '1 <= string <= 60',\n}).onUndeclaredKey('reject')\n\n/** Parses a bind value (`local` | `lan` | ipv4); null when it is not one. */\nexport function parseBind(value: string): Bind | null {\n const parsed = bindSchema(value)\n return parsed instanceof type.errors ? null : parsed\n}\n\n/** `null` means \"no port\": no readiness probe, no health supervision, no preflight. */\nexport const portSchema = type('1 <= number.integer <= 65535 | null')\n\n/**\n * What to do when something already listens on the entry's port. `follow` and\n * `reclaim` only ever act on a holder proven to be this entry's own detached\n * successor (the `HHOSTED_SERVER_ID` marker, POSIX only); `kill` is the blunt one:\n * it stops any holder except the panel's own process tree.\n */\nexport const onPortConflictSchema = type.enumerated('block', 'warn', 'follow', 'reclaim', 'kill')\nexport type OnPortConflict = typeof onPortConflictSchema.infer\n\n/** The stored forms carry the default; a patch must not (see the patch schemas below). */\nexport const onPortConflictDefaultSchema = onPortConflictSchema.default('block')\n\nexport const restartSchema = type({\n enabled: 'boolean = true',\n maxRetries: 'number.integer >= 0 = 3',\n baseDelayMs: 'number >= 0 = 1000',\n factor: 'number >= 1 = 2',\n maxDelayMs: 'number >= 0 = 30000',\n /** A process alive this long is considered healthy again and the retry counter resets. */\n resetAfterMs: 'number >= 0 = 60000',\n}).onUndeclaredKey('reject')\n\nexport type RestartConfig = typeof restartSchema.infer\n\nexport const httpCheckSchema = type({\n /** `https` is for a backend that serves TLS itself; pair it with `allowInvalidCert` when it is self-signed. */\n scheme: '\"http\" | \"https\" = \"http\"',\n /** Accept any certificate. A self-signed pair is the normal case here, and the probe is local. */\n allowInvalidCert: 'boolean = false',\n /** Path on the server's own port, e.g. `/healthz`. */\n path: 'string = \"/\"',\n method: '\"GET\" | \"HEAD\" = \"GET\"',\n /** Exact status to accept; `null` (or omitted) means any status below `expectStatusBelow`. */\n expectStatus: 'number.integer | null?',\n expectStatusBelow: 'number.integer = 400',\n /** Substring that must appear in the response body. */\n expectBody: 'string = \"\"',\n}).onUndeclaredKey('reject')\nexport type HttpCheckConfig = typeof httpCheckSchema.infer\n\n/** Restart guards for the process tree. */\nexport const resourcesSchema = type({\n /** Restart when the tree's RSS exceeds this; 0 disables. */\n maxRssBytes: 'number.integer >= 0 = 0',\n}).onUndeclaredKey('reject')\n\nexport const healthSchema = type({\n enabled: 'boolean = true',\n /** `port` = TCP connect only; `http` = fetch `http.path` and assert the response. */\n mode: '\"port\" | \"http\" = \"port\"',\n http: httpCheckSchema.default(() => ({})),\n intervalMs: 'number >= 500 = 5000',\n timeoutMs: 'number >= 100 = 1500',\n /** Consecutive failed probes before the warning state is shown. */\n unhealthyThreshold: 'number.integer >= 1 = 3',\n /** 0 disables it; otherwise a port stuck unhealthy this long forces a restart. */\n forceRestartAfterMs: 'number >= 0 = 0',\n /** How long to wait for the port to accept connections after spawn. */\n startTimeoutMs: 'number >= 0 = 20000',\n}).onUndeclaredKey('reject')\n\nexport type HealthConfig = typeof healthSchema.infer\n\nexport const stopSchema = type({\n signal: '\"SIGTERM\" | \"SIGINT\" | \"SIGKILL\" = \"SIGTERM\"',\n killGroup: 'boolean = true',\n graceMs: 'number >= 0 = 5000',\n /** Last resort for wrappers that detach their real server. */\n killPortHolders: 'boolean = false',\n}).onUndeclaredKey('reject')\n\nexport type StopConfig = typeof stopSchema.infer\n\nexport const bootstrapSchema = type({\n command: 'string',\n args: type('string[]').default(() => []),\n env: type('Record<string, string>').default(() => ({})),\n timeoutMs: 'number >= 1000 = 120000',\n /** Run once per `up` session; whatever it installs persists on disk. */\n runOnce: 'boolean = true',\n}).onUndeclaredKey('reject')\nexport const bootstrapOrNullSchema = bootstrapSchema.or(type('null'))\n\n/**\n * The `bootstrap` group as a patch carries it: every field optional, and **no defaults**.\n *\n * A patch must not fill a default in (`AGENTS.md`), and it could not here for a second reason.\n * `bootstrap` is not in `SERVER_MERGE_KEYS`, so `applyPatch` **replaces** the whole group; the\n * defaults on `bootstrapSchema` used to arrive with the patch, so sending one changed field\n * wrote a group with the other four reset. Measured on `PATCH /api/servers/db` with\n * `{\"bootstrap\":{\"command\":\"next.sh\"}}`: stored `args: [\"--ci\"]` became `[]`, `runOnce: false`\n * became `true` — re-arming a one-shot bootstrap to run on every `up` — and `timeoutMs: 5000`\n * became `120000`. The group is still replaced, so a caller sends the fields it means to keep;\n * what changes is that the panel no longer invents the ones it did not send.\n */\nexport const bootstrapPatchSchema = type({\n command: 'string >= 1?',\n args: 'string[]?',\n env: 'Record<string, string>?',\n timeoutMs: 'number >= 1000?',\n runOnce: 'boolean?',\n}).onUndeclaredKey('reject')\nexport const bootstrapPatchOrNullSchema = bootstrapPatchSchema.or(type('null'))\n\n/**\n * A command run around a backup, for engines that need one to produce a consistent copy.\n *\n * `mongodump` is the reason this exists: copying `dbPath` while the server writes gives a torn copy,\n * and a dump taken by the engine is the only supported way. Same shape as `bootstrap` — one program\n * and its args, never a command line — and the same rule that the panel never guesses what an engine\n * needs.\n *\n * `{dumpDir}` is created before `dump` runs and captured by the archive; on restore the same\n * directory is filled again before `load` runs, so the two hooks see the same path.\n */\nexport const backupHookSchema = type({\n // Non-empty: an empty command is accepted by `spawn`'s type but fails at run time, and a `dump`\n // hook that cannot start refuses **every** backup — a config mistake that reads as a broken feature.\n command: 'string >= 1',\n args: type('string[]').default(() => []),\n env: type('Record<string, string>').default(() => ({})),\n timeoutMs: 'number >= 1000 = 600000',\n /**\n * How long to wait for the entry to answer before running a `load`.\n *\n * Only matters for `load`, and only for an entry with no `port`: the wait is normally \"the port\n * accepts a connection\", which an entry that declares no port cannot offer. Two seconds by\n * default, because a portless entry usually starts fast and a fixed wait is pure delay; a slow\n * database reached over a socket should raise it.\n */\n waitMs: 'number >= 0 = 2000',\n}).onUndeclaredKey('reject')\nexport const backupHookOrNullSchema = backupHookSchema.or(type('null'))\n\n/**\n * The `dump`/`load` group as a patch carries it: every field optional, and **no defaults**.\n *\n * The same defect `bootstrapPatchSchema` exists for, in the same `editableFields`: both hooks are\n * replaced rather than merged, so the group's defaults used to arrive with a one-field edit and\n * reset `args`, `env`, `timeoutMs` and `waitMs` to values nobody sent. `waitMs` is the one that\n * bites hardest — a `load` waiting on a slow database would silently drop back to 2 s.\n */\nexport const backupHookPatchSchema = type({\n command: 'string >= 1?',\n args: 'string[]?',\n env: 'Record<string, string>?',\n timeoutMs: 'number >= 1000?',\n waitMs: 'number >= 0?',\n}).onUndeclaredKey('reject')\nexport const backupHookPatchOrNullSchema = backupHookPatchSchema.or(type('null'))\n\nexport type BackupHookConfig = typeof backupHookSchema.infer\n\n/**\n * A label that may be written as `null`, which means \"no label\" — the same spelling `port` and\n * `bootstrap` already accept in a file.\n *\n * `serverSchema.label` was `'string?'`, so a hand-edited `\"label\": null` refused the **whole config** with\n * `servers[0] (\"web\"): label must be a string (was null)`. The write side already tolerates `null`, and every\n * display falls back with `label ?? id` — which `null` satisfies and `''` does not.\n */\nexport const labelOrNullSchema = type('string | null')\n\nexport const logBufferLinesSchema = type('50 <= number.integer <= 100000')\n\nexport const serverSchema = type({\n id: '/^[a-z0-9][a-z0-9_-]*$/',\n label: labelOrNullSchema.optional(),\n enabled: 'boolean = true',\n autostart: 'boolean = false',\n /**\n * Handed to a nanny process that owns the pipes, so the entry keeps running when\n * this panel stops, restarts or is killed. `down`/`stop-all` leave it alone and\n * report it; only an explicit stop or restart stops it.\n */\n persistent: 'boolean = false',\n command: 'string >= 1',\n args: type('string[]').default(() => []),\n cwd: 'string = \".\"',\n env: type('Record<string, string>').default(() => ({})),\n /**\n * `ENV=path` pairs: exported to the process (overriding `env`) *and* the path\n * is backed up automatically — one declaration for data directories.\n */\n dataEnvs: type('Record<string, string>').default(() => ({})),\n bootstrap: bootstrapOrNullSchema.optional(),\n /**\n * Run before this entry's data is captured, writing into `{dumpDir}`.\n *\n * For a database: `mongodump --archive={dumpDir}/db.archive`. A failed dump **refuses the backup**\n * rather than archiving a stale directory next to it — the whole point is that the dump is the\n * authoritative copy.\n */\n dump: backupHookOrNullSchema.optional(),\n /** Run after this entry's data is restored, reading from `{dumpDir}`. Its server is stopped first. */\n load: backupHookOrNullSchema.optional(),\n port: portSchema.optional(),\n bind: bindSchema.default(() => 'local' as const),\n onPortConflict: onPortConflictDefaultSchema,\n restart: restartSchema.default(() => ({})),\n health: healthSchema.default(() => ({})),\n stop: stopSchema.default(() => ({})),\n logBufferLines: logBufferLinesSchema.default(() => 500),\n /** Ids this server needs running first (and healthy); `stop-all` stops dependents before it. */\n dependsOn: type('string[]').default(() => []),\n /** Optional KEY=value file loaded at spawn; its values override `env`. */\n envFile: 'string = \"\"',\n resources: resourcesSchema.default(() => ({})),\n /** Paths included in backups for this server (templates allowed). */\n backupPaths: type('string[]').default(() => []),\n /**\n * Skip well-known build output and dependency directories (`node_modules`,\n * `dist`, `.next`, caches, …) inside the paths this entry declares.\n */\n backupIgnoreGenerated: 'boolean = true',\n}).onUndeclaredKey('reject')\nexport type ServerConfig = Omit<typeof serverSchema.infer, 'port'> & { port: number | null }\n\n/**\n * Authentication for the control panel itself. The password never lives here —\n * only the policy does; its scrypt hash sits in a git-ignored secrets file.\n */\nexport const authSchema = type({\n enabled: 'boolean = true',\n /** Idle timeout: a session dies this long after its **last** request, not after login. */\n sessionTtlMs: 'number >= 60000 = 604800000',\n /** `auto` adds `Secure` when the request arrived over https (proxy-aware). */\n cookieSecure: '\"auto\" | \"always\" | \"never\" = \"auto\"',\n /** Trust `x-forwarded-*` from a reverse proxy; also drives the client IP. */\n trustProxy: 'boolean | \"loopback\" = \"loopback\"',\n maxLoginAttempts: 'number.integer >= 1 = 5',\n lockoutMs: 'number >= 1000 = 60000',\n}).onUndeclaredKey('reject')\nexport type AuthConfig = typeof authSchema.infer\n\n/**\n * The event toggles and the throttle — the part a target may **inherit** instead of setting.\n *\n * `enabled` is deliberately not here: \"send to this one\" is a property of the target, never\n * something to inherit. Everything else answers the same question for every transport, and one\n * definition means a fourth cannot quietly spell `onRecovered` differently.\n */\nconst notificationPolicyShape = {\n onCrash: 'boolean = true',\n onUnhealthy: 'boolean = true',\n onForcedRestart: 'boolean = true',\n onRecovered: 'boolean = false',\n /** Host vitals breaches (disk, memory, swap, load, temperature). */\n onHost: 'boolean = true',\n /** Dynamic DNS changes and failures. */\n onDdns: 'boolean = true',\n /** Per server *and* reason, so a flapping server cannot spam the chat. */\n cooldownMs: 'number >= 0 = 120000',\n} as const\n\n/**\n * The general settings: what applies to every target that does not override it.\n *\n * The point of the block is that the common case — \"tell me about crashes and host thresholds,\n * throttled every two minutes\" — is set **once**, instead of once per transport and again per\n * destination.\n */\nexport const notificationDefaultsSchema = type({\n ...notificationPolicyShape,\n}).onUndeclaredKey('reject')\nexport type NotificationDefaults = typeof notificationDefaultsSchema.infer\n\n/**\n * The same block **as a response**: tolerant of a key this release does not know.\n *\n * A request schema rejects undeclared keys, a response schema must not — an upgrade writes a new UI\n * while an old panel keeps serving, and a newer panel adding one field here must not blank this\n * build's whole app. Reusing the strict schema in the view did exactly that: one additive key in\n * `defaults` rejected the state frame and the page went blank.\n */\nexport const notificationDefaultsViewSchema = type({\n ...notificationPolicyShape,\n})\n\n/**\n * Whether a target follows the general block or carries its own.\n *\n * **Defaults to `true`**, which is what an existing config means: before this block existed every\n * target carried its own toggles, and reading one as \"inherit\" would silently change which events\n * it delivers on upgrade. A target the page creates opts *in* to inheritance explicitly, so the\n * new default applies to new targets without rewriting anybody's config.\n */\nconst useOwnSettingsSchema = 'boolean = true'\n\n/**\n * One Telegram destination.\n *\n * `chatId` is config; the bot token is a **secret**, keyed by this target's `id` in the workspace's\n * `.secrets.json`. More than one is allowed, which is why the token cannot be a singleton any more.\n */\nconst telegramDestinationSchema = type({\n kind: '\"telegram\"',\n id: '/^[a-z0-9][a-z0-9_-]*$/',\n /** Off until configured: a bare `enabled: true` with no chat would fail every send. */\n enabled: 'boolean = false',\n chatId: 'string = \"\"',\n useOwnSettings: useOwnSettingsSchema,\n ...notificationPolicyShape,\n // Rejects any other key, which is what keeps a `botToken` out of a config file: without this the\n // schema tolerated it, so a hand-edited settings.json loaded a plaintext secret with no warning.\n}).onUndeclaredKey('reject')\n\n/**\n * One webhook target: a URL, a method, and the headers to send with it.\n *\n * This is the general transport, and it is a *list* because a home panel alerts more than one\n * place — a phone, a chat channel, a dashboard. The headers are what make it general rather\n * than JSON-only: ntfy wants `Title`/`Priority` headers with a plain-text body, a bearer-token\n * receiver wants `Authorization`, and a JSON receiver wants `content-type`. One shape covers\n * all three; a per-service adapter would be a code change per service.\n */\n/** One webhook destination. */\nexport const webhookTargetSchema = type({\n kind: '\"webhook\"',\n id: '/^[a-z0-9][a-z0-9_-]*$/',\n /** Empty only while the target is a draft; the page will not save one without it. */\n url: 'string = \"\"',\n enabled: 'boolean = true',\n method: '\"POST\" | \"PUT\" = \"POST\"',\n /** Payload format: `json` sends the event as JSON, `text` sends the plain message. */\n format: '\"json\" | \"text\" = \"json\"',\n /**\n * Extra headers, `Name: value` per line. The one field that lets this transport talk to\n * ntfy (`Title`, `Priority`), a bearer-token endpoint (`Authorization`) or anything else\n * with a header-shaped contract.\n */\n headers: 'string = \"\"',\n useOwnSettings: useOwnSettingsSchema,\n ...notificationPolicyShape,\n}).onUndeclaredKey('reject')\nexport type WebhookTarget = typeof webhookTargetSchema.infer\n\n/** A destination is one of the kinds this build can deliver to. */\nexport const notificationTargetSchema = telegramDestinationSchema.or(webhookTargetSchema)\nexport type NotificationTarget = typeof notificationTargetSchema.infer\n\n/**\n * The destination list.\n *\n * `id` is the list key — the cooldown, the last-result record and a Telegram target's token are all\n * keyed by it — so it must be unique across kinds, not just within one. Enforced by\n * `duplicateWebhookIds` at the write; a schema `narrow` cannot be rendered to JSON Schema and every\n * route's `toJsonSchema()` would throw.\n */\nconst destinationListSchema = notificationTargetSchema.array()\n\nexport const notificationsSchema = type({\n /** What every destination inherits unless it carries its own settings. */\n defaults: notificationDefaultsSchema.default(() => ({})),\n /** Replaced by a patch, the same way `ddns.accounts` is: a merge cannot express removing one. */\n destinations: destinationListSchema.default(() => []),\n}).onUndeclaredKey('reject')\n\n/**\n * The ids that appear more than once, so a write can refuse them.\n *\n * A schema-level check is not available here (see above), and this is the one shape that has to\n * be told apart from a plain validation error: the list is valid, but its identity is not.\n */\nexport function duplicateWebhookIds(targets: ReadonlyArray<{ id: string }>): string[] {\n const seen = new Set<string>()\n const duplicates = new Set<string>()\n for (const target of targets) {\n if (seen.has(target.id))\n duplicates.add(target.id)\n seen.add(target.id)\n }\n return [...duplicates]\n}\nexport type NotificationsConfig = typeof notificationsSchema.infer\n\n/** On-disk log retention for the Logs page. */\nexport const logsSchema = type({\n persist: 'boolean = true',\n /** Per server, before rotating to `.1`, `.2`, ... */\n maxBytes: '10000 <= number <= 100000000 = 2000000',\n keep: '1 <= number.integer <= 10 = 3',\n}).onUndeclaredKey('reject')\nexport type LogsConfig = typeof logsSchema.infer\n\nexport const tlsSchema = type({\n enabled: 'boolean = false',\n}).onUndeclaredKey('reject')\n\n/** Host-level vitals and their alert thresholds. */\nexport const hostSchema = type({\n enabled: 'boolean = true',\n intervalMs: 'number >= 5000 = 15000',\n /** Filesystems reported and alerted on; templates and `~` are expanded. */\n diskPaths: type('string[]').default(() => ['.']),\n /**\n * 0 disables an individual alert. Each default is written from `HOST_ALERT_DEFAULTS`, so the\n * number a fresh config gets and the number a surface bands against when a frame carries no\n * threshold are one value — the same one-home rule `loadPerCpu` follows below.\n */\n diskUsedPercent: `number >= 0 = ${HOST_ALERT_DEFAULTS.diskUsedPercent}`,\n memoryUsedPercent: `number >= 0 = ${HOST_ALERT_DEFAULTS.memoryUsedPercent}`,\n swapUsedPercent: `number >= 0 = ${HOST_ALERT_DEFAULTS.swapUsedPercent}`,\n /**\n * The per-cpu load the panel notifies on. One home: the frame's `loadAlertPerCpu` is this value,\n * and `loadBand` reads it, so a surface cannot band the load against a number nobody configured.\n */\n loadPerCpu: type('number >= 0').default(LOAD_ALERT_PER_CPU_DEFAULT),\n tempCelsius: `number >= 0 = ${HOST_ALERT_DEFAULTS.tempCelsius}`,\n /**\n * How to read the CPU temperature when the kernel exposes no sensor.\n *\n * A command whose stdout is a number in °C — the escape hatch for a machine this panel cannot read\n * for itself (a WSL2 guest, a VM, a board whose hwmon chip is unsupported). Empty means \"use the\n * built-in probe\". It runs on the sampling interval, so it must be cheap; `docs/SERVERS.md` carries\n * the WSL2 setup.\n */\n tempCommand: 'string <= 512 = \"\"',\n /** How long that command may run before it is killed, so a hung helper cannot stall a sample. */\n tempCommandTimeoutMs: '100 <= number <= 30000 = 5000',\n}).onUndeclaredKey('reject')\nexport type HostConfig = typeof hostSchema.infer\n\n/** A record family the DDNS engine can point at this host. */\nexport const ddnsRecordTypeSchema = type.enumerated('A', 'AAAA')\nexport type DdnsRecordType = typeof ddnsRecordTypeSchema.infer\n\n/**\n * One DNS provider account. Its credentials are secrets and live in the secrets\n * file keyed by this `id`, never in the config.\n */\nexport const ddnsAccountSchema = type({\n id: '/^[a-z0-9][a-z0-9_-]*$/',\n provider: 'string >= 1',\n label: 'string = \"\"',\n}).onUndeclaredKey('reject')\nexport type DdnsAccount = typeof ddnsAccountSchema.infer\n\n/**\n * A hostname to keep pointed at this machine. That list is the whole user-facing\n * setup: the provider account it belongs to, and (optionally) which families.\n */\nexport const ddnsDomainSchema = type({\n host: '/^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/',\n account: 'string >= 1',\n /** Records to keep current; `A` unless the host needs IPv6 too. */\n types: ddnsRecordTypeSchema.array().default(() => ['A' as const]),\n /**\n * The registered domain (apex) this host sits in. Only needed where a\n * provider cannot look it up and the guess is wrong (three-label suffixes).\n */\n zone: 'string?',\n /** Seconds; `1` means \"automatic\" where the provider supports it. */\n ttl: 'number.integer >= 1?',\n /** Proxying is a property of the record, not the panel: Cloudflare only. */\n proxied: 'boolean = false',\n enabled: 'boolean = true',\n}).onUndeclaredKey('reject')\nexport type DdnsDomain = typeof ddnsDomainSchema.infer\n\n/** Which public IP families to detect; a provider is only called for the ones declared. */\nexport const ddnsIpv4Schema = type({\n enabled: 'boolean = true',\n /** Override the public-IP endpoint; empty uses the built-in list. */\n url: 'string = \"\"',\n}).onUndeclaredKey('reject')\n\nexport const ddnsIpv6Schema = type({\n enabled: 'boolean = false',\n url: 'string = \"\"',\n}).onUndeclaredKey('reject')\n\n/**\n * Dynamic DNS: keep a list of hostnames pointed at this machine's public IP.\n * Probing is cheap and constant; a provider is only called when the address it\n * last confirmed differs, which is what keeps simple endpoints (FreeDNS, No-IP)\n * inside their rate limits.\n */\nexport const ddnsConfigSchema = type({\n enabled: 'boolean = false',\n /** How often the public address is re-checked. */\n intervalMs: 'number >= 60000 = 300000',\n ipv4: ddnsIpv4Schema.default(() => ({})),\n ipv6: ddnsIpv6Schema.default(() => ({})),\n /** Default TTL for the records that accept one. */\n ttl: 'number.integer >= 1 = 1',\n accounts: ddnsAccountSchema.array().default(() => []),\n domains: ddnsDomainSchema.array().default(() => []),\n}).onUndeclaredKey('reject')\nexport type DdnsConfig = typeof ddnsConfigSchema.infer\n\nexport const ddnsRecordStateSchema = type('\"pending\" | \"ok\" | \"unchanged\" | \"error\" | \"skipped\"')\nexport type DdnsRecordState = typeof ddnsRecordStateSchema.infer\n\n/** What happened to one hostname on the last pass. */\nexport const ddnsRecordViewSchema = type({\n 'host': 'string',\n 'account': 'string',\n 'provider': 'string',\n 'type': ddnsRecordTypeSchema,\n 'ip': 'string | null',\n 'state': ddnsRecordStateSchema,\n 'message': 'string | null',\n 'updatedAt': 'number | null',\n /** The provider refused permanently; no retry until the hostname, account or credentials change, or a check. */\n 'stopped?': 'boolean',\n})\nexport type DdnsRecordView = typeof ddnsRecordViewSchema.infer\n\n/** Live DDNS state, as the state frame and the settings page read it. */\nexport const ddnsStatusSchema = type({\n enabled: 'boolean',\n running: 'boolean',\n lastRunAt: 'number | null',\n lastResult: 'string | null',\n ipv4: 'string | null',\n ipv6: 'string | null',\n records: ddnsRecordViewSchema.array(),\n})\nexport type DdnsStatus = typeof ddnsStatusSchema.infer\n\n/** What a provider needs from the person configuring it. */\nexport const ddnsProviderFieldSchema = type({\n key: 'string',\n label: 'string',\n hint: 'string = \"\"',\n optional: 'boolean = false',\n})\nexport type DdnsProviderField = typeof ddnsProviderFieldSchema.infer\n\n/** Provider capabilities, so the UI knows which options to show. */\nexport const ddnsProviderInfoSchema = type({\n id: 'string',\n label: 'string',\n docsUrl: 'string',\n families: ddnsRecordTypeSchema.array(),\n fields: ddnsProviderFieldSchema.array(),\n ttl: 'boolean',\n proxied: 'boolean',\n /** These credentials can also answer an ACME DNS-01 challenge (a TXT record). */\n txt: 'boolean',\n})\nexport type DdnsProviderInfo = typeof ddnsProviderInfoSchema.infer\n\n/** `GET /api/ddns`: the policy, the live state, and the providers this build knows. */\nexport const ddnsViewSchema = type({\n config: ddnsConfigSchema,\n status: ddnsStatusSchema,\n providers: ddnsProviderInfoSchema.array(),\n /** Account ids whose credentials are stored. */\n credentials: type('string[]'),\n}).onDeepUndeclaredKey('ignore')\nexport type DdnsView = typeof ddnsViewSchema.infer\n\n/**\n * `PUT /api/ddns/credentials/:id`: the secret fields that provider declares.\n *\n * The provider travels with the request because the account may still be an\n * unsaved draft — the server needs its field list, not a config entry.\n */\nexport const ddnsCredentialsSchema = type({\n provider: 'string >= 1',\n credentials: type('Record<string, string>'),\n}).onUndeclaredKey('reject')\n\n/**\n * The DDNS block as a patch: no defaults, and `accounts`/`domains` are lists a\n * patch **replaces** — a key-by-key merge cannot express removing a hostname.\n * `ipv4`/`ipv6` still merge, so a patch may decide just one of their members.\n */\nexport const ddnsPatchSchema = type({\n enabled: 'boolean?',\n intervalMs: 'number >= 60000?',\n ipv4: type({ enabled: 'boolean?', url: 'string?' }).onUndeclaredKey('reject').optional(),\n ipv6: type({ enabled: 'boolean?', url: 'string?' }).onUndeclaredKey('reject').optional(),\n ttl: 'number.integer >= 1?',\n accounts: ddnsAccountSchema.array().optional(),\n domains: ddnsDomainSchema.array().optional(),\n}).onUndeclaredKey('reject')\nexport type DdnsPatch = typeof ddnsPatchSchema.infer\n\n/** Tar archives of config, secrets, TLS and declared data paths. */\n/**\n * What an automatic backup captures, in the vocabulary the manual dialog and the CLI already use.\n *\n * `only` is `--include`, `except` is `--all --exclude`, and both name the same ids: a coarse id\n * (`workspace:default`) covers every leaf under it. Omitted means the full default scope, which is\n * what a schedule written before this field existed must keep meaning.\n *\n * An empty `ids` is refused rather than read as either \"nothing\" or \"everything\": those are the two\n * readings a person cannot tell apart from the file, and one of them captures nothing at all.\n */\nexport const backupScopeSchema = type({\n mode: '\"only\" | \"except\"',\n ids: type('string >= 1').array().atLeastLength(1),\n}).onUndeclaredKey('reject')\nexport type BackupScope = typeof backupScopeSchema.infer\n\n/** The scheduled half: an interval, a retention of its own, and what it captures. */\nexport const backupScheduleSchema = type({\n /** 0 turns the schedule off; otherwise the gap between automatic archives. */\n intervalMs: 'number.integer >= 0 = 0',\n /** How many automatic archives to keep. Manual ones are never pruned by it. */\n keep: 'number.integer >= 1 = 7',\n /**\n * Absent means the whole default scope — every workspace and `includePaths`. Deliberately not\n * defaulted to an explicit value: a reader cannot tell an untouched file from one that chose\n * \"everything\", and a default here would rewrite every existing schedule on its first save.\n */\n scope: backupScopeSchema.optional(),\n}).onUndeclaredKey('reject')\nexport type BackupScheduleConfig = typeof backupScheduleSchema.infer\n\nexport const backupsSchema = type({\n enabled: 'boolean = true',\n dir: 'string = \".backups\"',\n /** How many archives to keep in total, newest first. */\n keep: 'number.integer >= 1 = 5',\n /** Extra paths in every backup, in addition to each server's `backupPaths`. */\n includePaths: type('string[]').default(() => []),\n schedule: backupScheduleSchema.default(() => ({})),\n}).onUndeclaredKey('reject')\nexport type BackupsConfig = typeof backupsSchema.infer\n\nconst allowedHostsSchema = type(/^(?:\\*\\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i).array().atMostLength(64)\n\nexport const controlSchema = type({\n /** What the panel calls itself; the stock UI shows it in the sidebar. */\n label: '1 <= string <= 60 = \"home-hosted\"',\n port: '1 <= number.integer <= 65535 = 3999',\n /** Where the control panel itself listens; keep it `local` unless you mean it. */\n host: bindSchema.default(() => 'local' as const),\n openBrowser: 'boolean = false',\n /**\n * Public hostnames the panel answers to, besides IPs, local names and its own proxy routes —\n * a name an external reverse proxy or tunnel forwards. `*.example.com` matches subdomains.\n */\n allowedHosts: allowedHostsSchema.default(() => []),\n auth: authSchema.default(() => ({})),\n tls: tlsSchema.default(() => ({})),\n}).onUndeclaredKey('reject')\nexport type ControlConfig = typeof controlSchema.infer\n\n/** Applied to every server entry; whatever an entry sets wins. */\nexport const defaultsSchema = type({\n enabled: 'boolean = true',\n autostart: 'boolean = false',\n bind: bindSchema.default(() => 'local' as const),\n onPortConflict: onPortConflictDefaultSchema,\n restart: restartSchema.default(() => ({})),\n health: healthSchema.default(() => ({})),\n stop: stopSchema.default(() => ({})),\n logBufferLines: logBufferLinesSchema.default(() => 500),\n}).onUndeclaredKey('reject')\nexport type ServerDefaults = typeof defaultsSchema.infer\n\n// Patch variants stay default-free: an API client sends only what it changes, so\n// a partial nested group must not silently pull in the code defaults.\nconst restartPatchSchema = type({\n enabled: 'boolean?',\n maxRetries: 'number.integer >= 0?',\n baseDelayMs: 'number >= 0?',\n factor: 'number >= 1?',\n maxDelayMs: 'number >= 0?',\n resetAfterMs: 'number >= 0?',\n}).onUndeclaredKey('reject')\n\nconst httpCheckPatchSchema = type({\n scheme: '\"http\" | \"https\"?',\n allowInvalidCert: 'boolean?',\n path: 'string?',\n method: '\"GET\" | \"HEAD\"?',\n expectStatus: 'number.integer | null?',\n expectStatusBelow: 'number.integer?',\n expectBody: 'string?',\n}).onUndeclaredKey('reject')\n\nconst resourcesPatchSchema = type({\n maxRssBytes: 'number.integer >= 0?',\n}).onUndeclaredKey('reject')\n\nconst healthPatchSchema = type({\n enabled: 'boolean?',\n mode: '\"port\" | \"http\"?',\n http: httpCheckPatchSchema.optional(),\n intervalMs: 'number >= 500?',\n timeoutMs: 'number >= 100?',\n unhealthyThreshold: 'number.integer >= 1?',\n forceRestartAfterMs: 'number >= 0?',\n startTimeoutMs: 'number >= 0?',\n}).onUndeclaredKey('reject')\n\nconst stopPatchSchema = type({\n signal: '\"SIGTERM\" | \"SIGINT\" | \"SIGKILL\"?',\n killGroup: 'boolean?',\n graceMs: 'number >= 0?',\n killPortHolders: 'boolean?',\n}).onUndeclaredKey('reject')\n\nconst authPatchSchema = type({\n enabled: 'boolean?',\n sessionTtlMs: 'number >= 60000?',\n cookieSecure: '\"auto\" | \"always\" | \"never\"?',\n trustProxy: 'boolean | \"loopback\"?',\n maxLoginAttempts: 'number.integer >= 1?',\n lockoutMs: 'number >= 1000?',\n}).onUndeclaredKey('reject')\n\nconst notificationPolicyPatchShape = {\n onCrash: 'boolean?',\n onUnhealthy: 'boolean?',\n onForcedRestart: 'boolean?',\n onRecovered: 'boolean?',\n onHost: 'boolean?',\n onDdns: 'boolean?',\n cooldownMs: 'number >= 0?',\n} as const\n\n/**\n * The patch shape for one destination.\n *\n * `kind` is required: a patch cannot change a destination's kind (that would silently drop its\n * credential), so it names the kind it is addressing. The list is **replaced**, not merged — a merge\n * cannot express removing a destination, the same reason `ddns.accounts` is replaced.\n */\nconst destinationPatchSchema = type({\n kind: '\"telegram\" | \"webhook\"',\n id: '/^[a-z0-9][a-z0-9_-]*$/',\n enabled: 'boolean?',\n useOwnSettings: 'boolean?',\n /** Telegram only. */\n chatId: 'string?',\n /** Webhook only. */\n url: 'string?',\n method: '\"POST\" | \"PUT\"?',\n format: '\"json\" | \"text\"?',\n headers: 'string?',\n ...notificationPolicyPatchShape,\n}).onUndeclaredKey('reject')\n\nconst notificationsPatchSchema = type({\n /** Merged key by key, like the other nested groups. */\n /**\n * A merge key-by-key, and **every field optional** — `notificationPolicyPatchShape`, not a\n * `.partial()` of the defaults schema.\n *\n * ArkType's `.partial()` leaves a field's `= false` / `= 120000` default in place, so a body of\n * `{ onHost: false }` validated into all seven keys and one toggle overwrote the rest. A patch\n * schema here carries no defaults (the rule for every patch), and the store merges it over the\n * stored block.\n */\n defaults: type({ ...notificationPolicyPatchShape }).onUndeclaredKey('reject').optional(),\n /** Replaced whole, so a removed destination stays removed. */\n destinations: destinationPatchSchema.array().optional(),\n}).onUndeclaredKey('reject')\n\nconst hostPatchSchema = type({\n enabled: 'boolean?',\n intervalMs: 'number >= 5000?',\n diskPaths: type('string[]').optional(),\n diskUsedPercent: 'number >= 0?',\n memoryUsedPercent: 'number >= 0?',\n swapUsedPercent: 'number >= 0?',\n loadPerCpu: 'number >= 0?',\n tempCelsius: 'number >= 0?',\n tempCommand: 'string <= 512?',\n tempCommandTimeoutMs: '100 <= number <= 30000?',\n}).onUndeclaredKey('reject')\n\nconst backupSchedulePatchSchema = type({\n intervalMs: 'number.integer >= 0?',\n keep: 'number.integer >= 1?',\n /**\n * No defaults, like every patch: `null` clears it back to the full default scope, which is the\n * only way to spell \"forget the choice I made\" — an omitted key means \"leave it as it is\".\n */\n scope: backupScopeSchema.or(type('null')).optional(),\n}).onUndeclaredKey('reject')\n\nconst backupsPatchSchema = type({\n enabled: 'boolean?',\n dir: 'string?',\n keep: 'number.integer >= 1?',\n includePaths: type('string[]').optional(),\n schedule: backupSchedulePatchSchema.optional(),\n}).onUndeclaredKey('reject')\n\nconst logsPatchSchema = type({\n persist: 'boolean?',\n maxBytes: '10000 <= number <= 100000000?',\n keep: '1 <= number.integer <= 10?',\n}).onUndeclaredKey('reject')\n\nconst tlsPatchSchema = type({\n enabled: 'boolean?',\n}).onUndeclaredKey('reject')\n\nconst controlPatchSchema = type({\n label: '1 <= string <= 60 | null?',\n port: '1 <= number.integer <= 65535?',\n host: bindSchema.optional(),\n openBrowser: 'boolean?',\n allowedHosts: allowedHostsSchema.optional(),\n auth: authPatchSchema.optional(),\n tls: tlsPatchSchema.optional(),\n}).onUndeclaredKey('reject')\n\nconst defaultsPatchSchema = type({\n enabled: 'boolean?',\n autostart: 'boolean?',\n bind: bindSchema.optional(),\n onPortConflict: onPortConflictSchema.optional(),\n restart: restartPatchSchema.optional(),\n health: healthPatchSchema.optional(),\n stop: stopPatchSchema.optional(),\n logBufferLines: logBufferLinesSchema.optional(),\n}).onUndeclaredKey('reject')\n\nconst editableFields = {\n /**\n * `null` clears it, the same spelling `serverSchema` accepts and every display's `label ?? id`\n * fallback needs — an empty string satisfies neither. `serverPatchSchema` is what the editor\n * validates its payload against and what `PATCH /api/servers/:id` checks, so without this a\n * cleared Label was refused with \"label must be a string (was null)\" and could not be saved at all\n * (`1f58a5d` fixed `applyPatch` and the *control* patch schema, and cited that one in its message).\n */\n label: labelOrNullSchema.optional(),\n enabled: 'boolean?',\n autostart: 'boolean?',\n persistent: 'boolean?',\n command: 'string?',\n args: 'string[]?',\n cwd: 'string?',\n env: 'Record<string, string>?',\n dataEnvs: 'Record<string, string>?',\n bootstrap: bootstrapPatchOrNullSchema.optional(),\n dump: backupHookPatchOrNullSchema.optional(),\n load: backupHookPatchOrNullSchema.optional(),\n port: portSchema.optional(),\n bind: bindSchema.optional(),\n onPortConflict: onPortConflictSchema.optional(),\n restart: restartPatchSchema.optional(),\n health: healthPatchSchema.optional(),\n stop: stopPatchSchema.optional(),\n logBufferLines: logBufferLinesSchema.optional(),\n dependsOn: type('string[]').optional(),\n envFile: 'string?',\n resources: resourcesPatchSchema.optional(),\n backupPaths: type('string[]').optional(),\n backupIgnoreGenerated: 'boolean?',\n} as const\n\nexport const serverPatchSchema = type(editableFields).onUndeclaredKey('reject')\nexport type ServerPatch = typeof serverPatchSchema.infer\n\nexport const serverCreateSchema = type({\n id: '/^[a-z0-9][a-z0-9_-]*$/',\n ...editableFields,\n command: 'string',\n}).onUndeclaredKey('reject')\nexport type ServerCreate = typeof serverCreateSchema.infer\n\n/**\n * What the panel hands a persistent entry's nanny, written 0600 and unlinked by the\n * nanny as it reads it. Everything is already resolved and expanded, because\n * `Supervisor.resolveSpawn()` must stay the only resolver.\n */\nexport const nannySpecSchema = type({\n serverId: 'string',\n command: 'string',\n args: 'string[]',\n cwd: 'string',\n env: 'Record<string, string>',\n /** Directory of the JSONL the nanny writes; `<dir>/<id>.log`, exactly as the panel names it. */\n logDir: 'string',\n /** The same retention the panel applies, so the nanny rotates identically. */\n logs: logsSchema,\n /** How the nanny stops the child it owns. */\n stop: stopSchema,\n}).onUndeclaredKey('reject')\nexport type NannySpec = typeof nannySpecSchema.infer\n\n/** How the child of a nanny ended, recorded for a panel that may not have been there. */\nexport const nannyExitSchema = type({\n code: 'number | null',\n signal: 'string | null',\n at: 'number',\n runtimeMs: 'number',\n}).onUndeclaredKey('reject')\nexport type NannyExit = typeof nannyExitSchema.infer\n\n/**\n * A persistent entry's process state, written by its nanny (heartbeat included) and\n * read by the panel to re-adopt a survivor and to learn how a child it never saw\n * exit actually ended.\n */\nexport const nannyStateSchema = type({\n 'serverId': 'string',\n 'nannyPid': 'number',\n 'childPid': 'number | null',\n 'startedAt': 'number',\n 'logFile': 'string',\n 'heartbeatAt': 'number',\n 'lastExit?': nannyExitSchema,\n}).onUndeclaredKey('reject')\nexport type NannyState = typeof nannyStateSchema.infer\n\n/**\n * The part of an entry's supervision the panel must remember across its own restarts.\n *\n * In memory alone, a crash loop was handed a fresh `maxRetries` by every panel start\n * (`restarts` counted \"since the control plane started\"), and a `runOnce` bootstrap\n * re-ran for the same reason. Both are decisions whose whole point is to outlast the\n * process that made them.\n */\nexport const entryStateSchema = type({\n /** Attempts spent on the current crash sequence; reset once the process stays up. */\n 'restarts': 'number.integer >= 0',\n /**\n * Force restarts spent on the current unhealthy sequence.\n *\n * Separate from `restarts` because the two are different failures — a process that keeps dying\n * and a process that stays up but cannot serve. Persisted for the same reason the crash counter\n * is: a budget that lives only in memory is handed back fresh by every panel restart, so a\n * health-storm that is restarted often enough never exhausts it.\n */\n 'healthRestarts?': 'number.integer >= 0',\n /** The `runOnce` bootstrap already ran for this entry. */\n 'bootstrapDone': 'boolean',\n /**\n * A restored dump this entry still has to load, and where it is.\n *\n * The restore cannot run the load hook itself: `mongorestore` needs a server that is answering, and\n * the entry is stopped at that moment. So the restore stages the dump and records it here, and the\n * next `start` runs the hook once the process is up. Persisted, because a restore followed by a\n * panel restart must not lose the load.\n */\n 'pendingLoad?': 'string | null',\n /**\n * The last child this panel spawned for a non-persistent entry. A detached child\n * outlives the panel, so this is the only way a later boot recognizes its own\n * survivor instead of spawning a second copy beside it.\n */\n 'lastPid?': 'number | null',\n 'lastStartedAt?': 'number | null',\n})\nexport type EntryState = typeof entryStateSchema.infer\n\n/** Edits to the panel-wide settings: listener, auth, TLS policy, host vitals, backups. */\nexport const settingsPatchSchema = type({\n control: controlPatchSchema.optional(),\n host: hostPatchSchema.optional(),\n backups: backupsPatchSchema.optional(),\n}).onUndeclaredKey('reject')\nexport type SettingsPatch = typeof settingsPatchSchema.infer\n\n/** Edits to one workspace's settings: server defaults, log retention, notifications. */\nexport const workspaceSettingsPatchSchema = type({\n defaults: defaultsPatchSchema.optional(),\n logs: logsPatchSchema.optional(),\n notifications: notificationsPatchSchema.optional(),\n}).onUndeclaredKey('reject')\nexport type WorkspaceSettingsPatch = typeof workspaceSettingsPatchSchema.infer\n\nexport const authStatusSchema = type({\n enabled: 'boolean',\n passwordSet: 'boolean',\n passwordUpdatedAt: 'number | null',\n /**\n * An API token is set; it is shown here as a flag, never as a value. Optional so\n * a freshly built UI still parses the state of a panel process that predates it:\n * an upgrade replaces `uis/stock/dist` on disk while the old process keeps\n * serving, and a missing key must not blank the whole app.\n */\n apiTokenSet: 'boolean?',\n /** Still the boot-time default; the login page says so and exposure stays blocked. */\n usingDefaultPassword: 'boolean',\n /** The panel currently listens beyond loopback. */\n exposed: 'boolean',\n /** Non-null when that exposure is not backed by a password. */\n blockedReason: 'string | null',\n sessionTtlMs: 'number',\n cookieSecure: 'string',\n trustProxy: 'boolean | \"loopback\"',\n maxLoginAttempts: 'number',\n lockoutMs: 'number',\n})\nexport type AuthStatus = typeof authStatusSchema.infer\n\nexport const tlsStatusSchema = type({\n enabled: 'boolean',\n certPresent: 'boolean',\n subject: 'string | null',\n issuer: 'string | null',\n validFrom: 'string | null',\n validTo: 'string | null',\n daysRemaining: 'number | null',\n fingerprint: 'string | null',\n keyMatches: 'boolean | null',\n error: 'string | null',\n})\nexport type TlsStatus = typeof tlsStatusSchema.infer\n\n/**\n * The reverse-proxy engine this panel can drive. One engine ships today; the\n * field exists so a config written now keeps working if a second one lands.\n */\nexport const proxyEngineSchema = type.enumerated('caddy')\nexport type ProxyEngine = typeof proxyEngineSchema.infer\n\n/** What a route forwards to: a supervised entry, the panel itself, or a literal upstream. */\nexport const proxyTargetSchema = type.enumerated('server', 'panel', 'external')\nexport type ProxyTarget = typeof proxyTargetSchema.infer\n\n/** `auto` lets the engine decide: a public name gets ACME, a local one its own CA. */\nexport const proxyTlsModeSchema = type.enumerated('auto', 'off', 'manual')\nexport type ProxyTlsMode = typeof proxyTlsModeSchema.infer\n\n/**\n * One public hostname, and where it goes. A route is panel-wide on purpose — the\n * point is one domain per service across every workspace — so a target that\n * names an entry names its workspace too.\n */\nexport const proxyRouteSchema = type({\n id: '/^[a-z0-9][a-z0-9_-]*$/',\n /** The public hostname this route answers for. */\n host: '/^[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\\\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*$/',\n enabled: 'boolean = true',\n target: proxyTargetSchema.default(() => 'server' as const),\n /** `target: \"server\"` — an id is only unique inside its workspace. */\n workspace: 'string = \"\"',\n server: 'string = \"\"',\n /** `target: \"external\"` — a literal upstream such as `http://10.0.0.5:8080`. */\n url: 'string = \"\"',\n /** Optional path prefix; empty serves the whole host. */\n path: 'string = \"\"',\n tls: proxyTlsModeSchema.default(() => 'auto' as const),\n /**\n * Which DNS account answers a DNS-01 challenge for this hostname, as\n * `<workspace>/<account>` — the account belongs to a workspace, so the proxy\n * references it rather than owning it. Empty picks the workspace's only\n * account that can write TXT records.\n */\n dnsAccount: 'string = \"\"',\n}).onUndeclaredKey('reject')\nexport type ProxyRoute = typeof proxyRouteSchema.infer\n\n/**\n * One uploaded PEM pair. The pair itself lives on disk (0600) beside the panel's\n * own; this is the entry that names it, so a route can be checked against it.\n */\nexport const proxyCertificateSchema = type({\n id: '/^[a-z0-9][a-z0-9_-]*$/',\n label: 'string = \"\"',\n}).onUndeclaredKey('reject')\n\n/**\n * What a route's certificate situation is, for the page to show. `fallback` is a\n * public name the CA would not issue for, so the engine is serving its own CA.\n */\nexport const proxyCertificateStateSchema = type.enumerated('off', 'local', 'uploaded', 'issued', 'pending', 'failed', 'fallback')\nexport type ProxyCertificateState = typeof proxyCertificateStateSchema.infer\n\n/**\n * DNS-01, answered by the panel instead of the engine.\n *\n * The engine never holds DNS credentials: it asks the panel over the ACMEProxy\n * protocol, and the panel writes the challenge record through the workspace\n * account a route names. `resolvers` overrides the nameservers Caddy uses to see\n * the record, which is what split-horizon DNS needs.\n */\nexport const proxyDns01Schema = type({\n /** Off means the engine uses HTTP-01/TLS-ALPN-01, exactly as before. */\n enabled: 'boolean = false',\n /** Nameservers Caddy checks the TXT record against; empty uses its own defaults. */\n resolvers: type('string[]').default(() => []),\n}).onUndeclaredKey('reject')\n\n/** Reverse proxy: expose the stack through one engine, with automatic HTTPS. */\nexport const proxyConfigSchema = type({\n enabled: 'boolean = false',\n engine: proxyEngineSchema.default(() => 'caddy' as const),\n /** Cleartext side: ACME HTTP-01 challenges and the redirect to HTTPS. */\n httpPort: '1 <= number.integer <= 65535 = 80',\n httpsPort: '1 <= number.integer <= 65535 = 443',\n /** ACME account address; a public certificate needs one. */\n email: 'string = \"\"',\n /** The ACME staging endpoint: untrusted certificates, no rate-limit burn. */\n staging: 'boolean = false',\n dns01: proxyDns01Schema.default(() => ({})),\n /** PEM pairs a route with `tls: \"manual\"` may serve; the engine picks by SNI. */\n certificates: proxyCertificateSchema.array().default(() => []),\n routes: proxyRouteSchema.array().default(() => []),\n}).onUndeclaredKey('reject')\nexport type ProxyConfig = typeof proxyConfigSchema.infer\n\n/** Where the binary came from: the release we downloaded, or a path a person set. */\nexport const proxyEngineSourceSchema = type.enumerated('downloaded', 'custom')\n\n/** What the panel knows about the installed engine. */\nexport const proxyEngineStatusSchema = type({\n id: proxyEngineSchema,\n installed: 'boolean',\n /** The version the binary reports; `null` until it has been probed. */\n version: 'string | null',\n source: proxyEngineSourceSchema.or(type('null')),\n path: 'string | null',\n bytes: 'number | null',\n error: 'string | null',\n})\nexport type ProxyEngineStatus = typeof proxyEngineStatusSchema.infer\n\n/** Engine capabilities, so the page knows which options to offer. */\nexport const proxyEngineInfoSchema = type({\n id: proxyEngineSchema,\n label: 'string',\n docsUrl: 'string',\n releaseUrl: 'string',\n acme: 'boolean',\n internalCa: 'boolean',\n dns01: 'boolean',\n tcp: 'boolean',\n})\nexport type ProxyEngineInfo = typeof proxyEngineInfoSchema.infer\n\nexport const proxyRouteStatusSchema = type.enumerated('ok', 'disabled', 'no-upstream', 'error')\nexport type ProxyRouteStatus = typeof proxyRouteStatusSchema.infer\n\n/** A route as the page reads it: the config, plus the upstream resolved live. */\nexport const proxyRouteViewSchema = type({\n 'route': proxyRouteSchema,\n 'status': proxyRouteStatusSchema,\n 'upstream': 'string | null',\n 'message': 'string | null',\n /** Where this hostname's certificate stands. Optional: an older panel omits it. */\n 'certificate?': type({\n 'state': proxyCertificateStateSchema,\n 'message': 'string | null',\n /**\n * For `fallback`: minutes until the engine tries the CA again by itself, read\n * from the certificate it fell back to. Optional, so an older client ignores it.\n */\n 'retryInMinutes?': 'number',\n }),\n}).onDeepUndeclaredKey('ignore')\nexport type ProxyRouteView = typeof proxyRouteViewSchema.infer\n\nexport const proxyRunStateSchema = type.enumerated('off', 'stopped', 'starting', 'running', 'error', 'unsupported')\nexport type ProxyRunState = typeof proxyRunStateSchema.infer\n\n/** Live engine state. */\nexport const proxyStatusSchema = type({\n state: proxyRunStateSchema,\n pid: 'number | null',\n /** The addresses the engine serves on, for the page to show. */\n urls: type('string[]'),\n /** Days until the soonest publicly-issued certificate expires; `null` when none. */\n certExpiryDays: 'number | null',\n since: 'number | null',\n lastError: 'string | null',\n})\nexport type ProxyStatus = typeof proxyStatusSchema.infer\n\n/** One uploaded pair, described: what it is for, and whether it is usable. */\nexport const proxyCertificateViewSchema = type({\n id: 'string',\n label: 'string',\n /** Both halves are on disk. */\n present: 'boolean',\n /** The engine would serve this pair for at least one manual route. */\n used: 'boolean',\n subject: 'string | null',\n issuer: 'string | null',\n validTo: 'string | null',\n daysRemaining: 'number | null',\n /** Hostnames the pair covers, read from its SANs. */\n hosts: type('string[]'),\n error: 'string | null',\n})\nexport type ProxyCertificateView = typeof proxyCertificateViewSchema.infer\n\n/**\n * A DNS account the route table may name, flattened across workspaces so the proxy\n * page can offer one list. The account itself stays in its workspace.\n */\nexport const proxyDnsAccountViewSchema = type({\n workspace: 'string',\n account: 'string',\n provider: 'string',\n label: 'string',\n /** The credentials can write a TXT record, so this account can answer a challenge. */\n writesTxt: 'boolean',\n /** Credentials are stored; an account without them cannot answer yet. */\n hasCredentials: 'boolean',\n})\nexport type ProxyDnsAccountView = typeof proxyDnsAccountViewSchema.infer\n\n/** `GET /api/proxy`: the policy, the engine, the live state and the resolved routes. */\nexport const proxyViewSchema = type({\n 'config': proxyConfigSchema,\n 'engine': proxyEngineStatusSchema,\n 'engines': proxyEngineInfoSchema.array(),\n 'status': proxyStatusSchema,\n 'routes': proxyRouteViewSchema.array(),\n /** Every uploaded pair, with what it covers and when it expires. */\n 'certificates': proxyCertificateViewSchema.array(),\n /** Every DNS account a route may name. Optional: an older panel omits it. */\n 'dnsAccounts?': proxyDnsAccountViewSchema.array(),\n}).onDeepUndeclaredKey('ignore')\nexport type ProxyView = typeof proxyViewSchema.infer\n\n/**\n * A route as a patch sends it: every field optional, so a client may change one\n * member of a route — or add a route with only the two fields that matter.\n */\nexport const proxyRoutePatchSchema = type({\n id: 'string',\n host: 'string',\n enabled: 'boolean?',\n target: proxyTargetSchema.optional(),\n workspace: 'string?',\n server: 'string?',\n url: 'string?',\n path: 'string?',\n tls: proxyTlsModeSchema.optional(),\n dnsAccount: 'string?',\n}).onUndeclaredKey('reject')\nexport type ProxyRoutePatch = typeof proxyRoutePatchSchema.infer\n\n/**\n * The proxy block as a patch: no defaults, and `routes` is a list a patch\n * **replaces** — a key-by-key merge cannot express removing a route.\n */\nexport const proxyPatchSchema = type({\n enabled: 'boolean?',\n engine: proxyEngineSchema.optional(),\n httpPort: '1 <= number.integer <= 65535?',\n httpsPort: '1 <= number.integer <= 65535?',\n email: 'string?',\n staging: 'boolean?',\n /**\n * A patch shape, not the config's: both keys are optional and merge, so a client\n * may send one without resetting the other, and an explicit `null` clears a key.\n */\n dns01: type({\n enabled: 'boolean | null?',\n resolvers: 'string[] | null?',\n }).onUndeclaredKey('reject').optional(),\n certificates: proxyCertificateSchema.array().optional(),\n routes: proxyRoutePatchSchema.array().optional(),\n}).onUndeclaredKey('reject')\nexport type ProxyPatch = typeof proxyPatchSchema.infer\n\n/** `PUT /api/proxy/certificates/:id`: the pair itself, plus what to call it. */\nexport const proxyCertificateUploadSchema = type({\n label: 'string = \"\"',\n certificate: 'string >= 1',\n privateKey: 'string >= 1',\n}).onUndeclaredKey('reject')\n\n/** `POST /api/proxy/engine`: which release to install; empty means the current one. */\nexport const proxyEngineInstallSchema = type({\n version: 'string = \"\"',\n}).onUndeclaredKey('reject')\n\n/** The policy columns a destination row carries — the values a send will actually use. */\nconst notificationPolicyStatusShape = {\n onCrash: 'boolean',\n onUnhealthy: 'boolean',\n onForcedRestart: 'boolean',\n onRecovered: 'boolean',\n /** Host vitals breaches (disk, memory, swap, load, temperature). */\n onHost: 'boolean',\n /** Dynamic DNS, when this panel knows about it (optional for an older panel). */\n onDdns: 'boolean?',\n cooldownMs: 'number',\n} as const\n\n/**\n * One destination as the page reads it: the fields it owns, the policy it will use, and the outcome\n * of the last send to it.\n *\n * The policy here is the **effective** one — inherited from the general block when\n * `useOwnSettings` is false — so the page shows what will happen, not what is stored.\n */\nexport const destinationStatusSchema = type({\n 'id': 'string',\n 'kind': '\"telegram\" | \"webhook\"',\n 'enabled': 'boolean',\n 'useOwnSettings': 'boolean',\n ...notificationPolicyStatusShape,\n /** Telegram only, null on a webhook. */\n 'chatId': 'string | null',\n /** Telegram only: whether a bot token is stored for this destination. */\n 'tokenSet': 'boolean',\n /** Webhook only, null on a Telegram destination. */\n 'url': 'string | null',\n 'method': '\"POST\" | \"PUT\" | null',\n 'format': '\"json\" | \"text\" | null',\n 'headers': 'string | null',\n /** Last delivery outcome, for the page. Optional: a newer panel may not have sent one yet. */\n 'lastResult?': 'string | null',\n 'lastResultAt?': 'number | null',\n})\nexport type DestinationStatusView = typeof destinationStatusSchema.infer\n\n/**\n * The chats a bot can see, as `POST /notifications/destinations/:id/detect-chats` answers them.\n *\n * This was declared inline in the route while `TelegramChat` in `providers/telegram.ts` described the\n * same two fields — one shape written twice, which is the drift this file exists to prevent.\n */\nexport const telegramChatsSchema = type({\n chats: type({ id: 'string | number', title: 'string' }).array(),\n})\n\nexport const notificationViewSchema = type({\n /** The general block: what a destination inherits unless it overrides it. Optional for an older panel. */\n 'defaults?': notificationDefaultsViewSchema,\n /** Every destination, in config order. Optional for an older panel. */\n 'destinations?': destinationStatusSchema.array(),\n})\nexport type NotificationView = typeof notificationViewSchema.infer\n\nexport const sessionViewSchema = type({\n authenticated: 'boolean',\n authRequired: 'boolean',\n passwordSet: 'boolean',\n /** A long-lived API token is configured; optional for the same reason as above. */\n apiTokenSet: 'boolean?',\n usingDefaultPassword: 'boolean',\n /** The boot-time password, exposed only while it is still in use. */\n defaultPassword: 'string | null',\n sessionTtlMs: 'number',\n})\nexport type SessionView = typeof sessionViewSchema.infer\n\n/** `POST /api/auth/token`: the new token, returned once, and the readable head the panel keeps. */\nexport const apiTokenCreatedSchema = type({ token: 'string', hint: 'string' })\n\nexport const loginSchema = type({ password: 'string <= 512' }).onUndeclaredKey('reject')\nexport type LoginRequest = typeof loginSchema.infer\n\n/** Any non-empty password is allowed; only a sanity cap on the length. */\nexport const passwordValueSchema = type('1 <= string <= 512')\n\nexport const passwordSchema = type({\n currentPassword: 'string?',\n newPassword: passwordValueSchema,\n}).onUndeclaredKey('reject')\nexport type PasswordRequest = typeof passwordSchema.infer\n\nexport const serverStatusSchema = type('\"stopped\" | \"starting\" | \"running\" | \"stopping\" | \"backoff\" | \"crashed\" | \"conflict\"')\nexport type ServerStatus = typeof serverStatusSchema.infer\n\nexport const healthStateSchema = type('\"disabled\" | \"unknown\" | \"healthy\" | \"unhealthy\"')\nexport type HealthState = typeof healthStateSchema.infer\n\nexport const portStateSchema = type('\"unknown\" | \"free\" | \"in-use\"')\nexport type PortState = typeof portStateSchema.infer\n\nexport const logStreamSchema = type('\"stdout\" | \"stderr\" | \"system\"')\nexport type LogStream = typeof logStreamSchema.infer\n\nexport const logLineSchema = type({\n ts: 'number',\n stream: logStreamSchema,\n text: 'string',\n})\nexport type LogLine = typeof logLineSchema.infer\n\n/**\n * Who asked for something, so a restart can be attributed.\n *\n * `policy` is the panel acting on its own (a health-forced restart, a memory ceiling);\n * `user` is a signed-in browser; `agent` is a request carrying an API token; `boot` is\n * the autostart pass. Optional: events written before this field existed carry none.\n */\nexport const historyActorSchema = type.enumerated('policy', 'user', 'agent', 'boot')\nexport type HistoryActor = typeof historyActorSchema.infer\n\nexport const historyEventSchema = type({\n 'serverId': 'string',\n 'ts': 'number',\n 'type': '\"start\" | \"exit\" | \"crash\" | \"forced-restart\" | \"unhealthy\" | \"recovered\"',\n 'detail': 'string',\n /** How long the process had been up, recorded on exit and crash. */\n 'runtimeMs': 'number?',\n /** Who caused it; absent on events from before this field existed. */\n 'actor?': historyActorSchema,\n})\nexport type HistoryEvent = typeof historyEventSchema.infer\n\n/** Rolling window stats derived from the persisted event log. */\nexport const serverHistorySchema = type({\n windowMs: 'number',\n /** Share of the window the process was up (null when nothing is known yet). */\n uptimeRatio: 'number | null',\n restarts: 'number',\n crashes: 'number',\n forcedRestarts: 'number',\n lastCrashAt: 'number | null',\n lastExitAt: 'number | null',\n lastRuntimeMs: 'number | null',\n events: historyEventSchema.array(),\n})\nexport type ServerHistory = typeof serverHistorySchema.infer\n\nexport const processResourcesSchema = type({\n cpuPercent: 'number | null',\n /** RSS of the process and its descendants. */\n rssBytes: 'number | null',\n processes: 'number',\n sampledAt: 'number',\n})\nexport type ProcessResources = typeof processResourcesSchema.infer\n\nexport const hostDiskSchema = type({\n path: 'string',\n totalBytes: 'number',\n freeBytes: 'number',\n usedPercent: 'number',\n})\n\nexport const hostViewSchema = type({\n 'enabled': 'boolean',\n 'cpus': 'number',\n 'loadAvg': type('number[]'),\n /**\n * Share of this machine's CPU capacity in use over the last sampling interval, 0–100.\n *\n * Optional: an older panel sends no such field, and a required one rejects the whole frame and\n * blanks the UI that panel is serving. `null` on the first sample, which has no window to\n * measure yet — a number there would be invented.\n */\n 'cpuUsedPercent?': 'number | null',\n 'uptimeMs': 'number',\n 'memoryUsedPercent': 'number',\n 'swapUsedPercent': 'number',\n 'tempCelsius': 'number | null',\n 'disks': hostDiskSchema.array(),\n /** Human readable threshold breaches, for the banner and notifications. */\n 'alerts': type('string[]'),\n 'sampledAt': 'number | null',\n /**\n * The per-cpu load this panel notifies on — `host.loadPerCpu`, the number the alert fires at.\n *\n * Optional: a panel that predates this field alerts on the default, which is what the UI's band\n * assumes when the field is absent. It travels here because the frame is the only thing a host\n * surface reads, and a surface that cannot see the threshold hardcoded `2`/`1.4` — so raising\n * the threshold in Settings left the tile painting a healthy box `danger` while the alert the\n * threshold governs stayed silent. `0` disables the alert, so nothing can breach it.\n */\n 'loadAlertPerCpu?': 'number',\n /**\n * The percentage alert thresholds — `host.diskUsedPercent`, `host.memoryUsedPercent`,\n * `host.swapUsedPercent` and `host.tempCelsius` — the numbers the panel notifies at.\n *\n * Optional for the same reason as `loadAlertPerCpu`, and carried for the same reason: a surface\n * that cannot see the threshold has to invent one, and the invented ones disagreed with the\n * panel's verdict. The swap bar called 50% `warn` while the alert fired there; raising\n * `host.tempCelsius` to 95 left a 90 °C box painted `danger` for a notification that never\n * arrives; and a disk threshold lowered to 80 notified at 82% while every disk bar called it\n * `warn`. `0` disables that alert, so nothing can breach it.\n */\n 'memoryUsedPercentAlert?': 'number',\n 'swapUsedPercentAlert?': 'number',\n 'tempCelsiusAlert?': 'number',\n /**\n * `host.diskUsedPercent`, the threshold a filesystem is banded against.\n *\n * It travels once for the frame rather than per disk: the threshold is one config value that\n * applies to every configured path, which is why `hostReadings` copies it onto each disk's `band`.\n */\n 'diskUsedPercentAlert?': 'number',\n})\nexport type HostView = typeof hostViewSchema.infer\n\n/**\n * The WSL2 temperature bridge, as the settings page reports it.\n *\n * A WSL2 guest cannot read a CPU temperature at all, so the panel offers to install a Windows-side\n * helper and point `host.tempCommand` at it. `supported` is false on any other platform, which is\n * how the UI hides the whole block rather than offering a button that cannot work.\n */\nexport const wslTemperatureSchema = type({\n /** This process runs under WSL. */\n 'wsl': 'boolean',\n /** The setup can work here — the same as `wsl` today, separate so a future bridge can differ. */\n 'supported': 'boolean',\n /** `host.tempCommand` already names a command. */\n 'configured': 'boolean',\n /** The helper script exists on disk. */\n 'scriptWritten': 'boolean',\n /** LibreHardwareMonitor was found on the Windows side. */\n 'libraryPresent': 'boolean',\n /** Where the helper was written, for the sentence that tells a person what to delete. */\n 'scriptPath': 'string | null',\n /** The command the panel would run, absent until it is configured. */\n 'tempCommand?': 'string | null',\n /** The last probe's reading, so the page can say \"this works\" without running it again. */\n 'lastReadingCelsius?': 'number | null',\n /** Why the last probe failed, if it did — a missing library and no sensor read differently. */\n 'lastError?': 'string | null',\n /**\n * The library is missing and installing it needs consent.\n *\n * The panel will not download a third-party binary on a click that did not mention one, so the\n * first press answers `needsDownload` and the page asks. Absent on an older panel.\n */\n 'needsDownload?': 'boolean',\n})\nexport type WslTemperatureStatus = typeof wslTemperatureSchema.infer\n\nexport const backupFileSchema = type({\n name: 'string',\n sizeBytes: 'number',\n createdAt: 'number',\n /** The archive carries a password-protected payload. */\n encrypted: 'boolean',\n})\n\nexport type BackupFile = typeof backupFileSchema.infer\n\n/**\n * One selectable entry in a backup: a global item (`global:settings`,\n * `global:secrets`, `global:tls`) or a workspace, whose `items` are the\n * sub-choices a per-workspace dialog offers.\n */\nexport const backupEntrySchema = type({\n /** `global:settings` | `global:secrets` | `global:tls` | `workspace:<id>`. */\n 'id': 'string',\n /**\n * The panel's own English wording. Kept because it is what an older UI reads, and what a\n * single-language UI wants; a translated UI prefers the `*Key` beside it.\n */\n 'label': 'string',\n /** A catalog key for `label`, with its placeholder values, so a UI can render its own language. */\n 'labelKey?': 'string',\n 'labelParams?': 'Record<string, string>',\n 'kind': '\"settings\" | \"secrets\" | \"tls\" | \"workspace\"',\n 'workspaceId?': 'string',\n 'note': 'string | null',\n /** The same pair for `note`: the panel knows which reason it is, the UI knows the wording. */\n 'noteKey?': 'string',\n 'noteParams?': 'Record<string, string>',\n /** What this entry would capture; a workspace carries several leaves. */\n 'items': type({\n 'id': 'string',\n 'label': 'string',\n 'labelKey?': 'string',\n 'labelParams?': 'Record<string, string>',\n /** `settings`/`servers`/`secrets` for a workspace, `data` for a declared path. */\n 'kind': '\"settings\" | \"servers\" | \"secrets\" | \"data\"',\n /** Which secret a `secrets` leaf carries (`password`, `apiToken`, `telegram`, `ddns`, …). */\n 'secret?': 'string',\n 'path?': 'string',\n /** Who declared a data path: `global`, `<serverId>:backupPaths` or `<serverId>:<ENV>`. */\n 'origin?': 'string',\n 'included': 'boolean',\n 'note': 'string | null',\n 'noteKey?': 'string',\n 'noteParams?': 'Record<string, string>',\n 'ignoreGenerated?': 'boolean',\n }).array(),\n})\nexport type BackupEntry = typeof backupEntrySchema.infer\n\n/**\n * The schedule as a *response* carries it: undeclared keys are accepted, at both levels.\n *\n * A response schema may not reject (a newer panel may add a field an older client still reads), and\n * `scope` is one level deep — so the outer `.onUndeclaredKey` on the config schema is not enough:\n * a frame carrying `schedule.scope` rejected outright while this was the config shape.\n */\nexport const backupScheduleViewSchema = backupScheduleSchema.onDeepUndeclaredKey('ignore')\n\nexport const backupsViewSchema = type({\n 'enabled': 'boolean',\n 'dir': 'string',\n 'keep': 'number',\n /**\n * The scheduled half, so the page can show and edit it.\n *\n * Optional because the panel and the UI upgrade separately: an older panel does not send it,\n * and a required field would blank the settings page for that panel. The page reads it as\n * \"off, keep 7\" when absent — the schema defaults — so nothing changes for it.\n */\n 'schedule?': backupScheduleViewSchema,\n /** When the last automatic archive was written; null until one has run. Optional for the same reason. */\n 'lastAutomaticAt?': 'number | null',\n /**\n * Why the last scheduled pass failed, and when it tried.\n *\n * A failed pass wrote only a panel-console warning, so \"enabled, zero archives\" looked the same\n * as \"failing every interval since the day it was enabled\" — indistinguishable from the page,\n * which is the only place a person looks. Null once a pass succeeds.\n */\n 'scheduleError?': type({\n message: 'string',\n at: 'number',\n }),\n /** Extra paths from the global config, in addition to each server's own. */\n 'includePaths': type('string[]'),\n /**\n * The selection model, carried here only by a panel older than this release.\n *\n * Reading it costs a `readFileSync` of the global and every workspace's `.secrets.json` plus a\n * `statSync` per archive, and the state frame is rebuilt ~13×/s — so it moved to\n * `GET /api/backups` (`backupSelectionSchema`), which a dialog fetches when it opens. Optional on\n * purpose: a newer UI reads a panel that still sends it, and a UI must never reject a payload for\n * a field it does not use. Absent means \"ask the endpoint\".\n */\n 'entries?': backupEntrySchema.array(),\n 'files?': backupFileSchema.array(),\n})\nexport type BackupsView = typeof backupsViewSchema.infer\n\n/**\n * The backup *selection model*: what a capture could include, and what is already on disk.\n *\n * Its own route rather than a field of the state frame, because building it reads every workspace's\n * secrets file and stats every archive — work proportional to workspaces × archives, on a path that\n * runs per frame. A dialog needs it when it opens and not otherwise.\n */\nexport const backupSelectionSchema = type({\n /** The archive directory, so a dialog can print the path without a second read. */\n dir: 'string',\n /** Every selectable entry, global first, then each workspace. */\n entries: backupEntrySchema.array(),\n files: backupFileSchema.array(),\n})\nexport type BackupSelection = typeof backupSelectionSchema.infer\n\n/** One restorable slice of an archive: a global item, a workspace item, or a data path. */\nexport const restoreItemSchema = type({\n /** A backup entry or leaf id (`workspace:<id>:servers`, `data:<path>`, ...). */\n 'id': 'string',\n 'label': 'string',\n 'labelKey?': 'string',\n 'labelParams?': 'Record<string, string>',\n 'kind': '\"settings\" | \"secrets\" | \"servers\" | \"tls\" | \"data\"',\n 'workspaceId?': 'string',\n /** false when the current instance does not declare it, or it is not in the archive. */\n 'restorable': 'boolean',\n /** Echo of the request's selection, so the checkboxes round-trip. */\n 'selected': 'boolean',\n 'note': 'string | null',\n 'noteKey?': 'string',\n 'noteParams?': 'Record<string, string>',\n})\nexport type RestoreItem = typeof restoreItemSchema.infer\n\n/**\n * Why one thing was skipped, as a reason the UI can word itself.\n *\n * `skipped` stays a list of ready-made English sentences for an older UI and for\n * `noc-console`; this is the same list in parts, so a translated UI says it in the\n * reader's language instead of showing the panel's English inside its own sentence.\n */\nexport const restoreSkipSchema = type({\n 'label': 'string',\n 'labelKey?': 'string',\n 'labelParams?': 'Record<string, string>',\n /** A catalog key for the parenthesis, e.g. `not selected`; absent when there is none. */\n 'reasonKey?': 'string',\n 'reasonParams?': 'Record<string, string>',\n})\nexport type RestoreSkip = typeof restoreSkipSchema.infer\n\nexport const restorePlanSchema = type({\n 'dryRun': 'boolean',\n 'encrypted': 'boolean',\n /** The archive needs a password (none or a wrong one was supplied). */\n 'needsPassword': 'boolean',\n /**\n * Where the archive says it came from. Optional: an archive written before this\n * stamp existed carries neither field, and an older panel never sends the row.\n */\n 'archive?': type({\n 'writtenBy?': 'string',\n 'schema?': 'number',\n }),\n 'items': restoreItemSchema.array(),\n /**\n * One row per backup hook that ran, so a person can see which entries brought their own dump.\n *\n * Optional, like every new response field: an older panel never sends it and an older UI never\n * reads it. `output` is a bounded tail, not a log — enough to see what `mongorestore` said.\n */\n 'hooks?': type({\n 'serverId': 'string',\n 'workspaceId': 'string',\n 'action': '\"dump\" | \"load\"',\n 'ok': 'boolean',\n 'output?': 'string',\n }).array(),\n 'applied': type('string[]'),\n /**\n * The ids `applied` names, so a UI resolves each through `items` and renders its own label.\n * `applied` itself stays: it is what a UI with one language reads.\n */\n 'appliedIds?': type('string[]'),\n 'skipped': type('string[]'),\n 'skippedItems?': restoreSkipSchema.array(),\n /** Only the panel's own listener needs a restart; its servers are re-read live. */\n 'restartRequired': 'boolean',\n /** The panel re-read the restored config within this same restore. */\n 'reloaded': 'boolean',\n /**\n * Servers that are **running now** and whose declared data path this restore overwrote.\n *\n * A data path is copied over while its owner keeps running, holding open handles to files\n * that were just replaced — the process keeps its old view and the archive's copy wins on\n * disk, so anything written since the archive was taken is gone. The plan has to say which\n * entries that happened to, because nothing else in the result mentions them.\n *\n * Optional: an older panel does not send it, and a plan that touched no running entry sends none.\n */\n 'replacedUnderRunning?': type({\n workspaceId: 'string',\n serverId: 'string',\n path: 'string',\n }).array(),\n /**\n * Workspaces this restore created because the archive named them and the host did not\n * have them. Optional: an older panel never sends the row, and an archive written\n * before the registry was captured creates none.\n */\n 'createdWorkspaces?': type('string[]'),\n 'error': 'string?',\n})\nexport type RestorePlan = typeof restorePlanSchema.infer\n\nexport const backupCreateSchema = type({\n /** Optional: encrypts the archive. Never stored. */\n password: passwordValueSchema.optional(),\n /** Leaf ids to capture (`global:settings`, `workspace:<id>:servers`, `data:<path>`, ...); omitted means everything. */\n include: type('string[] >= 1').optional(),\n /**\n * Leaf ids to leave out, applied after `include` — the CLI's `--exclude`, and the one thing to\n * name when the archive should carry everything but the credentials.\n *\n * Empty is refused for the same reason `include` refuses it: an empty list reads as \"nothing\" to\n * a person and as \"everything\" to a reader, so it must not be sent at all.\n */\n exclude: type('string[] >= 1').optional(),\n}).onUndeclaredKey('reject')\nexport type BackupCreate = typeof backupCreateSchema.infer\n\nexport const restoreRequestSchema = type({\n name: 'string?',\n password: passwordValueSchema.optional(),\n /** Item ids to restore; omitted means every restorable item. */\n include: type('string[]').optional(),\n /**\n * Item ids to leave out, applied after `include` — the CLI's `--exclude` on the same command.\n *\n * `BackupService.restore()` has always taken it and the local channel has always sent it, but this\n * schema declared only `name`/`password`/`include` **and rejects undeclared keys**, so the same\n * request over `/api` answered `exclude must be removed`: a script or either UI could only say\n * \"these items\", never \"everything except these\", on the one path that overwrites a live host.\n *\n * Empty is refused for the same reason it is on a create — it reads as \"nothing\" to a person and\n * as \"everything\" to the reader, so it must not be sent at all.\n */\n exclude: type('string[] >= 1').optional(),\n}).onUndeclaredKey('reject')\nexport type RestoreRequest = typeof restoreRequestSchema.infer\n\n/** Runtime view of a server: its effective config plus everything observed. */\nexport const serverViewSchema = type({\n 'id': 'string',\n /** The workspace that owns it; optional so an older panel's frame still parses. */\n 'workspaceId?': 'string',\n 'config': serverSchema,\n 'bindHost': 'string',\n 'url': 'string | null',\n 'status': serverStatusSchema,\n 'health': healthStateSchema,\n 'portState': portStateSchema,\n 'pid': 'number | null',\n /** True when the process serving this entry was adopted, not spawned by the panel. */\n 'adopted': 'boolean?',\n /**\n * The panel stopped this entry because it could not serve, rather than someone asking.\n *\n * Optional, like every new field: an older panel does not send it. `/healthz` needs it because\n * the status alone cannot tell \"the operator switched this off\" (never a problem) from \"the\n * panel gave up on it\" (a broken service) — both are `stopped`.\n */\n 'stoppedByPanel?': 'boolean',\n 'startedAt': 'number | null',\n 'exitCode': 'number | null',\n 'exitSignal': 'string | null',\n 'restarts': 'number',\n 'maxRetries': 'number',\n 'lastError': 'string | null',\n 'nextRetryAt': 'number | null',\n 'unhealthySince': 'number | null',\n 'bufferedLines': 'number',\n 'history': serverHistorySchema,\n /** Last health probe latency (TCP connect or HTTP request). */\n 'responseMs': 'number | null',\n 'resources': processResourcesSchema.or(type('null')),\n}).onDeepUndeclaredKey('ignore')\n// `config` is emitted normalized (port is always `number | null`, never absent),\n// while the schema accepts both forms so a hand-written payload still validates.\nexport type ServerView = Omit<typeof serverViewSchema.infer, 'config'> & { config: ServerConfig }\n\n/**\n * What `/healthz` answers, on both statuses — 200 when serving, 503 when a server has crashed,\n * which shares this response's `content` in the spec. The detail fields are optional because they are\n * only included for an authenticated caller.\n */\nexport const healthResponseSchema = type({\n 'status': '\"ok\" | \"degraded\"',\n 'uptimeMs': 'number',\n 'servers?': type({ total: 'number', running: 'number', crashed: 'number', unhealthy: 'number' }),\n 'hostAlerts?': 'string[]',\n})\n\nexport const controlViewSchema = type({\n /** The configured panel name, for the shell to render. */\n 'label': 'string',\n 'port': 'number',\n /** The configured bind value (`local` | `lan` | ipv4). */\n 'host': 'string',\n /** The address actually bound. */\n 'bindHost': 'string',\n 'url': 'string',\n 'openBrowser': 'boolean',\n 'allowedHosts?': 'string[]',\n /** The live listener differs from the configured host/port. */\n 'restartRequired': 'boolean',\n 'protocol': 'string',\n 'auth': authStatusSchema,\n 'tls': tlsStatusSchema,\n})\nexport type ControlView = typeof controlViewSchema.infer\n\n/** Everything one workspace owns, plus the live state of its servers. */\n/**\n * A user-supplied UI, as the settings page shows it.\n *\n * Every field is optional, and none of them is a fallback: a `ui.json` may be written by\n * the panel (which adds `uploadedAt`/`files`) **or dropped in by hand** following\n * `docs/UI_CREATION.md`, which documents only the author-facing fields. Requiring ours\n * meant a hand-written file parsed to nothing at all, taking `repo`/`tag` with it and\n * silently disabling `ui-update` for exactly the UI that declared itself.\n */\nexport const uiMetaSchema = type({\n 'name?': 'string',\n 'version?': 'string | null',\n /** Set by the panel, not by the author. */\n 'uploadedAt?': 'number',\n /** Counted by the panel, not declared. */\n 'files?': 'number.integer >= 1',\n /** `owner/name` of the UI's own repository, for `ui-update`. */\n 'repo?': 'string',\n /** The release tag this build came from, e.g. `v0.6.0`. Stamped by the build, never committed. */\n 'tag?': 'string',\n /** The release asset name, e.g. `home-hosted-ui-noc-console`. */\n 'asset?': 'string',\n /** When the UI was built, in unix epoch seconds. Stamped by the build, never committed. */\n 'unix?': 'number.integer >= 0',\n})\nexport type UiMeta = typeof uiMetaSchema.infer\n\nexport const uiStatusSchema = type({\n /** A user-supplied UI is being served instead of the stock one. */\n custom: 'boolean',\n /** Where that UI lives, whether or not it exists yet. */\n dir: 'string',\n meta: uiMetaSchema.or(type('null')),\n})\nexport type UiStatus = typeof uiStatusSchema.infer\n\n/** One process a panel spawned that no configured entry claims any more. */\nexport const serverOrphanSchema = type({\n /** The id it was started as, which is also the key of the state file it was found in. */\n serverId: 'string',\n pid: 'number',\n /** When the panel spawned it; null when the record predates the stamp. */\n startedAt: 'number | null',\n})\nexport type ServerOrphan = typeof serverOrphanSchema.infer\n\nexport const workspaceViewSchema = type({\n 'id': 'string',\n 'label': 'string',\n /** The workspace's servers config; the settings file sits beside it. */\n 'configPath': 'string',\n 'settingsPath': 'string',\n 'configError': 'string | null',\n /** Keys a newer release wrote that this one ignores. */\n 'configWarnings?': type('string[]'),\n 'logsDir': 'string',\n 'defaults': defaultsSchema,\n 'logs': logsSchema,\n 'notifications': notificationViewSchema,\n /** Dynamic DNS state. Optional so a newer UI still frames an older payload. */\n 'ddns?': ddnsStatusSchema,\n 'serverCount': 'number',\n 'runningCount': 'number',\n 'crashedCount': 'number',\n /**\n * Processes this panel started that no current entry owns.\n *\n * A detached child outlives a hard panel death, and its handle is the entry-state file keyed by\n * the *id* it was started under. Rename the entry and nothing ever reads that file again; delete\n * the entry while the panel is down and the file is reclaimed, destroying the last handle. The\n * orphan then runs with no card, no `/healthz` line and no CLI action — for a queue consumer,\n * two consumers of the same queue. This is the view that makes it actionable.\n *\n * Optional: an older panel never sends it.\n */\n 'orphans?': serverOrphanSchema.array(),\n 'servers': serverViewSchema.array(),\n}).onDeepUndeclaredKey('ignore')\nexport type WorkspaceView = typeof workspaceViewSchema.infer\n\n/**\n * The whole panel in one frame: global state plus every workspace. Workspace\n * pages read their own subtree; the global pages read across all of them.\n */\nexport const appStateSchema = type({\n 'control': controlViewSchema,\n 'host': hostViewSchema,\n 'backups': backupsViewSchema,\n 'ui': uiStatusSchema,\n 'workspaces': workspaceViewSchema.array(),\n /** The reverse proxy, when this panel has one. Optional: an older panel does not send it. */\n 'proxy?': proxyViewSchema,\n /** The directory the panel was started from; relative entry paths use it. */\n 'projectDir': 'string',\n /** `HHOSTED_HOME`: every file home-hosted owns lives under here. */\n 'dataRoot': 'string',\n /** The release this panel is running. Optional: an older panel does not send one. */\n 'version?': 'string',\n}).onDeepUndeclaredKey('ignore')\nexport type AppState = typeof appStateSchema.infer\n\n/** One SSE frame, discriminated by `type`: a client narrowing on it gets the payload that frame carries. */\nconst stateFrameSchema = type({\n type: '\"hello\" | \"state\"',\n ts: 'number',\n state: appStateSchema,\n}).onDeepUndeclaredKey('ignore')\nconst serverFrameSchema = type({\n 'type': '\"server\"',\n 'ts': 'number',\n 'workspaceId?': 'string',\n 'serverId': 'string',\n 'server': serverViewSchema,\n}).onDeepUndeclaredKey('ignore')\nconst logFrameSchema = type({\n 'type': '\"log\"',\n 'ts': 'number',\n 'workspaceId?': 'string',\n 'serverId': 'string',\n 'lines': logLineSchema.array(),\n}).onDeepUndeclaredKey('ignore')\nexport const sseMessageSchema = stateFrameSchema.or(serverFrameSchema).or(logFrameSchema)\nexport type SseMessage = typeof sseMessageSchema.infer\n\nexport const logQuerySchema = type({\n limit: 'string?',\n})\n\n/**\n * What a per-server lifecycle action answers with.\n *\n * `ok`/`error` are what the panel returns and every UI already reads; `code` was added so a\n * script can branch without matching English, and it is **absent on success** — a code names a\n * failure.\n */\nexport const actionResultSchema = type({\n 'ok': 'boolean',\n 'error?': 'string',\n 'message?': 'string',\n 'code?': 'string',\n})\nexport type ActionResultBody = typeof actionResultSchema.infer\n\n/** Whether a probe (a test send, a token check) worked, and why not when it did not. */\nexport const deliveryResultSchema = type({\n 'ok': 'boolean',\n 'error?': 'string',\n})\n\n/** A password was set or changed, and what that means for the caller's session. */\nexport const passwordSetResponseSchema = type({\n ok: 'boolean',\n enabled: 'boolean',\n sessionsInvalidated: 'boolean',\n})\n\n/**\n * What both TLS mutation routes answer: the panel's listener and the move that is in flight.\n *\n * Declared once because the two routes return the same `review()` body — the DELETE declared\n * `okResponseSchema` while returning this, so a generated client read `undefined` for every field.\n */\nexport const tlsReviewResponseSchema = type({\n control: controlViewSchema,\n rebinding: 'boolean',\n targetUrl: 'string',\n})\n\n/**\n * The plain acknowledgement most mutations answer with.\n *\n * Defined once because a dozen routes return it, and each was declaring its own or none at all —\n * which is why the spec had untyped `200`s where a generated client needs a shape.\n */\nexport const okResponseSchema = type({ ok: 'boolean' })\n\n/** A backup was removed: the archive list it leaves behind. */\nexport const backupFilesResponseSchema = type({\n ok: 'boolean',\n files: backupFileSchema.array(),\n})\n\n/** A UI build was installed (it also reports the build), or reverted. */\nexport const uiInstallResponseSchema = type({\n 'ok': 'boolean',\n 'meta?': uiStatusSchema.get('meta'),\n 'ui': uiStatusSchema,\n /** Revert only: whether there was a custom UI to remove. */\n 'removed?': 'boolean',\n})\n\n/** A backup was created: the new archive and the list it belongs to. */\nexport const backupCreatedResponseSchema = type({\n file: backupFileSchema,\n files: backupFileSchema.array(),\n})\n\n/** Buffered or persisted log lines, the shape every log-reading route returns. */\n/**\n * `GET /api/servers/:id/logs` — the **buffered** lines, straight from memory.\n *\n * It is not the disk history below: this route has no window, no rotation and no search, so it\n * answers `{ lines }` and nothing else. The schema used to be a copy of the disk shape\n * (`serverId`/`enabled`/`sizeBytes`/`files`/`searched`), so the documented response named five\n * fields the handler never sent — and `searched` was declared as an array here while the disk route\n * sends a number. `test/api/panel.test.ts` only walks routes it can reach with a live fixture and\n * skipped this one, so nothing caught it.\n */\nexport const bufferedLogsResponseSchema = type({\n lines: logLineSchema.array(),\n})\nexport type BufferedLogsResponse = typeof bufferedLogsResponseSchema.infer\n\n/**\n * `GET /api/logs/:id` — one entry's log **from disk**, with its rotation and its search window.\n *\n * This is the shape the UIs parse (`logHistoryViewSchema` below is the same thing with its own\n * name for the client side), and it is what `logLinesResponseSchema` should always have been.\n */\nexport const logLinesResponseSchema = type({\n serverId: 'string',\n enabled: 'boolean',\n sizeBytes: 'number',\n /** The rotated files this entry has, newest first. */\n files: 'string[]',\n /** How many lines the search looked at, or null when the request carried no `search`. */\n searched: 'number | null',\n lines: logLineSchema.array(),\n})\n\n/**\n * One server's live resource reading, for `home-hosted usage`.\n *\n * `cpuPercent` and `rssBytes` are `number | null` because a reading can be absent — a process the\n * sampler has not seen yet, or one that just exited. Absent is **not** zero: a `0` here would read as\n * \"idle\" and hide a server that is not being measured at all.\n */\nexport const usageEntrySchema = type({\n 'id': 'string',\n 'workspaceId': 'string',\n 'label': 'string',\n 'status': serverStatusSchema,\n /** Absent when nothing is running or the sampler has no sample yet. */\n 'cpuPercent?': 'number',\n 'rssBytes?': 'number',\n /** Processes in this entry's tree, including an adopted successor's. */\n 'processes?': 'number',\n 'sampledAt?': 'number',\n /**\n * How the entry has behaved over the panel's history window, so `usage` can answer \"is this\n * restarting every few minutes\" and not only \"what is it using right now\". Copied from the same\n * `ServerView.history` the page reads; absent when nothing is known yet.\n */\n 'restarts?': 'number',\n 'crashes?': 'number',\n 'uptimeRatio?': 'number',\n 'lastExitAt?': 'number',\n})\n\nexport const usageViewSchema = type({\n 'servers': usageEntrySchema.array(),\n /** When the host-level sample was taken, so a caller can tell live numbers from a frozen frame. */\n 'sampledAt?': 'number',\n})\n\n/**\n * What a `free-port` attempt did. The pids are reported so the UI can say which\n * process left, and which listeners were deliberately left alone because this\n * panel supervises them.\n */\nexport const freePortResultSchema = type({\n ok: 'boolean',\n port: 'number | null',\n /** Asked to leave with SIGTERM, and the ones that ignored it. */\n terminated: 'number[]',\n forced: 'number[]',\n /** Listeners this panel supervises; never signalled. */\n skipped: 'number[]',\n /** The port answers no more after the attempt. */\n free: 'boolean',\n})\nexport type FreePortResult = typeof freePortResultSchema.infer\n\nexport const logHistoryQuerySchema = type({\n tail: 'string?',\n /**\n * Case-insensitive substring filter. Both this and `stream` are filters, so the route reads a\n * wider window than `tail` and applies them to that: filtering only the display tail would\n * report an older match as \"no results\", and \"the last N stderr lines\" as whatever happened\n * to fall in a window sized for all streams. `searched` reports how many lines were read.\n */\n search: 'string?',\n stream: '\"stdout\" | \"stderr\" | \"system\"?',\n})\n\nexport const logFileInfoSchema = type({\n name: 'string',\n sizeBytes: 'number',\n})\n\nexport const logServerViewSchema = type({\n serverId: 'string',\n label: 'string',\n status: serverStatusSchema,\n enabled: 'boolean',\n sizeBytes: 'number',\n files: logFileInfoSchema.array(),\n})\nexport type LogServerView = typeof logServerViewSchema.infer\n\nexport const logServersViewSchema = type({\n servers: logServerViewSchema.array(),\n})\n\nexport const logHistoryViewSchema = type({\n serverId: 'string',\n enabled: 'boolean',\n sizeBytes: 'number',\n files: type('string[]'),\n /** How many lines the search looked at, or null when not searching. */\n searched: 'number | null',\n lines: logLineSchema.array(),\n})\nexport type LogHistoryView = typeof logHistoryViewSchema.infer\n\nexport const notificationActionSchema = type({\n /** Optional override, so the token can be tried before it is saved. */\n botToken: 'string?',\n chatId: 'string?',\n}).onUndeclaredKey('reject')\n\n/**\n * The `:id` path parameter of a destination route.\n *\n * Validated, because the id is not only a lookup key: it also keys a bot token in the secrets file.\n * Unvalidated, `DELETE /destinations/ghost/token` answered `200`, and an id of `botToken` wrote the\n * literal secrets key `telegram.botToken`, which the reader then took for the **legacy singleton** —\n * every real destination's token became unreachable.\n */\nexport const destinationIdParamSchema = type({\n id: '/^[a-z0-9][a-z0-9_-]*$/',\n})\n\n/**\n * `POST /api/notifications/test-webhook`: the webhook to try, as a draft or by id.\n *\n * The target travels whole because the page tests what is in its form, which may not be saved yet —\n * and the request schema rejects undeclared keys, so the webhook shape is reused rather than a\n * second DTO that could drift from it.\n */\nexport const destinationTestSchema = type({\n target: webhookTargetSchema.omit('kind', 'id').and(type({ id: 'string?', kind: '\"webhook\"?' })),\n /** Echoed so the result is recorded against the right row; absent for a draft. */\n id: 'string?',\n}).onUndeclaredKey('reject')\n\nexport const telegramTokenSchema = type({\n botToken: 'string >= 1',\n}).onUndeclaredKey('reject')\n\n/**\n * The single error envelope every route answers failures with.\n *\n * `detail` is **optional**: `toErrorBody()` omits the key when the error carries none, which is the\n * common case — measured, `/api/logs/ghost`, `/api/servers/ghost` and `/api/settings/ui` all answer\n * `{ message, code }` and nothing else. Requiring it here told every OpenAPI client to expect a field\n * that is usually absent, and disagreed with `ApiErrorBody` in `helpers/error.ts`, which has it\n * optional because that is what it actually serialises.\n */\nexport const apiErrorSchema = type({\n 'message': 'string',\n /** Stable, machine-readable; `AUTH_REQUIRED` also drives the login redirect. */\n 'code': 'string',\n /** Structured context when the failure has any — a field list, the routes holding a certificate. */\n 'detail?': 'unknown',\n})\n\nexport const tlsUploadSchema = type({\n certificate: 'string >= 1',\n privateKey: 'string >= 1',\n}).onUndeclaredKey('reject')\n\n/** `GET /api/settings`: the panel-wide configuration, as Global Settings reads it. */\nexport const settingsViewSchema = type({\n control: controlViewSchema,\n host: hostSchema,\n backups: backupsViewSchema,\n ui: uiStatusSchema,\n}).onDeepUndeclaredKey('ignore')\nexport type SettingsView = typeof settingsViewSchema.infer\n\n/** `PATCH /api/settings` answers with the saved view, plus where the listener lands. */\nexport const settingsSavedSchema = settingsViewSchema.and(type({\n /** The listener is moving; reconnect at `targetUrl` when it stops being null. */\n rebinding: 'boolean',\n targetUrl: 'string | null',\n}))\nexport type SettingsSaved = typeof settingsSavedSchema.infer\n\n/**\n * `GET /api/settings/workspace?workspace=<id>`: what a workspace owns and can\n * change on its own. Global things (listener, auth, host, backups, TLS) are not\n * here — they belong to the panel, not to any workspace.\n */\nexport const workspaceSettingsViewSchema = type({\n id: 'string',\n label: 'string',\n settingsPath: 'string',\n configPath: 'string',\n configError: 'string | null',\n defaults: defaultsSchema,\n logs: logsSchema,\n notifications: notificationViewSchema,\n}).onDeepUndeclaredKey('ignore')\nexport type WorkspaceSettingsView = typeof workspaceSettingsViewSchema.infer\n\nexport const workspaceSettingsSavedSchema = workspaceSettingsViewSchema\n"],"mappings":";;;;;;;;;AAyCA,IAAa,sBAAsB;CAAE,iBAAiB;CAAI,mBAAmB;CAAI,iBAAiB;CAAI,aAAa;AAAG;AAkFtH,IAAM,kBAAgC;CACpC,SAAS;CACT,gBAAgB;CAChB,mBAAmB;CACnB,iBAAiB;CACjB,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,YAAY;CACZ,aAAa;CACb,OAAO,CAAC;CACR,UAAU;CACV,YAAY;CACZ,UAAU;CACV,UAAU;AACZ;;AAGA,SAAS,QAAQ,OAAiD;CAChE,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE;;;;;;;;;;;AAYA,SAAgB,SAAS,YAA2B,aAA2C;CAC7F,OAAO,cAAc,YAAY,aAAA,CAAuC;AAC1E;;;;;;;;;;AAoCA,SAAgB,eAAe,OAAsB,SAA6B,UAA4B;CAC5G,OAAO,cAAc,OAAO,SAAS,QAAQ;AAC/C;AAgCA,SAAS,cAAc,OAAsB,SAA6B,UAA4B;CACpG,IAAI,UAAU,QAAQ,CAAC,OAAO,SAAS,KAAK,GAC1C,OAAO;CAET,MAAM,YAAY,YAAY,KAAA,KAAa,CAAC,OAAO,SAAS,OAAO,IAAI,WAAW;CAClF,IAAI,aAAa,GACf,OAAO;CACT,IAAI,SAAS,WACX,OAAO;CACT,IAAI,SAAS,YAAY,IACvB,OAAO;CACT,OAAO;AACT;;AAGA,SAAgB,aAAa,MAA0D;CACrF,IAAI,SAAS,QAAQ,SAAS,KAAA,GAC5B,OAAO;CAET,IAAI,EADY,KAAK,cAAc,OAEjC,OAAO;EAAE,GAAG;EAAiB,OAAO,CAAC;CAAE;CAGzC,MAAM,SAAS,QAAQ,KAAK,QAAQ,EAAE;CACtC,M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D,IAAa,2BAA2B,KAAK;;CAE3C,UAAU;CACV,QAAQ;AACV,CAAC,CAAC,CAAC,gBAAgB,QAAQ;;;;;;;;;AAU3B,IAAa,2BAA2B,KAAK,EAC3C,IAAI,0BACN,CAAC;;;;;;;;AASD,IAAa,wBAAwB,KAAK;CACxC,QAAQ,oBAAoB,KAAK,QAAQ,IAAI,CAAC,CAAC,IAAI,KAAK;EAAE,IAAI;EAAW,MAAM;CAAa,CAAC,CAAC;;CAE9F,IAAI;AACN,CAAC,CAAC,CAAC,gBAAgB,QAAQ;AAE3B,IAAa,sBAAsB,KAAK,EACtC,UAAU,cACZ,CAAC,CAAC,CAAC,gBAAgB,QAAQ;;;;;;;;;;AAW3B,IAAa,iBAAiB,KAAK;CACjC,WAAW;;CAEX,QAAQ;;CAER,WAAW;AACb,CAAC;AAED,IAAa,kBAAkB,KAAK;CAClC,aAAa;CACb,YAAY;AACd,CAAC,CAAC,CAAC,gBAAgB,QAAQ;;AAG3B,IAAa,qBAAqB,KAAK;CACrC,SAAS;CACT,MAAM;CACN,SAAS;CACT,IAAI;AACN,CAAC,CAAC,CAAC,oBAAoB,QAAQ;;AAI/B,IAAa,sBAAsB,mBAAmB,IAAI,KAAK;;CAE7D,WAAW;CACX,WAAW;AACb,CAAC,CAAC;;;;;;AAQF,IAAa,8BAA8B,KAAK;CAC9C,IAAI;CACJ,OAAO;CACP,cAAc;CACd,YAAY;CACZ,aAAa;CACb,UAAU;CACV,MAAM;CACN,eAAe;AACjB,CAAC,CAAC,CAAC,oBAAoB,QAAQ;AAG/B,IAAa,+BAA+B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"daemon-TwXk5vb8.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'\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 = 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, '/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/**\n * Where a panel is answering, when no `run.json` says it should be — or `null`.\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` had already learned the same lesson (it refuses instead of\n * letting `down && up` start a second panel over a live one). The port comes from the state root's\n * own `settings.json`, because that is the only record left once `run.json` is gone.\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 — a stranger's service on 3999 must not be\n * reported as this panel.\n */\nexport async function configuredPanelAddress(): Promise<string | null> {\n const { readStateFile } = await import('#src/helpers/config-text')\n const { globalSettingsPath } = 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 | null = null\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 return port !== null && await probePort('127.0.0.1', port) ? `http://127.0.0.1:${port}` : null\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, `/_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, 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(runtime: Runtime, 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(`${runtime.probeUrl}${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":";;;;;;;;;;;;;;AAeA,IAAa,gBAAgB,KAAK;CAChC,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;AAG3B,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,CAAC;AACxC;AAEA,SAAgB,WAAmB;CACjC,OAAO,YAAY,EAAE,CAAC,CAAC,SAAS,WAAW;AAC7C;;;;;AAcA,eAAsB,gBAAgB,SAA4C;CAChF,OAAO,MAAM,gBAAgB,QAAQ,KAAK,QAAQ,SAAS;AAC7D;;;;;;;;;;;;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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 +0,0 @@
1
- {"version":3,"file":"docker-CGv4Uv7w.js","names":[],"sources":["../../src/providers/docker.ts"],"sourcesContent":["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 { type } from 'arktype'\n\nconst execFileAsync = promisify(execFile)\n\n/**\n * CPU and memory of a compose project's **containers**, which the process-tree sampler cannot see.\n *\n * A compose stack is not a process tree: `docker compose up` is a wrapper, and its containers live\n * in another namespace. A stack burning 99% CPU reported `cpuPercent: 0` — the wrapper — so\n * `resources.maxRssBytes` could never fire for a leaking container.\n *\n * Detection is deliberately narrow: `command` must be `docker` (with `compose`) or `docker-compose`.\n * A shell that runs docker and a `docker run` are not recognized and keep the process-tree sample,\n * because a wrong guess attributes a stranger's containers to an entry. An entry's own `env` and\n * `envFile` **are** read; the panel's own environment is not. Attribution is by compose's own\n * labels, never \"every container on this machine\".\n *\n * See `.agentDocs/GOTCHAS.md` (\"Metrics\") for the measured failure and the deliberate limits.\n */\n\n/** How long a completed reading is reused. */\nconst DOCKER_CACHE_MS = 10_000\n\n/**\n * `docker stats --no-stream` samples for about a second before printing (measured 2.0–2.2 s per\n * call here), so it is not a read to perform inside the 1 s supervisor tick: it would delay the\n * whole state frame. Nor one per entry per 5 s sample, which is why one call names every container\n * of every docker-backed entry.\n *\n * Reusing a reading for ten seconds keeps the frame responsive and cuts the spawns from roughly\n * 17 000 a day per entry to about 8 600 for the whole workspace; a memory ceiling that acts up to\n * ~12 s late is still a ceiling. The same discipline, and for the same reason, as `SWAP_CACHE_MS`\n * in `src/providers/host.ts`.\n */\n\n/** The file names compose itself tries, in order, in the directory it runs from (or a parent of it). */\nconst COMPOSE_FILES = ['compose.yaml', 'compose.yml', 'docker-compose.yaml', 'docker-compose.yml']\n\n/** A compose global option before the subcommand, whose value is the next word. */\nconst COMPOSE_VALUE_FLAGS = new Set(['-p', '--project-name', '-f', '--file', '--project-directory', '--env-file', '--profile', '--ansi', '--progress', '--parallel'])\n\n/** A compose global option before the subcommand that takes no value. */\nconst COMPOSE_VALUELESS_FLAGS = new Set(['--compatibility', '--dry-run', '--no-ansi', '--verbose', '-h', '--help'])\n\n/** `docker`'s own options before `compose`, whose value is the next word. */\nconst DOCKER_VALUE_FLAGS = new Set(['-c', '--context', '-H', '--host', '-l', '--log-level', '--config'])\n\nconst PS_FORMAT = '{{.ID}}\\t{{.Names}}\\t{{.Label \"com.docker.compose.project\"}}\\t{{.Label \"com.docker.compose.project.config_files\"}}'\n\n/** One container docker reports, with the labels that attribute it to a project. */\nexport interface ContainerRow {\n id: string\n name: string\n project: string | null\n configFiles: string[]\n}\n\n/** What one compose entry's containers add up to. */\nexport interface ComposeReading {\n /** Summed CPU share, so 200 is two saturated cores. */\n cpuPercent: number\n rssBytes: number\n /** Processes inside the containers — the same question the tree sampler answers. */\n processes: number\n /** How many containers the sum covers. */\n containers: number\n}\n\n/** The evidence that an entry runs a compose project, and the key its containers are attributed by. */\nexport interface ComposeTarget {\n /** What the caller looks the reading up by: the project, else the compose files. */\n key: string\n project: string | null\n configFiles: string[]\n}\n\nconst EMPTY: ReadonlyMap<string, ComposeReading> = new Map()\n\n/** One `docker stats --format json` line. Unknown keys are normal — docker adds fields over time. */\nconst statsLineSchema = type({\n 'CPUPerc': 'string',\n 'ID': 'string',\n 'MemUsage': 'string',\n 'PIDs': 'string',\n '+': 'ignore',\n})\n\nconst BYTE_SCALES: Record<string, number> = {\n b: 1,\n kb: 1000,\n kib: 1024,\n mb: 1000 ** 2,\n mib: 1024 ** 2,\n gb: 1000 ** 3,\n gib: 1024 ** 3,\n tb: 1000 ** 4,\n tib: 1024 ** 4,\n}\n\n/** `816KiB` -> bytes. Docker prints binary units for memory, and `0B` for a container that is not running. */\nexport function parseHumanBytes(value: string): number | null {\n const match = /^([\\d.]+)\\s*([a-z]+)$/i.exec(value.trim())\n if (match === null)\n return null\n const amount = Number.parseFloat(match[1]!)\n const scale = BYTE_SCALES[match[2]!.toLowerCase()]\n if (scale === undefined || !Number.isFinite(amount))\n return null\n return amount * scale\n}\n\n/** `MemUsage` is `used / limit`; only the used part measures this stack. */\nexport function parseMemUsage(value: string): number | null {\n const [used = ''] = value.split('/')\n return parseHumanBytes(used)\n}\n\n/** `99.61%` -> 99.61. `--` is docker's \"no reading\", which must not become a zero. */\nexport function parsePercent(value: string): number | null {\n const match = /^([\\d.]+)%$/.exec(value.trim())\n if (match === null)\n return null\n const parsed = Number.parseFloat(match[1]!)\n return Number.isFinite(parsed) ? parsed : null\n}\n\n/** The containers docker reports, from the tab-separated `--format` above. */\nexport function parseDockerPs(text: string): ContainerRow[] {\n const rows: ContainerRow[] = []\n for (const line of text.split(/\\r?\\n/)) {\n if (line.trim().length === 0)\n continue\n const [id = '', name = '', project = '', files = ''] = line.split('\\t')\n if (id.trim().length === 0)\n continue\n rows.push({\n id: id.trim(),\n name: name.trim(),\n project: project.trim().length > 0 ? project.trim() : null,\n configFiles: files.split(',').map(entry => entry.trim()).filter(entry => entry.length > 0),\n })\n }\n return rows\n}\n\n/** Per-container readings from `docker stats --no-stream --format json`, keyed by container id. */\nexport function parseDockerStats(text: string): Map<string, Omit<ComposeReading, 'containers'>> {\n const readings = new Map<string, Omit<ComposeReading, 'containers'>>()\n for (const line of text.split(/\\r?\\n/)) {\n if (line.trim().length === 0)\n continue\n let raw: unknown\n try {\n raw = JSON.parse(line)\n }\n catch {\n continue\n }\n const parsed = statsLineSchema(raw)\n if (parsed instanceof type.errors)\n continue\n const cpuPercent = parsePercent(parsed.CPUPerc)\n const rssBytes = parseMemUsage(parsed.MemUsage)\n const processes = Number.parseInt(parsed.PIDs, 10)\n // One unreadable field makes the container unmeasured; a zero there would be invented.\n if (cpuPercent === null || rssBytes === null || !Number.isInteger(processes))\n continue\n /*\n * A container with no processes is not idle — it is not running this stack's work.\n *\n * `docker stats` prints `0.00% / 0B / 0 PIDs` for one in `Restarting`, and publishing that is\n * the zero the repo forbids: measured, a flapping entry served `hh_server_rss_bytes 0` and\n * `hh_server_cpu_percent 0`, steady while reported `running`, indistinguishable from a real\n * idle reading and structurally unable to trip `resources.maxRssBytes`. `PIDs 0` is the one\n * field that says so — a live container always has at least one.\n */\n if (processes === 0)\n continue\n // Docker prints a rounded human size (`1.035MiB`), so the byte value is fractional; rounded to\n // a whole byte here, so every reading has the same unit whatever produced it.\n readings.set(parsed.ID, { cpuPercent, rssBytes: Math.round(rssBytes), processes })\n }\n return readings\n}\n\n/** Same file, on a platform whose paths are case-insensitive. */\nfunction samePath(left: string, right: string): boolean {\n const a = path.resolve(left)\n const b = path.resolve(right)\n return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b\n}\n\n/** The argv of the compose command this entry runs, or null when the entry is not docker-backed. */\nfunction composeArgv(command: string, args: string[]): string[] | null {\n const name = path.basename(command).toLowerCase().replace(/\\.exe$/, '')\n if (name === 'docker-compose')\n return args\n if (name !== 'docker')\n return null\n\n for (let index = 0; index < args.length; index++) {\n const arg = args[index]!\n if (arg === 'compose')\n return args.slice(index + 1)\n if (arg.startsWith('-')) {\n // `docker --context box compose up`: the flag's value is not the subcommand.\n if (DOCKER_VALUE_FLAGS.has(arg) && !arg.includes('='))\n index += 1\n continue\n }\n // A different docker subcommand, so there is no compose project behind this entry.\n return null\n }\n return null\n}\n\n/**\n * The compose options before the subcommand, and where the subcommand starts.\n *\n * Compose requires its global options **before** the subcommand — it answers `unknown shorthand\n * flag: 'p'` for `up -p x` — so only this leading run can carry the project name or the file.\n */\nexport function parseComposeHead(args: string[]): {\n subcommandAt: number\n projectName: string | null\n files: string[]\n projectDirectory: string | null\n} {\n const result = { subcommandAt: args.length, projectName: null as string | null, files: [] as string[], projectDirectory: null as string | null }\n\n for (let index = 0; index < args.length; index++) {\n const arg = args[index]!\n if (!arg.startsWith('-')) {\n result.subcommandAt = index\n return result\n }\n // `--file=compose.yml` and the short attached `-fcompose.yml` / `-pblog` forms.\n if (arg.startsWith('--') && arg.includes('=')) {\n const [flag, value = ''] = [arg.slice(0, arg.indexOf('=')), arg.slice(arg.indexOf('=') + 1)]\n if (flag === '--project-name' || flag === '--file' || flag === '--project-directory') {\n if (flag === '--project-name')\n result.projectName = value\n else if (flag === '--file')\n result.files.push(value)\n else result.projectDirectory = value\n }\n continue\n }\n if (!arg.startsWith('--') && arg.length > 2 && COMPOSE_VALUE_FLAGS.has(arg.slice(0, 2))) {\n const value = arg.slice(2)\n if (arg.startsWith('-p'))\n result.projectName = value\n else if (arg.startsWith('-f'))\n result.files.push(value)\n continue\n }\n\n if (COMPOSE_VALUELESS_FLAGS.has(arg))\n continue\n if (!COMPOSE_VALUE_FLAGS.has(arg))\n // An option this does not know: it still takes no *subcommand* position, so keep scanning.\n continue\n\n const value = args[index + 1]\n if (value === undefined)\n return result\n index += 1\n if (arg === '-p' || arg === '--project-name')\n result.projectName = value\n else if (arg === '-f' || arg === '--file')\n result.files.push(value)\n else if (arg === '--project-directory')\n result.projectDirectory = value\n }\n\n return result\n}\n\n/** The compose file compose would pick: the first known name here or in a parent directory. */\nexport function findComposeFile(from: string): string[] {\n let dir = path.resolve(from)\n for (;;) {\n for (const name of COMPOSE_FILES) {\n const candidate = path.join(dir, name)\n try {\n if (fs.statSync(candidate).isFile())\n return [candidate]\n }\n catch {\n // Not this name.\n }\n }\n const parent = path.dirname(dir)\n if (parent === dir)\n return []\n dir = parent\n }\n}\n\n/** Whether this argv runs a compose stack, without resolving anything — a cheap pre-check. */\nexport function isComposeCommand(command: string, args: string[]): boolean {\n return composeArgv(command, args) !== null\n}\n\n/**\n * The compose project an entry runs, from evidence in its own config: the command it spawns, its\n * argv, its cwd and its environment. `null` means \"sample the process tree\", which is the right\n * answer for every entry this cannot attribute honestly — see the module comment for the limits.\n */\nexport function composeTarget(input: {\n command: string\n args: string[]\n cwd: string\n env?: Record<string, string | undefined>\n}): ComposeTarget | null {\n const composeArgs = composeArgv(input.command, input.args)\n if (composeArgs === null)\n return null\n\n const head = parseComposeHead(composeArgs)\n /*\n * The entry's own environment only — **not** `process.env`.\n *\n * The panel itself often runs under compose, and inheriting its `COMPOSE_PROJECT_NAME` made that\n * one name every entry's project: measured with two entries and the panel's env carrying\n * `COMPOSE_PROJECT_NAME=shared-stack`, both reported `cpuPercent: 199.4, rssBytes: 183500800` —\n * each summing both stacks — and a memory ceiling on one fired on the other's containers. The\n * panel's environment is not the entry's.\n */\n const project = head.projectName\n ?? (input.env?.COMPOSE_PROJECT_NAME !== undefined && input.env.COMPOSE_PROJECT_NAME.length > 0\n ? input.env.COMPOSE_PROJECT_NAME\n : null)\n\n const directory = head.projectDirectory === null ? input.cwd : path.resolve(input.cwd, head.projectDirectory)\n const configFiles = head.files.length > 0\n ? head.files.map(file => path.resolve(directory, file))\n : findComposeFile(directory)\n\n if (project === null && configFiles.length === 0)\n // Neither label to attribute by: these containers cannot be told from the rest of the box's.\n return null\n\n return { key: project === null ? `files:${configFiles.join('\\u0000')}` : `project:${project}`, project, configFiles }\n}\n\n/**\n * The containers belonging to one target, or `null` when that cannot be decided.\n *\n * `null` is the ambiguity refusal: two projects sharing a compose file can only be told apart by an\n * explicit project name, so picking one would report another stack's CPU and RSS as this entry's.\n */\nexport function attributeContainers(target: ComposeTarget, rows: ContainerRow[]): ContainerRow[] | null {\n if (target.project !== null)\n return rows.filter(row => row.project === target.project)\n\n const matched = rows.filter(row => row.configFiles.some(file => target.configFiles.some(own => samePath(file, own))))\n const projects = new Set(matched.map(row => row.project))\n return projects.size <= 1 ? matched : null\n}\n\n/**\n * The sum over one project's containers.\n *\n * Exported so the arithmetic is testable against the shapes docker actually prints; the class below\n * only decides when to spawn. `null` for no containers, and for a listed container without a\n * reading — an under-report is the one direction a memory ceiling must not miss.\n */\nexport function sumContainers(rows: ContainerRow[], readings: Map<string, Omit<ComposeReading, 'containers'>>): ComposeReading | null {\n if (rows.length === 0)\n return null\n let cpuPercent = 0\n let rssBytes = 0\n let processes = 0\n for (const row of rows) {\n const reading = readings.get(row.id)\n if (reading === undefined)\n return null\n cpuPercent += reading.cpuPercent\n rssBytes += reading.rssBytes\n processes += reading.processes\n }\n return {\n cpuPercent: Math.round(cpuPercent * 10) / 10,\n rssBytes: Math.round(rssBytes),\n processes,\n containers: rows.length,\n }\n}\n\n/** Whether a container publishing a port belongs to the stack this entry itself declares. */\nexport function isOwnStack(holder: { project: string | null, composeDir: string | null }, target: ComposeTarget | null): boolean {\n if (target === null)\n return false\n // A non-null project on both sides is the exact answer, and `null === null` must not read as one.\n if (holder.project !== null && target.project !== null)\n return holder.project === target.project\n // Otherwise the working directory compose recorded is the one holding this entry's compose file.\n // Most entries never pass `-p`, so the project name is unknown on both sides and the directory is\n // the evidence that remains — measured: without this, an entry's own already-up stack read as a\n // stranger, and the only escape hatch offered was `kill`.\n if (holder.composeDir === null)\n return false\n return target.configFiles.some(file => samePath(path.dirname(file), holder.composeDir!))\n}\n\n/** One target's running containers from a fresh `docker ps`, or `null` when docker cannot answer. */\nexport async function composeContainers(target: ComposeTarget): Promise<ContainerRow[] | null> {\n try {\n const listing = await execFileAsync('docker', [\n 'ps',\n '--filter',\n 'label=com.docker.compose.project',\n '--format',\n PS_FORMAT,\n ], { timeout: 5000, maxBuffer: 4 * 1024 * 1024 })\n return attributeContainers(target, parseDockerPs(listing.stdout))\n }\n catch {\n // Docker absent, down or not permissioned. \"Cannot ask\" is not \"nothing is running\".\n return null\n }\n}\n\n/**\n * Stops every container of one target and reports what is still running afterwards.\n *\n * The answer comes from a **fresh listing**, not from `docker stop`'s exit code: a stop that\n * printed success for a container still listed is the empty success this exists to refuse.\n * `null` means docker could not be asked, which is not the same as \"it stopped\".\n */\nexport async function stopComposeContainers(target: ComposeTarget): Promise<{ stopped: string[], survivors: string[] } | null> {\n const before = await composeContainers(target)\n if (before === null)\n return null\n if (before.length === 0)\n return { stopped: [], survivors: [] }\n\n try {\n await execFileAsync('docker', ['stop', ...before.map(row => row.name)], { timeout: 120_000, maxBuffer: 4 * 1024 * 1024 })\n }\n catch {\n // A non-zero exit only means one name failed; the relisting below is what decides.\n }\n\n const after = await composeContainers(target)\n if (after === null)\n return null\n const remaining = new Set(after.map(row => row.name))\n return {\n stopped: before.map(row => row.name).filter(name => !remaining.has(name)),\n survivors: after.map(row => row.name),\n }\n}\n\n/**\n * Container readings per compose project, refreshed out of band.\n *\n * One `docker ps` and one batched `docker stats` serve every docker-backed entry, however many\n * there are. When docker cannot be reached the cache is emptied rather than filled with zeros: the\n * caller keeps the process-tree sample, which is at least true of the wrapper, and a metric with no\n * reading is never published as an idle one.\n */\nexport class DockerMetrics {\n private cache: { at: number, byKey: Map<string, ComposeReading> } | null = null\n private refreshing: Promise<void> | null = null\n\n /**\n * The last completed readings, and a refresh started when they are stale.\n *\n * Deliberately synchronous: the spawn takes seconds, and awaiting it here would stretch the\n * supervisor tick that publishes the whole state frame. A fresh reading lands on a later tick.\n */\n readings(targets: ComposeTarget[], now = Date.now()): ReadonlyMap<string, ComposeReading> {\n // A stamp in the future (a backwards clock step) counts as stale, so a reading cannot stick.\n const fresh = this.cache !== null && now >= this.cache.at && now - this.cache.at < DOCKER_CACHE_MS\n if (!fresh && targets.length > 0 && this.refreshing === null) {\n this.refreshing = this.refresh(targets, now).finally(() => {\n this.refreshing = null\n })\n }\n return this.cache?.byKey ?? EMPTY\n }\n\n /** Resolves once the refresh in flight, if any, has finished. */\n async settle(): Promise<void> {\n await this.refreshing\n }\n\n /** One listing and one batched stats call; replaces the cache only with a complete answer. */\n async refresh(targets: ComposeTarget[], now = Date.now()): Promise<void> {\n const byKey = new Map<string, ComposeReading>()\n try {\n const listing = await execFileAsync('docker', [\n 'ps',\n // A compose container is the only kind this can attribute, and the filter also keeps a box\n // full of `docker run` containers out of the listing.\n '--filter',\n 'label=com.docker.compose.project',\n '--format',\n PS_FORMAT,\n ], { timeout: 5000, maxBuffer: 4 * 1024 * 1024 })\n\n const rows = parseDockerPs(listing.stdout)\n const perTarget = new Map<string, ContainerRow[]>()\n const ids = new Set<string>()\n for (const target of targets) {\n const matched = attributeContainers(target, rows)\n // No running container of this project: there is nothing of the stack to measure, and the\n // wrapper the entry spawned is the truth of what is running. The caller keeps its sample.\n if (matched === null || matched.length === 0)\n continue\n perTarget.set(target.key, matched)\n for (const row of matched) ids.add(row.id)\n }\n if (ids.size === 0) {\n this.cache = { at: now, byKey }\n return\n }\n\n const stats = await execFileAsync('docker', ['stats', '--no-stream', '--format', 'json', ...ids], {\n timeout: 15_000,\n maxBuffer: 8 * 1024 * 1024,\n })\n const readings = parseDockerStats(stats.stdout)\n for (const [key, matched] of perTarget) {\n // A partial sum is not a smaller reading, it is a wrong one; only complete sums are kept.\n const summed = sumContainers(matched, readings)\n if (summed !== null)\n byKey.set(key, summed)\n }\n }\n catch {\n // docker absent, not running or not permissioned: no reading, never a zero.\n byKey.clear()\n }\n this.cache = { at: now, byKey }\n }\n}\n"],"mappings":";;;;;;;AAOA,IAAM,gBAAgB,UAAU,QAAQ;;;;;;;;;;;;;;;;;AAmBxC,IAAM,kBAAkB;;;;;;;;;;;;;AAexB,IAAM,gBAAgB;CAAC;CAAgB;CAAe;CAAuB;AAAoB;;AAGjG,IAAM,sCAAsB,IAAI,IAAI;CAAC;CAAM;CAAkB;CAAM;CAAU;CAAuB;CAAc;CAAa;CAAU;CAAc;AAAY,CAAC;;AAGpK,IAAM,0CAA0B,IAAI,IAAI;CAAC;CAAmB;CAAa;CAAa;CAAa;CAAM;AAAQ,CAAC;;AAGlH,IAAM,qCAAqB,IAAI,IAAI;CAAC;CAAM;CAAa;CAAM;CAAU;CAAM;CAAe;AAAU,CAAC;AAEvG,IAAM,Y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,QAAQ,SAA0B,MAAM,KAAK,IAAI,GAAkB;EACvE,MAAM,wBAAQ,IAAI,IAA4B;EAC9C,IAAI;GAWF,MAAM,OAAO,eAAc,MAVL,cAAc,UAAU;IAC5C;IAGA;IACA;IACA;IACA;GACF,GAAG;IAAE,SAAS;IAAM,WAAW;GAAgB,CAAC,EAAA,CAEb,MAAM;GACzC,MAAM,4BAAY,IAAI,IAA4B;GAClD,MAAM,sBAAM,IAAI,IAAY;GAC5B,KAAK,MAAM,UAAU,SAAS;IAC5B,MAAM,UAAU,oBAAoB,QAAQ,IAAI;IAGhD,IAAI,YAAY,QAAQ,QAAQ,WAAW,GACzC;IACF,UAAU,IAAI,OAAO,KAAK,OAAO;IACjC,KAAK,MAAM,OAAO,SAAS,IAAI,IAAI,IAAI,EAAE;GAC3C;GACA,IAAI,IAAI,SAAS,GAAG;IAClB,KAAK,QAAQ;KAAE,IAAI;KAAK;IAAM;IAC9B;GACF;GAMA,MAAM,WAAW,kBAAiB,MAJd,cAAc,UAAU;IAAC;IAAS;IAAe;IAAY;IAAQ,GAAG;GAAG,GAAG;IAChG,SAAS;IACT,WAAW;GACb,CAAC,EAAA,CACuC,MAAM;GAC9C,KAAK,MAAM,CAAC,KAAK,YAAY,WAAW;IAEtC,MAAM,SAAS,cAAc,SAAS,QAAQ;IAC9C,IAAI,WAAW,MACb,MAAM,IAAI,KAAK,MAAM;GACzB;EACF,QACM;GAEJ,MAAM,MAAM;EACd;EACA,KAAK,QAAQ;GAAE,IAAI;GAAK;EAAM;CAChC;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"down-BlX5X3bm.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 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 = { 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 !== null) {\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(`something is already answering on ${leftover}, 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 // Persistent entries are still the thing easiest to forget, so their report still runs.\n return finish()\n }\n process.stdout.write('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 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":";;;;;;;;AA8BA,eAAsB,QAAQ,UAAuB,CAAC,GAAwB;CAC5E,MAAM,EAAE,cAAc,wBAAwB,gBAAgB,aAAa,iBAAiB,oBAAoB,MAAM,OAAO;CAE7H,MAAM,SAAqB,EAAE,mBAAmB,CAAC,EAAE;CAInD,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,aAAa,MAAM;GAGrB,QAAQ,qCAAqC,SAAS,oGAAoG,WAAW,EAAE,MAAM;GAC7K,QAAQ,WAAW;GAEnB,OAAO,OAAO;EAChB;EACA,QAAQ,OAAO,MAAM,8BAA8B;EAGnD,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,OAAO;CAChB;;CAGA,MAAM,iBAAiB,WAA0B;EAC/C,QAAQ,OAAO,MAAM,GAAG,MAAM,SAAS,IAAI,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sourcesContent":["import type { Stats } from 'node:fs'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { shellQuote } from '#src/helpers/shell'\nimport { appVersion } from '#src/helpers/version'\n\nexport type PackageManager = 'pnpm' | 'npm' | 'yarn' | 'bun'\n\nexport interface InitOptions {\n dir: string\n name: string\n pm: PackageManager\n install: boolean\n git: boolean\n}\n\nexport interface InitResult {\n dir: string\n created: boolean\n files: string[]\n installed: boolean\n git: boolean\n}\n\n/** The scripts every scaffolded project gets; all of them keep state inside the project. */\nexport function projectScripts(): Record<string, string> {\n const withState = (args: string): string => `home-hosted ${args} --home ./state`\n return {\n 'up': withState('up'),\n 'down': withState('down'),\n 'restart': withState('restart'),\n 'status': withState('status'),\n 'set-password': withState('set-password'),\n 'set-token': withState('set-token'),\n 'migrate': withState('migrate'),\n }\n}\n\n/** `home-hosted` is pinned to the version that wrote the project, and open to newer ones. */\nexport function projectManifest(name: string): string {\n return `${JSON.stringify({\n name,\n version: '0.1.0',\n private: true,\n description: 'Servers supervised by home-hosted.',\n type: 'module',\n engines: { node: '>=24.0.0' },\n scripts: projectScripts(),\n dependencies: { 'home-hosted': `^${appVersion()}` },\n }, null, 2)}\\n`\n}\n\n/**\n * State is generated, so it stays out. The workspace definitions worth committing\n * (`.hh/settings.json`, `.hh/workspaces.json`, and each workspace's\n * `settings.json` + `servers.config.json`) are un-ignored explicitly.\n */\nexport function projectGitignore(): string {\n // `state/.hh/*` excludes the workspace *directories*, and git will not descend into\n // an excluded directory — so the file-level negations below can never match unless\n // the directories themselves are un-ignored first. Without `!state/.hh/*/` the\n // workspace definitions stayed out of the very repo this scaffold creates.\n return `node_modules/\n\n# home-hosted: state is local, the workspace definitions are tracked\nstate/.hh/*\n!state/.hh/settings.json\n!state/.hh/workspaces.json\nstate/.hh/*/*\n!state/.hh/*/\n!state/.hh/*/settings.json\n!state/.hh/*/servers.config.json\ndata/\n`\n}\n\nexport function isEmptyDir(dir: string): boolean {\n try {\n return fs.readdirSync(dir).every(entry => entry === '.git')\n }\n catch {\n return true\n }\n}\n\nfunction assertUsableDir(dir: string): void {\n let stats: Stats | null = null\n try {\n stats = fs.statSync(dir)\n }\n catch {\n return\n }\n if (!stats.isDirectory())\n throw new Error(`${dir} exists and is not a directory`)\n if (!isEmptyDir(dir))\n throw new Error(`${dir} is not empty — pick another directory, or empty it first`)\n}\n\n/** Writes the project skeleton. Nothing is installed or initialized here. */\nexport function scaffold(options: InitOptions): InitResult {\n const dir = path.resolve(options.dir)\n assertUsableDir(dir)\n\n const existed = fs.existsSync(dir)\n fs.mkdirSync(dir, { recursive: true })\n\n const files: Array<[string, string]> = [\n ['package.json', projectManifest(options.name)],\n ['.gitignore', projectGitignore()],\n ]\n for (const [name, contents] of files)\n fs.writeFileSync(path.join(dir, name), contents)\n\n return {\n dir,\n created: !existed,\n files: files.map(([name]) => name),\n installed: false,\n git: false,\n }\n}\n\nexport const PACKAGE_MANAGERS: PackageManager[] = ['pnpm', 'npm', 'yarn', 'bun']\n\n/** The package manager this machine actually has, preferring pnpm. */\nexport function detectPackageManager(exists: (command: string) => boolean): PackageManager {\n const found = PACKAGE_MANAGERS.find(pm => exists(pm))\n return found ?? 'npm'\n}\n\n/** How to run one of the project's scripts with a given package manager. */\nexport function runCommand(pm: PackageManager, script: string): string {\n return pm === 'npm' ? `npm run ${script}` : `${pm} run ${script}`\n}\n\n/**\n * One line of `init`'s \"Next:\" block. A step is either a command to type or a prose line beneath\n * the one above it, and the two are kept apart so the block can be asserted without a terminal.\n */\nexport interface NextStep {\n /** The command, already `cd`-prefixed; `null` when the line is prose about the step above. */\n command: string | null\n /** What the command does, or the prose itself. */\n text: string\n}\n\n/**\n * What `init` hands the person once the project is written.\n *\n * Built here rather than printed inline for two reasons, both measured. The install step was\n * missing under `--no-install`, so the scripts it went on to name answered `home-hosted: command\n * not found` (npm exits 127) — the one sequence the scaffold exists to hand over, broken at step\n * one. And the password hint named a page the UI does not have: the sidebar entry is **Global\n * settings**, and \"Settings → Authentication\" names nothing a person can click.\n */\nexport function nextSteps(pm: PackageManager, install: boolean, cd: string): NextStep[] {\n // The block is a sequence a person walks down, so `cd` belongs on the first command only: the\n // reader arrives in the project once and every later line runs from there.\n const steps: NextStep[] = []\n const lead = (command: string): string => (steps.length === 0 ? `${cd}${command}` : command)\n\n // The dependency has to exist before any of the project's scripts resolve: `pnpm run up` shells\n // out to `node_modules/.bin/home-hosted`, which `--no-install` deliberately leaves absent.\n if (!install)\n steps.push({ command: lead(installCommand(pm)), text: 'install the dependency' })\n steps.push({ command: lead(runCommand(pm, 'up')), text: 'start the panel (default password `hh`)' })\n steps.push({ command: null, text: 'then change that password under Global settings → Authentication, and add your servers' })\n steps.push({ command: `${runCommand(pm, 'set-token')} --generate`, text: 'for scripts and agents' })\n return steps\n}\n\n/**\n * The `cd` that reaches a scaffolded project, quoted for the shell it will be pasted into.\n *\n * The quoting rule is `shellQuote` (`helpers/shell.ts`), shared with every other string this\n * package prints for a person to copy: `init` printed `cd my servers && npm run up` for a directory\n * with a space, which the shell answers `cd: too many arguments` — an error naming a command the\n * person did not compose, on the one line the scaffold exists to hand them over.\n */\nexport function cdCommand(where: string): string {\n return `cd ${shellQuote(where)} && `\n}\n\n/** Install arguments for a scaffolded project (the manifest already lists the dependency). */\nexport function installArgs(pm: PackageManager): string[] {\n return pm === 'yarn' ? [] : ['install']\n}\n\n/**\n * The install command as a person types it — `pnpm install`, `yarn` with no argument.\n *\n * Distinct from `runCommand`, which runs one of the project's **scripts**: `npm run install` is not\n * an install, it is a script named `install` that this manifest does not declare.\n */\nexport function installCommand(pm: PackageManager): string {\n return [pm, ...installArgs(pm)].join(' ')\n}\n","import { spawnSync } from 'node:child_process'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { defineCommand } from 'citty'\nimport { bold, confirm, dim, fail, green, paint, prompt } from '#src/cli/io'\nimport { cdCommand, detectPackageManager, installArgs, nextSteps, PACKAGE_MANAGERS, scaffold } from '#src/services/init'\nimport { errorMessage } from '#src/shared/error-message'\n\n/**\n * `init` scaffolds a project that keeps its whole setup — state, data and the\n * server definitions — inside its own directory. Interactive by nature, but\n * `--yes` takes every default so an agent or a CI job can run it unattended.\n */\n\nexport const initArgs = {\n dir: { type: 'string', description: 'where to scaffold (default: ./my-servers)' },\n name: { type: 'string', description: 'package name (default: the directory name)' },\n pm: { type: 'string', description: 'pnpm | npm | yarn | bun (default: the first one installed)' },\n install: { type: 'boolean', default: true, negativeDescription: 'write the files, install nothing' },\n yes: { type: 'boolean', alias: 'y', description: 'take every default, ask nothing' },\n} as const\n\nfunction which(command: string): boolean {\n const probe = spawnSync(command, ['--version'], { stdio: 'ignore', shell: process.platform === 'win32' })\n return probe.status === 0\n}\n\nexport async function runInit(options: { dir?: string, name?: string, pm?: string, noInstall: boolean, yes: boolean }): Promise<void> {\n const assumeYes = options.yes\n if (!assumeYes && process.stdin.isTTY !== true) {\n fail('init needs a terminal to ask in.\\n take the defaults with: home-hosted init --yes [--dir <dir>]')\n }\n\n const defaultDir = options.dir ?? './my-servers'\n const dir = assumeYes ? defaultDir : (await prompt(`Project directory (${defaultDir}) `)).trim() || defaultDir\n const defaultName = path.basename(path.resolve(dir))\n const name = options.name ?? (assumeYes ? defaultName : (await prompt(`Package name (${defaultName}) `)).trim() || defaultName)\n\n let pm = options.pm\n if (pm !== undefined && !(PACKAGE_MANAGERS as string[]).includes(pm))\n fail(`unknown package manager: ${pm} (expected one of ${PACKAGE_MANAGERS.join(', ')})`)\n const detected = detectPackageManager(which)\n if (pm === undefined)\n pm = assumeYes ? detected : (await prompt(`Package manager (${detected}) `)).trim() || detected\n\n const install = options.noInstall\n ? false\n : assumeYes || (await confirm('Install the dependencies now?', true))\n const git = assumeYes ? which('git') : which('git') && (await confirm('Initialize a git repository?', true))\n\n try {\n const result = scaffold({ dir, name, pm: pm as never, install, git })\n process.stdout.write(`${green('project created')} in ${result.dir}\\n`)\n for (const file of result.files)\n process.stdout.write(` ${dim(file)}\\n`)\n }\n catch (error) {\n fail(errorMessage(error))\n }\n\n const target = path.resolve(dir)\n if (git) {\n spawnSync('git', ['init', '-q'], { cwd: target, stdio: 'inherit', shell: process.platform === 'win32' })\n process.stdout.write(` ${dim('git repository initialized')}\\n`)\n }\n\n if (install) {\n process.stdout.write(`${dim(`installing with ${pm}…`)}\\n`)\n const result = spawnSync(pm as string, installArgs(pm as never), {\n cwd: target,\n stdio: 'inherit',\n shell: process.platform === 'win32',\n })\n if (result.status !== 0) {\n process.stdout.write(`${paint('33', 'install failed')} — run it yourself in ${target}\\n`)\n }\n }\n\n // A path inside the working directory reads better relative; anything else absolute.\n const relative = path.relative(process.cwd(), target)\n const where = relative.length === 0 || relative.startsWith('..') ? target : relative\n const cd = relative.length === 0 ? '' : cdCommand(where)\n process.stdout.write(`\\nNext:\\n`)\n for (const step of nextSteps(pm as never, install, cd)) {\n if (step.command === null) {\n process.stdout.write(` ${dim(step.text)}\\n`)\n continue\n }\n // The command is the bold half; the line's own explanation keeps its place beside it.\n const padding = ' '.repeat(5)\n process.stdout.write(` ${bold(step.command)}${padding}${step.text}\\n`)\n }\n}\n\nexport const initCommand = defineCommand({\n meta: { name: 'init' },\n args: initArgs,\n run: async ({ args }) => {\n await runInit({\n dir: args.dir,\n name: args.name,\n pm: args.pm,\n noInstall: args.install === false,\n yes: args.yes === true,\n })\n },\n})\n"],"mappings":";;;;;;;;AAyBA,SAAgB,iBAAyC;CACvD,MAAM,aAAa,SAAyB,eAAe,KAAK;CAChE,OAAO;EACL,MAAM,UAAU,IAAI;EACpB,QAAQ,UAAU,MAAM;EACxB,WAAW,UAAU,SAAS;EAC9B,UAAU,UAAU,QAAQ;EAC5B,gBAAgB,UAAU,cAAc;EACxC,aAAa,UAAU,WAAW;EAClC,WAAW,UAAU,SAAS;CAChC;AACF;;AAGA,SAAgB,gBAAgB,MAAsB;CACpD,OAAO,GAAG,KAAK,UAAU;EACvB;EACA,SAAS;EACT,SAAS;EACT,aAAa;EACb,MAAM;EACN,SAAS,EAAE,MAAM,WAAW;EAC5B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