home-hosted 0.9.7 → 0.9.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -738,7 +738,7 @@ function duplicateWebhookIds(targets) {
738
738
  }
739
739
  return [...duplicates];
740
740
  }
741
- var bindSchema, workspaceIdSchema, workspaceSchema, workspaceCreateSchema, workspaceRenameSchema, portSchema, onPortConflictSchema, onPortConflictDefaultSchema, restartSchema, httpCheckSchema, resourcesSchema, healthSchema, stopSchema, bootstrapSchema, bootstrapOrNullSchema, backupHookSchema, backupHookOrNullSchema, labelOrNullSchema, logBufferLinesSchema, serverSchema, authSchema, notificationPolicyShape, notificationDefaultsSchema, notificationDefaultsViewSchema, useOwnSettingsSchema, telegramDestinationSchema, webhookTargetSchema, notificationTargetSchema, destinationListSchema, notificationsSchema, logsSchema, tlsSchema, hostSchema, ddnsRecordTypeSchema, ddnsAccountSchema, ddnsDomainSchema, ddnsIpv4Schema, ddnsIpv6Schema, ddnsConfigSchema, ddnsRecordStateSchema, ddnsRecordViewSchema, ddnsStatusSchema, ddnsProviderFieldSchema, ddnsProviderInfoSchema, ddnsViewSchema, ddnsCredentialsSchema, backupScheduleSchema, backupsSchema, controlSchema, defaultsSchema, restartPatchSchema, httpCheckPatchSchema, resourcesPatchSchema, healthPatchSchema, stopPatchSchema, authPatchSchema, notificationPolicyPatchShape, destinationPatchSchema, notificationsPatchSchema, hostPatchSchema, backupSchedulePatchSchema, backupsPatchSchema, logsPatchSchema, tlsPatchSchema, controlPatchSchema, defaultsPatchSchema, editableFields, serverPatchSchema, serverCreateSchema, nannySpecSchema, nannyExitSchema, nannyStateSchema, entryStateSchema, settingsPatchSchema, workspaceSettingsPatchSchema, authStatusSchema, tlsStatusSchema, proxyEngineSchema, proxyTargetSchema, proxyTlsModeSchema, proxyRouteSchema, proxyCertificateSchema, proxyCertificateStateSchema, proxyDns01Schema, proxyConfigSchema, proxyEngineSourceSchema, proxyEngineStatusSchema, proxyEngineInfoSchema, proxyRouteStatusSchema, proxyRouteViewSchema, proxyRunStateSchema, proxyStatusSchema, proxyCertificateViewSchema, proxyDnsAccountViewSchema, proxyViewSchema, proxyRoutePatchSchema, proxyPatchSchema, proxyCertificateUploadSchema, proxyEngineInstallSchema, notificationPolicyStatusShape, destinationStatusSchema, telegramChatsSchema, notificationViewSchema, sessionViewSchema, loginSchema, passwordValueSchema, passwordSchema, serverStatusSchema, healthStateSchema, portStateSchema, logStreamSchema, logLineSchema, historyActorSchema, historyEventSchema, serverHistorySchema, processResourcesSchema, hostDiskSchema, hostViewSchema, backupFileSchema, backupEntrySchema, backupsViewSchema, restoreItemSchema, restoreSkipSchema, restorePlanSchema, backupCreateSchema, restoreRequestSchema, serverViewSchema, healthResponseSchema, controlViewSchema, uiMetaSchema, uiStatusSchema, serverOrphanSchema, workspaceViewSchema, appStateSchema, logQuerySchema, actionResultSchema, deliveryResultSchema, passwordSetResponseSchema, tlsReviewResponseSchema, okResponseSchema, backupFilesResponseSchema, uiInstallResponseSchema, backupCreatedResponseSchema, logLinesResponseSchema, freePortResultSchema, logHistoryQuerySchema, logFileInfoSchema, logServerViewSchema, logServersViewSchema, notificationActionSchema, destinationIdParamSchema, destinationTestSchema, telegramTokenSchema, apiErrorSchema, tlsUploadSchema, settingsViewSchema, settingsSavedSchema, workspaceSettingsViewSchema, workspaceSettingsSavedSchema;
741
+ var bindSchema, workspaceIdSchema, workspaceSchema, workspaceCreateSchema, workspaceRenameSchema, portSchema, onPortConflictSchema, onPortConflictDefaultSchema, restartSchema, httpCheckSchema, resourcesSchema, healthSchema, stopSchema, bootstrapSchema, bootstrapOrNullSchema, backupHookSchema, backupHookOrNullSchema, labelOrNullSchema, logBufferLinesSchema, serverSchema, authSchema, notificationPolicyShape, notificationDefaultsSchema, notificationDefaultsViewSchema, useOwnSettingsSchema, telegramDestinationSchema, webhookTargetSchema, notificationTargetSchema, destinationListSchema, notificationsSchema, logsSchema, tlsSchema, hostSchema, ddnsRecordTypeSchema, ddnsAccountSchema, ddnsDomainSchema, ddnsIpv4Schema, ddnsIpv6Schema, ddnsConfigSchema, ddnsRecordStateSchema, ddnsRecordViewSchema, ddnsStatusSchema, ddnsProviderFieldSchema, ddnsProviderInfoSchema, ddnsViewSchema, ddnsCredentialsSchema, backupScopeSchema, backupScheduleSchema, backupsSchema, controlSchema, defaultsSchema, restartPatchSchema, httpCheckPatchSchema, resourcesPatchSchema, healthPatchSchema, stopPatchSchema, authPatchSchema, notificationPolicyPatchShape, destinationPatchSchema, notificationsPatchSchema, hostPatchSchema, backupSchedulePatchSchema, backupsPatchSchema, logsPatchSchema, tlsPatchSchema, controlPatchSchema, defaultsPatchSchema, editableFields, serverPatchSchema, serverCreateSchema, nannySpecSchema, nannyExitSchema, nannyStateSchema, entryStateSchema, settingsPatchSchema, workspaceSettingsPatchSchema, authStatusSchema, tlsStatusSchema, proxyEngineSchema, proxyTargetSchema, proxyTlsModeSchema, proxyRouteSchema, proxyCertificateSchema, proxyCertificateStateSchema, proxyDns01Schema, proxyConfigSchema, proxyEngineSourceSchema, proxyEngineStatusSchema, proxyEngineInfoSchema, proxyRouteStatusSchema, proxyRouteViewSchema, proxyRunStateSchema, proxyStatusSchema, proxyCertificateViewSchema, proxyDnsAccountViewSchema, proxyViewSchema, proxyRoutePatchSchema, proxyPatchSchema, proxyCertificateUploadSchema, proxyEngineInstallSchema, notificationPolicyStatusShape, destinationStatusSchema, telegramChatsSchema, notificationViewSchema, sessionViewSchema, loginSchema, passwordValueSchema, passwordSchema, serverStatusSchema, healthStateSchema, portStateSchema, logStreamSchema, logLineSchema, historyActorSchema, historyEventSchema, serverHistorySchema, processResourcesSchema, hostDiskSchema, hostViewSchema, backupFileSchema, backupEntrySchema, backupScheduleViewSchema, backupsViewSchema, restoreItemSchema, restoreSkipSchema, restorePlanSchema, backupCreateSchema, restoreRequestSchema, serverViewSchema, healthResponseSchema, controlViewSchema, uiMetaSchema, uiStatusSchema, serverOrphanSchema, workspaceViewSchema, appStateSchema, logQuerySchema, actionResultSchema, deliveryResultSchema, passwordSetResponseSchema, tlsReviewResponseSchema, okResponseSchema, backupFilesResponseSchema, uiInstallResponseSchema, backupCreatedResponseSchema, logLinesResponseSchema, freePortResultSchema, logHistoryQuerySchema, logFileInfoSchema, logServerViewSchema, logServersViewSchema, notificationActionSchema, destinationIdParamSchema, destinationTestSchema, telegramTokenSchema, apiErrorSchema, tlsUploadSchema, settingsViewSchema, settingsSavedSchema, workspaceSettingsViewSchema, workspaceSettingsSavedSchema;
742
742
  var init_contracts = __esmMin((() => {
743
743
  bindSchema = type("\"local\" | \"lan\" | /^\\d{1,3}(?:\\.\\d{1,3}){3}$/");
744
744
  workspaceIdSchema = type("/^[a-z0-9][a-z0-9_-]*$/");
@@ -1064,11 +1064,21 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1064
1064
  accounts: ddnsAccountSchema.array().optional(),
1065
1065
  domains: ddnsDomainSchema.array().optional()
1066
1066
  }).onUndeclaredKey("reject");
1067
+ backupScopeSchema = type({
1068
+ mode: "\"only\" | \"except\"",
1069
+ ids: type("string >= 1").array().atLeastLength(1)
1070
+ }).onUndeclaredKey("reject");
1067
1071
  backupScheduleSchema = type({
1068
1072
  /** 0 turns the schedule off; otherwise the gap between automatic archives. */
1069
1073
  intervalMs: "number.integer >= 0 = 0",
1070
1074
  /** How many automatic archives to keep. Manual ones are never pruned by it. */
1071
- keep: "number.integer >= 1 = 7"
1075
+ keep: "number.integer >= 1 = 7",
1076
+ /**
1077
+ * Absent means the whole default scope — every workspace and `includePaths`. Deliberately not
1078
+ * defaulted to an explicit value: a reader cannot tell an untouched file from one that chose
1079
+ * "everything", and a default here would rewrite every existing schedule on its first save.
1080
+ */
1081
+ scope: backupScopeSchema.optional()
1072
1082
  }).onUndeclaredKey("reject");
1073
1083
  backupsSchema = type({
1074
1084
  enabled: "boolean = true",
@@ -1191,7 +1201,12 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1191
1201
  }).onUndeclaredKey("reject");
1192
1202
  backupSchedulePatchSchema = type({
1193
1203
  intervalMs: "number.integer >= 0?",
1194
- keep: "number.integer >= 1?"
1204
+ keep: "number.integer >= 1?",
1205
+ /**
1206
+ * No defaults, like every patch: `null` clears it back to the full default scope, which is the
1207
+ * only way to spell "forget the choice I made" — an omitted key means "leave it as it is".
1208
+ */
1209
+ scope: backupScopeSchema.or(type("null")).optional()
1195
1210
  }).onUndeclaredKey("reject");
1196
1211
  backupsPatchSchema = type({
1197
1212
  enabled: "boolean?",
@@ -1642,17 +1657,25 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1642
1657
  usedPercent: "number"
1643
1658
  });
1644
1659
  hostViewSchema = type({
1645
- enabled: "boolean",
1646
- cpus: "number",
1647
- loadAvg: type("number[]"),
1648
- uptimeMs: "number",
1649
- memoryUsedPercent: "number",
1650
- swapUsedPercent: "number",
1651
- tempCelsius: "number | null",
1652
- disks: hostDiskSchema.array(),
1660
+ "enabled": "boolean",
1661
+ "cpus": "number",
1662
+ "loadAvg": type("number[]"),
1663
+ /**
1664
+ * Share of this machine's CPU capacity in use over the last sampling interval, 0–100.
1665
+ *
1666
+ * Optional: an older panel sends no such field, and a required one rejects the whole frame and
1667
+ * blanks the UI that panel is serving. `null` on the first sample, which has no window to
1668
+ * measure yet — a number there would be invented.
1669
+ */
1670
+ "cpuUsedPercent?": "number | null",
1671
+ "uptimeMs": "number",
1672
+ "memoryUsedPercent": "number",
1673
+ "swapUsedPercent": "number",
1674
+ "tempCelsius": "number | null",
1675
+ "disks": hostDiskSchema.array(),
1653
1676
  /** Human readable threshold breaches, for the banner and notifications. */
1654
- alerts: type("string[]"),
1655
- sampledAt: "number | null"
1677
+ "alerts": type("string[]"),
1678
+ "sampledAt": "number | null"
1656
1679
  });
1657
1680
  backupFileSchema = type({
1658
1681
  name: "string",
@@ -1698,6 +1721,7 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1698
1721
  "ignoreGenerated?": "boolean"
1699
1722
  }).array()
1700
1723
  });
1724
+ backupScheduleViewSchema = backupScheduleSchema.onDeepUndeclaredKey("ignore");
1701
1725
  backupsViewSchema = type({
1702
1726
  "enabled": "boolean",
1703
1727
  "dir": "string",
@@ -1709,7 +1733,7 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1709
1733
  * and a required field would blank the settings page for that panel. The page reads it as
1710
1734
  * "off, keep 7" when absent — the schema defaults — so nothing changes for it.
1711
1735
  */
1712
- "schedule?": backupScheduleSchema,
1736
+ "schedule?": backupScheduleViewSchema,
1713
1737
  /** When the last automatic archive was written; null until one has run. Optional for the same reason. */
1714
1738
  "lastAutomaticAt?": "number | null",
1715
1739
  /**
@@ -1819,7 +1843,15 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1819
1843
  /** Optional: encrypts the archive. Never stored. */
1820
1844
  password: passwordValueSchema.optional(),
1821
1845
  /** Leaf ids to capture (`global:settings`, `workspace:<id>:servers`, `data:<path>`, ...); omitted means everything. */
1822
- include: type("string[] >= 1").optional()
1846
+ include: type("string[] >= 1").optional(),
1847
+ /**
1848
+ * Leaf ids to leave out, applied after `include` — the CLI's `--exclude`, and the one thing to
1849
+ * name when the archive should carry everything but the credentials.
1850
+ *
1851
+ * Empty is refused for the same reason `include` refuses it: an empty list reads as "nothing" to
1852
+ * a person and as "everything" to a reader, so it must not be sent at all.
1853
+ */
1854
+ exclude: type("string[] >= 1").optional()
1823
1855
  }).onUndeclaredKey("reject");
1824
1856
  restoreRequestSchema = type({
1825
1857
  name: "string?",
@@ -3528,7 +3560,8 @@ function createBackupsRoute(deps) {
3528
3560
  const body = c.req.valid("json");
3529
3561
  const result = await deps.backups.create({
3530
3562
  password: body.password,
3531
- include: body.include
3563
+ include: body.include,
3564
+ exclude: body.exclude
3532
3565
  });
3533
3566
  if (!result.ok) throw backupFailed(result.error);
3534
3567
  return c.json({
@@ -4026,6 +4059,55 @@ var init_workspace = __esmMin((() => {
4026
4059
  workspaceQuerySchema = type({ "workspace?": "string" });
4027
4060
  }));
4028
4061
  //#endregion
4062
+ //#region src/shared/backup-scope.ts
4063
+ /**
4064
+ * What a configured automatic scope asks a `create` for.
4065
+ *
4066
+ * `only` is `--include` and `except` is `--all --exclude`, because a schedule and a person typing
4067
+ * flags have to mean the same thing. An absent scope is the full default the schedule took before
4068
+ * it could be configured, which is what keeps an existing config exactly as it was.
4069
+ */
4070
+ function scopeSelection(scope) {
4071
+ if (scope === void 0) return {};
4072
+ return scope.mode === "only" ? { include: [...scope.ids] } : { exclude: [...scope.ids] };
4073
+ }
4074
+ /**
4075
+ * What a selection asks for, from `include` and `exclude` together.
4076
+ *
4077
+ * One implementation for `create`, `restore`, the control channel's plan and both UIs: a second
4078
+ * copy of "does this id count as selected" is how an `--exclude` that works on backup silently does
4079
+ * nothing on restore, or how a page ticks a row the panel will not capture.
4080
+ *
4081
+ * `include` omitted means everything; `exclude` is applied after it, and an id under an excluded
4082
+ * entry is excluded too.
4083
+ */
4084
+ function selectionOf(options) {
4085
+ const wanted = options.include === void 0 ? null : new Set(options.include);
4086
+ const unwanted = new Set(options.exclude ?? []);
4087
+ const isExcluded = (id) => unwanted.has(id) || [...unwanted].some((entry) => id.startsWith(`${entry}:`));
4088
+ const selects = ((id) => {
4089
+ if (isExcluded(id)) return false;
4090
+ return wanted === null || wanted.has(id) || [...wanted].some((entry) => id.startsWith(`${entry}:`));
4091
+ });
4092
+ selects.isExcluded = isExcluded;
4093
+ return selects;
4094
+ }
4095
+ /**
4096
+ * Which of `ids` name nothing the panel can capture.
4097
+ *
4098
+ * The rule `backup create --include` already applies: an id names something when it is an entry or
4099
+ * leaf id, or a prefix of one (`workspace:default` covers its leaves). A typo matters more on a
4100
+ * schedule than anywhere else — nobody is watching — and it cuts both ways: an unknown `only` id
4101
+ * silently narrows the archive, an unknown `except` id silently widens it back over what the
4102
+ * person meant to leave out.
4103
+ */
4104
+ function unknownBackupIds(ids, entries) {
4105
+ const available = entries.flatMap((entry) => [entry.id, ...(entry.items ?? []).map((item) => item.id)]);
4106
+ const known = (id) => available.some((candidate) => candidate === id || candidate.startsWith(`${id}:`));
4107
+ return ids.filter((id) => !known(id));
4108
+ }
4109
+ var init_backup_scope = __esmMin((() => {}));
4110
+ //#endregion
4029
4111
  //#region src/api/control.ts
4030
4112
  /**
4031
4113
  * The local control channel used by `home-hosted down` and `home-hosted start|stop`.
@@ -4134,10 +4216,18 @@ function createControlRoute(deps) {
4134
4216
  assertLocalCall(c, "create a backup");
4135
4217
  const password = c.req.query("password");
4136
4218
  const include = c.req.query("include")?.split(",").filter((part) => part.length > 0);
4219
+ const exclude = c.req.query("exclude")?.split(",").filter((part) => part.length > 0);
4137
4220
  if (c.req.query("confirm") !== "true") {
4138
4221
  const view = buildBackupsView(deps.backups);
4139
- const wanted = include === void 0 ? null : new Set(include);
4140
- const entries = view.entries.filter((entry) => wanted === null || wanted.has(entry.id) || entry.workspaceId !== void 0 && wanted.has(`workspace:${entry.workspaceId}`));
4222
+ const selects = selectionOf({
4223
+ include,
4224
+ exclude
4225
+ });
4226
+ const namesLeafOf = (id) => include !== void 0 && include.some((entry) => entry.startsWith(`${id}:`));
4227
+ const entries = view.entries.filter((entry) => selects(entry.id) || namesLeafOf(entry.id)).map((entry) => ({
4228
+ ...entry,
4229
+ items: entry.items.filter((item) => selects(item.id))
4230
+ }));
4141
4231
  return c.json({
4142
4232
  apply: false,
4143
4233
  entries,
@@ -4146,7 +4236,8 @@ function createControlRoute(deps) {
4146
4236
  }
4147
4237
  const result = await deps.backups.create({
4148
4238
  password,
4149
- include
4239
+ include,
4240
+ exclude
4150
4241
  });
4151
4242
  if (!result.ok) throw new DetailedError(result.error ?? "the backup failed", {
4152
4243
  statusCode: 400,
@@ -4182,10 +4273,12 @@ function createControlRoute(deps) {
4182
4273
  code: "BACKUP_NOT_FOUND"
4183
4274
  });
4184
4275
  const include = c.req.query("include")?.split(",").filter((part) => part.length > 0);
4276
+ const exclude = c.req.query("exclude")?.split(",").filter((part) => part.length > 0);
4185
4277
  return c.json(await deps.backups.restore(archive, {
4186
4278
  confirm,
4187
4279
  password: c.req.query("password"),
4188
- include
4280
+ include,
4281
+ exclude
4189
4282
  }));
4190
4283
  });
4191
4284
  }
@@ -4200,6 +4293,7 @@ var init_control = __esmMin((() => {
4200
4293
  init_workspace();
4201
4294
  init_loopback();
4202
4295
  init_state$1();
4296
+ init_backup_scope();
4203
4297
  init_contracts();
4204
4298
  }));
4205
4299
  //#endregion
@@ -7809,6 +7903,48 @@ function collectTree(rootPid, children) {
7809
7903
  return pids;
7810
7904
  }
7811
7905
  /**
7906
+ * CPU time a tree used over one interval, from per-pid cumulative counters.
7907
+ *
7908
+ * Pure, and separated from the scan because this is where both CPU bugs lived — and a scan of the
7909
+ * live process table cannot pin arithmetic that depends on a child appearing or vanishing between
7910
+ * two reads.
7911
+ *
7912
+ * `previous` is the **whole process table** of the prior scan, not just this tree: that is what
7913
+ * lets a process which joins the tree later be charged only its interval, and what the caller
7914
+ * guarantees.
7915
+ *
7916
+ * Three rules make the answer a real interval:
7917
+ *
7918
+ * - A pid in both maps contributes the difference. `next >= previous` is required: a recycled pid
7919
+ * reports less than the process that used to hold it, and that is not a delta.
7920
+ * - A pid only in `next` was **born inside the window**, so its whole counter accrued in it.
7921
+ * - A pid only in `previous` **exited inside the window**; its time is already accounted for by the
7922
+ * samples where it was alive, and it contributes nothing. The old code summed the tree on both
7923
+ * sides, so an exit made the total *drop*, the delta went negative and the reading was discarded
7924
+ * — the gap. Summing only pids present in `next` is what removes it.
7925
+ *
7926
+ * `null` when the map has nothing usable, so a caller reports "unknown" instead of `0`.
7927
+ */
7928
+ function treeCpuUsedSeconds(previous, next, treePids) {
7929
+ let used = 0;
7930
+ let sawAny = false;
7931
+ for (const pid of treePids) {
7932
+ const current = next.get(pid);
7933
+ if (current === void 0) continue;
7934
+ const before = previous.get(pid);
7935
+ if (before === void 0) {
7936
+ used += current;
7937
+ sawAny = true;
7938
+ continue;
7939
+ }
7940
+ if (current >= before) {
7941
+ used += current - before;
7942
+ sawAny = true;
7943
+ }
7944
+ }
7945
+ return sawAny ? used : null;
7946
+ }
7947
+ /**
7812
7948
  * The roots and every descendant of theirs, from one scan of the process table.
7813
7949
  *
7814
7950
  * Ownership has to mean the *tree*: a persistent entry runs under a nanny, and a
@@ -7873,7 +8009,30 @@ var init_proc = __esmMin((() => {
7873
8009
  execFileAsync$4 = promisify(execFile);
7874
8010
  clockTicks = null;
7875
8011
  ProcessSampler = class {
7876
- previous = /* @__PURE__ */ new Map();
8012
+ /**
8013
+ * Cumulative CPU seconds per pid, from the **whole process table** of the last scan.
8014
+ *
8015
+ * A tree is not a fixed set of processes: a wrapper spawns and reaps children continuously, so
8016
+ * "the sum over whatever is in the tree now" is not comparable with the previous sum. Measuring
8017
+ * that rule against a wrapper respawning a 1.5 s worker, **two samples in every three were
8018
+ * discarded**: the child's exit made the sum drop, the delta went negative, and the reading was
8019
+ * thrown away — the gaps a person sees on a live server.
8020
+ *
8021
+ * Baselining every pid the scan saw, rather than only the tree's, is what makes each delta a
8022
+ * real interval. A process that was already running has a previous counter even if it only
8023
+ * joined this tree afterwards, so it cannot be charged its whole lifetime; and a pid absent from
8024
+ * the previous scan was born inside the window, so its counter really did accrue in it.
8025
+ */
8026
+ previousTable = null;
8027
+ /**
8028
+ * Roots whose next sample must not be differenced, stamped with when they were forgotten.
8029
+ *
8030
+ * `forget` is called when an entry stops, exits or is restarted: the pid is gone, so the reading
8031
+ * after it must be `null` rather than a delta against a previous life. The baseline is one table
8032
+ * for the whole scan, so this is the per-root suppression. Pruned at each scan, which bounds it
8033
+ * to the restarts that happened since the last one.
8034
+ */
8035
+ forgotten = /* @__PURE__ */ new Map();
7877
8036
  async sample(rootPid, now = Date.now()) {
7878
8037
  return (await this.sampleMany([rootPid], now)).get(rootPid) ?? null;
7879
8038
  }
@@ -7893,41 +8052,31 @@ var init_proc = __esmMin((() => {
7893
8052
  siblings.push(row.pid);
7894
8053
  children.set(row.ppid, siblings);
7895
8054
  }
8055
+ const before = this.previousTable;
8056
+ const elapsedSeconds = before === null ? 0 : (now - before.at) / 1e3;
8057
+ const ticks = process.platform === "linux" ? await getClockTicks() : 1;
8058
+ const tableCpuSeconds = /* @__PURE__ */ new Map();
8059
+ for (const row of rows) if (row.cpuSeconds !== void 0) tableCpuSeconds.set(row.pid, row.cpuSeconds / ticks);
7896
8060
  for (const rootPid of rootPids) {
7897
8061
  if (!byPid.has(rootPid)) {
7898
- this.previous.delete(rootPid);
7899
8062
  results.set(rootPid, null);
7900
8063
  continue;
7901
8064
  }
8065
+ const wasForgotten = this.forgotten.delete(rootPid);
7902
8066
  const pids = collectTree(rootPid, children);
7903
8067
  let rssKb = 0;
7904
- let cpuSeconds = 0;
7905
8068
  let percentAverage = null;
8069
+ const treeSeconds = /* @__PURE__ */ new Map();
7906
8070
  for (const pid of pids) {
7907
8071
  const row = byPid.get(pid);
7908
8072
  if (!row) continue;
7909
8073
  rssKb += row.rssKb;
7910
- if (row.cpuSeconds === void 0) cpuSeconds = null;
7911
- else if (cpuSeconds !== null) cpuSeconds += row.cpuSeconds;
7912
8074
  if (row.cpuPercent !== void 0) percentAverage = (percentAverage ?? 0) + row.cpuPercent;
8075
+ if (row.cpuSeconds !== void 0) treeSeconds.set(pid, row.cpuSeconds / ticks);
7913
8076
  }
8077
+ const usedSeconds = before === null ? null : treeCpuUsedSeconds(before.cpuSeconds, treeSeconds, pids);
7914
8078
  let cpuPercent = percentAverage;
7915
- if (cpuPercent === null && cpuSeconds !== null) {
7916
- if (process.platform === "linux") {
7917
- const ticks = await getClockTicks();
7918
- cpuSeconds /= ticks;
7919
- }
7920
- const before = this.previous.get(rootPid);
7921
- if (before !== void 0 && now > before.at) {
7922
- const elapsedSeconds = (now - before.at) / 1e3;
7923
- const usedSeconds = cpuSeconds - before.cpuSeconds;
7924
- if (elapsedSeconds > 0 && usedSeconds >= 0) cpuPercent = usedSeconds / elapsedSeconds * 100;
7925
- }
7926
- this.previous.set(rootPid, {
7927
- cpuSeconds,
7928
- at: now
7929
- });
7930
- } else this.previous.delete(rootPid);
8079
+ if (cpuPercent === null && !wasForgotten && usedSeconds !== null && elapsedSeconds > 0) cpuPercent = usedSeconds / elapsedSeconds * 100;
7931
8080
  results.set(rootPid, {
7932
8081
  cpuPercent: cpuPercent === null ? null : Math.round(cpuPercent * 10) / 10,
7933
8082
  rssBytes: Math.round(rssKb * 1024),
@@ -7935,10 +8084,22 @@ var init_proc = __esmMin((() => {
7935
8084
  sampledAt: now
7936
8085
  });
7937
8086
  }
8087
+ this.previousTable = {
8088
+ at: now,
8089
+ cpuSeconds: tableCpuSeconds
8090
+ };
7938
8091
  return results;
7939
8092
  }
8093
+ /**
8094
+ * Marks a root's next reading as the first of a new life.
8095
+ *
8096
+ * Called when an entry stops, exits or is restarted. Without it a recycled pid — or the very
8097
+ * next sample of the same root — would be differenced against a counter from the previous run,
8098
+ * which is not an interval. The scan-wide table cannot be cleared per root, so the suppression
8099
+ * is remembered here and consumed by that root's next sample.
8100
+ */
7940
8101
  forget(rootPid) {
7941
- this.previous.delete(rootPid);
8102
+ this.forgotten.set(rootPid, Date.now());
7942
8103
  }
7943
8104
  };
7944
8105
  }));
@@ -11636,6 +11797,14 @@ function createSettingsRoute(deps) {
11636
11797
  statusCode: 400,
11637
11798
  code: "PROXY_EXPOSURE_BLOCKED"
11638
11799
  });
11800
+ const scope = patch.backups?.schedule?.scope;
11801
+ if (scope !== void 0 && scope !== null) {
11802
+ const unknown = unknownBackupIds(scope.ids, deps.backups.view().entries);
11803
+ if (unknown.length > 0) throw new DetailedError(`the automatic backup scope names ${unknown.map((id) => `"${id}"`).join(", ")}, which this panel cannot capture`, {
11804
+ statusCode: 400,
11805
+ code: "INVALID_SETTINGS"
11806
+ });
11807
+ }
11639
11808
  const previous = {
11640
11809
  trustProxy: current.auth.trustProxy,
11641
11810
  tlsEnabled: current.tls.enabled
@@ -11813,6 +11982,7 @@ var init_settings = __esmMin((() => {
11813
11982
  init_workspace();
11814
11983
  init_exposure();
11815
11984
  init_state$1();
11985
+ init_backup_scope();
11816
11986
  init_contracts();
11817
11987
  MAX_UI_UPLOAD_BYTES = 134217728;
11818
11988
  }));
@@ -12586,7 +12756,7 @@ var init_acme_challenge = __esmMin((() => {
12586
12756
  */
12587
12757
  function secretParts(scope, present) {
12588
12758
  const keys = new Set(present);
12589
- const known = KNOWN[scope];
12759
+ const known = KNOWN_SECRET_KEYS[scope];
12590
12760
  const parts = known.filter((key) => keys.has(key)).map((key) => ({
12591
12761
  key,
12592
12762
  fields: EXTRA_FIELDS[key] ?? [key],
@@ -12642,10 +12812,10 @@ function mergeSecrets(current, piece, fields) {
12642
12812
  }
12643
12813
  return merged;
12644
12814
  }
12645
- var KNOWN, KNOWN_SCOPES, EXTRA_FIELDS;
12815
+ var KNOWN_SECRET_KEYS, KNOWN_SCOPES, EXTRA_FIELDS;
12646
12816
  var init_secret_parts = __esmMin((() => {
12647
12817
  init_shape();
12648
- KNOWN = {
12818
+ KNOWN_SECRET_KEYS = {
12649
12819
  global: ["password", "apiToken"],
12650
12820
  workspace: ["telegram", "ddns"]
12651
12821
  };
@@ -15771,6 +15941,7 @@ var init_backups = __esmMin((() => {
15771
15941
  init_archive();
15772
15942
  init_backup_hook();
15773
15943
  init_supervisor();
15944
+ init_backup_scope();
15774
15945
  init_contracts();
15775
15946
  init_error_message();
15776
15947
  init_generated();
@@ -15889,17 +16060,20 @@ var init_backups = __esmMin((() => {
15889
16060
  error: "backups are disabled"
15890
16061
  };
15891
16062
  const password = options.password !== void 0 && options.password.length > 0 ? options.password : null;
16063
+ const selects = selectionOf(options);
15892
16064
  const wanted = options.include === void 0 ? null : new Set(options.include);
15893
- const capturesGlobal = (id) => wanted === null || wanted.has(id);
15894
- const capturesWorkspace = (id, suffix) => wanted === null || wanted.has(`workspace:${id}`) || wanted.has(`workspace:${id}:${suffix}`);
16065
+ const capturesGlobal = (id) => selects(id);
16066
+ const capturesWorkspace = (id, suffix) => selects(`workspace:${id}:${suffix}`);
15895
16067
  /**
15896
16068
  * The secrets of one scope the request asked for; `null` means "every one of them".
15897
16069
  * `workspaceId` is how a bare `workspace:<id>` selection covers all of its leaves.
15898
16070
  */
15899
16071
  const selectedSecretFields = (entryId, path, scope, workspaceId) => {
15900
16072
  const parts = secretParts(scope, presentSecretKeys(parseSecrets(readText(path) ?? "")));
15901
- const coversEntry = wanted === null || wanted.has(entryId) || workspaceId !== void 0 && wanted.has(`workspace:${workspaceId}`);
15902
- const picked = parts.filter((part) => coversEntry || wanted.has(`${entryId}:${part.key}`) || part.fields.some((field) => wanted.has(`${entryId}:${field}`)));
16073
+ const picked = parts.filter((part) => {
16074
+ if (selects.isExcluded(entryId) || selects.isExcluded(`${entryId}:${part.key}`)) return false;
16075
+ return wanted === null || wanted.has(entryId) || workspaceId !== void 0 && wanted.has(`workspace:${workspaceId}`) || wanted.has(`${entryId}:${part.key}`) || part.fields.some((field) => wanted.has(`${entryId}:${field}`));
16076
+ });
15903
16077
  return picked.length === parts.length ? null : picked.flatMap((part) => part.fields);
15904
16078
  };
15905
16079
  const dir = this.resolveDir();
@@ -15939,9 +16113,9 @@ var init_backups = __esmMin((() => {
15939
16113
  * True when the request touches a secrets entry at all: the entry itself, one of its
15940
16114
  * leaves, or — for a workspace — the workspace id, which names every leaf it has.
15941
16115
  */
15942
- const capturesSecrets = (entryId, workspaceId) => wanted === null || wanted.has(entryId) || workspaceId !== void 0 && wanted.has(`workspace:${workspaceId}`) || [...wanted].some((id) => id.startsWith(`${entryId}:`));
16116
+ const touchesSecrets = (entryId, workspaceId) => selects(entryId) || wanted !== null && [...wanted].some((id) => id.startsWith(`${entryId}:`)) || workspaceId !== void 0 && selects(`workspace:${workspaceId}:secrets`);
15943
16117
  if (capturesGlobal("global:settings")) copy("global/settings.json", sources.globalSettingsPath);
15944
- if (capturesSecrets("global:secrets")) copySecrets("global/secrets.json", sources.globalSecretsPath, "global:secrets", "global");
16118
+ if (touchesSecrets("global:secrets")) copySecrets("global/secrets.json", sources.globalSecretsPath, "global:secrets", "global");
15945
16119
  if (capturesGlobal("global:tls")) copy("global/tls", sources.tlsDir);
15946
16120
  this.copyInto(staging, `global/${REGISTRY}`, sources.registryPath);
15947
16121
  /**
@@ -15956,7 +16130,7 @@ var init_backups = __esmMin((() => {
15956
16130
  for (const workspace of sources.workspaces) for (const server of workspace.servers) {
15957
16131
  const hook = server.dump;
15958
16132
  if (hook === void 0 || hook === null) continue;
15959
- if (wanted !== null && !wanted.has(`workspace:${workspace.id}`) && !wanted.has(`workspace:${workspace.id}:dump:${server.id}`)) continue;
16133
+ if (!selects(`workspace:${workspace.id}:dump:${server.id}`)) continue;
15960
16134
  const relative = path.join("dumps", workspace.id, server.id);
15961
16135
  const result = await runBackupHook(hook, server, path.join(staging, relative));
15962
16136
  if (!result.ok) {
@@ -15979,7 +16153,7 @@ var init_backups = __esmMin((() => {
15979
16153
  const root = `workspaces/${workspace.id}`;
15980
16154
  if (capturesWorkspace(workspace.id, "settings")) copy(`${root}/settings.json`, workspace.settingsPath);
15981
16155
  if (capturesWorkspace(workspace.id, "servers")) copy(`${root}/servers.config.json`, workspace.serversPath);
15982
- if (capturesSecrets(`workspace:${workspace.id}:secrets`, workspace.id)) copySecrets(`${root}/secrets.json`, workspace.secretsPath, `workspace:${workspace.id}:secrets`, "workspace", workspace.id);
16156
+ if (touchesSecrets(`workspace:${workspace.id}:secrets`, workspace.id)) copySecrets(`${root}/secrets.json`, workspace.secretsPath, `workspace:${workspace.id}:secrets`, "workspace", workspace.id);
15983
16157
  for (const declared of this.declaredData(workspace.servers, sources.includePaths)) {
15984
16158
  if (!declared.included) continue;
15985
16159
  if (!capturesWorkspace(workspace.id, `data:${declared.path}`)) continue;
@@ -15996,7 +16170,7 @@ var init_backups = __esmMin((() => {
15996
16170
  });
15997
16171
  }
15998
16172
  }
15999
- if (wanted !== null && captured === 0) {
16173
+ if ((wanted !== null || (options.exclude?.length ?? 0) > 0) && captured === 0) {
16000
16174
  fs.rmSync(staging, {
16001
16175
  recursive: true,
16002
16176
  force: true
@@ -16147,7 +16321,7 @@ var init_backups = __esmMin((() => {
16147
16321
  error: `written by home-hosted ${manifest.writtenBy ?? "a newer release"} (config schema ${manifest.schema}); this release understands schema 2`
16148
16322
  };
16149
16323
  const sources = this.options.getSources();
16150
- const selectedIds = options.include === void 0 ? null : new Set(options.include);
16324
+ const selects = selectionOf(options);
16151
16325
  const actions = /* @__PURE__ */ new Map();
16152
16326
  const addItem = (item, apply, aliases = []) => {
16153
16327
  if (apply === null) {
@@ -16165,7 +16339,7 @@ var init_backups = __esmMin((() => {
16165
16339
  });
16166
16340
  return;
16167
16341
  }
16168
- const selected = selectedIds === null || selectedIds.has(item.id) || aliases.some((alias) => selectedIds.has(alias));
16342
+ const selected = !(selects.isExcluded(item.id) || aliases.some((alias) => selects.isExcluded(alias))) && (selects(item.id) || aliases.some((alias) => selects(alias)));
16169
16343
  plan.items.push({
16170
16344
  ...item,
16171
16345
  selected
@@ -16203,6 +16377,7 @@ var init_backups = __esmMin((() => {
16203
16377
  }, ["config"]);
16204
16378
  const globalSecrets = readText(path.join(staging, "global", "secrets.json"));
16205
16379
  if (globalSecrets !== null) {
16380
+ const globalSecretKeys = presentSecretKeys(parseSecrets(globalSecrets));
16206
16381
  addItem({
16207
16382
  id: "global:secrets",
16208
16383
  label: "Global secrets (password, API token)",
@@ -16210,8 +16385,9 @@ var init_backups = __esmMin((() => {
16210
16385
  kind: "secrets",
16211
16386
  restorable: true,
16212
16387
  note: null
16213
- }, () => {
16214
- writeFileAtomic(sources.globalSecretsPath, globalSecrets, { mode: 384 });
16388
+ }, secretParts("global", globalSecretKeys).every((part) => !selects.isExcluded(`global:secrets:${part.key}`) && !part.fields.some((field) => selects.isExcluded(`global:secrets:${field}`))) ? () => writeFileAtomic(sources.globalSecretsPath, globalSecrets, { mode: 384 }) : () => {
16389
+ const take = secretParts("global", globalSecretKeys).filter((part) => !selects.isExcluded(`global:secrets:${part.key}`) && !part.fields.some((field) => selects.isExcluded(`global:secrets:${field}`))).flatMap((part) => part.fields);
16390
+ mergeIntoFile(sources.globalSecretsPath, globalSecrets, take);
16215
16391
  }, ["secrets"]);
16216
16392
  for (const part of secretParts("global", presentSecretKeys(parseSecrets(globalSecrets)))) addItem({
16217
16393
  id: `global:secrets:${part.key}`,
@@ -16486,7 +16662,7 @@ var init_backups = __esmMin((() => {
16486
16662
  continue;
16487
16663
  }
16488
16664
  const ownerId = target.origin.split(":")[0] ?? "";
16489
- if ((selectedIds === null || selectedIds.has(base.id) || aliases.includes(base.id)) && runningOwners.has(`${target.workspace}:${ownerId}`)) plan.replacedUnderRunning.push({
16665
+ if (!selects.isExcluded(base.id) && (selects(base.id) || aliases.some((alias) => selects(alias))) && runningOwners.has(`${target.workspace}:${ownerId}`)) plan.replacedUnderRunning.push({
16490
16666
  workspaceId: target.workspace,
16491
16667
  serverId: ownerId,
16492
16668
  path: target.path
@@ -16651,9 +16827,9 @@ var init_backups = __esmMin((() => {
16651
16827
  * secret that can be captured but never restored individually.
16652
16828
  */
16653
16829
  secretItems(scope, entryId, path) {
16654
- const present = presentSecretKeys(parseSecrets(readText(path) ?? ""));
16655
- if (present.length === 0) return [];
16656
- return secretParts(scope, present).map((part) => ({
16830
+ const parts = secretParts(scope, presentSecretKeys(parseSecrets(readText(path) ?? "")));
16831
+ const missing = KNOWN_SECRET_KEYS[scope].filter((key) => !parts.some((part) => part.key === key));
16832
+ return [...parts.map((part) => ({
16657
16833
  id: `${entryId}:${part.key}`,
16658
16834
  label: SECRET_LABELS[part.key]?.en ?? part.key,
16659
16835
  ...SECRET_LABELS[part.key] === void 0 ? {} : { labelKey: SECRET_LABELS[part.key].key },
@@ -16661,7 +16837,16 @@ var init_backups = __esmMin((() => {
16661
16837
  secret: part.key,
16662
16838
  included: true,
16663
16839
  note: null
16664
- }));
16840
+ })), ...missing.map((key) => ({
16841
+ id: `${entryId}:${key}`,
16842
+ label: SECRET_LABELS[key]?.en ?? key,
16843
+ ...SECRET_LABELS[key] === void 0 ? {} : { labelKey: SECRET_LABELS[key].key },
16844
+ kind: "secrets",
16845
+ secret: key,
16846
+ included: false,
16847
+ note: "not set",
16848
+ noteKey: "settings.backup.noteMissing"
16849
+ }))];
16665
16850
  }
16666
16851
  workspaceItems(workspace, includePaths) {
16667
16852
  const id = workspace.id;
@@ -16791,7 +16976,7 @@ var init_backups = __esmMin((() => {
16791
16976
  for (const name of [...this.flags.keys()]) if (!present.has(name)) this.flags.delete(name);
16792
16977
  }
16793
16978
  missingNote(target) {
16794
- return fs.existsSync(target) ? null : "does not exist yet";
16979
+ return fs.existsSync(target) ? null : "not set";
16795
16980
  }
16796
16981
  /** Copies one source into the staging tree; false when there was nothing there. */
16797
16982
  copyInto(staging, relative, source, ignoreGenerated = false) {
@@ -16845,7 +17030,10 @@ var init_backups = __esmMin((() => {
16845
17030
  if (latest !== null && now - latest < config.schedule.intervalMs) return;
16846
17031
  this.running = true;
16847
17032
  this.lastAttemptAt = now;
16848
- this.create({ automatic: true }).then((result) => {
17033
+ this.create({
17034
+ automatic: true,
17035
+ ...scopeSelection(config.schedule.scope)
17036
+ }).then((result) => {
16849
17037
  if (result.ok) {
16850
17038
  this.scheduleError = null;
16851
17039
  return;
@@ -17128,6 +17316,35 @@ async function readSwapUsedPercent() {
17128
17316
  }
17129
17317
  return 0;
17130
17318
  }
17319
+ function cpuTimesSnapshot(cpus = os.cpus()) {
17320
+ let busyMs = 0;
17321
+ let totalMs = 0;
17322
+ for (const cpu of cpus) {
17323
+ const times = cpu.times;
17324
+ const idle = times.idle;
17325
+ const busy = times.user + (times.nice ?? 0) + times.sys + (times.irq ?? 0);
17326
+ busyMs += busy;
17327
+ totalMs += busy + idle;
17328
+ }
17329
+ return {
17330
+ busyMs,
17331
+ totalMs
17332
+ };
17333
+ }
17334
+ /**
17335
+ * Share of the machine's CPU capacity in use between two snapshots, 0–100.
17336
+ *
17337
+ * `null` when the window is empty or the counters went backwards (a suspended host, a clock
17338
+ * resync), because "no reading" is honest while a fabricated 0 reads as "idle". Pure, so the
17339
+ * arithmetic is testable against snapshots a runner can construct rather than only the one its
17340
+ * own scheduler happens to produce.
17341
+ */
17342
+ function cpuUsedPercent(previous, next) {
17343
+ const totalDelta = next.totalMs - previous.totalMs;
17344
+ const busyDelta = next.busyMs - previous.busyMs;
17345
+ if (!(totalDelta > 0) || busyDelta < 0) return null;
17346
+ return Math.max(0, Math.min(100, busyDelta / totalDelta * 100));
17347
+ }
17131
17348
  /**
17132
17349
  * Memory used, as a percentage of what the machine actually has.
17133
17350
  *
@@ -17290,6 +17507,9 @@ async function sampleHost(config, resolvePath) {
17290
17507
  const cpus = os.cpus().length || 1;
17291
17508
  const loadAvg = os.loadavg();
17292
17509
  const memory = memoryInfo();
17510
+ const cpuTimes = cpuTimesSnapshot();
17511
+ const cpuUsedPercentNow = previousCpuTimes === null ? null : cpuUsedPercent(previousCpuTimes, cpuTimes);
17512
+ previousCpuTimes = cpuTimes;
17293
17513
  if (process.platform === "win32") loadAvg.fill(0);
17294
17514
  if (memory.swapUsedPercent === 0 && process.platform !== "linux") memory.swapUsedPercent = await swapUsedPercent();
17295
17515
  const tempCelsius = cpuTemperature();
@@ -17305,6 +17525,7 @@ async function sampleHost(config, resolvePath) {
17305
17525
  enabled: config.enabled,
17306
17526
  cpus,
17307
17527
  loadAvg: [...loadAvg],
17528
+ cpuUsedPercent: cpuUsedPercentNow,
17308
17529
  uptimeMs: os.uptime() * 1e3,
17309
17530
  memoryUsedPercent: memory.memoryUsedPercent,
17310
17531
  swapUsedPercent: memory.swapUsedPercent,
@@ -17323,6 +17544,7 @@ function emptyHostView(config) {
17323
17544
  0,
17324
17545
  0
17325
17546
  ],
17547
+ cpuUsedPercent: null,
17326
17548
  uptimeMs: os.uptime() * 1e3,
17327
17549
  memoryUsedPercent: 0,
17328
17550
  swapUsedPercent: 0,
@@ -17332,11 +17554,12 @@ function emptyHostView(config) {
17332
17554
  sampledAt: null
17333
17555
  };
17334
17556
  }
17335
- var execFileAsync, SWAP_CACHE_MS, swapCache;
17557
+ var execFileAsync, SWAP_CACHE_MS, swapCache, previousCpuTimes;
17336
17558
  var init_host = __esmMin((() => {
17337
17559
  execFileAsync = promisify(execFile);
17338
17560
  SWAP_CACHE_MS = 6e4;
17339
17561
  swapCache = null;
17562
+ previousCpuTimes = null;
17340
17563
  }));
17341
17564
  //#endregion
17342
17565
  //#region src/services/host-monitor.ts
@@ -21588,6 +21811,49 @@ var backup_exports = /* @__PURE__ */ __exportAll({
21588
21811
  runBackupList: () => runBackupList,
21589
21812
  runBackupRestore: () => runBackupRestore
21590
21813
  });
21814
+ /**
21815
+ * Render plan ids as the tree they already are.
21816
+ *
21817
+ * Every id is a colon-separated path, so the hierarchy is in the data and the renderer's only job is
21818
+ * to show it: one row per prefix, each one level deeper than its parent. Depth is whatever the id
21819
+ * says, not a fixed number of columns — `workspace:default:secrets:telegram` sits three deep, and a
21820
+ * renderer that assumed two printed it beside its own parent.
21821
+ *
21822
+ * Both directions print through this, and so does the "what could I act on" list, so the three read
21823
+ * alike. A row's note is the panel's own wording, passed through untouched.
21824
+ */
21825
+ function printPlanTree(rows) {
21826
+ const known = new Set(rows.map((row) => row.id));
21827
+ const nodes = /* @__PURE__ */ new Map();
21828
+ const ensure = (id) => {
21829
+ const existing = nodes.get(id);
21830
+ if (existing !== void 0) return existing;
21831
+ const created = {
21832
+ note: null,
21833
+ children: /* @__PURE__ */ new Set()
21834
+ };
21835
+ nodes.set(id, created);
21836
+ return created;
21837
+ };
21838
+ for (const row of rows) {
21839
+ const segments = row.id.split(":");
21840
+ for (let depth = 1; depth <= segments.length; depth++) {
21841
+ const id = segments.slice(0, depth).join(":");
21842
+ const node = ensure(id);
21843
+ if (depth > 1) ensure(segments.slice(0, depth - 1).join(":")).children.add(id);
21844
+ if (depth === segments.length && known.has(row.id)) node.note = row.note ?? null;
21845
+ }
21846
+ }
21847
+ const roots = [...nodes.keys()].filter((id) => !id.includes(":"));
21848
+ const write = (id, depth) => {
21849
+ const node = nodes.get(id);
21850
+ if (node === void 0) return;
21851
+ const padding = " ".repeat(depth);
21852
+ process.stdout.write(`${padding}${depth === 1 ? "" : "- "}${id}${node.note === null ? "" : ` ${dim(`(${node.note})`)}`}\n`);
21853
+ for (const child of node.children) write(child, depth + 1);
21854
+ };
21855
+ for (const root of roots) write(root, 1);
21856
+ }
21591
21857
  function human(bytes) {
21592
21858
  if (bytes < 1024) return `${bytes} B`;
21593
21859
  if (bytes < 1048576) return `${Math.round(bytes / 1024)} KB`;
@@ -21650,14 +21916,83 @@ function parseScope(all, raw) {
21650
21916
  };
21651
21917
  }
21652
21918
  /**
21919
+ * The plan rows a scope selects, and an exclusion drops.
21920
+ *
21921
+ * `kind` is deliberately not part of this: it is the panel's label for a row, not an id, and every id
21922
+ * the plan prints is already prefixed with it (`global:settings`, `workspace:default:servers`).
21923
+ */
21924
+ /** Flatten a nested plan into the rows the tree renders. */
21925
+ function flattenRows(rows) {
21926
+ return rows.flatMap((row) => [{
21927
+ id: row.id,
21928
+ note: row.note ?? null
21929
+ }, ...(row.items ?? []).map((leaf) => ({
21930
+ id: leaf.id,
21931
+ note: leaf.note ?? null
21932
+ }))]);
21933
+ }
21934
+ function filterEntries(entries, scope, exclude) {
21935
+ const unwanted = exclude ?? [];
21936
+ const excluded = (id) => unwanted.some((entry) => id === entry || id.startsWith(`${entry}:`));
21937
+ const named = (id) => scope.kind === "all" || scope.ids.some((entry) => id === entry || id.startsWith(`${entry}:`) || entry.startsWith(`${id}:`));
21938
+ return entries.filter((entry) => named(entry.id) && !excluded(entry.id)).map((entry) => entry.items === void 0 ? entry : {
21939
+ ...entry,
21940
+ items: entry.items.filter((leaf) => named(leaf.id) && !excluded(leaf.id))
21941
+ });
21942
+ }
21943
+ /**
21944
+ * Refuse an id the plan does not have.
21945
+ *
21946
+ * An id that matches nothing is silently ignored by the service, which is right for an archive that
21947
+ * simply does not carry something — and wrong for a typo: `--exclude global:secret` excludes nothing
21948
+ * and says nothing, so the archive carries the credentials the person believed they had dropped.
21949
+ */
21950
+ function assertKnown(ids, entries, flag) {
21951
+ if (ids === void 0) return;
21952
+ const unknown = unknownBackupIds(ids, entries);
21953
+ if (unknown.length > 0) fail(`${flag} names ${unknown.map((id) => `"${id}"`).join(", ")}, which ${unknown.length === 1 ? "is" : "are"} not in this plan — \`backup create\` with no flags lists the ids`);
21954
+ }
21955
+ /** `--exclude` parsed. An empty value is a mistake, not "exclude nothing". */
21956
+ function parseExclude(raw) {
21957
+ if (raw === void 0) return void 0;
21958
+ const ids = raw.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
21959
+ if (ids.length === 0) fail("--exclude is empty — name the ids to leave out, or drop the flag");
21960
+ return ids;
21961
+ }
21962
+ /**
21653
21963
  * Neither flag given. Refused outright — the ids are a *bonus*, not the reason.
21654
21964
  *
21655
21965
  * The refusal must not depend on a panel being up: a mistyped command deserves the flag error, not
21656
21966
  * "home-hosted is not running". So the list is best-effort, and a failure to produce it is silent.
21657
21967
  */
21658
21968
  async function refuseWithoutScope(action, suffix) {
21659
- const ids = await availableIdsFor(action, suffix).catch(() => []);
21660
- fail(`name what to act on — pass --include <ids> or --all${ids.length === 0 ? "" : `\n\navailable:\n${ids.map((id) => ` ${id}`).join("\n")}`}`);
21969
+ const rows = await availableRows(action, suffix).catch(() => []);
21970
+ if (rows.length === 0) fail("name what to act on — pass --include <ids> or --all");
21971
+ process.stderr.write(`${paint("31", "error")} name what to act on — pass --include <ids> or --all\n\n`);
21972
+ process.stderr.write("available (or narrow it):\n");
21973
+ printPlanTree(flattenRows(rows));
21974
+ process.stderr.write("\n--exclude <ids> leaves those out: --all --exclude global:secrets\n");
21975
+ process.exit(1);
21976
+ }
21977
+ /**
21978
+ * The ids an offline run could act on, read from the state files.
21979
+ *
21980
+ * The refusal has to name real ids whether or not a panel is up — an empty list is the one answer
21981
+ * worse than no list, because it reads as "there is nothing to back up".
21982
+ */
21983
+ async function availableRowsFromDisk(action, suffix) {
21984
+ try {
21985
+ const { service } = await offlineBackup();
21986
+ await service.warm();
21987
+ if (action === "create") return service.view().entries;
21988
+ const name = new URLSearchParams(suffix.startsWith("?") ? suffix.slice(1) : suffix).get("name");
21989
+ if (name === null || name.length === 0) return [];
21990
+ const archive = service.resolve(name);
21991
+ if (archive === null) return [];
21992
+ return ((await service.restore(archive, { confirm: false })).items ?? []).filter((item) => item.selected !== false);
21993
+ } catch {
21994
+ return [];
21995
+ }
21661
21996
  }
21662
21997
  /**
21663
21998
  * The ids this action could be scoped to.
@@ -21666,15 +22001,15 @@ async function refuseWithoutScope(action, suffix) {
21666
22001
  * panel, so the list in a refusal is the real one rather than a hardcoded guess. A panel that cannot
21667
22002
  * be reached yields no ids — the refusal still fires, it just cannot enumerate.
21668
22003
  */
21669
- async function availableIdsFor(action, suffix) {
22004
+ async function availableRows(action, suffix) {
21670
22005
  const daemon = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
21671
22006
  const runtime = daemon.readRuntime();
21672
- if (runtime === null) return [];
22007
+ if (runtime === null || !await daemon.runtimeIsAlive(runtime)) return await availableRowsFromDisk(action, suffix);
21673
22008
  const path = action === "create" ? "/_hh/backups" : "/_hh/backups/restore";
21674
22009
  const answer = await daemon.requestControl(runtime, `${path}${suffix}`, 12e4);
21675
22010
  if (answer === null || answer.status !== 200) return [];
21676
22011
  const body = answer.body;
21677
- return ((action === "create" ? body?.entries : body?.items) ?? []).map((item) => item.id).filter((id) => typeof id === "string");
22012
+ return action === "create" ? body?.entries ?? [] : body?.items ?? [];
21678
22013
  }
21679
22014
  /** `?a=b`, or `''`. */
21680
22015
  function suffixOf(query) {
@@ -21772,7 +22107,9 @@ async function runBackupCreate(options) {
21772
22107
  await service.warm();
21773
22108
  return service.view().entries;
21774
22109
  })();
21775
- const wanted = scope.kind === "all" ? entries : entries.filter((entry) => scope.ids.some((id) => entry.id === id || id.startsWith(`${entry.id}:`)));
22110
+ assertKnown(options.exclude, entries, "--exclude");
22111
+ assertKnown(scope.kind === "include" ? scope.ids : void 0, entries, "--include");
22112
+ const wanted = filterEntries(entries, scope, options.exclude);
21776
22113
  if (!options.confirm) {
21777
22114
  if (options.json) {
21778
22115
  process.stdout.write(`${JSON.stringify({
@@ -21783,10 +22120,7 @@ async function runBackupCreate(options) {
21783
22120
  return;
21784
22121
  }
21785
22122
  process.stdout.write(`${bold("Plan")} — what a backup would capture; nothing has been written yet\n`);
21786
- for (const entry of wanted) {
21787
- process.stdout.write(` ${String(entry.kind ?? "entry").padEnd(10)} ${entry.id}${entry.note == null ? "" : ` ${dim(`(${entry.note})`)}`}\n`);
21788
- for (const item of entry.items ?? []) process.stdout.write(` ${dim("-")} ${item.id}\n`);
21789
- }
22123
+ printPlanTree(flattenRows(wanted));
21790
22124
  if (wanted.length === 0) {
21791
22125
  process.stdout.write(" (nothing matched — check --include, or what the entries declare)\n");
21792
22126
  return;
@@ -21795,6 +22129,7 @@ async function runBackupCreate(options) {
21795
22129
  if (!await consent("Take this backup?")) return;
21796
22130
  }
21797
22131
  const include = scope.kind === "include" ? scope.ids : void 0;
22132
+ const exclude = options.exclude;
21798
22133
  const file = (await (async () => {
21799
22134
  if (online) {
21800
22135
  const runtime = await livePanel();
@@ -21802,6 +22137,7 @@ async function runBackupCreate(options) {
21802
22137
  const query = new URLSearchParams();
21803
22138
  if (options.password !== void 0 && options.password.length > 0) query.set("password", options.password);
21804
22139
  if (include !== void 0) query.set("include", include.join(","));
22140
+ if (exclude !== void 0) query.set("exclude", exclude.join(","));
21805
22141
  const answer = await runtime.request(runtime, `/_hh/backups${withParam(suffixOf(query), "confirm", "true")}`, 6e5);
21806
22142
  if (answer === null) fail(`the control panel is not answering on ${runtime.probeUrl}`);
21807
22143
  if (answer.status !== 200) refusal(answer);
@@ -21812,7 +22148,8 @@ async function runBackupCreate(options) {
21812
22148
  await service.warm();
21813
22149
  const result = await service.create({
21814
22150
  password: options.password,
21815
- include
22151
+ include,
22152
+ exclude
21816
22153
  });
21817
22154
  if (!result.ok) fail(result.error ?? "the backup failed");
21818
22155
  return { file: result.file };
@@ -21849,7 +22186,8 @@ async function runBackupRestore(options) {
21849
22186
  return await service.restore(archive, {
21850
22187
  confirm: false,
21851
22188
  password: options.password,
21852
- include: scope.kind === "include" ? scope.ids : void 0
22189
+ include: scope.kind === "include" ? scope.ids : void 0,
22190
+ exclude: options.exclude
21853
22191
  });
21854
22192
  }
21855
22193
  const runtime = await livePanel();
@@ -21857,6 +22195,7 @@ async function runBackupRestore(options) {
21857
22195
  const base = new URLSearchParams({ name: options.name });
21858
22196
  if (options.password !== void 0 && options.password.length > 0) base.set("password", options.password);
21859
22197
  if (scope.kind === "include") base.set("include", scope.ids.join(","));
22198
+ if (options.exclude !== void 0) base.set("exclude", options.exclude.join(","));
21860
22199
  const answer = await runtime.request(runtime, `/_hh/backups/restore${suffixOf(base)}`, 12e4);
21861
22200
  if (answer === null) fail(`the control panel is not answering at ${runtime.probeUrl}`);
21862
22201
  if (answer.status !== 200) refusal(answer);
@@ -21875,7 +22214,10 @@ async function runBackupRestore(options) {
21875
22214
  }
21876
22215
  if (!options.json) {
21877
22216
  process.stdout.write(`${bold("Plan")} for ${options.name} — nothing has been written yet\n`);
21878
- for (const item of items) process.stdout.write(` ${String(item.kind ?? "item").padEnd(10)} ${item.id ?? item.label ?? ""}\n`);
22217
+ printPlanTree(items.map((item) => ({
22218
+ id: item.id,
22219
+ note: item.note ?? null
22220
+ })));
21879
22221
  for (const warning of plan?.warnings ?? []) process.stdout.write(` ${dim("!")} ${warning}\n`);
21880
22222
  if (items.length === 0) {
21881
22223
  process.stdout.write(" (nothing to restore — check --include, or what this host declares)\n");
@@ -21890,7 +22232,8 @@ async function runBackupRestore(options) {
21890
22232
  const result = await service.restore(archive, {
21891
22233
  confirm: true,
21892
22234
  password: options.password,
21893
- include: scope.kind === "include" ? scope.ids : void 0
22235
+ include: scope.kind === "include" ? scope.ids : void 0,
22236
+ exclude: options.exclude
21894
22237
  });
21895
22238
  return {
21896
22239
  items: (result.items ?? []).filter((item) => item.selected !== false),
@@ -21902,6 +22245,7 @@ async function runBackupRestore(options) {
21902
22245
  const base = new URLSearchParams({ name: options.name });
21903
22246
  if (options.password !== void 0 && options.password.length > 0) base.set("password", options.password);
21904
22247
  if (scope.kind === "include") base.set("include", scope.ids.join(","));
22248
+ if (options.exclude !== void 0) base.set("exclude", options.exclude.join(","));
21905
22249
  const answer = await runtime.request(runtime, `/_hh/backups/restore${withParam(suffixOf(base), "confirm", "true")}`, 6e5);
21906
22250
  if (answer === null) fail(`the control panel is not answering at ${runtime.probeUrl}`);
21907
22251
  if (answer.status !== 200) refusal(answer);
@@ -21933,6 +22277,7 @@ var backupCommand;
21933
22277
  var init_backup = __esmMin((() => {
21934
22278
  init_backup_offline();
21935
22279
  init_io();
22280
+ init_backup_scope();
21936
22281
  init_error_message();
21937
22282
  backupCommand = defineCommand({
21938
22283
  meta: { name: "backup" },
@@ -21955,6 +22300,10 @@ var init_backup = __esmMin((() => {
21955
22300
  type: "string",
21956
22301
  description: "comma-separated item ids to act on"
21957
22302
  },
22303
+ exclude: {
22304
+ type: "string",
22305
+ description: "comma-separated item ids to leave out, applied after --include"
22306
+ },
21958
22307
  all: {
21959
22308
  type: "boolean",
21960
22309
  description: "act on everything, rather than naming ids"
@@ -21972,12 +22321,14 @@ var init_backup = __esmMin((() => {
21972
22321
  try {
21973
22322
  const action = args.action === void 0 || args.action.length === 0 ? "list" : args.action;
21974
22323
  const parsed = action === "create" || action === "restore" ? parseScope(args.all === true, args.include) : null;
22324
+ const exclude = action === "create" || action === "restore" ? parseExclude(args.exclude) : void 0;
21975
22325
  if (action === "list") await runBackupList(args.json === true);
21976
22326
  else if (action === "create") {
21977
22327
  const scope = parsed ?? await refuseWithoutScope("create", "");
21978
22328
  await runBackupCreate({
21979
22329
  password: args.password,
21980
22330
  scope,
22331
+ exclude,
21981
22332
  confirm: args.confirm === true,
21982
22333
  json: args.json === true
21983
22334
  });
@@ -21988,6 +22339,7 @@ var init_backup = __esmMin((() => {
21988
22339
  name: args.target,
21989
22340
  password: args.password,
21990
22341
  scope,
22342
+ exclude,
21991
22343
  confirm: args.confirm === true,
21992
22344
  json: args.json === true
21993
22345
  });
@@ -22243,6 +22595,7 @@ var BACKUP_SECTION = {
22243
22595
  ["<name>", "the archive, for restore — `backup list` shows them"],
22244
22596
  ["--include <ids>", "comma-separated item ids to act on (required for create/restore)"],
22245
22597
  ["--all", "act on everything; one of --include or --all is required"],
22598
+ ["--exclude <ids>", "leave these out; --all --exclude global:secrets keeps the password and token out of the archive"],
22246
22599
  ["--password <text>", "encrypt a new archive, or unlock one on restore"],
22247
22600
  ["--confirm", "apply without asking (create and restore plan first)"],
22248
22601
  ["--json", "print the plan or the result as JSON"]