home-hosted 0.9.6 → 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
@@ -252,7 +252,6 @@ function rejectUnknownFlags(argv, argsDef) {
252
252
  */
253
253
  function buildDaemonArgv(flags) {
254
254
  const args = ["up", "--foreground"];
255
- if (flags.config !== void 0) args.push("--config", flags.config);
256
255
  if (flags.port !== void 0) args.push("--port", String(flags.port));
257
256
  if (flags.host !== void 0) args.push("--host", flags.host);
258
257
  if (!flags.autostart) args.push("--no-autostart");
@@ -739,7 +738,7 @@ function duplicateWebhookIds(targets) {
739
738
  }
740
739
  return [...duplicates];
741
740
  }
742
- var bindSchema, workspaceIdSchema, workspaceSchema, workspaceCreateSchema, workspaceRenameSchema, portSchema, onPortConflictSchema, onPortConflictDefaultSchema, restartSchema, httpCheckSchema, resourcesSchema, healthSchema, stopSchema, bootstrapSchema, bootstrapOrNullSchema, 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;
743
742
  var init_contracts = __esmMin((() => {
744
743
  bindSchema = type("\"local\" | \"lan\" | /^\\d{1,3}(?:\\.\\d{1,3}){3}$/");
745
744
  workspaceIdSchema = type("/^[a-z0-9][a-z0-9_-]*$/");
@@ -811,6 +810,22 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
811
810
  runOnce: "boolean = true"
812
811
  }).onUndeclaredKey("reject");
813
812
  bootstrapOrNullSchema = bootstrapSchema.or(type("null"));
813
+ backupHookSchema = type({
814
+ command: "string >= 1",
815
+ args: type("string[]").default(() => []),
816
+ env: type("Record<string, string>").default(() => ({})),
817
+ timeoutMs: "number >= 1000 = 600000",
818
+ /**
819
+ * How long to wait for the entry to answer before running a `load`.
820
+ *
821
+ * Only matters for `load`, and only for an entry with no `port`: the wait is normally "the port
822
+ * accepts a connection", which an entry that declares no port cannot offer. Two seconds by
823
+ * default, because a portless entry usually starts fast and a fixed wait is pure delay; a slow
824
+ * database reached over a socket should raise it.
825
+ */
826
+ waitMs: "number >= 0 = 2000"
827
+ }).onUndeclaredKey("reject");
828
+ backupHookOrNullSchema = backupHookSchema.or(type("null"));
814
829
  labelOrNullSchema = type("string | null");
815
830
  logBufferLinesSchema = type("50 <= number.integer <= 100000");
816
831
  serverSchema = type({
@@ -834,6 +849,16 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
834
849
  */
835
850
  dataEnvs: type("Record<string, string>").default(() => ({})),
836
851
  bootstrap: bootstrapOrNullSchema.optional(),
852
+ /**
853
+ * Run before this entry's data is captured, writing into `{dumpDir}`.
854
+ *
855
+ * For a database: `mongodump --archive={dumpDir}/db.archive`. A failed dump **refuses the backup**
856
+ * rather than archiving a stale directory next to it — the whole point is that the dump is the
857
+ * authoritative copy.
858
+ */
859
+ dump: backupHookOrNullSchema.optional(),
860
+ /** Run after this entry's data is restored, reading from `{dumpDir}`. Its server is stopped first. */
861
+ load: backupHookOrNullSchema.optional(),
837
862
  port: portSchema.optional(),
838
863
  bind: bindSchema.default(() => "local"),
839
864
  onPortConflict: onPortConflictDefaultSchema,
@@ -1039,11 +1064,21 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1039
1064
  accounts: ddnsAccountSchema.array().optional(),
1040
1065
  domains: ddnsDomainSchema.array().optional()
1041
1066
  }).onUndeclaredKey("reject");
1067
+ backupScopeSchema = type({
1068
+ mode: "\"only\" | \"except\"",
1069
+ ids: type("string >= 1").array().atLeastLength(1)
1070
+ }).onUndeclaredKey("reject");
1042
1071
  backupScheduleSchema = type({
1043
1072
  /** 0 turns the schedule off; otherwise the gap between automatic archives. */
1044
1073
  intervalMs: "number.integer >= 0 = 0",
1045
1074
  /** How many automatic archives to keep. Manual ones are never pruned by it. */
1046
- 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()
1047
1082
  }).onUndeclaredKey("reject");
1048
1083
  backupsSchema = type({
1049
1084
  enabled: "boolean = true",
@@ -1166,7 +1201,12 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1166
1201
  }).onUndeclaredKey("reject");
1167
1202
  backupSchedulePatchSchema = type({
1168
1203
  intervalMs: "number.integer >= 0?",
1169
- 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()
1170
1210
  }).onUndeclaredKey("reject");
1171
1211
  backupsPatchSchema = type({
1172
1212
  enabled: "boolean?",
@@ -1217,6 +1257,8 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1217
1257
  env: "Record<string, string>?",
1218
1258
  dataEnvs: "Record<string, string>?",
1219
1259
  bootstrap: bootstrapOrNullSchema.optional(),
1260
+ dump: backupHookOrNullSchema.optional(),
1261
+ load: backupHookOrNullSchema.optional(),
1220
1262
  port: portSchema.optional(),
1221
1263
  bind: bindSchema.optional(),
1222
1264
  onPortConflict: onPortConflictSchema.optional(),
@@ -1279,6 +1321,15 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1279
1321
  /** The `runOnce` bootstrap already ran for this entry. */
1280
1322
  "bootstrapDone": "boolean",
1281
1323
  /**
1324
+ * A restored dump this entry still has to load, and where it is.
1325
+ *
1326
+ * The restore cannot run the load hook itself: `mongorestore` needs a server that is answering, and
1327
+ * the entry is stopped at that moment. So the restore stages the dump and records it here, and the
1328
+ * next `start` runs the hook once the process is up. Persisted, because a restore followed by a
1329
+ * panel restart must not lose the load.
1330
+ */
1331
+ "pendingLoad?": "string | null",
1332
+ /**
1282
1333
  * The last child this panel spawned for a non-persistent entry. A detached child
1283
1334
  * outlives the panel, so this is the only way a later boot recognizes its own
1284
1335
  * survivor instead of spawning a second copy beside it.
@@ -1606,17 +1657,25 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1606
1657
  usedPercent: "number"
1607
1658
  });
1608
1659
  hostViewSchema = type({
1609
- enabled: "boolean",
1610
- cpus: "number",
1611
- loadAvg: type("number[]"),
1612
- uptimeMs: "number",
1613
- memoryUsedPercent: "number",
1614
- swapUsedPercent: "number",
1615
- tempCelsius: "number | null",
1616
- 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(),
1617
1676
  /** Human readable threshold breaches, for the banner and notifications. */
1618
- alerts: type("string[]"),
1619
- sampledAt: "number | null"
1677
+ "alerts": type("string[]"),
1678
+ "sampledAt": "number | null"
1620
1679
  });
1621
1680
  backupFileSchema = type({
1622
1681
  name: "string",
@@ -1662,6 +1721,7 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1662
1721
  "ignoreGenerated?": "boolean"
1663
1722
  }).array()
1664
1723
  });
1724
+ backupScheduleViewSchema = backupScheduleSchema.onDeepUndeclaredKey("ignore");
1665
1725
  backupsViewSchema = type({
1666
1726
  "enabled": "boolean",
1667
1727
  "dir": "string",
@@ -1673,7 +1733,7 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1673
1733
  * and a required field would blank the settings page for that panel. The page reads it as
1674
1734
  * "off, keep 7" when absent — the schema defaults — so nothing changes for it.
1675
1735
  */
1676
- "schedule?": backupScheduleSchema,
1736
+ "schedule?": backupScheduleViewSchema,
1677
1737
  /** When the last automatic archive was written; null until one has run. Optional for the same reason. */
1678
1738
  "lastAutomaticAt?": "number | null",
1679
1739
  /**
@@ -1731,6 +1791,19 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1731
1791
  "schema?": "number"
1732
1792
  }),
1733
1793
  "items": restoreItemSchema.array(),
1794
+ /**
1795
+ * One row per backup hook that ran, so a person can see which entries brought their own dump.
1796
+ *
1797
+ * Optional, like every new response field: an older panel never sends it and an older UI never
1798
+ * reads it. `output` is a bounded tail, not a log — enough to see what `mongorestore` said.
1799
+ */
1800
+ "hooks?": type({
1801
+ "serverId": "string",
1802
+ "workspaceId": "string",
1803
+ "action": "\"dump\" | \"load\"",
1804
+ "ok": "boolean",
1805
+ "output?": "string"
1806
+ }).array(),
1734
1807
  "applied": type("string[]"),
1735
1808
  /**
1736
1809
  * The ids `applied` names, so a UI resolves each through `items` and renders its own label.
@@ -1770,7 +1843,15 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1770
1843
  /** Optional: encrypts the archive. Never stored. */
1771
1844
  password: passwordValueSchema.optional(),
1772
1845
  /** Leaf ids to capture (`global:settings`, `workspace:<id>:servers`, `data:<path>`, ...); omitted means everything. */
1773
- 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()
1774
1855
  }).onUndeclaredKey("reject");
1775
1856
  restoreRequestSchema = type({
1776
1857
  name: "string?",
@@ -3479,7 +3560,8 @@ function createBackupsRoute(deps) {
3479
3560
  const body = c.req.valid("json");
3480
3561
  const result = await deps.backups.create({
3481
3562
  password: body.password,
3482
- include: body.include
3563
+ include: body.include,
3564
+ exclude: body.exclude
3483
3565
  });
3484
3566
  if (!result.ok) throw backupFailed(result.error);
3485
3567
  return c.json({
@@ -3977,6 +4059,55 @@ var init_workspace = __esmMin((() => {
3977
4059
  workspaceQuerySchema = type({ "workspace?": "string" });
3978
4060
  }));
3979
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
3980
4111
  //#region src/api/control.ts
3981
4112
  /**
3982
4113
  * The local control channel used by `home-hosted down` and `home-hosted start|stop`.
@@ -4085,10 +4216,18 @@ function createControlRoute(deps) {
4085
4216
  assertLocalCall(c, "create a backup");
4086
4217
  const password = c.req.query("password");
4087
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);
4088
4220
  if (c.req.query("confirm") !== "true") {
4089
4221
  const view = buildBackupsView(deps.backups);
4090
- const wanted = include === void 0 ? null : new Set(include);
4091
- 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
+ }));
4092
4231
  return c.json({
4093
4232
  apply: false,
4094
4233
  entries,
@@ -4097,7 +4236,8 @@ function createControlRoute(deps) {
4097
4236
  }
4098
4237
  const result = await deps.backups.create({
4099
4238
  password,
4100
- include
4239
+ include,
4240
+ exclude
4101
4241
  });
4102
4242
  if (!result.ok) throw new DetailedError(result.error ?? "the backup failed", {
4103
4243
  statusCode: 400,
@@ -4133,10 +4273,12 @@ function createControlRoute(deps) {
4133
4273
  code: "BACKUP_NOT_FOUND"
4134
4274
  });
4135
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);
4136
4277
  return c.json(await deps.backups.restore(archive, {
4137
4278
  confirm,
4138
4279
  password: c.req.query("password"),
4139
- include
4280
+ include,
4281
+ exclude
4140
4282
  }));
4141
4283
  });
4142
4284
  }
@@ -4151,6 +4293,7 @@ var init_control = __esmMin((() => {
4151
4293
  init_workspace();
4152
4294
  init_loopback();
4153
4295
  init_state$1();
4296
+ init_backup_scope();
4154
4297
  init_contracts();
4155
4298
  }));
4156
4299
  //#endregion
@@ -7760,6 +7903,48 @@ function collectTree(rootPid, children) {
7760
7903
  return pids;
7761
7904
  }
7762
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
+ /**
7763
7948
  * The roots and every descendant of theirs, from one scan of the process table.
7764
7949
  *
7765
7950
  * Ownership has to mean the *tree*: a persistent entry runs under a nanny, and a
@@ -7824,7 +8009,30 @@ var init_proc = __esmMin((() => {
7824
8009
  execFileAsync$4 = promisify(execFile);
7825
8010
  clockTicks = null;
7826
8011
  ProcessSampler = class {
7827
- 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();
7828
8036
  async sample(rootPid, now = Date.now()) {
7829
8037
  return (await this.sampleMany([rootPid], now)).get(rootPid) ?? null;
7830
8038
  }
@@ -7844,41 +8052,31 @@ var init_proc = __esmMin((() => {
7844
8052
  siblings.push(row.pid);
7845
8053
  children.set(row.ppid, siblings);
7846
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);
7847
8060
  for (const rootPid of rootPids) {
7848
8061
  if (!byPid.has(rootPid)) {
7849
- this.previous.delete(rootPid);
7850
8062
  results.set(rootPid, null);
7851
8063
  continue;
7852
8064
  }
8065
+ const wasForgotten = this.forgotten.delete(rootPid);
7853
8066
  const pids = collectTree(rootPid, children);
7854
8067
  let rssKb = 0;
7855
- let cpuSeconds = 0;
7856
8068
  let percentAverage = null;
8069
+ const treeSeconds = /* @__PURE__ */ new Map();
7857
8070
  for (const pid of pids) {
7858
8071
  const row = byPid.get(pid);
7859
8072
  if (!row) continue;
7860
8073
  rssKb += row.rssKb;
7861
- if (row.cpuSeconds === void 0) cpuSeconds = null;
7862
- else if (cpuSeconds !== null) cpuSeconds += row.cpuSeconds;
7863
8074
  if (row.cpuPercent !== void 0) percentAverage = (percentAverage ?? 0) + row.cpuPercent;
8075
+ if (row.cpuSeconds !== void 0) treeSeconds.set(pid, row.cpuSeconds / ticks);
7864
8076
  }
8077
+ const usedSeconds = before === null ? null : treeCpuUsedSeconds(before.cpuSeconds, treeSeconds, pids);
7865
8078
  let cpuPercent = percentAverage;
7866
- if (cpuPercent === null && cpuSeconds !== null) {
7867
- if (process.platform === "linux") {
7868
- const ticks = await getClockTicks();
7869
- cpuSeconds /= ticks;
7870
- }
7871
- const before = this.previous.get(rootPid);
7872
- if (before !== void 0 && now > before.at) {
7873
- const elapsedSeconds = (now - before.at) / 1e3;
7874
- const usedSeconds = cpuSeconds - before.cpuSeconds;
7875
- if (elapsedSeconds > 0 && usedSeconds >= 0) cpuPercent = usedSeconds / elapsedSeconds * 100;
7876
- }
7877
- this.previous.set(rootPid, {
7878
- cpuSeconds,
7879
- at: now
7880
- });
7881
- } else this.previous.delete(rootPid);
8079
+ if (cpuPercent === null && !wasForgotten && usedSeconds !== null && elapsedSeconds > 0) cpuPercent = usedSeconds / elapsedSeconds * 100;
7882
8080
  results.set(rootPid, {
7883
8081
  cpuPercent: cpuPercent === null ? null : Math.round(cpuPercent * 10) / 10,
7884
8082
  rssBytes: Math.round(rssKb * 1024),
@@ -7886,10 +8084,22 @@ var init_proc = __esmMin((() => {
7886
8084
  sampledAt: now
7887
8085
  });
7888
8086
  }
8087
+ this.previousTable = {
8088
+ at: now,
8089
+ cpuSeconds: tableCpuSeconds
8090
+ };
7889
8091
  return results;
7890
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
+ */
7891
8101
  forget(rootPid) {
7892
- this.previous.delete(rootPid);
8102
+ this.forgotten.set(rootPid, Date.now());
7893
8103
  }
7894
8104
  };
7895
8105
  }));
@@ -11587,6 +11797,14 @@ function createSettingsRoute(deps) {
11587
11797
  statusCode: 400,
11588
11798
  code: "PROXY_EXPOSURE_BLOCKED"
11589
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
+ }
11590
11808
  const previous = {
11591
11809
  trustProxy: current.auth.trustProxy,
11592
11810
  tlsEnabled: current.tls.enabled
@@ -11764,6 +11982,7 @@ var init_settings = __esmMin((() => {
11764
11982
  init_workspace();
11765
11983
  init_exposure();
11766
11984
  init_state$1();
11985
+ init_backup_scope();
11767
11986
  init_contracts();
11768
11987
  MAX_UI_UPLOAD_BYTES = 134217728;
11769
11988
  }));
@@ -12537,7 +12756,7 @@ var init_acme_challenge = __esmMin((() => {
12537
12756
  */
12538
12757
  function secretParts(scope, present) {
12539
12758
  const keys = new Set(present);
12540
- const known = KNOWN[scope];
12759
+ const known = KNOWN_SECRET_KEYS[scope];
12541
12760
  const parts = known.filter((key) => keys.has(key)).map((key) => ({
12542
12761
  key,
12543
12762
  fields: EXTRA_FIELDS[key] ?? [key],
@@ -12593,10 +12812,10 @@ function mergeSecrets(current, piece, fields) {
12593
12812
  }
12594
12813
  return merged;
12595
12814
  }
12596
- var KNOWN, KNOWN_SCOPES, EXTRA_FIELDS;
12815
+ var KNOWN_SECRET_KEYS, KNOWN_SCOPES, EXTRA_FIELDS;
12597
12816
  var init_secret_parts = __esmMin((() => {
12598
12817
  init_shape();
12599
- KNOWN = {
12818
+ KNOWN_SECRET_KEYS = {
12600
12819
  global: ["password", "apiToken"],
12601
12820
  workspace: ["telegram", "ddns"]
12602
12821
  };
@@ -12914,6 +13133,142 @@ var init_archive = __esmMin((() => {
12914
13133
  ];
12915
13134
  }));
12916
13135
  //#endregion
13136
+ //#region src/providers/process.ts
13137
+ /**
13138
+ * Resolves a bare command through the entry's own directory and the project's
13139
+ * `node_modules/.bin` first, so a server installed as a project dependency is
13140
+ * found even when the launcher's PATH has no pnpm-injected bin dir.
13141
+ */
13142
+ function resolveCommand(command, ...searchDirs) {
13143
+ if (command.includes("/") || command.includes("\\")) return command;
13144
+ const candidates = process.platform === "win32" && path.extname(command) === "" ? [command, ...WINDOWS_SHIM_EXTENSIONS.map((extension) => `${command}${extension}`)] : [command];
13145
+ for (const dir of searchDirs) for (const candidate of candidates) {
13146
+ const local = path.join(dir, "node_modules", ".bin", candidate);
13147
+ if (fs.existsSync(local)) return local;
13148
+ }
13149
+ return command;
13150
+ }
13151
+ /** Relative entry paths belong to the project that launched the panel. */
13152
+ function resolveCwd(cwd, base = projectDir) {
13153
+ return path.resolve(base, cwd);
13154
+ }
13155
+ /** Node cannot spawn a Windows `.cmd`/`.bat` shim without a shell (EINVAL). */
13156
+ function needsShell(command) {
13157
+ return process.platform === "win32" && /\.(?:cmd|bat)$/i.test(command);
13158
+ }
13159
+ function spawnManaged(spec, options = {}) {
13160
+ return spawn(spec.command, spec.args, {
13161
+ cwd: spec.cwd,
13162
+ env: {
13163
+ ...process.env,
13164
+ ...spec.env
13165
+ },
13166
+ detached: options.detached ?? true,
13167
+ stdio: [
13168
+ "ignore",
13169
+ "pipe",
13170
+ "pipe"
13171
+ ],
13172
+ shell: needsShell(spec.command),
13173
+ windowsHide: true
13174
+ });
13175
+ }
13176
+ /** SIGTERM (default) to the child, escalating to SIGKILL after the grace period. */
13177
+ async function terminate(child, options) {
13178
+ if (child.exitCode !== null || child.signalCode !== null) return "exited";
13179
+ const exited = waitForExit$1(child, options.graceMs);
13180
+ signalChild(child, options.signal, options.killGroup);
13181
+ if (await exited) return "exited";
13182
+ signalChild(child, "SIGKILL", options.killGroup);
13183
+ await waitForExit$1(child, 2e3);
13184
+ return "force-killed";
13185
+ }
13186
+ /**
13187
+ * Windows has no process groups and no SIGTERM: `taskkill /T` walks the tree and
13188
+ * `/F` is the only reliable way to stop a console process.
13189
+ */
13190
+ async function killTreeWindows(pid) {
13191
+ try {
13192
+ await execFileAsync$1("taskkill", [
13193
+ "/pid",
13194
+ String(pid),
13195
+ "/T",
13196
+ "/F"
13197
+ ], { timeout: 5e3 });
13198
+ } catch {}
13199
+ }
13200
+ function signalChild(child, signal, killGroup) {
13201
+ const pid = child.pid;
13202
+ if (pid === void 0) return;
13203
+ signalPid(pid, signal, killGroup);
13204
+ }
13205
+ function signalPid(pid, signal, killGroup) {
13206
+ if (process.platform === "win32") {
13207
+ if (killGroup) killTreeWindows(pid);
13208
+ else try {
13209
+ process.kill(pid, signal);
13210
+ } catch {}
13211
+ return;
13212
+ }
13213
+ if (killGroup) try {
13214
+ process.kill(-pid, signal);
13215
+ return;
13216
+ } catch {}
13217
+ try {
13218
+ process.kill(pid, signal);
13219
+ } catch {}
13220
+ }
13221
+ /**
13222
+ * The same shutdown a supervised child gets, for a process we adopted instead of
13223
+ * spawned: a detached successor is not our child, so it is signalled by pid (and
13224
+ * by process group when asked) and its exit is polled rather than awaited.
13225
+ *
13226
+ * Liveness comes from `isProcessAlive`, never a local signal-0 copy: a second definition returned
13227
+ * `false` for `EPERM`, so a process that was there but not ours to signal read as "exited" and
13228
+ * `'force-killed'` was returned for one still running. One predicate, one answer.
13229
+ */
13230
+ async function terminatePid(pid, options) {
13231
+ if (!isProcessAlive(pid)) return "exited";
13232
+ signalPid(pid, options.signal, options.killGroup);
13233
+ const deadline = Date.now() + Math.max(0, options.graceMs);
13234
+ while (Date.now() < deadline && isProcessAlive(pid)) await delay$1(50);
13235
+ if (!isProcessAlive(pid)) return "exited";
13236
+ signalPid(pid, "SIGKILL", options.killGroup);
13237
+ const hardDeadline = Date.now() + 2e3;
13238
+ while (Date.now() < hardDeadline && isProcessAlive(pid)) await delay$1(50);
13239
+ return "force-killed";
13240
+ }
13241
+ function delay$1(ms) {
13242
+ return new Promise((resolve) => setTimeout(resolve, ms));
13243
+ }
13244
+ function waitForExit$1(child, timeoutMs) {
13245
+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
13246
+ if (timeoutMs <= 0) return Promise.resolve(false);
13247
+ return new Promise((resolve) => {
13248
+ const timer = setTimeout(() => {
13249
+ child.removeListener("exit", onExit);
13250
+ resolve(false);
13251
+ }, timeoutMs);
13252
+ function onExit() {
13253
+ clearTimeout(timer);
13254
+ resolve(true);
13255
+ }
13256
+ child.once("exit", onExit);
13257
+ });
13258
+ }
13259
+ var execFileAsync$1, WINDOWS_SHIM_EXTENSIONS;
13260
+ var init_process = __esmMin((() => {
13261
+ init_paths();
13262
+ init_port();
13263
+ execFileAsync$1 = promisify(execFile);
13264
+ WINDOWS_SHIM_EXTENSIONS = [
13265
+ ".cmd",
13266
+ ".exe",
13267
+ ".bat",
13268
+ ".ps1"
13269
+ ];
13270
+ }));
13271
+ //#endregion
12917
13272
  //#region src/helpers/backoff.ts
12918
13273
  /** Exponential backoff: base * factor^(attempt - 1), capped at maxDelayMs. */
12919
13274
  function computeBackoff(attempt, options) {
@@ -13128,164 +13483,28 @@ var init_health_check = __esmMin((() => {
13128
13483
  MAX_BODY_BYTES = 1e6;
13129
13484
  }));
13130
13485
  //#endregion
13131
- //#region src/providers/process.ts
13486
+ //#region src/services/dependencies.ts
13132
13487
  /**
13133
- * Resolves a bare command through the entry's own directory and the project's
13134
- * `node_modules/.bin` first, so a server installed as a project dependency is
13135
- * found even when the launcher's PATH has no pnpm-injected bin dir.
13488
+ * Orders servers so every dependency comes before its dependents.
13489
+ *
13490
+ * Cycles and unknown ids are ignored here — the config store reports them as
13491
+ * config errors — so this can never throw and stall supervision.
13136
13492
  */
13137
- function resolveCommand(command, ...searchDirs) {
13138
- if (command.includes("/") || command.includes("\\")) return command;
13139
- const candidates = process.platform === "win32" && path.extname(command) === "" ? [command, ...WINDOWS_SHIM_EXTENSIONS.map((extension) => `${command}${extension}`)] : [command];
13140
- for (const dir of searchDirs) for (const candidate of candidates) {
13141
- const local = path.join(dir, "node_modules", ".bin", candidate);
13142
- if (fs.existsSync(local)) return local;
13143
- }
13144
- return command;
13145
- }
13146
- /** Relative entry paths belong to the project that launched the panel. */
13147
- function resolveCwd(cwd, base = projectDir) {
13148
- return path.resolve(base, cwd);
13149
- }
13150
- /** Node cannot spawn a Windows `.cmd`/`.bat` shim without a shell (EINVAL). */
13151
- function needsShell(command) {
13152
- return process.platform === "win32" && /\.(?:cmd|bat)$/i.test(command);
13153
- }
13154
- function spawnManaged(spec, options = {}) {
13155
- return spawn(spec.command, spec.args, {
13156
- cwd: spec.cwd,
13157
- env: {
13158
- ...process.env,
13159
- ...spec.env
13160
- },
13161
- detached: options.detached ?? true,
13162
- stdio: [
13163
- "ignore",
13164
- "pipe",
13165
- "pipe"
13166
- ],
13167
- shell: needsShell(spec.command),
13168
- windowsHide: true
13169
- });
13170
- }
13171
- /** SIGTERM (default) to the child, escalating to SIGKILL after the grace period. */
13172
- async function terminate(child, options) {
13173
- if (child.exitCode !== null || child.signalCode !== null) return "exited";
13174
- const exited = waitForExit$1(child, options.graceMs);
13175
- signalChild(child, options.signal, options.killGroup);
13176
- if (await exited) return "exited";
13177
- signalChild(child, "SIGKILL", options.killGroup);
13178
- await waitForExit$1(child, 2e3);
13179
- return "force-killed";
13180
- }
13181
- /**
13182
- * Windows has no process groups and no SIGTERM: `taskkill /T` walks the tree and
13183
- * `/F` is the only reliable way to stop a console process.
13184
- */
13185
- async function killTreeWindows(pid) {
13186
- try {
13187
- await execFileAsync$1("taskkill", [
13188
- "/pid",
13189
- String(pid),
13190
- "/T",
13191
- "/F"
13192
- ], { timeout: 5e3 });
13193
- } catch {}
13194
- }
13195
- function signalChild(child, signal, killGroup) {
13196
- const pid = child.pid;
13197
- if (pid === void 0) return;
13198
- signalPid(pid, signal, killGroup);
13199
- }
13200
- function signalPid(pid, signal, killGroup) {
13201
- if (process.platform === "win32") {
13202
- if (killGroup) killTreeWindows(pid);
13203
- else try {
13204
- process.kill(pid, signal);
13205
- } catch {}
13206
- return;
13207
- }
13208
- if (killGroup) try {
13209
- process.kill(-pid, signal);
13210
- return;
13211
- } catch {}
13212
- try {
13213
- process.kill(pid, signal);
13214
- } catch {}
13215
- }
13216
- /**
13217
- * The same shutdown a supervised child gets, for a process we adopted instead of
13218
- * spawned: a detached successor is not our child, so it is signalled by pid (and
13219
- * by process group when asked) and its exit is polled rather than awaited.
13220
- *
13221
- * Liveness comes from `isProcessAlive`, never a local signal-0 copy: a second definition returned
13222
- * `false` for `EPERM`, so a process that was there but not ours to signal read as "exited" and
13223
- * `'force-killed'` was returned for one still running. One predicate, one answer.
13224
- */
13225
- async function terminatePid(pid, options) {
13226
- if (!isProcessAlive(pid)) return "exited";
13227
- signalPid(pid, options.signal, options.killGroup);
13228
- const deadline = Date.now() + Math.max(0, options.graceMs);
13229
- while (Date.now() < deadline && isProcessAlive(pid)) await delay$1(50);
13230
- if (!isProcessAlive(pid)) return "exited";
13231
- signalPid(pid, "SIGKILL", options.killGroup);
13232
- const hardDeadline = Date.now() + 2e3;
13233
- while (Date.now() < hardDeadline && isProcessAlive(pid)) await delay$1(50);
13234
- return "force-killed";
13235
- }
13236
- function delay$1(ms) {
13237
- return new Promise((resolve) => setTimeout(resolve, ms));
13238
- }
13239
- function waitForExit$1(child, timeoutMs) {
13240
- if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
13241
- if (timeoutMs <= 0) return Promise.resolve(false);
13242
- return new Promise((resolve) => {
13243
- const timer = setTimeout(() => {
13244
- child.removeListener("exit", onExit);
13245
- resolve(false);
13246
- }, timeoutMs);
13247
- function onExit() {
13248
- clearTimeout(timer);
13249
- resolve(true);
13250
- }
13251
- child.once("exit", onExit);
13252
- });
13253
- }
13254
- var execFileAsync$1, WINDOWS_SHIM_EXTENSIONS;
13255
- var init_process = __esmMin((() => {
13256
- init_paths();
13257
- init_port();
13258
- execFileAsync$1 = promisify(execFile);
13259
- WINDOWS_SHIM_EXTENSIONS = [
13260
- ".cmd",
13261
- ".exe",
13262
- ".bat",
13263
- ".ps1"
13264
- ];
13265
- }));
13266
- //#endregion
13267
- //#region src/services/dependencies.ts
13268
- /**
13269
- * Orders servers so every dependency comes before its dependents.
13270
- *
13271
- * Cycles and unknown ids are ignored here — the config store reports them as
13272
- * config errors — so this can never throw and stall supervision.
13273
- */
13274
- function orderByDependencies(servers) {
13275
- const byId = new Map(servers.map((server) => [server.id, server]));
13276
- const ordered = [];
13277
- const visited = /* @__PURE__ */ new Set();
13278
- const visit = (server) => {
13279
- if (visited.has(server.id)) return;
13280
- visited.add(server.id);
13281
- for (const dependency of server.dependsOn) {
13282
- const target = byId.get(dependency);
13283
- if (target && target.id !== server.id) visit(target);
13284
- }
13285
- ordered.push(server);
13286
- };
13287
- for (const server of servers) visit(server);
13288
- return ordered;
13493
+ function orderByDependencies(servers) {
13494
+ const byId = new Map(servers.map((server) => [server.id, server]));
13495
+ const ordered = [];
13496
+ const visited = /* @__PURE__ */ new Set();
13497
+ const visit = (server) => {
13498
+ if (visited.has(server.id)) return;
13499
+ visited.add(server.id);
13500
+ for (const dependency of server.dependsOn) {
13501
+ const target = byId.get(dependency);
13502
+ if (target && target.id !== server.id) visit(target);
13503
+ }
13504
+ ordered.push(server);
13505
+ };
13506
+ for (const server of servers) visit(server);
13507
+ return ordered;
13289
13508
  }
13290
13509
  /**
13291
13510
  * The transitive dependencies of a server, **deepest first** — the order they have to be started in, so
@@ -13676,6 +13895,7 @@ var init_supervisor = __esmMin((() => {
13676
13895
  init_paths();
13677
13896
  init_runtime();
13678
13897
  init_template();
13898
+ init_backup_hook();
13679
13899
  init_entry_state();
13680
13900
  init_health_check();
13681
13901
  init_identity();
@@ -13847,7 +14067,10 @@ var init_supervisor = __esmMin((() => {
13847
14067
  ok: false,
13848
14068
  error: `server "${id}" is disabled`
13849
14069
  };
13850
- if (entry.status === "running" || entry.status === "starting" || entry.starting) return { ok: true };
14070
+ if (entry.status === "running" || entry.status === "starting" || entry.starting) {
14071
+ if (entry.pendingLoad !== null) this.runPendingLoad(entry);
14072
+ return { ok: true };
14073
+ }
13851
14074
  if (entry.stopping) return {
13852
14075
  ok: false,
13853
14076
  error: `server "${id}" is stopping`
@@ -13898,11 +14121,58 @@ var init_supervisor = __esmMin((() => {
13898
14121
  error: conflict.error
13899
14122
  };
13900
14123
  if (conflict.kind === "adopt") return this.adoptEntry(entry, conflict.pid, `a detached restart of this entry is already serving port ${entry.config.port}`);
13901
- return this.spawnEntry(entry);
14124
+ const started = this.spawnEntry(entry);
14125
+ if (entry.pendingLoad !== null) this.runPendingLoad(entry);
14126
+ return started;
13902
14127
  } finally {
13903
14128
  entry.starting = false;
13904
14129
  }
13905
14130
  }
14131
+ /**
14132
+ * Run the load hook a restore left behind, once the entry is answering.
14133
+ *
14134
+ * Waits for the port to accept a connection before running it: `mongorestore` and `pg_restore`
14135
+ * connect, so running them the instant the process is spawned fails with "connection refused" —
14136
+ * which is exactly the failure that made this a staged load rather than an inline one.
14137
+ */
14138
+ async runPendingLoad(entry) {
14139
+ const dumpDir = entry.pendingLoad;
14140
+ const hook = entry.config.load;
14141
+ if (entry.loadingPending || dumpDir === null || hook === void 0 || hook === null) {
14142
+ if (hook === void 0 || hook === null) {
14143
+ entry.pendingLoad = null;
14144
+ this.persistEntryState(entry);
14145
+ }
14146
+ return;
14147
+ }
14148
+ entry.loadingPending = true;
14149
+ if (entry.config.port !== null) {
14150
+ const deadline = Date.now() + hook.timeoutMs;
14151
+ while (Date.now() < deadline && entry.status !== "stopped") {
14152
+ if (await probePort("127.0.0.1", entry.config.port)) break;
14153
+ await new Promise((resolve) => setTimeout(resolve, 500));
14154
+ }
14155
+ } else if (hook.waitMs > 0) await new Promise((resolve) => setTimeout(resolve, hook.waitMs));
14156
+ entry.pendingLoad = null;
14157
+ this.persistEntryState(entry);
14158
+ const result = await runBackupHook(hook, entry.config, dumpDir);
14159
+ entry.loadingPending = false;
14160
+ this.log(entry, "system", result.ok ? "load: the restored dump was applied" : `load: ${hookFailure("load", entry.config, result)}`);
14161
+ }
14162
+ /**
14163
+ * Mark that a restored dump is waiting to be loaded, on the entry and on disk.
14164
+ *
14165
+ * Persisted because the restore normally happens before the entry has ever started, and a panel
14166
+ * restart in between must not lose it.
14167
+ */
14168
+ stagePendingLoad(id, dumpDir) {
14169
+ const entry = this.entries.get(id);
14170
+ if (entry === void 0) return;
14171
+ entry.pendingLoad = dumpDir;
14172
+ this.persistEntryState(entry);
14173
+ this.log(entry, "system", `load: a restored dump is waiting, it runs on the next start`);
14174
+ if (entry.status === "running" && !entry.starting) this.runPendingLoad(entry);
14175
+ }
13906
14176
  async stop(id) {
13907
14177
  const entry = this.entries.get(id);
13908
14178
  if (!entry) return missingServer(id);
@@ -14229,6 +14499,8 @@ var init_supervisor = __esmMin((() => {
14229
14499
  actor: "policy",
14230
14500
  removed: false,
14231
14501
  bootstrapDone: persisted?.bootstrapDone ?? !config.bootstrap,
14502
+ pendingLoad: persisted?.pendingLoad ?? null,
14503
+ loadingPending: false,
14232
14504
  logs: new LogBuffer(config.logBufferLines),
14233
14505
  echoed: /* @__PURE__ */ new Set(),
14234
14506
  responseMs: null,
@@ -15142,6 +15414,7 @@ var init_supervisor = __esmMin((() => {
15142
15414
  restarts: entry.restarts,
15143
15415
  healthRestarts: entry.healthRestarts,
15144
15416
  bootstrapDone: entry.bootstrapDone,
15417
+ pendingLoad: entry.pendingLoad,
15145
15418
  lastPid: entry.config.persistent ? null : entry.lastChild?.pid ?? null,
15146
15419
  lastStartedAt: entry.config.persistent ? null : entry.lastChild?.startedAt ?? null
15147
15420
  });
@@ -15221,6 +15494,103 @@ var init_supervisor = __esmMin((() => {
15221
15494
  };
15222
15495
  }));
15223
15496
  //#endregion
15497
+ //#region src/providers/backup-hook.ts
15498
+ function tail(previous, chunk) {
15499
+ const next = previous + chunk;
15500
+ return next.length <= OUTPUT_TAIL_BYTES ? next : next.slice(next.length - OUTPUT_TAIL_BYTES);
15501
+ }
15502
+ /**
15503
+ * Run a hook for one entry.
15504
+ *
15505
+ * `dumpDir` is passed in rather than templated by the caller so the same absolute path can be handed
15506
+ * to `dump` and later to `load`, which is what makes the pair symmetric.
15507
+ */
15508
+ async function runBackupHook(hook, server, dumpDir, options = {}) {
15509
+ const vars = {
15510
+ ...serverTemplateVars(server),
15511
+ dumpDir
15512
+ };
15513
+ const cwd = resolveCwd(server.cwd);
15514
+ const args = resolveTemplates(hook.args, vars);
15515
+ if (options.requireDumpDir !== false) fs.mkdirSync(dumpDir, { recursive: true });
15516
+ let child;
15517
+ try {
15518
+ child = spawn(hook.command, args, {
15519
+ cwd,
15520
+ env: {
15521
+ ...process.env,
15522
+ ...resolveRecord(hook.env, vars)
15523
+ },
15524
+ stdio: [
15525
+ "ignore",
15526
+ "pipe",
15527
+ "pipe"
15528
+ ],
15529
+ windowsHide: true
15530
+ });
15531
+ } catch (error) {
15532
+ return {
15533
+ ok: false,
15534
+ code: null,
15535
+ output: "",
15536
+ error: `could not start: ${error.message}`
15537
+ };
15538
+ }
15539
+ let output = "";
15540
+ child.stdout?.on("data", (chunk) => {
15541
+ output = tail(output, chunk.toString());
15542
+ });
15543
+ child.stderr?.on("data", (chunk) => {
15544
+ output = tail(output, chunk.toString());
15545
+ });
15546
+ const outcome = await new Promise((resolve) => {
15547
+ const timer = setTimeout(() => {
15548
+ try {
15549
+ child.kill("SIGKILL");
15550
+ } catch {}
15551
+ resolve({
15552
+ code: null,
15553
+ error: `timed out after ${hook.timeoutMs}ms`
15554
+ });
15555
+ }, hook.timeoutMs);
15556
+ child.once("exit", (code) => {
15557
+ clearTimeout(timer);
15558
+ resolve({ code });
15559
+ });
15560
+ child.once("error", (error) => {
15561
+ clearTimeout(timer);
15562
+ resolve({
15563
+ code: null,
15564
+ error: error.message
15565
+ });
15566
+ });
15567
+ });
15568
+ return {
15569
+ ok: outcome.error === void 0 && outcome.code === 0,
15570
+ code: outcome.code,
15571
+ output,
15572
+ ...outcome.error === void 0 ? {} : { error: outcome.error }
15573
+ };
15574
+ }
15575
+ /**
15576
+ * The line a person reads when a hook fails.
15577
+ *
15578
+ * Names the entry, the program and the last thing it said — a bare "the backup failed" would send
15579
+ * them to the panel's log to find out which of five databases refused.
15580
+ */
15581
+ function hookFailure(action, server, result) {
15582
+ const detail = result.error ?? (result.code === null ? "no exit code" : `exit ${result.code}`);
15583
+ const said = result.output.trim().split("\n").filter((line) => line.trim().length > 0).slice(-3).join(" / ");
15584
+ return `the ${action} hook for "${server.id}" failed (${detail})${said.length === 0 ? "" : `: ${said}`}`;
15585
+ }
15586
+ var OUTPUT_TAIL_BYTES;
15587
+ var init_backup_hook = __esmMin((() => {
15588
+ init_template();
15589
+ init_process();
15590
+ init_supervisor();
15591
+ OUTPUT_TAIL_BYTES = 8192;
15592
+ }));
15593
+ //#endregion
15224
15594
  //#region src/shared/generated.ts
15225
15595
  /**
15226
15596
  * True when a path *relative to the declared root* looks generated. Accepts
@@ -15290,6 +15660,23 @@ var init_generated = __esmMin((() => {
15290
15660
  * is made of allowed characters, so segments are checked explicitly and any
15291
15661
  * entry that could resolve outside the staging directory aborts the restore.
15292
15662
  */
15663
+ /**
15664
+ * The servers an archive carries for one workspace, from its staged config.
15665
+ *
15666
+ * A restore reads this rather than `getSources()` because the live config is the *old* one at this
15667
+ * point: the files have just been overwritten, and the hooks to run belong to the machine being
15668
+ * cloned. A config that will not parse yields no servers, so the caller reports a missing hook
15669
+ * rather than throwing.
15670
+ */
15671
+ function readArchivedServers(staging, workspaceId, defaults = {}) {
15672
+ const text = readText(path.join(staging, "workspaces", workspaceId, "servers.config.json"));
15673
+ if (text === null) return [];
15674
+ try {
15675
+ return parseServersFile(JSON.parse(text), defaults).servers;
15676
+ } catch {
15677
+ return [];
15678
+ }
15679
+ }
15293
15680
  function isSafeArchiveEntry(entry) {
15294
15681
  if (entry.startsWith("/") || entry.includes("\0")) return false;
15295
15682
  const cleaned = entry.replace(/^\.\//, "").replace(/\/+$/, "");
@@ -15538,7 +15925,7 @@ function readableWorkspaceSettings(text) {
15538
15925
  return false;
15539
15926
  }
15540
15927
  }
15541
- var MANIFEST, REGISTRY, ALLOWED_ROOTS, SUFFIX, AUTO_PREFIX, RELOADABLE, SECRET_LABELS, BackupService;
15928
+ var MANIFEST, REGISTRY, ALLOWED_ROOTS, SUFFIX, PENDING_LOAD, AUTO_PREFIX, RELOADABLE, SECRET_LABELS, BackupService;
15542
15929
  var init_backups = __esmMin((() => {
15543
15930
  init_migrations();
15544
15931
  init_parse();
@@ -15552,7 +15939,9 @@ var init_backups = __esmMin((() => {
15552
15939
  init_template();
15553
15940
  init_version();
15554
15941
  init_archive();
15942
+ init_backup_hook();
15555
15943
  init_supervisor();
15944
+ init_backup_scope();
15556
15945
  init_contracts();
15557
15946
  init_error_message();
15558
15947
  init_generated();
@@ -15562,9 +15951,11 @@ var init_backups = __esmMin((() => {
15562
15951
  ALLOWED_ROOTS = /* @__PURE__ */ new Set([
15563
15952
  "global",
15564
15953
  "workspaces",
15565
- "data"
15954
+ "data",
15955
+ "dumps"
15566
15956
  ]);
15567
15957
  SUFFIX = ".zip";
15958
+ PENDING_LOAD = "pending-load";
15568
15959
  AUTO_PREFIX = "auto";
15569
15960
  RELOADABLE = /^global:settings$|^workspace:[^:]+:(?:settings|servers)$/;
15570
15961
  SECRET_LABELS = {
@@ -15669,17 +16060,20 @@ var init_backups = __esmMin((() => {
15669
16060
  error: "backups are disabled"
15670
16061
  };
15671
16062
  const password = options.password !== void 0 && options.password.length > 0 ? options.password : null;
16063
+ const selects = selectionOf(options);
15672
16064
  const wanted = options.include === void 0 ? null : new Set(options.include);
15673
- const capturesGlobal = (id) => wanted === null || wanted.has(id);
15674
- 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}`);
15675
16067
  /**
15676
16068
  * The secrets of one scope the request asked for; `null` means "every one of them".
15677
16069
  * `workspaceId` is how a bare `workspace:<id>` selection covers all of its leaves.
15678
16070
  */
15679
16071
  const selectedSecretFields = (entryId, path, scope, workspaceId) => {
15680
16072
  const parts = secretParts(scope, presentSecretKeys(parseSecrets(readText(path) ?? "")));
15681
- const coversEntry = wanted === null || wanted.has(entryId) || workspaceId !== void 0 && wanted.has(`workspace:${workspaceId}`);
15682
- 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
+ });
15683
16077
  return picked.length === parts.length ? null : picked.flatMap((part) => part.fields);
15684
16078
  };
15685
16079
  const dir = this.resolveDir();
@@ -15719,17 +16113,47 @@ var init_backups = __esmMin((() => {
15719
16113
  * True when the request touches a secrets entry at all: the entry itself, one of its
15720
16114
  * leaves, or — for a workspace — the workspace id, which names every leaf it has.
15721
16115
  */
15722
- 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`);
15723
16117
  if (capturesGlobal("global:settings")) copy("global/settings.json", sources.globalSettingsPath);
15724
- 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");
15725
16119
  if (capturesGlobal("global:tls")) copy("global/tls", sources.tlsDir);
15726
16120
  this.copyInto(staging, `global/${REGISTRY}`, sources.registryPath);
16121
+ /**
16122
+ * The dump phase: give every entry with a `dump` hook the chance to produce a consistent copy.
16123
+ *
16124
+ * Before anything is copied, because the dump is the authoritative artifact — the raw data
16125
+ * directory beside it is a convenience, and a dump that failed must not leave an archive that
16126
+ * looks complete. The output lands in `dumps/<workspace>/<server>/`, which the restore side
16127
+ * fills again at the same path, so `{dumpDir}` means the same thing in both directions.
16128
+ */
16129
+ const dumped = [];
16130
+ for (const workspace of sources.workspaces) for (const server of workspace.servers) {
16131
+ const hook = server.dump;
16132
+ if (hook === void 0 || hook === null) continue;
16133
+ if (!selects(`workspace:${workspace.id}:dump:${server.id}`)) continue;
16134
+ const relative = path.join("dumps", workspace.id, server.id);
16135
+ const result = await runBackupHook(hook, server, path.join(staging, relative));
16136
+ if (!result.ok) {
16137
+ fs.rmSync(staging, {
16138
+ recursive: true,
16139
+ force: true
16140
+ });
16141
+ return {
16142
+ ok: false,
16143
+ error: hookFailure("dump", server, result)
16144
+ };
16145
+ }
16146
+ dumped.push({
16147
+ workspaceId: workspace.id,
16148
+ serverId: server.id
16149
+ });
16150
+ }
15727
16151
  const data = [];
15728
16152
  for (const workspace of sources.workspaces) {
15729
16153
  const root = `workspaces/${workspace.id}`;
15730
16154
  if (capturesWorkspace(workspace.id, "settings")) copy(`${root}/settings.json`, workspace.settingsPath);
15731
16155
  if (capturesWorkspace(workspace.id, "servers")) copy(`${root}/servers.config.json`, workspace.serversPath);
15732
- 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);
15733
16157
  for (const declared of this.declaredData(workspace.servers, sources.includePaths)) {
15734
16158
  if (!declared.included) continue;
15735
16159
  if (!capturesWorkspace(workspace.id, `data:${declared.path}`)) continue;
@@ -15746,7 +16170,7 @@ var init_backups = __esmMin((() => {
15746
16170
  });
15747
16171
  }
15748
16172
  }
15749
- if (wanted !== null && captured === 0) {
16173
+ if ((wanted !== null || (options.exclude?.length ?? 0) > 0) && captured === 0) {
15750
16174
  fs.rmSync(staging, {
15751
16175
  recursive: true,
15752
16176
  force: true
@@ -15762,7 +16186,8 @@ var init_backups = __esmMin((() => {
15762
16186
  hostname: os.hostname(),
15763
16187
  writtenBy: appVersion(),
15764
16188
  schema: 2,
15765
- data
16189
+ data,
16190
+ ...dumped.length === 0 ? {} : { dumps: dumped }
15766
16191
  };
15767
16192
  fs.writeFileSync(path.join(staging, MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`);
15768
16193
  await createZip(staging, destination, password === null ? {} : { password });
@@ -15896,7 +16321,7 @@ var init_backups = __esmMin((() => {
15896
16321
  error: `written by home-hosted ${manifest.writtenBy ?? "a newer release"} (config schema ${manifest.schema}); this release understands schema 2`
15897
16322
  };
15898
16323
  const sources = this.options.getSources();
15899
- const selectedIds = options.include === void 0 ? null : new Set(options.include);
16324
+ const selects = selectionOf(options);
15900
16325
  const actions = /* @__PURE__ */ new Map();
15901
16326
  const addItem = (item, apply, aliases = []) => {
15902
16327
  if (apply === null) {
@@ -15914,7 +16339,7 @@ var init_backups = __esmMin((() => {
15914
16339
  });
15915
16340
  return;
15916
16341
  }
15917
- 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)));
15918
16343
  plan.items.push({
15919
16344
  ...item,
15920
16345
  selected
@@ -15952,6 +16377,7 @@ var init_backups = __esmMin((() => {
15952
16377
  }, ["config"]);
15953
16378
  const globalSecrets = readText(path.join(staging, "global", "secrets.json"));
15954
16379
  if (globalSecrets !== null) {
16380
+ const globalSecretKeys = presentSecretKeys(parseSecrets(globalSecrets));
15955
16381
  addItem({
15956
16382
  id: "global:secrets",
15957
16383
  label: "Global secrets (password, API token)",
@@ -15959,8 +16385,9 @@ var init_backups = __esmMin((() => {
15959
16385
  kind: "secrets",
15960
16386
  restorable: true,
15961
16387
  note: null
15962
- }, () => {
15963
- 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);
15964
16391
  }, ["secrets"]);
15965
16392
  for (const part of secretParts("global", presentSecretKeys(parseSecrets(globalSecrets)))) addItem({
15966
16393
  id: `global:secrets:${part.key}`,
@@ -16188,6 +16615,18 @@ var init_backups = __esmMin((() => {
16188
16615
  * apply closure so a dry run reports the same list the apply would.
16189
16616
  */
16190
16617
  const runningOwners = new Set((sources.runningServers?.() ?? []).map((entry) => `${entry.workspaceId}:${entry.serverId}`));
16618
+ for (const dump of manifest.dumps ?? []) {
16619
+ const from = path.join(staging, "dumps", dump.workspaceId, dump.serverId);
16620
+ if (!fs.existsSync(from)) continue;
16621
+ addItem({
16622
+ id: `workspace:${dump.workspaceId}:dump:${dump.serverId}`,
16623
+ label: `dump:${dump.serverId}`,
16624
+ kind: "data",
16625
+ restorable: true,
16626
+ workspaceId: dump.workspaceId,
16627
+ note: null
16628
+ }, () => {});
16629
+ }
16191
16630
  const archivedEntries = Array.isArray(manifest.data) ? manifest.data.filter(isRecord) : [];
16192
16631
  for (const entry of archivedEntries) {
16193
16632
  const archivedPath = typeof entry.path === "string" ? entry.path : "";
@@ -16223,7 +16662,7 @@ var init_backups = __esmMin((() => {
16223
16662
  continue;
16224
16663
  }
16225
16664
  const ownerId = target.origin.split(":")[0] ?? "";
16226
- 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({
16227
16666
  workspaceId: target.workspace,
16228
16667
  serverId: ownerId,
16229
16668
  path: target.path
@@ -16267,6 +16706,49 @@ var init_backups = __esmMin((() => {
16267
16706
  });
16268
16707
  plan.createdWorkspaces.push(workspace.id);
16269
16708
  }
16709
+ /**
16710
+ * The load phase: let each restored entry put its own dump back.
16711
+ *
16712
+ * After the files landed and before the panel reloads, so the engine reads a config this
16713
+ * release has just written rather than the one it replaced. Only the entries the archive
16714
+ * actually brought a dump for — an archive taken before the hook existed has none, and running
16715
+ * `mongorestore` on a directory that is not there fails the whole restore for no reason.
16716
+ */
16717
+ const archivedDumps = manifest.dumps ?? [];
16718
+ const pendingLoads = [];
16719
+ for (const entry of archivedDumps) {
16720
+ if (!plan.appliedIds.some((id) => id.startsWith(`workspace:${entry.workspaceId}:`))) continue;
16721
+ if (!actions.has(`workspace:${entry.workspaceId}:dump:${entry.serverId}`) && !actions.has(`workspace:${entry.workspaceId}`)) continue;
16722
+ const server = readArchivedServers(staging, entry.workspaceId).find((candidate) => candidate.id === entry.serverId);
16723
+ if (server?.load === void 0 || server.load === null) {
16724
+ plan.skipped.push(`the dump for "${entry.serverId}" was restored but this entry has no load hook`);
16725
+ continue;
16726
+ }
16727
+ const dumpDir = path.join(staging, "dumps", entry.workspaceId, entry.serverId);
16728
+ if (!fs.existsSync(dumpDir)) {
16729
+ plan.skipped.push(`the dump for "${entry.serverId}" is missing from the archive`);
16730
+ continue;
16731
+ }
16732
+ const staged = path.join(this.options.dataRoot, PENDING_LOAD, entry.workspaceId, entry.serverId);
16733
+ fs.mkdirSync(path.dirname(staged), { recursive: true });
16734
+ fs.cpSync(dumpDir, staged, {
16735
+ recursive: true,
16736
+ force: true
16737
+ });
16738
+ pendingLoads.push({
16739
+ workspaceId: entry.workspaceId,
16740
+ serverId: entry.serverId,
16741
+ staged
16742
+ });
16743
+ plan.hooks = [...plan.hooks ?? [], {
16744
+ serverId: entry.serverId,
16745
+ workspaceId: entry.workspaceId,
16746
+ action: "load",
16747
+ ok: true,
16748
+ output: "staged — runs when this entry next starts"
16749
+ }];
16750
+ }
16751
+ for (const load of pendingLoads) this.options.onLoadPending?.(load.workspaceId, load.serverId, load.staged);
16270
16752
  if (this.options.onRestored !== void 0 && [...actions.keys()].some((id) => RELOADABLE.test(id))) {
16271
16753
  plan.reloaded = true;
16272
16754
  this.options.onRestored();
@@ -16345,9 +16827,9 @@ var init_backups = __esmMin((() => {
16345
16827
  * secret that can be captured but never restored individually.
16346
16828
  */
16347
16829
  secretItems(scope, entryId, path) {
16348
- const present = presentSecretKeys(parseSecrets(readText(path) ?? ""));
16349
- if (present.length === 0) return [];
16350
- 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) => ({
16351
16833
  id: `${entryId}:${part.key}`,
16352
16834
  label: SECRET_LABELS[part.key]?.en ?? part.key,
16353
16835
  ...SECRET_LABELS[part.key] === void 0 ? {} : { labelKey: SECRET_LABELS[part.key].key },
@@ -16355,7 +16837,16 @@ var init_backups = __esmMin((() => {
16355
16837
  secret: part.key,
16356
16838
  included: true,
16357
16839
  note: null
16358
- }));
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
+ }))];
16359
16850
  }
16360
16851
  workspaceItems(workspace, includePaths) {
16361
16852
  const id = workspace.id;
@@ -16485,7 +16976,7 @@ var init_backups = __esmMin((() => {
16485
16976
  for (const name of [...this.flags.keys()]) if (!present.has(name)) this.flags.delete(name);
16486
16977
  }
16487
16978
  missingNote(target) {
16488
- return fs.existsSync(target) ? null : "does not exist yet";
16979
+ return fs.existsSync(target) ? null : "not set";
16489
16980
  }
16490
16981
  /** Copies one source into the staging tree; false when there was nothing there. */
16491
16982
  copyInto(staging, relative, source, ignoreGenerated = false) {
@@ -16539,7 +17030,10 @@ var init_backups = __esmMin((() => {
16539
17030
  if (latest !== null && now - latest < config.schedule.intervalMs) return;
16540
17031
  this.running = true;
16541
17032
  this.lastAttemptAt = now;
16542
- this.create({ automatic: true }).then((result) => {
17033
+ this.create({
17034
+ automatic: true,
17035
+ ...scopeSelection(config.schedule.scope)
17036
+ }).then((result) => {
16543
17037
  if (result.ok) {
16544
17038
  this.scheduleError = null;
16545
17039
  return;
@@ -16822,6 +17316,35 @@ async function readSwapUsedPercent() {
16822
17316
  }
16823
17317
  return 0;
16824
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
+ }
16825
17348
  /**
16826
17349
  * Memory used, as a percentage of what the machine actually has.
16827
17350
  *
@@ -16984,6 +17507,9 @@ async function sampleHost(config, resolvePath) {
16984
17507
  const cpus = os.cpus().length || 1;
16985
17508
  const loadAvg = os.loadavg();
16986
17509
  const memory = memoryInfo();
17510
+ const cpuTimes = cpuTimesSnapshot();
17511
+ const cpuUsedPercentNow = previousCpuTimes === null ? null : cpuUsedPercent(previousCpuTimes, cpuTimes);
17512
+ previousCpuTimes = cpuTimes;
16987
17513
  if (process.platform === "win32") loadAvg.fill(0);
16988
17514
  if (memory.swapUsedPercent === 0 && process.platform !== "linux") memory.swapUsedPercent = await swapUsedPercent();
16989
17515
  const tempCelsius = cpuTemperature();
@@ -16999,6 +17525,7 @@ async function sampleHost(config, resolvePath) {
16999
17525
  enabled: config.enabled,
17000
17526
  cpus,
17001
17527
  loadAvg: [...loadAvg],
17528
+ cpuUsedPercent: cpuUsedPercentNow,
17002
17529
  uptimeMs: os.uptime() * 1e3,
17003
17530
  memoryUsedPercent: memory.memoryUsedPercent,
17004
17531
  swapUsedPercent: memory.swapUsedPercent,
@@ -17017,6 +17544,7 @@ function emptyHostView(config) {
17017
17544
  0,
17018
17545
  0
17019
17546
  ],
17547
+ cpuUsedPercent: null,
17020
17548
  uptimeMs: os.uptime() * 1e3,
17021
17549
  memoryUsedPercent: 0,
17022
17550
  swapUsedPercent: 0,
@@ -17026,11 +17554,12 @@ function emptyHostView(config) {
17026
17554
  sampledAt: null
17027
17555
  };
17028
17556
  }
17029
- var execFileAsync, SWAP_CACHE_MS, swapCache;
17557
+ var execFileAsync, SWAP_CACHE_MS, swapCache, previousCpuTimes;
17030
17558
  var init_host = __esmMin((() => {
17031
17559
  execFileAsync = promisify(execFile);
17032
17560
  SWAP_CACHE_MS = 6e4;
17033
17561
  swapCache = null;
17562
+ previousCpuTimes = null;
17034
17563
  }));
17035
17564
  //#endregion
17036
17565
  //#region src/services/host-monitor.ts
@@ -18151,6 +18680,7 @@ var init_panel = __esmMin((() => {
18151
18680
  init_paths();
18152
18681
  init_version();
18153
18682
  init_ddns$2();
18683
+ init_entry_state();
18154
18684
  init_backups();
18155
18685
  init_config_watch();
18156
18686
  init_ddns();
@@ -18361,6 +18891,25 @@ var init_panel = __esmMin((() => {
18361
18891
  * an archive brought therefore waited for a panel restart — which is why the start of
18362
18892
  * newly appeared autostart entries belongs here, the one place that knows what was new.
18363
18893
  */
18894
+ /**
18895
+ * Record a dump a restore staged, so this entry's next start loads it.
18896
+ *
18897
+ * Written to the entry's own state file rather than memory: the restore usually happens before the
18898
+ * entry has ever started, and a panel restart between the two must not lose the load.
18899
+ */
18900
+ stagePendingLoad(workspaceId, serverId, dumpDir) {
18901
+ const stateDir = workspaceStateDir(workspaceId);
18902
+ fs.mkdirSync(stateDir, { recursive: true });
18903
+ const statePath = entryStatePath(stateDir, serverId);
18904
+ writeEntryState(statePath, {
18905
+ ...readEntryState(statePath) ?? {
18906
+ restarts: 0,
18907
+ bootstrapDone: false
18908
+ },
18909
+ pendingLoad: dumpDir
18910
+ });
18911
+ this.runtimes.get(workspaceId)?.supervisor.stagePendingLoad(serverId, dumpDir);
18912
+ }
18364
18913
  reloadAll() {
18365
18914
  this.options.settings.load();
18366
18915
  for (const runtime of this.workspaces()) {
@@ -18404,7 +18953,7 @@ var init_panel = __esmMin((() => {
18404
18953
  createRuntime(workspace) {
18405
18954
  const id = workspace.id;
18406
18955
  fs.mkdirSync(workspaceDir(id), { recursive: true });
18407
- const store = new WorkspaceStore(id, workspaceSettingsPath(id), id === this.options.registry.defaultId && this.options.defaultServersPath !== void 0 ? this.options.defaultServersPath : workspaceServersPath(id));
18956
+ const store = new WorkspaceStore(id, workspaceSettingsPath(id), workspaceServersPath(id));
18408
18957
  store.load();
18409
18958
  store.writeJsonSchema();
18410
18959
  const secrets = new SecretsStore(workspaceSecretsPath(id), void 0, "workspace");
@@ -19357,7 +19906,7 @@ async function runControlPlane(options) {
19357
19906
  });
19358
19907
  if (trustWarning !== null) logger.warn(trustWarning);
19359
19908
  if (options.printConfig) {
19360
- printEffectiveConfig(settings, registry, options);
19909
+ printEffectiveConfig(settings, registry);
19361
19910
  return;
19362
19911
  }
19363
19912
  if (!await isPortFree(intended.port)) {
@@ -19430,7 +19979,8 @@ async function runControlPlane(options) {
19430
19979
  getConfig: () => settings.backups,
19431
19980
  getSources: () => panel.backupSources(),
19432
19981
  ensureWorkspace: (input) => panel?.ensureWorkspace(input),
19433
- onRestored: () => panel?.reloadAll()
19982
+ onRestored: () => panel?.reloadAll(),
19983
+ onLoadPending: (workspaceId, serverId, dumpDir) => panel?.stagePendingLoad(workspaceId, serverId, dumpDir)
19434
19984
  });
19435
19985
  panel = new PanelService({
19436
19986
  registry,
@@ -19444,8 +19994,7 @@ async function runControlPlane(options) {
19444
19994
  hub,
19445
19995
  control: () => controlServer.endpoint,
19446
19996
  proxy: () => proxy,
19447
- autostart: options.autostart,
19448
- ...options.configPath === void 0 ? {} : { defaultServersPath: options.configPath }
19997
+ autostart: options.autostart
19449
19998
  });
19450
19999
  for (const workspace of panel.workspaces()) {
19451
20000
  const store = workspace.store;
@@ -19549,7 +20098,7 @@ async function runControlPlane(options) {
19549
20098
  process.on("SIGTERM", () => onSignal("SIGTERM"));
19550
20099
  }
19551
20100
  /** `--print-config`: the global settings and every workspace, without starting anything. */
19552
- function printEffectiveConfig(settings, registry, options) {
20101
+ function printEffectiveConfig(settings, registry) {
19553
20102
  const workspaces = registry.all().map((workspace) => {
19554
20103
  const dir = path.join(hhDir, workspace.id);
19555
20104
  const read = (name) => {
@@ -19559,18 +20108,11 @@ function printEffectiveConfig(settings, registry, options) {
19559
20108
  return null;
19560
20109
  }
19561
20110
  };
19562
- const serversFile = workspace.id === registry.defaultId && options.configPath !== void 0 ? options.configPath : path.join(dir, "servers.config.json");
19563
- let servers = null;
19564
- try {
19565
- servers = JSON.parse(fs.readFileSync(serversFile, "utf8"));
19566
- } catch {
19567
- servers = null;
19568
- }
19569
20111
  return {
19570
20112
  id: workspace.id,
19571
20113
  label: workspace.label,
19572
20114
  settings: read("settings.json"),
19573
- servers
20115
+ servers: read("servers.config.json")
19574
20116
  };
19575
20117
  });
19576
20118
  process.stdout.write(`${JSON.stringify({
@@ -19626,7 +20168,6 @@ function toUpFlags(args) {
19626
20168
  if (!Number.isInteger(port) || port <= 0 || port > 65535) fail(`invalid port: ${args.port}`);
19627
20169
  }
19628
20170
  return {
19629
- config: args.config,
19630
20171
  port,
19631
20172
  host: args.host,
19632
20173
  autostart: args.autostart !== false,
@@ -19639,7 +20180,6 @@ async function runUp(flags, entry) {
19639
20180
  if (flags.foreground || flags.printConfig) {
19640
20181
  const { runControlPlane } = await Promise.resolve().then(() => (init_src(), src_exports));
19641
20182
  await runControlPlane({
19642
- configPath: flags.config,
19643
20183
  port: flags.port,
19644
20184
  host: flags.host,
19645
20185
  autostart: flags.autostart,
@@ -19725,11 +20265,6 @@ var init_up = __esmMin((() => {
19725
20265
  init_version();
19726
20266
  DEFAULT_PORT$1 = 3999;
19727
20267
  upArgs = {
19728
- config: {
19729
- type: "string",
19730
- alias: "c",
19731
- description: "the default workspace's servers config (default: <state>/.hh/default/servers.config.json)"
19732
- },
19733
20268
  port: {
19734
20269
  type: "string",
19735
20270
  alias: "p",
@@ -20334,7 +20869,7 @@ var migrate_exports = /* @__PURE__ */ __exportAll({
20334
20869
  runMigrate: () => runMigrate
20335
20870
  });
20336
20871
  /** Every file a migration may have to stamp, and how this release reads it. */
20337
- function targets(configOverride) {
20872
+ function targets() {
20338
20873
  const list = [{
20339
20874
  file: globalSettingsPath,
20340
20875
  label: "global settings",
@@ -20350,7 +20885,7 @@ function targets(configOverride) {
20350
20885
  validate: (raw) => parseWorkspaceSettings(raw).errors[0] ?? null
20351
20886
  });
20352
20887
  list.push({
20353
- file: workspace.id === registry.defaultId && configOverride !== void 0 ? configOverride : workspaceServersPath(workspace.id),
20888
+ file: workspaceServersPath(workspace.id),
20354
20889
  label: `workspace ${workspace.id} servers`,
20355
20890
  validate: (raw) => {
20356
20891
  let defaults = {};
@@ -20366,8 +20901,8 @@ function targets(configOverride) {
20366
20901
  }
20367
20902
  return list;
20368
20903
  }
20369
- async function runMigrate(config, dryRun, yes) {
20370
- const existing = targets(config).filter((target) => fs.existsSync(target.file));
20904
+ async function runMigrate(dryRun, yes) {
20905
+ const existing = targets().filter((target) => fs.existsSync(target.file));
20371
20906
  if (existing.length === 0) fail(`no home-hosted state to migrate — nothing at ${globalSettingsPath} or any workspace`);
20372
20907
  const consented = yes || (process.env.HHOSTED_MIGRATE ?? "").toLowerCase() === "allow";
20373
20908
  let stampOnly = 0;
@@ -20440,11 +20975,6 @@ var init_migrate = __esmMin((() => {
20440
20975
  init_error_message();
20441
20976
  init_shape();
20442
20977
  migrateArgs = {
20443
- config: {
20444
- type: "string",
20445
- alias: "c",
20446
- description: "the default workspace's servers config (default: <state>/.hh/default/servers.config.json)"
20447
- },
20448
20978
  dryRun: {
20449
20979
  type: "boolean",
20450
20980
  description: "print what would change, write nothing"
@@ -20459,7 +20989,7 @@ var init_migrate = __esmMin((() => {
20459
20989
  meta: { name: "migrate" },
20460
20990
  args: migrateArgs,
20461
20991
  run: async ({ args }) => {
20462
- await runMigrate(args.config, args.dryRun === true, args.yes === true);
20992
+ await runMigrate(args.dryRun === true, args.yes === true);
20463
20993
  }
20464
20994
  });
20465
20995
  }));
@@ -21228,6 +21758,24 @@ function createOfflineBackup(options = {}) {
21228
21758
  * panel there is nobody to do it, so the registry is written here — otherwise a restored
21229
21759
  * workspace's files land on disk unreachable, and the next `up` never looks at them.
21230
21760
  */
21761
+ /**
21762
+ * Record the staged dump so the entry's next `up` loads it.
21763
+ *
21764
+ * Nothing is running to hold it in memory, so this is the only path that matters offline: the
21765
+ * panel is started afterwards, reads the entry state, and runs the hook.
21766
+ */
21767
+ onLoadPending: (workspaceId, serverId, dumpDir) => {
21768
+ const dir = path.join(hhDir$1, workspaceId, ".state");
21769
+ fs.mkdirSync(dir, { recursive: true });
21770
+ const statePath = entryStatePath(dir, serverId);
21771
+ writeEntryState(statePath, {
21772
+ ...readEntryState(statePath) ?? {
21773
+ restarts: 0,
21774
+ bootstrapDone: false
21775
+ },
21776
+ pendingLoad: dumpDir
21777
+ });
21778
+ },
21231
21779
  ensureWorkspace: (input) => {
21232
21780
  if (registry.has(input.id)) return;
21233
21781
  registry.create(input);
@@ -21251,6 +21799,7 @@ var init_backup_offline = __esmMin((() => {
21251
21799
  init_store();
21252
21800
  init_workspaces();
21253
21801
  init_paths();
21802
+ init_entry_state();
21254
21803
  init_nanny$2();
21255
21804
  init_backups();
21256
21805
  }));
@@ -21262,6 +21811,49 @@ var backup_exports = /* @__PURE__ */ __exportAll({
21262
21811
  runBackupList: () => runBackupList,
21263
21812
  runBackupRestore: () => runBackupRestore
21264
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
+ }
21265
21857
  function human(bytes) {
21266
21858
  if (bytes < 1024) return `${bytes} B`;
21267
21859
  if (bytes < 1048576) return `${Math.round(bytes / 1024)} KB`;
@@ -21292,11 +21884,9 @@ async function usesPanel() {
21292
21884
  /**
21293
21885
  * The offline service.
21294
21886
  *
21295
- * `--config` is an `up`-only flag: it is not written to settings, and `run.json`'s `configPath` is the
21296
- * state directory, not a servers file. So an offline run cannot know about one, and reads the default
21297
- * workspace's `servers.config.json` — the same file the panel reads when started without `--config`.
21298
- * A `--config` project has to start the panel first, which is the honest limit rather than a silent
21299
- * difference between the two paths.
21887
+ * It reads the same files the panel does — every workspace's `settings.json` and
21888
+ * `servers.config.json` under the state root — so an archive taken with the panel down holds what a
21889
+ * running one would have captured.
21300
21890
  */
21301
21891
  async function offlineBackup() {
21302
21892
  return createOfflineBackup();
@@ -21326,14 +21916,83 @@ function parseScope(all, raw) {
21326
21916
  };
21327
21917
  }
21328
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
+ /**
21329
21963
  * Neither flag given. Refused outright — the ids are a *bonus*, not the reason.
21330
21964
  *
21331
21965
  * The refusal must not depend on a panel being up: a mistyped command deserves the flag error, not
21332
21966
  * "home-hosted is not running". So the list is best-effort, and a failure to produce it is silent.
21333
21967
  */
21334
21968
  async function refuseWithoutScope(action, suffix) {
21335
- const ids = await availableIdsFor(action, suffix).catch(() => []);
21336
- 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
+ }
21337
21996
  }
21338
21997
  /**
21339
21998
  * The ids this action could be scoped to.
@@ -21342,15 +22001,15 @@ async function refuseWithoutScope(action, suffix) {
21342
22001
  * panel, so the list in a refusal is the real one rather than a hardcoded guess. A panel that cannot
21343
22002
  * be reached yields no ids — the refusal still fires, it just cannot enumerate.
21344
22003
  */
21345
- async function availableIdsFor(action, suffix) {
22004
+ async function availableRows(action, suffix) {
21346
22005
  const daemon = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
21347
22006
  const runtime = daemon.readRuntime();
21348
- if (runtime === null) return [];
22007
+ if (runtime === null || !await daemon.runtimeIsAlive(runtime)) return await availableRowsFromDisk(action, suffix);
21349
22008
  const path = action === "create" ? "/_hh/backups" : "/_hh/backups/restore";
21350
22009
  const answer = await daemon.requestControl(runtime, `${path}${suffix}`, 12e4);
21351
22010
  if (answer === null || answer.status !== 200) return [];
21352
22011
  const body = answer.body;
21353
- return ((action === "create" ? body?.entries : body?.items) ?? []).map((item) => item.id).filter((id) => typeof id === "string");
22012
+ return action === "create" ? body?.entries ?? [] : body?.items ?? [];
21354
22013
  }
21355
22014
  /** `?a=b`, or `''`. */
21356
22015
  function suffixOf(query) {
@@ -21448,7 +22107,9 @@ async function runBackupCreate(options) {
21448
22107
  await service.warm();
21449
22108
  return service.view().entries;
21450
22109
  })();
21451
- 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);
21452
22113
  if (!options.confirm) {
21453
22114
  if (options.json) {
21454
22115
  process.stdout.write(`${JSON.stringify({
@@ -21459,10 +22120,7 @@ async function runBackupCreate(options) {
21459
22120
  return;
21460
22121
  }
21461
22122
  process.stdout.write(`${bold("Plan")} — what a backup would capture; nothing has been written yet\n`);
21462
- for (const entry of wanted) {
21463
- process.stdout.write(` ${String(entry.kind ?? "entry").padEnd(10)} ${entry.id}${entry.note == null ? "" : ` ${dim(`(${entry.note})`)}`}\n`);
21464
- for (const item of entry.items ?? []) process.stdout.write(` ${dim("-")} ${item.id}\n`);
21465
- }
22123
+ printPlanTree(flattenRows(wanted));
21466
22124
  if (wanted.length === 0) {
21467
22125
  process.stdout.write(" (nothing matched — check --include, or what the entries declare)\n");
21468
22126
  return;
@@ -21471,6 +22129,7 @@ async function runBackupCreate(options) {
21471
22129
  if (!await consent("Take this backup?")) return;
21472
22130
  }
21473
22131
  const include = scope.kind === "include" ? scope.ids : void 0;
22132
+ const exclude = options.exclude;
21474
22133
  const file = (await (async () => {
21475
22134
  if (online) {
21476
22135
  const runtime = await livePanel();
@@ -21478,6 +22137,7 @@ async function runBackupCreate(options) {
21478
22137
  const query = new URLSearchParams();
21479
22138
  if (options.password !== void 0 && options.password.length > 0) query.set("password", options.password);
21480
22139
  if (include !== void 0) query.set("include", include.join(","));
22140
+ if (exclude !== void 0) query.set("exclude", exclude.join(","));
21481
22141
  const answer = await runtime.request(runtime, `/_hh/backups${withParam(suffixOf(query), "confirm", "true")}`, 6e5);
21482
22142
  if (answer === null) fail(`the control panel is not answering on ${runtime.probeUrl}`);
21483
22143
  if (answer.status !== 200) refusal(answer);
@@ -21488,7 +22148,8 @@ async function runBackupCreate(options) {
21488
22148
  await service.warm();
21489
22149
  const result = await service.create({
21490
22150
  password: options.password,
21491
- include
22151
+ include,
22152
+ exclude
21492
22153
  });
21493
22154
  if (!result.ok) fail(result.error ?? "the backup failed");
21494
22155
  return { file: result.file };
@@ -21525,7 +22186,8 @@ async function runBackupRestore(options) {
21525
22186
  return await service.restore(archive, {
21526
22187
  confirm: false,
21527
22188
  password: options.password,
21528
- include: scope.kind === "include" ? scope.ids : void 0
22189
+ include: scope.kind === "include" ? scope.ids : void 0,
22190
+ exclude: options.exclude
21529
22191
  });
21530
22192
  }
21531
22193
  const runtime = await livePanel();
@@ -21533,6 +22195,7 @@ async function runBackupRestore(options) {
21533
22195
  const base = new URLSearchParams({ name: options.name });
21534
22196
  if (options.password !== void 0 && options.password.length > 0) base.set("password", options.password);
21535
22197
  if (scope.kind === "include") base.set("include", scope.ids.join(","));
22198
+ if (options.exclude !== void 0) base.set("exclude", options.exclude.join(","));
21536
22199
  const answer = await runtime.request(runtime, `/_hh/backups/restore${suffixOf(base)}`, 12e4);
21537
22200
  if (answer === null) fail(`the control panel is not answering at ${runtime.probeUrl}`);
21538
22201
  if (answer.status !== 200) refusal(answer);
@@ -21551,7 +22214,10 @@ async function runBackupRestore(options) {
21551
22214
  }
21552
22215
  if (!options.json) {
21553
22216
  process.stdout.write(`${bold("Plan")} for ${options.name} — nothing has been written yet\n`);
21554
- 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
+ })));
21555
22221
  for (const warning of plan?.warnings ?? []) process.stdout.write(` ${dim("!")} ${warning}\n`);
21556
22222
  if (items.length === 0) {
21557
22223
  process.stdout.write(" (nothing to restore — check --include, or what this host declares)\n");
@@ -21560,36 +22226,49 @@ async function runBackupRestore(options) {
21560
22226
  }
21561
22227
  if (!options.confirm && !await consent(`Restore these ${items.length} item(s) over this host?`)) return;
21562
22228
  {
21563
- const applied = await (async () => {
22229
+ const outcome = await (async () => {
21564
22230
  if (service !== null) {
21565
22231
  const archive = service.resolve(options.name);
21566
- return ((await service.restore(archive, {
22232
+ const result = await service.restore(archive, {
21567
22233
  confirm: true,
21568
22234
  password: options.password,
21569
- include: scope.kind === "include" ? scope.ids : void 0
21570
- })).items ?? []).filter((item) => item.selected !== false);
22235
+ include: scope.kind === "include" ? scope.ids : void 0,
22236
+ exclude: options.exclude
22237
+ });
22238
+ return {
22239
+ items: (result.items ?? []).filter((item) => item.selected !== false),
22240
+ hooks: (result.hooks ?? []).filter((hook) => hook.action === "load")
22241
+ };
21571
22242
  }
21572
22243
  const runtime = await livePanel();
21573
22244
  if (runtime === null) fail("the control panel stopped answering — nothing further was written");
21574
22245
  const base = new URLSearchParams({ name: options.name });
21575
22246
  if (options.password !== void 0 && options.password.length > 0) base.set("password", options.password);
21576
22247
  if (scope.kind === "include") base.set("include", scope.ids.join(","));
22248
+ if (options.exclude !== void 0) base.set("exclude", options.exclude.join(","));
21577
22249
  const answer = await runtime.request(runtime, `/_hh/backups/restore${withParam(suffixOf(base), "confirm", "true")}`, 6e5);
21578
22250
  if (answer === null) fail(`the control panel is not answering at ${runtime.probeUrl}`);
21579
22251
  if (answer.status !== 200) refusal(answer);
21580
- return (answer.body?.items ?? plan?.items ?? []).filter((item) => item.selected !== false);
22252
+ const result = answer.body;
22253
+ return {
22254
+ items: (result?.items ?? plan?.items ?? []).filter((item) => item.selected !== false),
22255
+ hooks: (result?.hooks ?? plan?.hooks ?? []).filter((hook) => hook.action === "load")
22256
+ };
21581
22257
  })();
22258
+ const applied = outcome.items;
21582
22259
  if (options.json) {
21583
22260
  process.stdout.write(`${JSON.stringify({
21584
22261
  action: "restore",
21585
22262
  apply: true,
21586
22263
  name: options.name,
21587
22264
  items: applied,
22265
+ hooks: outcome.hooks,
21588
22266
  warnings: plan?.warnings ?? []
21589
22267
  }, null, 2)}\n`);
21590
22268
  return;
21591
22269
  }
21592
22270
  process.stdout.write(`${green("restored")} ${applied.length} ${applied.length === 1 ? "item" : "items"} from ${options.name}\n`);
22271
+ for (const hook of outcome.hooks) process.stdout.write(` ${dim(`load ${hook.serverId}: ${hook.output ?? "staged"}`)}\n`);
21593
22272
  for (const warning of plan?.warnings ?? []) process.stdout.write(` ${dim("!")} ${warning}\n`);
21594
22273
  if (service !== null) process.stdout.write(dim(`the panel is not running, so nothing was reloaded — the next \`${invocation()} up\` reads what was restored\n`));
21595
22274
  }
@@ -21598,6 +22277,7 @@ var backupCommand;
21598
22277
  var init_backup = __esmMin((() => {
21599
22278
  init_backup_offline();
21600
22279
  init_io();
22280
+ init_backup_scope();
21601
22281
  init_error_message();
21602
22282
  backupCommand = defineCommand({
21603
22283
  meta: { name: "backup" },
@@ -21620,6 +22300,10 @@ var init_backup = __esmMin((() => {
21620
22300
  type: "string",
21621
22301
  description: "comma-separated item ids to act on"
21622
22302
  },
22303
+ exclude: {
22304
+ type: "string",
22305
+ description: "comma-separated item ids to leave out, applied after --include"
22306
+ },
21623
22307
  all: {
21624
22308
  type: "boolean",
21625
22309
  description: "act on everything, rather than naming ids"
@@ -21637,12 +22321,14 @@ var init_backup = __esmMin((() => {
21637
22321
  try {
21638
22322
  const action = args.action === void 0 || args.action.length === 0 ? "list" : args.action;
21639
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;
21640
22325
  if (action === "list") await runBackupList(args.json === true);
21641
22326
  else if (action === "create") {
21642
22327
  const scope = parsed ?? await refuseWithoutScope("create", "");
21643
22328
  await runBackupCreate({
21644
22329
  password: args.password,
21645
22330
  scope,
22331
+ exclude,
21646
22332
  confirm: args.confirm === true,
21647
22333
  json: args.json === true
21648
22334
  });
@@ -21653,6 +22339,7 @@ var init_backup = __esmMin((() => {
21653
22339
  name: args.target,
21654
22340
  password: args.password,
21655
22341
  scope,
22342
+ exclude,
21656
22343
  confirm: args.confirm === true,
21657
22344
  json: args.json === true
21658
22345
  });
@@ -21881,7 +22568,6 @@ var OPTION_WIDTH = 21;
21881
22568
  var UP_SECTION = {
21882
22569
  heading: "Options for up/restart",
21883
22570
  lines: [
21884
- ["-c, --config <file>", "default workspace servers config (default: <state>/.hh/default/servers.config.json)"],
21885
22571
  ["-p, --port <port>", "control panel port (default: 3999)"],
21886
22572
  ["--host <bind>", "local | lan | an ipv4 address (default: local)"],
21887
22573
  ["--open", "open the panel in a browser once it is up"],
@@ -21909,6 +22595,7 @@ var BACKUP_SECTION = {
21909
22595
  ["<name>", "the archive, for restore — `backup list` shows them"],
21910
22596
  ["--include <ids>", "comma-separated item ids to act on (required for create/restore)"],
21911
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"],
21912
22599
  ["--password <text>", "encrypt a new archive, or unlock one on restore"],
21913
22600
  ["--confirm", "apply without asking (create and restore plan first)"],
21914
22601
  ["--json", "print the plan or the result as JSON"]
@@ -21936,11 +22623,7 @@ var SET_TOKEN_SECTION = {
21936
22623
  };
21937
22624
  var MIGRATE_SECTION = {
21938
22625
  heading: "Options for migrate",
21939
- lines: [
21940
- ["-c, --config <file>", "one config file to migrate (default: every file this state root owns)"],
21941
- ["--dry-run", "print what would change, write nothing"],
21942
- ["-y, --yes", "apply without asking (or set HHOSTED_MIGRATE=allow)"]
21943
- ]
22626
+ lines: [["--dry-run", "print what would change, write nothing"], ["-y, --yes", "apply without asking (or set HHOSTED_MIGRATE=allow)"]]
21944
22627
  };
21945
22628
  var INIT_SECTION = {
21946
22629
  heading: "Options for init",