@kvbox/server 0.6.11 → 0.6.13

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.
@@ -9,6 +9,12 @@ var KvboxError = class extends Error {
9
9
  }
10
10
  exitCode;
11
11
  };
12
+ var NotImplementedError = class extends KvboxError {
13
+ constructor(what) {
14
+ super(`${what}: not implemented yet`, 2);
15
+ this.name = "NotImplementedError";
16
+ }
17
+ };
12
18
  var NotFoundError = class extends KvboxError {
13
19
  constructor(what) {
14
20
  super(`${what}: not found`, 1);
@@ -734,6 +740,7 @@ function macFor(ip) {
734
740
  import { spawn as spawn2 } from "node:child_process";
735
741
  import { closeSync, existsSync as existsSync2, openSync as openSync2 } from "node:fs";
736
742
  import { readFile as readFile3, rm as rm2 } from "node:fs/promises";
743
+ import { relative } from "node:path";
737
744
 
738
745
  // src/core/proc.ts
739
746
  import { setTimeout as sleep } from "node:timers/promises";
@@ -890,6 +897,7 @@ var FirecrackerClient = class {
890
897
  // src/core/drivers/firecracker/vm.ts
891
898
  var GUEST_CID = 3;
892
899
  var OVERLAY_REL = "overlay.ext4";
900
+ var vsockRel = (m) => relative(m.dir, m.vsock);
893
901
  function bootArgs(name, ip, cfg, pubkeyB64) {
894
902
  const args = `console=ttyS0 reboot=k panic=1 init=/sbin/overlay-init kvbox.overlay=/dev/vdb ip=${ip}::${cfg.gateway}:255.255.255.0:${name}:eth0:off kvbox.name=${name} kvbox.sshkey=${pubkeyB64}`;
895
903
  return process.arch === "arm64" ? `keep_bootcon ${args}` : args;
@@ -945,7 +953,7 @@ async function boot(spec, disks, tap, cfg, p) {
945
953
  for (const v of disks.volumes) await fc.volumeDrive(v.id, v.path);
946
954
  await fc.machineConfig(spec.vcpu, spec.memMib);
947
955
  await fc.networkInterface("eth0", tap, spec.mac);
948
- await fc.vsock(GUEST_CID, m.vsock);
956
+ await fc.vsock(GUEST_CID, vsockRel(m));
949
957
  await fc.start();
950
958
  });
951
959
  return pid;
@@ -965,7 +973,7 @@ async function restore(box, state, tap, cfg, p) {
965
973
  snapshotPath: state.vmstate,
966
974
  memFilePath: state.mem,
967
975
  tap: { ifaceId: "eth0", hostDevName: tap },
968
- vsockPath: m.vsock,
976
+ vsockPath: vsockRel(m),
969
977
  trackDirtyPages: true,
970
978
  resume: false
971
979
  })
@@ -996,6 +1004,9 @@ async function cleanup(box, p) {
996
1004
  await rm2(m.sock, { force: true });
997
1005
  await rm2(m.vsock, { force: true });
998
1006
  }
1007
+ function guestSocket(box, port, p) {
1008
+ return `${p.machine(box.owner, box.name).vsock}_${port}`;
1009
+ }
999
1010
 
1000
1011
  // src/core/drivers/firecracker/index.ts
1001
1012
  var firecrackerDriver = {
@@ -1012,7 +1023,8 @@ var firecrackerDriver = {
1012
1023
  resume,
1013
1024
  shutdown,
1014
1025
  saveState,
1015
- cleanup
1026
+ cleanup,
1027
+ guestSocket
1016
1028
  },
1017
1029
  net: {
1018
1030
  prepare: ensureHostNetwork,
@@ -1295,7 +1307,13 @@ var MachineMetaSchema = z3.object({
1295
1307
  * was removed but the rule would not close; kept only so this box's next stop closes it, never opened
1296
1308
  * again, never listed (a new box of the same name may get the same IP). Absent: none.
1297
1309
  */
1298
- links: z3.array(z3.object({ owner: z3.string(), name: z3.string(), ip: z3.string(), port: z3.number().int(), stale: z3.literal(true).optional() })).optional()
1310
+ links: z3.array(z3.object({ owner: z3.string(), name: z3.string(), ip: z3.string(), port: z3.number().int(), stale: z3.literal(true).optional() })).optional(),
1311
+ /**
1312
+ * The integrations turned on for the box (#205): names only (`github`), never a credential. The box asks
1313
+ * for one each time it needs it (core/machines/integrations.ts) and is answered only for a name in this
1314
+ * list. Plain strings, so a name a newer server wrote still reads. Absent: none.
1315
+ */
1316
+ integrations: z3.array(z3.string()).optional()
1299
1317
  });
1300
1318
  var VolumeMetaSchema = z3.object({
1301
1319
  /** Host-unique like a box id (#91): the ledger's key, so a name removed and made again is two volumes. */
@@ -1328,7 +1346,9 @@ var SnapshotMetaSchema = z3.object({
1328
1346
  * and their mounts in the memory image, but their data is not here. A box restored from the snapshot
1329
1347
  * gets an empty placeholder of each size at the drive's path and drops the mounts through kvbox-agent.
1330
1348
  */
1331
- volumes: z3.array(z3.object({ name: z3.string(), sizeGib: z3.number().int() })).optional()
1349
+ volumes: z3.array(z3.object({ name: z3.string(), sizeGib: z3.number().int() })).optional(),
1350
+ /** The source box's integrations when it was frozen (#205): a box restored from the snapshot has them on too. */
1351
+ integrations: z3.array(z3.string()).optional()
1332
1352
  });
1333
1353
  async function ensureLayout(p = paths()) {
1334
1354
  for (const dir of [p.home, p.ssh, p.bin, p.assets, p.machines, p.snapshots, p.volumes]) {
@@ -1744,7 +1764,7 @@ function namesIn(text) {
1744
1764
 
1745
1765
  // src/core/machines/change.ts
1746
1766
  import { statSync as statSync3 } from "node:fs";
1747
- import { rename as rename5, rm as rm6 } from "node:fs/promises";
1767
+ import { rename as rename5, rm as rm8 } from "node:fs/promises";
1748
1768
 
1749
1769
  // src/core/capacity.ts
1750
1770
  import { cpus, totalmem } from "node:os";
@@ -1766,1048 +1786,1158 @@ import { existsSync as existsSync5, statSync } from "node:fs";
1766
1786
  import { lstat, mkdir as mkdir2, readdir as readdir3, rm as rm3, statfs, symlink, truncate, writeFile as writeFile3 } from "node:fs/promises";
1767
1787
 
1768
1788
  // ../shared/src/api.ts
1789
+ import { z as z6 } from "zod";
1790
+
1791
+ // ../shared/src/integrations.ts
1769
1792
  import { z as z5 } from "zod";
1770
- var SizeSchema = z5.enum(SIZE_NAMES);
1771
- var BoxStatusSchema = z5.enum(["running", "standby", "hibernated", "stopped", "unknown"]);
1772
- var PortProtoSchema = z5.enum(["tcp", "udp"]);
1793
+ var INTEGRATION_IDS = ["github"];
1794
+ var IntegrationIdSchema = z5.enum(INTEGRATION_IDS);
1795
+ var INTEGRATION_KINDS = ["oauth", "app", "api-key", "subscription"];
1796
+ var IntegrationKindSchema = z5.enum(INTEGRATION_KINDS);
1797
+ var INTEGRATION_STATUSES = ["ok", "needs-reconnect"];
1798
+ var IntegrationStatusSchema = z5.enum(INTEGRATION_STATUSES);
1799
+ var IntegrationListSchema = z5.array(z5.string().min(1).max(40)).max(20).transform((list) => [...new Set(list)]);
1800
+ function assertKnownIntegrations(list, who, hint = `the integrations are: ${INTEGRATION_IDS.join(", ")}`) {
1801
+ const unknown = (list ?? []).filter((n) => !INTEGRATION_IDS.includes(n));
1802
+ if (unknown.length > 0) throw new KvboxError(`${who} does not know the integration ${unknown.join(", ")} (${hint})`);
1803
+ }
1804
+ var IntegrationCatalogEntrySchema = z5.object({
1805
+ /** A plain string, like `integration` in a listing row: a reader may be older than the control plane. */
1806
+ id: z5.string(),
1807
+ title: z5.string(),
1808
+ description: z5.string(),
1809
+ /** How Connect works: `oauth` sends the browser to the provider's consent screen. */
1810
+ connect: z5.enum(["oauth"]),
1811
+ /** What a user's slug and an org's may hold; an empty list: that kind of slug cannot connect it yet. */
1812
+ kinds: z5.object({ user: z5.array(IntegrationKindSchema), org: z5.array(IntegrationKindSchema) }),
1813
+ /** Whether this control plane is set up for it (a self-hosted one without a GitHub app is not). */
1814
+ available: z5.boolean(),
1815
+ /** Its guide, as a URL. */
1816
+ docs: z5.string().optional(),
1817
+ /** Where it is connected and disconnected: this control plane's web app, when it has one. */
1818
+ page: z5.string().optional()
1819
+ });
1820
+ var IntegrationSchema = z5.object({
1821
+ /** The slug it belongs to: a user's or an org's. */
1822
+ owner: z5.string(),
1823
+ /**
1824
+ * Which one (`github`). A plain string, not the ids above: this is an answer, read by every released CLI
1825
+ * and SDK, and one from before a new integration must still read the listing that has it.
1826
+ */
1827
+ integration: z5.string(),
1828
+ connected: z5.boolean(),
1829
+ /** The rest is null while not connected. */
1830
+ kind: IntegrationKindSchema.nullable(),
1831
+ /** Whose account, as shown: the GitHub login. Never a secret. */
1832
+ account: z5.string().nullable(),
1833
+ status: IntegrationStatusSchema.nullable(),
1834
+ connectedBy: z5.string().nullable(),
1835
+ connectedAt: z5.string().nullable(),
1836
+ /** The last time a box was handed the credential (to the minute). */
1837
+ lastUsedAt: z5.string().nullable(),
1838
+ /** Whether the caller may connect or disconnect it: the slug's own user, an org's owners. */
1839
+ canManage: z5.boolean()
1840
+ });
1841
+ var IntegrationConnectSchema = z5.object({ url: z5.string() });
1842
+ var IntegrationCompleteRequestSchema = z5.object({ code: z5.string().min(1), state: z5.string().min(1) });
1843
+ var IntegrationIdentitySchema = z5.object({ name: z5.string(), email: z5.string() });
1844
+ var CREDENTIAL_REFUSALS = ["off", "not-connected", "needs-reconnect", "unavailable"];
1845
+ var CredentialAnswerSchema = z5.discriminatedUnion("ok", [
1846
+ z5.object({
1847
+ ok: z5.literal(true),
1848
+ kind: IntegrationKindSchema,
1849
+ token: z5.string(),
1850
+ /** When the token ends (ISO), for one that does (a GitHub App's hour). */
1851
+ expiresAt: z5.string().optional(),
1852
+ identity: IntegrationIdentitySchema.optional()
1853
+ }),
1854
+ z5.object({
1855
+ ok: z5.literal(false),
1856
+ code: z5.enum(CREDENTIAL_REFUSALS),
1857
+ message: z5.string(),
1858
+ /** With `off`: whether the slug has it connected, so the box can say how to turn it on. */
1859
+ connected: z5.boolean().optional()
1860
+ })
1861
+ ]);
1862
+ var HostCredentialRequestSchema = z5.object({ owner: z5.string().min(1), box: z5.string().min(1), integration: IntegrationIdSchema, probe: z5.boolean().optional() });
1863
+ var ConnectedAnswerSchema = z5.object({ connected: z5.boolean(), identity: IntegrationIdentitySchema.optional() });
1864
+ var GUEST_REQUEST_PORT = 53;
1865
+ var GuestRequestSchema = z5.object({ op: z5.literal("credential"), integration: IntegrationIdSchema });
1866
+ var INTEGRATIONS_BASE = "0.17.0";
1867
+ var GUEST_REQUESTS_PER_MINUTE = 60;
1868
+
1869
+ // ../shared/src/api.ts
1870
+ var SizeSchema = z6.enum(SIZE_NAMES);
1871
+ var BoxStatusSchema = z6.enum(["running", "standby", "hibernated", "stopped", "unknown"]);
1872
+ var PortProtoSchema = z6.enum(["tcp", "udp"]);
1773
1873
  var MAX_BOX_PORTS = 16;
1774
- var PortForwardSchema = z5.object({
1775
- guestPort: z5.number().int().min(1).max(65535),
1776
- hostPort: z5.number().int(),
1874
+ var PortForwardSchema = z6.object({
1875
+ guestPort: z6.number().int().min(1).max(65535),
1876
+ hostPort: z6.number().int(),
1777
1877
  proto: PortProtoSchema,
1778
1878
  /** The host's public address; only the control plane fills it in, as for `ssh`. */
1779
- address: z5.string().optional(),
1879
+ address: z6.string().optional(),
1780
1880
  /**
1781
1881
  * Closed but kept (#173): nothing reaches the box through it, and the host port stays the box's, so
1782
1882
  * publishing the same box port again opens the same number. Absent: open while the box runs.
1783
1883
  */
1784
- closed: z5.literal(true).optional()
1884
+ closed: z6.literal(true).optional()
1785
1885
  });
1786
- var PortsRequest = z5.object({
1787
- ports: z5.array(z5.object({ guestPort: z5.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS),
1886
+ var PortsRequest = z6.object({
1887
+ ports: z6.array(z6.object({ guestPort: z6.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS),
1788
1888
  /** `DELETE` only (#173): close the ports but keep their host ports for the box (`closed`). */
1789
- keep: z5.boolean().optional()
1889
+ keep: z6.boolean().optional()
1790
1890
  });
1791
- var BoxPortSchema = z5.number().int().min(1).max(65535);
1891
+ var BoxPortSchema = z6.number().int().min(1).max(65535);
1792
1892
  var MAX_BOX_LINKS = 32;
1793
- var BoxLinkSchema = z5.object({ from: z5.string(), port: BoxPortSchema });
1794
- var LinkRequest = z5.object({ from: z5.string().min(1), fromOwner: z5.string().optional(), port: BoxPortSchema });
1795
- var ClaimSubdomainRequest = z5.object({ name: z5.string(), port: BoxPortSchema });
1796
- var SubdomainPortRequest = z5.object({ port: BoxPortSchema });
1797
- var SubdomainRouteRequest = z5.object({ name: z5.string(), port: BoxPortSchema });
1798
- var SubdomainSchema = z5.object({
1799
- owner: z5.string(),
1800
- box: z5.string(),
1801
- subdomain: z5.string(),
1893
+ var BoxLinkSchema = z6.object({ from: z6.string(), port: BoxPortSchema });
1894
+ var LinkRequest = z6.object({ from: z6.string().min(1), fromOwner: z6.string().optional(), port: BoxPortSchema });
1895
+ var ClaimSubdomainRequest = z6.object({ name: z6.string(), port: BoxPortSchema });
1896
+ var SubdomainPortRequest = z6.object({ port: BoxPortSchema });
1897
+ var SubdomainRouteRequest = z6.object({ name: z6.string(), port: BoxPortSchema });
1898
+ var SubdomainSchema = z6.object({
1899
+ owner: z6.string(),
1900
+ box: z6.string(),
1901
+ subdomain: z6.string(),
1802
1902
  port: BoxPortSchema,
1803
- url: z5.string(),
1804
- routes: z5.array(z5.object({ name: z5.string(), port: BoxPortSchema, url: z5.string() }))
1805
- });
1806
- var AddDomainRequest = z5.object({ domain: z5.string(), port: BoxPortSchema.optional() });
1807
- var DomainSchema = z5.object({
1808
- owner: z5.string(),
1809
- box: z5.string(),
1810
- domain: z5.string(),
1903
+ url: z6.string(),
1904
+ routes: z6.array(z6.object({ name: z6.string(), port: BoxPortSchema, url: z6.string() }))
1905
+ });
1906
+ var AddDomainRequest = z6.object({ domain: z6.string(), port: BoxPortSchema.optional() });
1907
+ var DomainSchema = z6.object({
1908
+ owner: z6.string(),
1909
+ box: z6.string(),
1910
+ domain: z6.string(),
1811
1911
  port: BoxPortSchema,
1812
- status: z5.enum(["pending", "live"]),
1813
- www: z5.boolean(),
1814
- url: z5.string(),
1815
- error: z5.string().nullable(),
1816
- records: z5.array(z5.object({ type: z5.enum(["A", "TXT", "CNAME"]), name: z5.string(), value: z5.string() })),
1817
- createdAt: z5.string()
1818
- });
1819
- var WakeHookSchema = z5.object({
1820
- id: z5.string(),
1821
- owner: z5.string(),
1822
- box: z5.string(),
1823
- url: z5.string(),
1824
- createdBy: z5.string().nullable(),
1825
- createdAt: z5.string(),
1826
- lastCalledAt: z5.string().nullable()
1827
- });
1828
- var CreatedWakeHookSchema = WakeHookSchema.extend({ secret: z5.string() });
1829
- var WakeHookCallSchema = z5.object({
1830
- box: z5.string(),
1831
- action: z5.enum(["wake", "resume", "none"]),
1832
- reason: z5.string().optional()
1912
+ status: z6.enum(["pending", "live"]),
1913
+ www: z6.boolean(),
1914
+ url: z6.string(),
1915
+ error: z6.string().nullable(),
1916
+ records: z6.array(z6.object({ type: z6.enum(["A", "TXT", "CNAME"]), name: z6.string(), value: z6.string() })),
1917
+ createdAt: z6.string()
1918
+ });
1919
+ var WakeHookSchema = z6.object({
1920
+ id: z6.string(),
1921
+ owner: z6.string(),
1922
+ box: z6.string(),
1923
+ url: z6.string(),
1924
+ createdBy: z6.string().nullable(),
1925
+ createdAt: z6.string(),
1926
+ lastCalledAt: z6.string().nullable()
1927
+ });
1928
+ var CreatedWakeHookSchema = WakeHookSchema.extend({ secret: z6.string() });
1929
+ var WakeHookCallSchema = z6.object({
1930
+ box: z6.string(),
1931
+ action: z6.enum(["wake", "resume", "none"]),
1932
+ reason: z6.string().optional()
1833
1933
  });
1834
1934
  var BACKUP_STATUSES = ["running", "ready", "failed"];
1835
1935
  var BACKUP_KINDS = ["box", "volume"];
1836
- var BackupSchema = z5.object({
1837
- id: z5.string(),
1838
- owner: z5.string(),
1839
- box: z5.string(),
1840
- status: z5.enum(BACKUP_STATUSES),
1936
+ var BackupSchema = z6.object({
1937
+ id: z6.string(),
1938
+ owner: z6.string(),
1939
+ box: z6.string(),
1940
+ /**
1941
+ * The box it was taken of has been removed (#141): a box called `box` now is another box, which this backup
1942
+ * never restores into; `kvbox new <name> --from-backup <id>` makes a box from it. Absent from a control plane
1943
+ * before #141.
1944
+ */
1945
+ boxRemoved: z6.boolean().optional(),
1946
+ status: z6.enum(BACKUP_STATUSES),
1841
1947
  /** Why it failed; null otherwise. */
1842
- error: z5.string().nullable(),
1948
+ error: z6.string().nullable(),
1843
1949
  /** The image version the disk stacks on (a restore needs it on the host), and the image (absent: base). */
1844
- base: z5.string().nullable(),
1845
- image: z5.string().optional(),
1846
- vcpu: z5.number().int().nullable(),
1847
- memMib: z5.number().int().nullable(),
1950
+ base: z6.string().nullable(),
1951
+ image: z6.string().optional(),
1952
+ vcpu: z6.number().int().nullable(),
1953
+ memMib: z6.number().int().nullable(),
1848
1954
  /** The disk's size. */
1849
- diskBytes: z5.number().int().nullable(),
1955
+ diskBytes: z6.number().int().nullable(),
1850
1956
  /** What it holds: the slots that are not all zeros. */
1851
- dataBytes: z5.number().int().nullable(),
1957
+ dataBytes: z6.number().int().nullable(),
1852
1958
  /** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
1853
- uploadedBytes: z5.number().int().nullable(),
1854
- createdBy: z5.string().nullable(),
1855
- createdAt: z5.string(),
1856
- finishedAt: z5.string().nullable()
1857
- });
1858
- var BackupLimitSchema = z5.object({
1859
- perDay: z5.number().int(),
1860
- used: z5.number().int(),
1861
- nextAt: z5.string().nullable()
1862
- });
1863
- var NamedBackupLimitSchema = BackupLimitSchema.extend({ owner: z5.string(), name: z5.string() });
1864
- var HostBackupRequest = z5.object({ id: z5.string(), key: z5.string() });
1865
- var HostBackupManifestSchema = z5.object({
1866
- id: z5.string(),
1867
- sizeBytes: z5.number().int(),
1868
- chunks: z5.array(z5.string().nullable()),
1869
- env: z5.string().nullable(),
1870
- base: z5.string(),
1871
- image: z5.string().optional(),
1872
- vcpu: z5.number().int(),
1873
- memMib: z5.number().int()
1874
- });
1875
- var HostUploadRequest = z5.object({ key: z5.string(), urls: z5.record(z5.string(), z5.string()), pin: z5.string().optional() });
1876
- var HostUploadResultSchema = z5.object({ chunks: z5.number().int(), bytes: z5.number().int(), sizes: z5.record(z5.string(), z5.number().int()) });
1877
- var HostRestoreRequest = z5.object({
1959
+ uploadedBytes: z6.number().int().nullable(),
1960
+ createdBy: z6.string().nullable(),
1961
+ createdAt: z6.string(),
1962
+ finishedAt: z6.string().nullable()
1963
+ });
1964
+ var BackupLimitSchema = z6.object({
1965
+ perDay: z6.number().int(),
1966
+ used: z6.number().int(),
1967
+ nextAt: z6.string().nullable()
1968
+ });
1969
+ var NamedBackupLimitSchema = BackupLimitSchema.extend({ owner: z6.string(), name: z6.string() });
1970
+ var HostBackupRequest = z6.object({ id: z6.string(), key: z6.string() });
1971
+ var HostBackupManifestSchema = z6.object({
1972
+ id: z6.string(),
1973
+ sizeBytes: z6.number().int(),
1974
+ chunks: z6.array(z6.string().nullable()),
1975
+ env: z6.string().nullable(),
1976
+ base: z6.string(),
1977
+ image: z6.string().optional(),
1978
+ vcpu: z6.number().int(),
1979
+ memMib: z6.number().int(),
1980
+ /** The box's integrations (#205), so a box made from the backup has them again. Absent: none, or an older host. */
1981
+ integrations: z6.array(z6.string()).optional()
1982
+ });
1983
+ var HostUploadRequest = z6.object({ key: z6.string(), urls: z6.record(z6.string(), z6.string()), pin: z6.string().optional() });
1984
+ var HostUploadResultSchema = z6.object({ chunks: z6.number().int(), bytes: z6.number().int(), sizes: z6.record(z6.string(), z6.number().int()) });
1985
+ var HostRestoreRequest = z6.object({
1878
1986
  /** The backup's id: its variables were sealed under it. */
1879
- id: z5.string(),
1880
- key: z5.string(),
1881
- sizeBytes: z5.number().int().positive(),
1882
- base: z5.string(),
1883
- image: z5.string().optional(),
1884
- env: z5.string().nullable(),
1885
- chunks: z5.array(z5.object({ index: z5.number().int().nonnegative(), hash: z5.string(), url: z5.string() })),
1987
+ id: z6.string(),
1988
+ key: z6.string(),
1989
+ sizeBytes: z6.number().int().positive(),
1990
+ base: z6.string(),
1991
+ image: z6.string().optional(),
1992
+ env: z6.string().nullable(),
1993
+ chunks: z6.array(z6.object({ index: z6.number().int().nonnegative(), hash: z6.string(), url: z6.string() })),
1886
1994
  /** The certificate fingerprint of the store the URLs point at (see HostUploadRequest). */
1887
- pin: z5.string().optional()
1995
+ pin: z6.string().optional()
1888
1996
  });
1889
- var VolumeBackupSchema = z5.object({
1890
- id: z5.string(),
1891
- owner: z5.string(),
1892
- volume: z5.string(),
1893
- status: z5.enum(BACKUP_STATUSES),
1997
+ var VolumeBackupSchema = z6.object({
1998
+ id: z6.string(),
1999
+ owner: z6.string(),
2000
+ volume: z6.string(),
2001
+ status: z6.enum(BACKUP_STATUSES),
1894
2002
  /** Why it failed; null otherwise. */
1895
- error: z5.string().nullable(),
2003
+ error: z6.string().nullable(),
1896
2004
  /** The volume's size when taken. */
1897
- diskBytes: z5.number().int().nullable(),
2005
+ diskBytes: z6.number().int().nullable(),
1898
2006
  /** What it holds: the slots that are not all zeros. */
1899
- dataBytes: z5.number().int().nullable(),
2007
+ dataBytes: z6.number().int().nullable(),
1900
2008
  /** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
1901
- uploadedBytes: z5.number().int().nullable(),
1902
- createdBy: z5.string().nullable(),
1903
- createdAt: z5.string(),
1904
- finishedAt: z5.string().nullable()
2009
+ uploadedBytes: z6.number().int().nullable(),
2010
+ createdBy: z6.string().nullable(),
2011
+ createdAt: z6.string(),
2012
+ finishedAt: z6.string().nullable()
1905
2013
  });
1906
- var BackupScheduleSchema = z5.object({
1907
- enabled: z5.boolean(),
2014
+ var BackupScheduleSchema = z6.object({
2015
+ enabled: z6.boolean(),
1908
2016
  /** 0-23, UTC. Kept while it is off, so turning it on again keeps the hour. */
1909
- hour: z5.number().int().min(0).max(23),
1910
- nextAt: z5.string().nullable(),
1911
- lastAt: z5.string().nullable(),
1912
- lastBackup: z5.string().nullable(),
1913
- lastError: z5.string().nullable()
1914
- });
1915
- var SetBackupScheduleRequest = z5.object({ enabled: z5.boolean().optional(), hour: z5.number().int().min(0).max(23).optional() });
1916
- var HostVolumeBackupManifestSchema = z5.object({ id: z5.string(), sizeBytes: z5.number().int(), chunks: z5.array(z5.string().nullable()) });
1917
- var HostVolumeRestoreRequest = z5.object({
1918
- id: z5.string(),
1919
- key: z5.string(),
1920
- sizeBytes: z5.number().int().positive(),
1921
- chunks: z5.array(z5.object({ index: z5.number().int().nonnegative(), hash: z5.string(), url: z5.string() })),
1922
- pin: z5.string().optional()
2017
+ hour: z6.number().int().min(0).max(23),
2018
+ nextAt: z6.string().nullable(),
2019
+ lastAt: z6.string().nullable(),
2020
+ lastBackup: z6.string().nullable(),
2021
+ lastError: z6.string().nullable()
2022
+ });
2023
+ var SetBackupScheduleRequest = z6.object({ enabled: z6.boolean().optional(), hour: z6.number().int().min(0).max(23).optional() });
2024
+ var HostVolumeBackupManifestSchema = z6.object({ id: z6.string(), sizeBytes: z6.number().int(), chunks: z6.array(z6.string().nullable()) });
2025
+ var HostVolumeRestoreRequest = z6.object({
2026
+ id: z6.string(),
2027
+ key: z6.string(),
2028
+ sizeBytes: z6.number().int().positive(),
2029
+ chunks: z6.array(z6.object({ index: z6.number().int().nonnegative(), hash: z6.string(), url: z6.string() })),
2030
+ pin: z6.string().optional()
1923
2031
  });
1924
2032
  var BACKUP_STORE_BUCKET = "kvbox-backups";
1925
2033
  var BACKUP_STORE_REGION = "kvbox";
1926
- var BackupStoreSetupRequest = z5.object({ path: z5.string().min(1), force: z5.boolean().optional(), newStore: z5.boolean().optional() });
1927
- var BackupStoreStatusSchema = z5.object({
1928
- path: z5.string(),
1929
- bucket: z5.string(),
1930
- accessKey: z5.string(),
2034
+ var BackupStoreSetupRequest = z6.object({ path: z6.string().min(1), force: z6.boolean().optional(), newStore: z6.boolean().optional() });
2035
+ var BackupStoreStatusSchema = z6.object({
2036
+ path: z6.string(),
2037
+ bucket: z6.string(),
2038
+ accessKey: z6.string(),
1931
2039
  /** Whether Garage is running and can store. */
1932
- running: z5.boolean(),
2040
+ running: z6.boolean(),
1933
2041
  /** The filesystem the path is on. */
1934
- totalBytes: z5.number().int(),
1935
- freeBytes: z5.number().int(),
2042
+ totalBytes: z6.number().int(),
2043
+ freeBytes: z6.number().int(),
1936
2044
  /** What the bucket holds, when Garage answers. */
1937
- objects: z5.number().int().optional(),
1938
- storedBytes: z5.number().int().optional(),
2045
+ objects: z6.number().int().optional(),
2046
+ storedBytes: z6.number().int().optional(),
1939
2047
  /** Whether the control plane took the store's registration at setup. */
1940
- registered: z5.boolean().optional()
2048
+ registered: z6.boolean().optional()
1941
2049
  });
1942
- var BackupStoreRegistration = z5.object({ bucket: z5.string().min(1), region: z5.string().min(1), accessKey: z5.string().min(1), secretKey: z5.string().min(1) });
1943
- var CloudBackupStoreSchema = z5.object({
1944
- id: z5.string(),
2050
+ var BackupStoreRegistration = z6.object({ bucket: z6.string().min(1), region: z6.string().min(1), accessKey: z6.string().min(1), secretKey: z6.string().min(1) });
2051
+ var CloudBackupStoreSchema = z6.object({
2052
+ id: z6.string(),
1945
2053
  /** Null while no host serves it (its host left; it comes back when a host registers its key and secret again). */
1946
- host: z5.string().nullable(),
1947
- endpoint: z5.string().nullable(),
1948
- bucket: z5.string(),
1949
- accessKey: z5.string(),
1950
- createdAt: z5.string(),
2054
+ host: z6.string().nullable(),
2055
+ endpoint: z6.string().nullable(),
2056
+ bucket: z6.string(),
2057
+ accessKey: z6.string(),
2058
+ createdAt: z6.string(),
1951
2059
  /** The host answered a poll in the last minute and its Garage runs. */
1952
- live: z5.boolean(),
2060
+ live: z6.boolean(),
1953
2061
  /** From the host's last poll; null when it never reported a store. */
1954
- totalBytes: z5.number().int().nullable(),
1955
- freeBytes: z5.number().int().nullable(),
2062
+ totalBytes: z6.number().int().nullable(),
2063
+ freeBytes: z6.number().int().nullable(),
1956
2064
  /** Ready backups kept here, and what their chunks take (encrypted, compressed). */
1957
- backups: z5.number().int(),
1958
- storedBytes: z5.number().int(),
2065
+ backups: z6.number().int(),
2066
+ storedBytes: z6.number().int(),
1959
2067
  /** How many boxes have a ready backup here (a box and an earlier one of the same name count once), how many volumes (#168) and managed databases (#186). */
1960
- boxes: z5.number().int(),
1961
- volumes: z5.number().int(),
1962
- databases: z5.number().int(),
2068
+ boxes: z6.number().int(),
2069
+ volumes: z6.number().int(),
2070
+ databases: z6.number().int(),
1963
2071
  /** When the newest ready backup kept here finished; null when it keeps none. */
1964
- lastBackupAt: z5.string().nullable()
2072
+ lastBackupAt: z6.string().nullable()
1965
2073
  });
1966
- var StoredItemSchema = z5.object({
1967
- kind: z5.enum(BACKUP_KINDS),
1968
- owner: z5.string(),
2074
+ var StoredItemSchema = z6.object({
2075
+ kind: z6.enum(BACKUP_KINDS),
2076
+ owner: z6.string(),
1969
2077
  /** The box's or volume's name; a managed database's (#186) for its hidden volume. */
1970
- name: z5.string(),
2078
+ name: z6.string(),
1971
2079
  /** The managed database's kind (`postgres`) when the volume is one's (#186); null otherwise. */
1972
- managed: z5.string().nullable(),
2080
+ managed: z6.string().nullable(),
1973
2081
  /** The host the box (or volume) is on now; null when it is gone (its backups stay). */
1974
- host: z5.string().nullable(),
2082
+ host: z6.string().nullable(),
1975
2083
  /** It is on the store's own host: losing that host loses it and its backups together. */
1976
- sameHost: z5.boolean(),
2084
+ sameHost: z6.boolean(),
1977
2085
  /** Ready backups kept here, and what they added to the store together (encrypted, compressed). */
1978
- backups: z5.number().int(),
1979
- uploadedBytes: z5.number().int(),
2086
+ backups: z6.number().int(),
2087
+ uploadedBytes: z6.number().int(),
1980
2088
  /** The newest backup sent here, whatever became of it. */
1981
- latest: z5.object({ id: z5.string(), status: z5.enum(BACKUP_STATUSES), error: z5.string().nullable(), createdAt: z5.string() })
2089
+ latest: z6.object({ id: z6.string(), status: z6.enum(BACKUP_STATUSES), error: z6.string().nullable(), createdAt: z6.string() })
1982
2090
  });
1983
- var FailedBackupSchema = z5.object({
1984
- id: z5.string(),
1985
- owner: z5.string(),
2091
+ var FailedBackupSchema = z6.object({
2092
+ id: z6.string(),
2093
+ owner: z6.string(),
1986
2094
  /** What it was a backup of: a box or a volume (#168), and its name; a managed database's (#186) for its hidden volume. */
1987
- kind: z5.enum(BACKUP_KINDS),
1988
- name: z5.string(),
2095
+ kind: z6.enum(BACKUP_KINDS),
2096
+ name: z6.string(),
1989
2097
  /** The managed database's kind (`postgres`) when the volume is one's; null otherwise. */
1990
- managed: z5.string().nullable(),
1991
- error: z5.string().nullable(),
2098
+ managed: z6.string().nullable(),
2099
+ error: z6.string().nullable(),
1992
2100
  /** The host that took it, and the host of the store it was going to; null when gone, or when it failed before a store was picked. */
1993
- host: z5.string().nullable(),
1994
- store: z5.string().nullable(),
1995
- createdAt: z5.string()
2101
+ host: z6.string().nullable(),
2102
+ store: z6.string().nullable(),
2103
+ createdAt: z6.string()
1996
2104
  });
1997
- var MachineSchema = z5.object({
2105
+ var MachineSchema = z6.object({
1998
2106
  /** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */
1999
- id: z5.string(),
2000
- name: z5.string(),
2107
+ id: z6.string(),
2108
+ name: z6.string(),
2001
2109
  /** Who the box belongs to; names are unique per owner. A bare name is local to the host, `user@control-plane` later. */
2002
- owner: z5.string(),
2003
- ip: z5.string(),
2004
- mac: z5.string(),
2005
- pid: z5.number().int().nullable(),
2006
- vcpu: z5.number().int(),
2007
- memMib: z5.number().int(),
2008
- diskBytes: z5.number().int(),
2110
+ owner: z6.string(),
2111
+ ip: z6.string(),
2112
+ mac: z6.string(),
2113
+ pid: z6.number().int().nullable(),
2114
+ vcpu: z6.number().int(),
2115
+ memMib: z6.number().int(),
2116
+ diskBytes: z6.number().int(),
2009
2117
  // the box's own writable disk, as the guest sees it
2010
- diskUsedBytes: z5.number().int(),
2118
+ diskUsedBytes: z6.number().int(),
2011
2119
  // what the box uses of it: the filesystem's own count, like the guest's `df` (#115)
2012
2120
  /** What the disk's sparse file occupies on the host. Grows while the box runs, `kvbox stop` trims it back. Hosts before 0.5.42 do not send it. */
2013
- diskHostBytes: z5.number().int().optional(),
2014
- base: z5.string(),
2121
+ diskHostBytes: z6.number().int().optional(),
2122
+ base: z6.string(),
2015
2123
  // version of the image the box's overlay stacks on
2016
2124
  /** The image (#87) when it is not the base one: `postgres`. `base` is then that image's version. */
2017
- image: z5.string().optional(),
2018
- createdAt: z5.string(),
2019
- source: z5.string(),
2020
- // "base", "snapshot:<owner/name>" or "fork:<owner/name>" (#79)
2125
+ image: z6.string().optional(),
2126
+ createdAt: z6.string(),
2127
+ source: z6.string(),
2128
+ // "base", "snapshot:<owner/name>", "fork:<owner/name>" (#79) or "backup:<id>" (#141)
2021
2129
  status: BoxStatusSchema,
2022
2130
  /**
2023
2131
  * Public TCP port on the host that reaches the box's SSH while it runs (#49). Only boxes made
2024
2132
  * through a control plane have one; the control plane adds the host's address for `connect` (#21).
2025
2133
  */
2026
- sshPort: z5.number().int().optional(),
2134
+ sshPort: z6.number().int().optional(),
2027
2135
  /**
2028
2136
  * Where `ssh` reaches the box from outside: the host's public address and that port (#21). Only
2029
2137
  * the control plane fills it in (a host does not know its own public address); absent for a box
2030
2138
  * whose host reported no port or did not answer.
2031
2139
  */
2032
- ssh: z5.object({ host: z5.string(), port: z5.number().int(), user: z5.string() }).optional(),
2140
+ ssh: z6.object({ host: z6.string(), port: z6.number().int(), user: z6.string() }).optional(),
2033
2141
  /** Box ports published on the host (#30). Absent: none. */
2034
- ports: z5.array(PortForwardSchema).optional(),
2142
+ ports: z6.array(PortForwardSchema).optional(),
2035
2143
  /** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /machines`. */
2036
- ownerKind: z5.enum(["user", "org"]).optional(),
2144
+ ownerKind: z6.enum(["user", "org"]).optional(),
2037
2145
  /**
2038
2146
  * The name of the host the box runs on. Only the control plane fills it in, on `GET /machines`: a box
2039
2147
  * links to, and a volume attaches to, only a box on the same host.
2040
2148
  */
2041
- host: z5.string().optional(),
2149
+ host: z6.string().optional(),
2042
2150
  /** The country code of that host (`RO`, `US`), when its admin gave one. Only the control plane fills it in. */
2043
- country: z5.string().optional(),
2151
+ country: z6.string().optional(),
2044
2152
  /**
2045
2153
  * The kind of managed service the box runs (`postgres`, `redis`, `storage`). Only an admin's
2046
2154
  * `GET /machines?all=1` lists such boxes, so a host's boxes add up; every other listing hides them.
2047
2155
  */
2048
- managed: z5.string().optional(),
2156
+ managed: z6.string().optional(),
2049
2157
  /** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
2050
- autoHibernateSec: z5.number().int().positive().optional(),
2158
+ autoHibernateSec: z6.number().int().positive().optional(),
2051
2159
  /** A script inside the box that says it is idle (#102, exit 0): auto-hibernate asks it instead of watching the traffic. */
2052
- idleCheck: z5.string().optional(),
2160
+ idleCheck: z6.string().optional(),
2053
2161
  /** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */
2054
- volumes: z5.array(z5.object({ name: z5.string(), sizeGib: z5.number().int(), mountPath: z5.string() })).optional(),
2162
+ volumes: z6.array(z6.object({ name: z6.string(), sizeGib: z6.number().int(), mountPath: z6.string() })).optional(),
2055
2163
  /** Boxes that may reach this one, each on one port (#98). Absent: none. */
2056
- links: z5.array(BoxLinkSchema).optional(),
2164
+ links: z6.array(BoxLinkSchema).optional(),
2165
+ /**
2166
+ * The integrations turned on for the box (#205, `github`): names only, the credential is fetched by the box
2167
+ * each time it is needed. Absent: none. A host before integrations never sends it.
2168
+ */
2169
+ integrations: z6.array(z6.string()).optional(),
2057
2170
  /** How to reach what the box serves, its secrets masked (#87): `postgres://postgres:****@db.kvbox:5432/postgres`. */
2058
- url: z5.string().optional(),
2171
+ url: z6.string().optional(),
2059
2172
  /**
2060
2173
  * Only in what `POST /machines` answers, for an image that declares one (#87): how to reach what it
2061
2174
  * serves, e.g. `postgres://postgres:<password>@db.kvbox:5432/postgres`. Holds the box's variables.
2062
2175
  */
2063
- connect: z5.string().optional()
2176
+ connect: z6.string().optional()
2064
2177
  });
2065
- var VolumeSchema = z5.object({
2178
+ var VolumeSchema = z6.object({
2066
2179
  /** The host's 6-hex volume id (#91): the ledger's key, so a name removed and made again is two volumes. */
2067
- id: z5.string(),
2068
- name: z5.string(),
2069
- owner: z5.string(),
2070
- sizeGib: z5.number().int(),
2180
+ id: z6.string(),
2181
+ name: z6.string(),
2182
+ owner: z6.string(),
2183
+ sizeGib: z6.number().int(),
2071
2184
  /** What the sparse file really occupies on the host. */
2072
- usedBytes: z5.number().int(),
2073
- attachedTo: z5.string().nullable(),
2074
- createdAt: z5.string(),
2185
+ usedBytes: z6.number().int(),
2186
+ attachedTo: z6.string().nullable(),
2187
+ createdAt: z6.string(),
2075
2188
  /** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /volumes`. */
2076
- ownerKind: z5.enum(["user", "org"]).optional(),
2189
+ ownerKind: z6.enum(["user", "org"]).optional(),
2077
2190
  /** The name of the host the volume lives on; only the control plane fills it in. It attaches only to a box there. */
2078
- host: z5.string().optional()
2191
+ host: z6.string().optional()
2079
2192
  });
2080
2193
  var MAX_VOLUME_GIB = 4096;
2081
2194
  var VOLUME_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
2082
2195
  var VOLUME_NAME_RULE = "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit";
2083
- var CreateVolumeRequest = z5.object({
2084
- name: z5.string(),
2085
- sizeGib: z5.number().int().min(1).max(MAX_VOLUME_GIB),
2196
+ var CreateVolumeRequest = z6.object({
2197
+ name: z6.string(),
2198
+ sizeGib: z6.number().int().min(1).max(MAX_VOLUME_GIB),
2086
2199
  /**
2087
2200
  * Through a control plane (#91): the box this volume is for, so it is made on that box's host; the
2088
2201
  * control plane requires it (a volume attaches only to a box on its own host, so one made for no box
2089
2202
  * could never attach) and the CLI attaches right after. A host ignores it.
2090
2203
  */
2091
- box: z5.string().optional()
2204
+ box: z6.string().optional()
2092
2205
  });
2093
- var AttachVolumeRequest = z5.object({
2094
- box: z5.string()
2206
+ var AttachVolumeRequest = z6.object({
2207
+ box: z6.string()
2095
2208
  });
2096
- var ResizeVolumeRequest = z5.object({
2097
- sizeGib: z5.number().int().min(1).max(MAX_VOLUME_GIB)
2209
+ var ResizeVolumeRequest = z6.object({
2210
+ sizeGib: z6.number().int().min(1).max(MAX_VOLUME_GIB)
2098
2211
  });
2099
- var RunScriptRequest = z5.object({ input: z5.unknown().optional() });
2100
- var ScriptOutputSchema = z5.object({ output: z5.unknown() });
2212
+ var RunScriptRequest = z6.object({ input: z6.unknown().optional() });
2213
+ var ScriptOutputSchema = z6.object({ output: z6.unknown() });
2101
2214
  var BOX_RUN_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
2102
- var StartRunRequest = z5.object({
2103
- id: z5.string().regex(BOX_RUN_ID_RE),
2104
- command: z5.string().min(1).max(8192),
2215
+ var StartRunRequest = z6.object({
2216
+ id: z6.string().regex(BOX_RUN_ID_RE),
2217
+ command: z6.string().min(1).max(8192),
2105
2218
  /** The command and everything it started are killed after this long. */
2106
- timeoutSec: z5.number().int().min(1).max(86400),
2219
+ timeoutSec: z6.number().int().min(1).max(86400),
2107
2220
  /**
2108
2221
  * The caller will read the output back (`exec`, #188): the box's kvbox-agent must know `runOutput`
2109
2222
  * (base v0.16.0+), which the host checks before the command starts, so an older box is `box-outdated`
2110
2223
  * without having run anything.
2111
2224
  */
2112
- output: z5.boolean().optional()
2225
+ output: z6.boolean().optional()
2113
2226
  });
2114
- var StartRunAnswerSchema = z5.object({
2115
- id: z5.string(),
2227
+ var StartRunAnswerSchema = z6.object({
2228
+ id: z6.string(),
2116
2229
  /** False: a run of this id was already there. */
2117
- started: z5.boolean(),
2230
+ started: z6.boolean(),
2118
2231
  /** The box was asleep and this request woke it. */
2119
- woke: z5.boolean()
2232
+ woke: z6.boolean()
2120
2233
  });
2121
2234
  var BOX_RUN_STATES = ["running", "exited", "timeout", "unknown"];
2122
- var BoxRunSchema = z5.object({
2123
- id: z5.string(),
2124
- state: z5.enum(BOX_RUN_STATES),
2235
+ var BoxRunSchema = z6.object({
2236
+ id: z6.string(),
2237
+ state: z6.enum(BOX_RUN_STATES),
2125
2238
  /** With `exited`; 128 + the signal for a command a signal ended. */
2126
- exitCode: z5.number().int().optional(),
2239
+ exitCode: z6.number().int().optional(),
2127
2240
  /**
2128
2241
  * With `exited` and `timeout`: how long the command itself ran, by the box's own clock (base v0.15.1
2129
2242
  * and later). The asker learns of the end seconds late, so its own count is too long.
2130
2243
  */
2131
- durationMs: z5.number().int().nonnegative().optional()
2244
+ durationMs: z6.number().int().nonnegative().optional()
2132
2245
  });
2133
- var RunRefusalSchema = z5.object({ error: z5.string(), code: z5.string().optional() });
2246
+ var RunRefusalSchema = z6.object({ error: z6.string(), code: z6.string().optional() });
2134
2247
  var RUN_OUTPUT_MAX_BYTES = 1 << 20;
2135
2248
  var RUN_STREAMS = ["stdout", "stderr"];
2136
- var RunOutputSchema = z5.object({
2137
- id: z5.string(),
2138
- stream: z5.enum(RUN_STREAMS),
2139
- offset: z5.number().int().nonnegative(),
2140
- size: z5.number().int().nonnegative(),
2141
- data: z5.string()
2142
- });
2143
- var ExecRequest = z5.object({
2144
- command: z5.string().min(1).max(8192),
2249
+ var RunOutputSchema = z6.object({
2250
+ id: z6.string(),
2251
+ stream: z6.enum(RUN_STREAMS),
2252
+ offset: z6.number().int().nonnegative(),
2253
+ size: z6.number().int().nonnegative(),
2254
+ data: z6.string()
2255
+ });
2256
+ var ExecRequest = z6.object({
2257
+ command: z6.string().min(1).max(8192),
2145
2258
  /** The command and everything it started are killed after this long (default DEFAULT_EXEC_TIMEOUT_SEC). */
2146
- timeoutSec: z5.number().int().min(1).max(86400).optional()
2259
+ timeoutSec: z6.number().int().min(1).max(86400).optional()
2147
2260
  });
2148
- var ExecStartSchema = z5.object({
2149
- id: z5.string(),
2261
+ var ExecStartSchema = z6.object({
2262
+ id: z6.string(),
2150
2263
  /** The box was asleep and this request woke it. */
2151
- woke: z5.boolean()
2264
+ woke: z6.boolean()
2152
2265
  });
2153
- var ExecSchema = z5.object({
2154
- id: z5.string(),
2155
- state: z5.enum(BOX_RUN_STATES),
2266
+ var ExecSchema = z6.object({
2267
+ id: z6.string(),
2268
+ state: z6.enum(BOX_RUN_STATES),
2156
2269
  /** With `exited`; 128 + the signal for a command a signal ended. */
2157
- exitCode: z5.number().int().optional(),
2270
+ exitCode: z6.number().int().optional(),
2158
2271
  /** With `exited` and `timeout`: how long the command itself ran. */
2159
- durationMs: z5.number().int().nonnegative().optional(),
2160
- stdout: z5.string().optional(),
2161
- stderr: z5.string().optional(),
2162
- stdoutBytes: z5.number().int().nonnegative().optional(),
2163
- stderrBytes: z5.number().int().nonnegative().optional(),
2164
- truncated: z5.boolean().optional()
2165
- });
2166
- var EnvVarSchema = z5.object({
2167
- name: z5.string(),
2168
- value: z5.string().optional(),
2169
- secret: z5.boolean(),
2170
- updatedAt: z5.string()
2171
- });
2172
- var BoxEnvSchema = z5.object({
2173
- box: z5.string(),
2174
- vars: z5.array(EnvVarSchema)
2175
- });
2176
- var BoxEnvChangeSchema = z5.object({
2177
- box: z5.string(),
2178
- name: z5.string(),
2272
+ durationMs: z6.number().int().nonnegative().optional(),
2273
+ stdout: z6.string().optional(),
2274
+ stderr: z6.string().optional(),
2275
+ stdoutBytes: z6.number().int().nonnegative().optional(),
2276
+ stderrBytes: z6.number().int().nonnegative().optional(),
2277
+ truncated: z6.boolean().optional()
2278
+ });
2279
+ var EnvVarSchema = z6.object({
2280
+ name: z6.string(),
2281
+ value: z6.string().optional(),
2282
+ secret: z6.boolean(),
2283
+ updatedAt: z6.string()
2284
+ });
2285
+ var BoxEnvSchema = z6.object({
2286
+ box: z6.string(),
2287
+ vars: z6.array(EnvVarSchema)
2288
+ });
2289
+ var BoxEnvChangeSchema = z6.object({
2290
+ box: z6.string(),
2291
+ name: z6.string(),
2179
2292
  /** Whether the box is running now: the change waits for its next start. */
2180
- running: z5.boolean()
2293
+ running: z6.boolean()
2181
2294
  });
2182
- var SetEnvRequest = z5.object({
2183
- value: z5.string(),
2184
- secret: z5.boolean().optional()
2295
+ var SetEnvRequest = z6.object({
2296
+ value: z6.string(),
2297
+ secret: z6.boolean().optional()
2185
2298
  });
2186
- var EnvChangeSchema = z5.object({
2187
- owner: z5.string(),
2188
- name: z5.string(),
2189
- boxes: z5.number().int()
2299
+ var EnvChangeSchema = z6.object({
2300
+ owner: z6.string(),
2301
+ name: z6.string(),
2302
+ boxes: z6.number().int()
2190
2303
  });
2191
- var HostEnvRequest = z5.object({
2192
- version: z5.number().int().min(0),
2193
- vars: z5.array(z5.object({ name: z5.string(), value: z5.string() }))
2304
+ var HostEnvRequest = z6.object({
2305
+ version: z6.number().int().min(0),
2306
+ vars: z6.array(z6.object({ name: z6.string(), value: z6.string() }))
2194
2307
  });
2195
- var HostEnvVersionsSchema = z5.array(z5.object({ owner: z5.string(), version: z5.number().int() }));
2196
- var CreateMachineRequest = z5.object({
2197
- name: z5.string().optional(),
2308
+ var HostEnvVersionsSchema = z6.array(z6.object({ owner: z6.string(), version: z6.number().int() }));
2309
+ var CreateMachineRequest = z6.object({
2310
+ name: z6.string().optional(),
2198
2311
  /** Ignored over the local socket (the caller is the host owner); the control plane sets it over HTTPS. */
2199
- owner: z5.string().optional(),
2312
+ owner: z6.string().optional(),
2200
2313
  size: SizeSchema.optional(),
2201
- from: z5.string().optional(),
2202
- force: z5.boolean().optional(),
2314
+ from: z6.string().optional(),
2315
+ force: z6.boolean().optional(),
2203
2316
  /**
2204
2317
  * Extra authorized_keys lines for the box, on top of the host's own key: the control plane sends
2205
2318
  * its SSH CA as one `cert-authority …` line (#51). Written into the box's authorized_keys at every
2206
2319
  * boot (#49); a host older than that ignores them.
2207
2320
  */
2208
- sshKeys: z5.array(z5.string()).optional(),
2321
+ sshKeys: z6.array(z6.string()).optional(),
2209
2322
  /** Seconds without network traffic before the box is hibernated (#47); 0: never. Absent: the host's default. */
2210
- autoHibernateSec: z5.number().int().min(0).optional(),
2323
+ autoHibernateSec: z6.number().int().min(0).optional(),
2211
2324
  /**
2212
2325
  * Place the box on the host of this box (#98, `kvbox new --near`), so the two can be linked. Only the
2213
2326
  * control plane reads it; a host has one place to put a box.
2214
2327
  */
2215
- near: z5.string().optional(),
2328
+ near: z6.string().optional(),
2216
2329
  /**
2217
2330
  * Place the box on a host in this country (`kvbox new --country romania`): a code or an English name,
2218
2331
  * `@kvbox/shared/country`. Only the control plane reads it.
2219
2332
  */
2220
- country: z5.string().optional(),
2333
+ country: z6.string().optional(),
2221
2334
  /**
2222
2335
  * Place the box on the host of this name and nowhere else (`kvbox new --host kvbox2`, a hidden flag):
2223
2336
  * an admin's, to try a host out. Only the control plane reads it, and refuses it from anyone else.
2224
2337
  */
2225
- host: z5.string().optional(),
2338
+ host: z6.string().optional(),
2226
2339
  /** The image to boot (#87, `kvbox new --base postgres`). Absent: the base image. */
2227
- image: z5.string().optional(),
2340
+ image: z6.string().optional(),
2228
2341
  /** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */
2229
- env: z5.array(z5.object({ name: z5.string(), value: z5.string() })).optional()
2342
+ env: z6.array(z6.object({ name: z6.string(), value: z6.string() })).optional(),
2343
+ /**
2344
+ * Start the box on this backup's disk (#141, `kvbox new --from-backup <id>`), a removed box's too: its image,
2345
+ * version and variables come from the backup, its size too unless given. Only the control plane reads it.
2346
+ */
2347
+ fromBackup: z6.string().optional(),
2348
+ /**
2349
+ * The integrations turned on for the box (#205, `kvbox new --integration github`). Absent: none, or with
2350
+ * `from` / `fromBackup` the list the snapshot or the backup was taken with.
2351
+ */
2352
+ integrations: IntegrationListSchema.optional()
2230
2353
  });
2231
- var ForkMachineRequest = z5.object({
2232
- name: z5.string().optional(),
2354
+ var HostFromBackupRequest = CreateMachineRequest.omit({ from: true, fromBackup: true, image: true, env: true }).extend({ backup: HostRestoreRequest });
2355
+ var ForkMachineRequest = z6.object({
2356
+ name: z6.string().optional(),
2233
2357
  /**
2234
2358
  * The new box's slug, bare (`acme`): the control plane sends the target of `--org` here; the host
2235
2359
  * qualifies it with the caller's realm. Absent: the source's owner. A CLI leaves it out.
2236
2360
  */
2237
- owner: z5.string().optional(),
2361
+ owner: z6.string().optional(),
2238
2362
  /** A cold fork only: a warm one keeps the source's vCPU and memory. */
2239
2363
  size: SizeSchema.optional(),
2240
- force: z5.boolean().optional(),
2364
+ force: z6.boolean().optional(),
2241
2365
  /** As in CreateMachineRequest: the control plane's CA line for the new box's owner. */
2242
- sshKeys: z5.array(z5.string()).optional(),
2243
- autoHibernateSec: z5.number().int().min(0).optional()
2366
+ sshKeys: z6.array(z6.string()).optional(),
2367
+ autoHibernateSec: z6.number().int().min(0).optional()
2244
2368
  });
2245
- var SetSshKeysRequest = z5.object({
2246
- sshKeys: z5.array(z5.string())
2369
+ var SetSshKeysRequest = z6.object({
2370
+ sshKeys: z6.array(z6.string())
2247
2371
  });
2248
- var RescaleMachineRequest = z5.object({
2372
+ var RescaleMachineRequest = z6.object({
2249
2373
  size: SizeSchema.optional(),
2250
- vcpu: z5.number().int().min(1).max(64).optional(),
2251
- memMib: z5.number().int().min(256).optional(),
2252
- diskGib: z5.number().int().min(1).optional(),
2374
+ vcpu: z6.number().int().min(1).max(64).optional(),
2375
+ memMib: z6.number().int().min(256).optional(),
2376
+ diskGib: z6.number().int().min(1).optional(),
2253
2377
  /** Skip the capacity guard when a running box grows (#37). */
2254
- force: z5.boolean().optional()
2378
+ force: z6.boolean().optional()
2255
2379
  });
2256
- var StartMachineRequest = z5.object({
2257
- force: z5.boolean().optional()
2380
+ var StartMachineRequest = z6.object({
2381
+ force: z6.boolean().optional()
2258
2382
  });
2259
- var SetMachineRequest = z5.object({
2383
+ var SetMachineRequest = z6.object({
2260
2384
  /** Seconds without network traffic before the box is hibernated (#47); 0: never. */
2261
- autoHibernateSec: z5.number().int().min(0).optional(),
2385
+ autoHibernateSec: z6.number().int().min(0).optional(),
2262
2386
  /** The box's idle check (#102): an absolute path to a script inside the box, exit 0 = idle; "": none, back to network traffic. */
2263
- idleCheck: z5.union([z5.literal(""), z5.string().max(255).regex(/^\/[^\0\n]*$/, "an absolute path inside the box")]).optional()
2264
- });
2265
- var SnapshotSchema = z5.object({
2266
- name: z5.string(),
2267
- owner: z5.string(),
2268
- source: z5.string(),
2387
+ idleCheck: z6.union([z6.literal(""), z6.string().max(255).regex(/^\/[^\0\n]*$/, "an absolute path inside the box")]).optional(),
2388
+ /** The box's integrations (#205), the whole list: `[]` turns every one off. Applies at once, in any state. */
2389
+ integrations: IntegrationListSchema.optional()
2390
+ });
2391
+ var SnapshotSchema = z6.object({
2392
+ name: z6.string(),
2393
+ owner: z6.string(),
2394
+ source: z6.string(),
2269
2395
  // the box it was taken from, as owner/name
2270
- base: z5.string(),
2396
+ base: z6.string(),
2271
2397
  // version of the image the overlay stacks on; a restore needs the same one
2272
2398
  /** As in MachineSchema: the image when it is not the base one (#87). */
2273
- image: z5.string().optional(),
2274
- vcpu: z5.number().int(),
2275
- memMib: z5.number().int(),
2276
- sizeBytes: z5.number().int(),
2399
+ image: z6.string().optional(),
2400
+ vcpu: z6.number().int(),
2401
+ memMib: z6.number().int(),
2402
+ sizeBytes: z6.number().int(),
2277
2403
  // what vmstate + mem + overlay really occupy on the host
2278
- createdAt: z5.string()
2404
+ createdAt: z6.string()
2279
2405
  });
2280
- var CreateSnapshotRequest = z5.object({
2281
- box: z5.string(),
2282
- name: z5.string(),
2406
+ var CreateSnapshotRequest = z6.object({
2407
+ box: z6.string(),
2408
+ name: z6.string(),
2283
2409
  /** Retake a snapshot under a name that exists (#83): the old one goes only once the new one is complete. */
2284
- replace: z5.boolean().optional()
2285
- });
2286
- var DiskCapacitySchema = z5.object({
2287
- totalGib: z5.number().int(),
2288
- freeGib: z5.number().int(),
2289
- volumesGib: z5.number().int(),
2290
- volumesUsedGib: z5.number().int(),
2291
- headroomGib: z5.number().int()
2292
- });
2293
- var CapacitySchema = z5.object({
2294
- hostMemMib: z5.number().int(),
2295
- hostCores: z5.number().int(),
2296
- reservedMemMib: z5.number().int(),
2297
- reservedVcpu: z5.number().int(),
2298
- running: z5.number().int(),
2410
+ replace: z6.boolean().optional()
2411
+ });
2412
+ var DiskCapacitySchema = z6.object({
2413
+ totalGib: z6.number().int(),
2414
+ freeGib: z6.number().int(),
2415
+ volumesGib: z6.number().int(),
2416
+ volumesUsedGib: z6.number().int(),
2417
+ headroomGib: z6.number().int()
2418
+ });
2419
+ var CapacitySchema = z6.object({
2420
+ hostMemMib: z6.number().int(),
2421
+ hostCores: z6.number().int(),
2422
+ reservedMemMib: z6.number().int(),
2423
+ reservedVcpu: z6.number().int(),
2424
+ running: z6.number().int(),
2299
2425
  /**
2300
2426
  * MiB of RAM the host keeps back from its boxes (config.json `memHeadroomMib`). Absent on a kvbox-server
2301
2427
  * from before the setting, which keeps 2 GB (`OLD_HOST_MEM_HEADROOM_MIB`).
2302
2428
  */
2303
- memHeadroomMib: z5.number().int().optional(),
2429
+ memHeadroomMib: z6.number().int().optional(),
2304
2430
  /** Absent on a host from before volumes (#91): it cannot take one. */
2305
2431
  disk: DiskCapacitySchema.optional(),
2306
2432
  /**
2307
2433
  * The images a new box can be made from here (#87), with the version `new` uses; the base is `base`.
2308
2434
  * Absent on a host from before images: it has only the base.
2309
2435
  */
2310
- images: z5.array(z5.object({ name: z5.string(), version: z5.string() })).optional(),
2436
+ images: z6.array(z6.object({ name: z6.string(), version: z6.string() })).optional(),
2311
2437
  /** kvbox-server's version, so the control plane's host list shows it without a call per host. Older servers omit it. */
2312
- version: z5.string().optional(),
2438
+ version: z6.string().optional(),
2313
2439
  /** Present on a host set up as a backup store: the disk its Garage keeps chunks on, and whether Garage runs. */
2314
- backupStore: z5.object({ totalBytes: z5.number().int(), freeBytes: z5.number().int(), running: z5.boolean() }).optional(),
2440
+ backupStore: z6.object({ totalBytes: z6.number().int(), freeBytes: z6.number().int(), running: z6.boolean() }).optional(),
2315
2441
  /** True on a kvbox-server that reaches a backup store by its certificate's `pin`; older ones omit it and cannot back up to a store. */
2316
- storeClient: z5.boolean().optional()
2317
- });
2318
- var ImageSchema = z5.object({ name: z5.string(), version: z5.string().nullable() });
2319
- var ImageIndexSchema = z5.object({
2320
- updatedAt: z5.string(),
2321
- images: z5.record(z5.string(), z5.object({ version: z5.string().min(1), minServer: z5.string().min(1).optional() }))
2322
- });
2323
- var LatestImagesSchema = z5.object({
2324
- updatedAt: z5.string().nullable(),
2442
+ storeClient: z6.boolean().optional(),
2443
+ /** True on a kvbox-server with `POST /machines/from-backup` (#141, `kvbox new --from-backup`); older ones omit it. */
2444
+ fromBackup: z6.boolean().optional(),
2445
+ /** True on a kvbox-server that keeps a box's `integrations` (#205); an older one drops the field without a word. */
2446
+ integrations: z6.boolean().optional()
2447
+ });
2448
+ var ImageSchema = z6.object({ name: z6.string(), version: z6.string().nullable() });
2449
+ var ImageIndexSchema = z6.object({
2450
+ updatedAt: z6.string(),
2451
+ images: z6.record(z6.string(), z6.object({ version: z6.string().min(1), minServer: z6.string().min(1).optional() }))
2452
+ });
2453
+ var LatestImagesSchema = z6.object({
2454
+ updatedAt: z6.string().nullable(),
2325
2455
  images: ImageIndexSchema.shape.images,
2326
- checkedAt: z5.string().nullable()
2327
- });
2328
- var RecoveryReportSchema = z5.object({
2329
- at: z5.string(),
2330
- booted: z5.array(z5.string()),
2331
- leftStopped: z5.array(z5.string()),
2332
- failed: z5.array(z5.object({ box: z5.string(), error: z5.string() }))
2333
- });
2334
- var HostUpdateSchema = z5.object({
2335
- state: z5.enum(["running", "done", "failed"]),
2336
- startedAt: z5.string(),
2337
- finishedAt: z5.string().nullable(),
2456
+ checkedAt: z6.string().nullable()
2457
+ });
2458
+ var RecoveryReportSchema = z6.object({
2459
+ at: z6.string(),
2460
+ booted: z6.array(z6.string()),
2461
+ leftStopped: z6.array(z6.string()),
2462
+ failed: z6.array(z6.object({ box: z6.string(), error: z6.string() }))
2463
+ });
2464
+ var HostUpdateSchema = z6.object({
2465
+ state: z6.enum(["running", "done", "failed"]),
2466
+ startedAt: z6.string(),
2467
+ finishedAt: z6.string().nullable(),
2338
2468
  /** kvbox-server's version when the update started, and when it ended (null while running or when it failed before). */
2339
- from: z5.string(),
2340
- to: z5.string().nullable(),
2341
- error: z5.string().nullable(),
2342
- needsManual: z5.array(z5.string())
2343
- });
2344
- var HealthSchema = z5.object({
2345
- ok: z5.literal(true),
2346
- version: z5.string(),
2347
- pid: z5.number().int(),
2469
+ from: z6.string(),
2470
+ to: z6.string().nullable(),
2471
+ error: z6.string().nullable(),
2472
+ needsManual: z6.array(z6.string())
2473
+ });
2474
+ var HealthSchema = z6.object({
2475
+ ok: z6.literal(true),
2476
+ version: z6.string(),
2477
+ pid: z6.number().int(),
2348
2478
  /** Base image version new boxes get (null when the host has no usable base image yet). */
2349
- base: z5.string().nullable(),
2479
+ base: z6.string().nullable(),
2350
2480
  /** Owner that boxes made over the local socket get (the Unix user running the server). */
2351
- owner: z5.string(),
2481
+ owner: z6.string(),
2352
2482
  /** The control plane this host joined (null when none). */
2353
- controlPlane: z5.object({
2483
+ controlPlane: z6.object({
2354
2484
  /** Realm name, e.g. kvbox.sh. */
2355
- name: z5.string(),
2356
- url: z5.string(),
2485
+ name: z6.string(),
2486
+ url: z6.string(),
2357
2487
  /** Where this host answers the control plane. */
2358
- hostUrl: z5.string()
2488
+ hostUrl: z6.string()
2359
2489
  }).nullable(),
2360
2490
  /** The relay this host reaches the internet through (#50); null when it has its own public address. Older servers omit it. */
2361
- relay: z5.object({
2362
- name: z5.string(),
2491
+ relay: z6.object({
2492
+ name: z6.string(),
2363
2493
  /** The public IP the relay owns for this host. */
2364
- publicIp: z5.string(),
2494
+ publicIp: z6.string(),
2365
2495
  /** The relay's WireGuard endpoint the tunnel dials. */
2366
- endpoint: z5.string(),
2496
+ endpoint: z6.string(),
2367
2497
  /** Times the server redialed the tunnel since it started, because the relay stopped answering. Older servers omit them. */
2368
- restarts: z5.number().int().optional(),
2369
- lastRestartAt: z5.string().nullable().optional()
2498
+ restarts: z6.number().int().optional(),
2499
+ lastRestartAt: z6.string().nullable().optional()
2370
2500
  }).nullable().optional(),
2371
2501
  /** Boxes brought back at the server's last start; null when there were none or it is still at it. Older servers omit it. */
2372
2502
  recovery: RecoveryReportSchema.nullable().optional(),
2373
2503
  /** The last self-update; null when none ran. Older servers omit it. */
2374
2504
  update: HostUpdateSchema.nullable().optional()
2375
2505
  });
2376
- var MachineUsageSchema = z5.object({
2377
- name: z5.string(),
2378
- owner: z5.string(),
2506
+ var MachineUsageSchema = z6.object({
2507
+ name: z6.string(),
2508
+ owner: z6.string(),
2379
2509
  status: BoxStatusSchema,
2380
- window: z5.object({ from: z5.string(), to: z5.string() }),
2381
- seconds: z5.object({
2382
- running: z5.number().int(),
2383
- standby: z5.number().int(),
2384
- hibernated: z5.number().int(),
2385
- stopped: z5.number().int()
2510
+ window: z6.object({ from: z6.string(), to: z6.string() }),
2511
+ seconds: z6.object({
2512
+ running: z6.number().int(),
2513
+ standby: z6.number().int(),
2514
+ hibernated: z6.number().int(),
2515
+ stopped: z6.number().int()
2386
2516
  }),
2387
- vcpuHours: z5.number(),
2388
- ramGibHours: z5.number(),
2389
- diskGibHours: z5.number(),
2390
- cost: z5.object({ amount: z5.number(), currency: z5.string() }).optional(),
2517
+ vcpuHours: z6.number(),
2518
+ ramGibHours: z6.number(),
2519
+ diskGibHours: z6.number(),
2520
+ cost: z6.object({ amount: z6.number(), currency: z6.string() }).optional(),
2391
2521
  /** Stops the server did not witness (Firecracker died, host rebooted) and dated to when it noticed. */
2392
- estimatedStops: z5.number().int(),
2393
- historyFrom: z5.string().nullable()
2522
+ estimatedStops: z6.number().int(),
2523
+ historyFrom: z6.string().nullable()
2394
2524
  });
2395
- var GuestStatsSchema = z5.object({
2525
+ var GuestStatsSchema = z6.object({
2396
2526
  /** Load average over 1, 5 and 15 minutes. */
2397
- load: z5.tuple([z5.number(), z5.number(), z5.number()]),
2398
- cpus: z5.number().int(),
2399
- memTotalMib: z5.number().int(),
2527
+ load: z6.tuple([z6.number(), z6.number(), z6.number()]),
2528
+ cpus: z6.number().int(),
2529
+ memTotalMib: z6.number().int(),
2400
2530
  /** Total minus available: page cache counts as free. */
2401
- memUsedMib: z5.number().int(),
2531
+ memUsedMib: z6.number().int(),
2402
2532
  /** The box's root, which is its overlay disk: the box's own writes, not the shared base. */
2403
- diskTotalBytes: z5.number().int(),
2404
- diskUsedBytes: z5.number().int(),
2405
- uptimeSec: z5.number().int()
2533
+ diskTotalBytes: z6.number().int(),
2534
+ diskUsedBytes: z6.number().int(),
2535
+ uptimeSec: z6.number().int()
2406
2536
  });
2407
- var MachineStatsSchema = z5.object({
2408
- name: z5.string(),
2409
- owner: z5.string(),
2537
+ var MachineStatsSchema = z6.object({
2538
+ name: z6.string(),
2539
+ owner: z6.string(),
2410
2540
  stats: GuestStatsSchema.nullable()
2411
2541
  });
2412
- var UsageStatusSchema = z5.enum([...BoxStatusSchema.options, "removed"]);
2542
+ var UsageStatusSchema = z6.enum([...BoxStatusSchema.options, "removed"]);
2413
2543
  var BoxUsageSchema = MachineUsageSchema.omit({ window: true, status: true }).extend({
2414
2544
  /** The host's box id; a name removed and recreated appears twice, with two ids. */
2415
- id: z5.string(),
2545
+ id: z6.string(),
2416
2546
  status: UsageStatusSchema,
2417
2547
  /** Through a control plane: whether the owner slug is a user's or an org's (what `kvbox ls` shows). */
2418
- ownerKind: z5.enum(["user", "org"]).optional(),
2548
+ ownerKind: z6.enum(["user", "org"]).optional(),
2419
2549
  /**
2420
2550
  * Through a control plane: the username that made the box (#60), absent when the box is gone from
2421
2551
  * the index (removed), was found by reconcile, or its maker was deleted. The ledger does not record it.
2422
2552
  */
2423
- createdBy: z5.string().optional()
2553
+ createdBy: z6.string().optional()
2424
2554
  });
2425
- var VolumeUsageSchema = z5.object({
2555
+ var VolumeUsageSchema = z6.object({
2426
2556
  /** The host's volume id; a name removed and made again appears twice, with two ids. */
2427
- id: z5.string(),
2428
- name: z5.string(),
2429
- owner: z5.string(),
2430
- ownerKind: z5.enum(["user", "org"]).optional(),
2557
+ id: z6.string(),
2558
+ name: z6.string(),
2559
+ owner: z6.string(),
2560
+ ownerKind: z6.enum(["user", "org"]).optional(),
2431
2561
  /** The size at the end of the window (or when removed). */
2432
- sizeGib: z5.number().int(),
2433
- status: z5.enum(["present", "removed"]),
2434
- volumeHours: z5.number(),
2435
- volumeGibHours: z5.number(),
2436
- cost: z5.object({ amount: z5.number(), currency: z5.string() }).optional(),
2437
- historyFrom: z5.string().nullable()
2438
- });
2439
- var CronUsageSchema = z5.object({
2440
- id: z5.string(),
2441
- name: z5.string(),
2442
- owner: z5.string(),
2443
- ownerKind: z5.enum(["user", "org"]).optional(),
2444
- status: z5.enum(["present", "removed"]),
2445
- hours: z5.number(),
2446
- cost: z5.object({ amount: z5.number(), currency: z5.string() }).optional(),
2562
+ sizeGib: z6.number().int(),
2563
+ status: z6.enum(["present", "removed"]),
2564
+ volumeHours: z6.number(),
2565
+ volumeGibHours: z6.number(),
2566
+ cost: z6.object({ amount: z6.number(), currency: z6.string() }).optional(),
2567
+ historyFrom: z6.string().nullable()
2568
+ });
2569
+ var CronUsageSchema = z6.object({
2570
+ id: z6.string(),
2571
+ name: z6.string(),
2572
+ owner: z6.string(),
2573
+ ownerKind: z6.enum(["user", "org"]).optional(),
2574
+ status: z6.enum(["present", "removed"]),
2575
+ hours: z6.number(),
2576
+ cost: z6.object({ amount: z6.number(), currency: z6.string() }).optional(),
2447
2577
  /** When it was made. */
2448
- historyFrom: z5.string().nullable()
2449
- });
2450
- var BackupUsageSchema = z5.object({
2451
- id: z5.string(),
2452
- kind: z5.string(),
2453
- name: z5.string(),
2454
- owner: z5.string(),
2455
- ownerKind: z5.enum(["user", "org"]).optional(),
2578
+ historyFrom: z6.string().nullable()
2579
+ });
2580
+ var BackupUsageSchema = z6.object({
2581
+ id: z6.string(),
2582
+ kind: z6.string(),
2583
+ name: z6.string(),
2584
+ owner: z6.string(),
2585
+ ownerKind: z6.enum(["user", "org"]).optional(),
2456
2586
  /** How many paid backups turned ready in the window. */
2457
- count: z5.number().int(),
2458
- cost: z5.object({ amount: z5.number(), currency: z5.string() })
2587
+ count: z6.number().int(),
2588
+ cost: z6.object({ amount: z6.number(), currency: z6.string() })
2459
2589
  });
2460
- var UsageDayItemSchema = z5.object({
2461
- id: z5.string(),
2462
- name: z5.string(),
2463
- owner: z5.string(),
2590
+ var UsageDayItemSchema = z6.object({
2591
+ id: z6.string(),
2592
+ name: z6.string(),
2593
+ owner: z6.string(),
2464
2594
  /** Removed by the end of the report's window. */
2465
- removed: z5.boolean(),
2466
- cost: z5.number()
2595
+ removed: z6.boolean(),
2596
+ cost: z6.number()
2467
2597
  });
2468
- var UsageDaySchema = z5.object({
2598
+ var UsageDaySchema = z6.object({
2469
2599
  /** `YYYY-MM-DD`, UTC. */
2470
- date: z5.string(),
2471
- from: z5.string(),
2472
- to: z5.string(),
2473
- cost: z5.number(),
2474
- currency: z5.string(),
2475
- boxes: z5.array(UsageDayItemSchema),
2476
- volumes: z5.array(UsageDayItemSchema),
2600
+ date: z6.string(),
2601
+ from: z6.string(),
2602
+ to: z6.string(),
2603
+ cost: z6.number(),
2604
+ currency: z6.string(),
2605
+ boxes: z6.array(UsageDayItemSchema),
2606
+ volumes: z6.array(UsageDayItemSchema),
2477
2607
  /** Object storage that existed that day (#182); absent on a day without any. */
2478
- storage: z5.array(UsageDayItemSchema).optional(),
2608
+ storage: z6.array(UsageDayItemSchema).optional(),
2479
2609
  /** Cron services that existed that day (#190); absent on a day without any. */
2480
- cron: z5.array(UsageDayItemSchema).optional(),
2610
+ cron: z6.array(UsageDayItemSchema).optional(),
2481
2611
  /** Paid backups that turned ready that day, summed per thing backed up (`id` is `<owner>/<kind>:<name>`); absent on a day without any. */
2482
- backups: z5.array(UsageDayItemSchema).optional()
2612
+ backups: z6.array(UsageDayItemSchema).optional()
2483
2613
  });
2484
- var UsageReportSchema = z5.object({
2485
- window: z5.object({ from: z5.string(), to: z5.string() }),
2486
- boxes: z5.array(BoxUsageSchema),
2614
+ var UsageReportSchema = z6.object({
2615
+ window: z6.object({ from: z6.string(), to: z6.string() }),
2616
+ boxes: z6.array(BoxUsageSchema),
2487
2617
  /** Absent from a side older than #91. */
2488
- volumes: z5.array(VolumeUsageSchema).optional(),
2618
+ volumes: z6.array(VolumeUsageSchema).optional(),
2489
2619
  /**
2490
2620
  * Object storage (#182, control plane only): one row per storage a slug has or had, shaped like a
2491
2621
  * volume's. `volumeHours` are the hours it existed, `volumeGibHours` those of the GiB beyond the
2492
2622
  * included ones, `sizeGib` its whole size. Absent when there is none.
2493
2623
  */
2494
- storage: z5.array(VolumeUsageSchema).optional(),
2624
+ storage: z6.array(VolumeUsageSchema).optional(),
2495
2625
  /** Cron services (#190, control plane only): one row per service a slug has or had. Absent when there is none. */
2496
- cron: z5.array(CronUsageSchema).optional(),
2626
+ cron: z6.array(CronUsageSchema).optional(),
2497
2627
  /** Paid backups (control plane only): one row per box, volume or service backed up by hand in the window. Absent when there is none. */
2498
- backups: z5.array(BackupUsageSchema).optional(),
2628
+ backups: z6.array(BackupUsageSchema).optional(),
2499
2629
  /** With `?by=day` only, oldest day first. */
2500
- days: z5.array(UsageDaySchema).optional(),
2501
- totals: z5.object({
2630
+ days: z6.array(UsageDaySchema).optional(),
2631
+ totals: z6.object({
2502
2632
  seconds: MachineUsageSchema.shape.seconds,
2503
- vcpuHours: z5.number(),
2504
- ramGibHours: z5.number(),
2505
- diskGibHours: z5.number(),
2506
- volumeHours: z5.number().optional(),
2507
- volumeGibHours: z5.number().optional(),
2633
+ vcpuHours: z6.number(),
2634
+ ramGibHours: z6.number(),
2635
+ diskGibHours: z6.number(),
2636
+ volumeHours: z6.number().optional(),
2637
+ volumeGibHours: z6.number().optional(),
2508
2638
  /** Boxes, volumes, object storage, cron services and paid backups together. */
2509
- cost: z5.object({ amount: z5.number(), currency: z5.string() }).optional()
2639
+ cost: z6.object({ amount: z6.number(), currency: z6.string() }).optional()
2510
2640
  })
2511
2641
  });
2512
- var UsageEventRowSchema = z5.object({
2513
- id: z5.number().int(),
2514
- boxId: z5.string(),
2515
- owner: z5.string(),
2516
- name: z5.string(),
2517
- at: z5.string(),
2518
- state: z5.enum(["running", "standby", "hibernated", "stopped"]),
2519
- vcpu: z5.number().int(),
2520
- memMib: z5.number().int(),
2521
- diskGib: z5.number().int(),
2522
- by: z5.string()
2523
- });
2524
- var UsageEventsResponseSchema = z5.object({
2525
- ledger: z5.string().min(1),
2526
- events: z5.array(UsageEventRowSchema),
2527
- next: z5.number().int()
2528
- });
2529
- var VolumeEventRowSchema = z5.object({
2530
- id: z5.number().int(),
2531
- volumeId: z5.string(),
2532
- owner: z5.string(),
2533
- name: z5.string(),
2534
- at: z5.string(),
2535
- sizeGib: z5.number().int(),
2536
- by: z5.enum(["create", "resize", "rm"])
2537
- });
2538
- var VolumeEventsResponseSchema = z5.object({
2539
- ledger: z5.string().min(1),
2540
- events: z5.array(VolumeEventRowSchema),
2541
- next: z5.number().int()
2642
+ var UsageEventRowSchema = z6.object({
2643
+ id: z6.number().int(),
2644
+ boxId: z6.string(),
2645
+ owner: z6.string(),
2646
+ name: z6.string(),
2647
+ at: z6.string(),
2648
+ state: z6.enum(["running", "standby", "hibernated", "stopped"]),
2649
+ vcpu: z6.number().int(),
2650
+ memMib: z6.number().int(),
2651
+ diskGib: z6.number().int(),
2652
+ by: z6.string()
2653
+ });
2654
+ var UsageEventsResponseSchema = z6.object({
2655
+ ledger: z6.string().min(1),
2656
+ events: z6.array(UsageEventRowSchema),
2657
+ next: z6.number().int()
2658
+ });
2659
+ var VolumeEventRowSchema = z6.object({
2660
+ id: z6.number().int(),
2661
+ volumeId: z6.string(),
2662
+ owner: z6.string(),
2663
+ name: z6.string(),
2664
+ at: z6.string(),
2665
+ sizeGib: z6.number().int(),
2666
+ by: z6.enum(["create", "resize", "rm"])
2667
+ });
2668
+ var VolumeEventsResponseSchema = z6.object({
2669
+ ledger: z6.string().min(1),
2670
+ events: z6.array(VolumeEventRowSchema),
2671
+ next: z6.number().int()
2542
2672
  });
2543
2673
  var API_ERROR_CODES = ["account-inactive", "org-inactive", "out-of-credit", "box-outdated", "storage-outdated", "object-exists", "storage-waking"];
2544
- var ApiErrorCodeSchema = z5.enum(API_ERROR_CODES);
2545
- var ApiErrorSchema = z5.object({
2546
- error: z5.string(),
2674
+ var ApiErrorCodeSchema = z6.enum(API_ERROR_CODES);
2675
+ var ApiErrorSchema = z6.object({
2676
+ error: z6.string(),
2547
2677
  code: ApiErrorCodeSchema.optional()
2548
2678
  });
2549
2679
  var ACTIVATED_BY = ["card", "admin"];
2550
- var ActivatedBySchema = z5.enum(ACTIVATED_BY);
2551
- var CloudUserSchema = z5.object({
2680
+ var ActivatedBySchema = z6.enum(ACTIVATED_BY);
2681
+ var CloudUserSchema = z6.object({
2552
2682
  /** The handle: what hosts file boxes under (`<username>@<control plane>`). Lowercase, no `@` or `/`. */
2553
- username: z5.string(),
2683
+ username: z6.string(),
2554
2684
  /** Display name, free text ("Alexandru Ghiura"). */
2555
- name: z5.string(),
2685
+ name: z6.string(),
2556
2686
  /** Login identity, unique. */
2557
- email: z5.string(),
2558
- role: z5.enum(["admin", "user"]),
2559
- createdAt: z5.string(),
2687
+ email: z6.string(),
2688
+ role: z6.enum(["admin", "user"]),
2689
+ createdAt: z6.string(),
2560
2690
  /**
2561
2691
  * False until a card is on file or an admin activates the account (#74): then only `/me` and
2562
2692
  * `/logout` answer. Admins are never gated. A control plane older than #74 does not send these and
2563
2693
  * gates nobody, hence the defaults: a newer CLI must still parse its answers.
2564
2694
  */
2565
- active: z5.boolean().default(true),
2695
+ active: z6.boolean().default(true),
2566
2696
  activatedBy: ActivatedBySchema.nullable().default(null),
2567
2697
  /** When too many wrong passwords locked the account (#161); null when it is not locked. Older control planes omit it. */
2568
- lockedAt: z5.string().nullable().default(null)
2698
+ lockedAt: z6.string().nullable().default(null)
2569
2699
  });
2570
2700
  var ORG_ROLES = ["owner", "admin", "member"];
2571
- var OrgRoleSchema = z5.enum(ORG_ROLES);
2572
- var CloudOrgSchema = z5.object({
2573
- slug: z5.string(),
2701
+ var OrgRoleSchema = z6.enum(ORG_ROLES);
2702
+ var CloudOrgSchema = z6.object({
2703
+ slug: z6.string(),
2574
2704
  /** Display name; the slug never changes, this may. */
2575
- name: z5.string(),
2576
- createdAt: z5.string(),
2705
+ name: z6.string(),
2706
+ createdAt: z6.string(),
2577
2707
  /** An org pays for itself (#74): off until it has a card or an admin activates it; its boxes are 402. Defaults as on CloudUser. */
2578
- active: z5.boolean().default(true),
2708
+ active: z6.boolean().default(true),
2579
2709
  activatedBy: ActivatedBySchema.nullable().default(null)
2580
2710
  });
2581
2711
  var OrgMembershipSchema = CloudOrgSchema.extend({ role: OrgRoleSchema });
2582
- var OrgMemberSchema = z5.object({
2583
- username: z5.string(),
2584
- name: z5.string(),
2712
+ var OrgMemberSchema = z6.object({
2713
+ username: z6.string(),
2714
+ name: z6.string(),
2585
2715
  role: OrgRoleSchema,
2586
- addedAt: z5.string()
2716
+ addedAt: z6.string()
2587
2717
  });
2588
- var OrgDetailSchema = CloudOrgSchema.extend({ members: z5.array(OrgMemberSchema) });
2589
- var CreateOrgRequestSchema = z5.object({
2590
- slug: z5.string().min(1),
2591
- name: z5.string().min(1)
2718
+ var OrgDetailSchema = CloudOrgSchema.extend({ members: z6.array(OrgMemberSchema) });
2719
+ var CreateOrgRequestSchema = z6.object({
2720
+ slug: z6.string().min(1),
2721
+ name: z6.string().min(1)
2592
2722
  });
2593
- var RenameOrgRequestSchema = z5.object({ name: z5.string().min(1) });
2594
- var AddMemberRequestSchema = z5.object({
2595
- username: z5.string().min(1),
2723
+ var RenameOrgRequestSchema = z6.object({ name: z6.string().min(1) });
2724
+ var AddMemberRequestSchema = z6.object({
2725
+ username: z6.string().min(1),
2596
2726
  role: OrgRoleSchema.default("member")
2597
2727
  });
2598
- var SetRoleRequestSchema = z5.object({ role: OrgRoleSchema });
2599
- var MeResponseSchema = CloudUserSchema.extend({ orgs: z5.array(OrgMembershipSchema) });
2600
- var BalanceSchema = z5.object({
2601
- slug: z5.string(),
2602
- balance: z5.number(),
2603
- currency: z5.string(),
2604
- topUps: z5.number(),
2605
- spent: z5.number(),
2728
+ var SetRoleRequestSchema = z6.object({ role: OrgRoleSchema });
2729
+ var MeResponseSchema = CloudUserSchema.extend({ orgs: z6.array(OrgMembershipSchema) });
2730
+ var BalanceSchema = z6.object({
2731
+ slug: z6.string(),
2732
+ balance: z6.number(),
2733
+ currency: z6.string(),
2734
+ topUps: z6.number(),
2735
+ spent: z6.number(),
2606
2736
  /** The first moment usage counts from: the slug's first top-up or redeemed code; null when it has none. */
2607
- since: z5.string().nullable(),
2737
+ since: z6.string().nullable(),
2608
2738
  /** When the slug ran out and its boxes were hibernated (the `sweep-credit` job); null in good standing. Absent from a control plane older than this field. */
2609
- suspendedAt: z5.string().nullable().default(null),
2739
+ suspendedAt: z6.string().nullable().default(null),
2610
2740
  /** Promo credit left (#163), already counted in `balance`; 0 with none. Absent from a control plane older than this field. */
2611
- promo: z5.number().default(0),
2741
+ promo: z6.number().default(0),
2612
2742
  /** When the next promo credit expires; null with none left. */
2613
- promoExpiresAt: z5.string().nullable().default(null)
2743
+ promoExpiresAt: z6.string().nullable().default(null)
2614
2744
  });
2615
- var TopUpRequestSchema = z5.object({
2616
- slug: z5.string().min(1),
2745
+ var TopUpRequestSchema = z6.object({
2746
+ slug: z6.string().min(1),
2617
2747
  /** In the control plane's currency; negative corrects a mistake. */
2618
- amount: z5.number().finite(),
2619
- note: z5.string().max(200).optional()
2620
- });
2621
- var TopUpSchema = z5.object({
2622
- id: z5.string(),
2623
- slug: z5.string(),
2624
- amount: z5.number(),
2625
- currency: z5.string(),
2748
+ amount: z6.number().finite(),
2749
+ note: z6.string().max(200).optional()
2750
+ });
2751
+ var TopUpSchema = z6.object({
2752
+ id: z6.string(),
2753
+ slug: z6.string(),
2754
+ amount: z6.number(),
2755
+ currency: z6.string(),
2626
2756
  /** `transfer` (#93): an owner moving credit to an org they own, a negative row on their slug and a positive one on the org's. */
2627
- source: z5.enum(["admin", "card", "trial", "transfer"]),
2628
- note: z5.string().nullable(),
2629
- at: z5.string()
2757
+ source: z6.enum(["admin", "card", "trial", "transfer"]),
2758
+ note: z6.string().nullable(),
2759
+ at: z6.string()
2630
2760
  });
2631
- var CreateCodeRequestSchema = z5.object({
2761
+ var CreateCodeRequestSchema = z6.object({
2632
2762
  /** In the control plane's currency, cents at most. */
2633
- amount: z5.number().positive().multipleOf(0.01, "amount is in cents at most"),
2763
+ amount: z6.number().positive().multipleOf(0.01, "amount is in cents at most"),
2634
2764
  /** A day (`2026-12-11`, through the end of it, UTC) or an ISO time. The credit is gone then, and so is the code. */
2635
- expiresAt: z5.string().min(1),
2636
- note: z5.string().max(200).optional()
2637
- });
2638
- var CreditCodeSchema = z5.object({
2639
- code: z5.string(),
2640
- amount: z5.number(),
2641
- currency: z5.string(),
2642
- expiresAt: z5.string(),
2643
- note: z5.string().nullable(),
2644
- status: z5.enum(["unused", "redeemed", "expired", "revoked"]),
2645
- createdBy: z5.string(),
2646
- createdAt: z5.string(),
2765
+ expiresAt: z6.string().min(1),
2766
+ note: z6.string().max(200).optional()
2767
+ });
2768
+ var CreditCodeSchema = z6.object({
2769
+ code: z6.string(),
2770
+ amount: z6.number(),
2771
+ currency: z6.string(),
2772
+ expiresAt: z6.string(),
2773
+ note: z6.string().nullable(),
2774
+ status: z6.enum(["unused", "redeemed", "expired", "revoked"]),
2775
+ createdBy: z6.string(),
2776
+ createdAt: z6.string(),
2647
2777
  /** Who redeemed it and the slug the credit went to (their own, or an org they own). */
2648
- redeemedBy: z5.string().nullable(),
2649
- redeemedSlug: z5.string().nullable(),
2650
- redeemedAt: z5.string().nullable(),
2651
- revokedAt: z5.string().nullable()
2652
- });
2653
- var RedeemRequestSchema = z5.object({
2654
- code: z5.string().min(1).max(64),
2655
- org: z5.string().min(1).optional()
2656
- });
2657
- var RedeemResponseSchema = z5.object({
2658
- slug: z5.string(),
2659
- amount: z5.number(),
2660
- currency: z5.string(),
2661
- expiresAt: z5.string(),
2778
+ redeemedBy: z6.string().nullable(),
2779
+ redeemedSlug: z6.string().nullable(),
2780
+ redeemedAt: z6.string().nullable(),
2781
+ revokedAt: z6.string().nullable()
2782
+ });
2783
+ var RedeemRequestSchema = z6.object({
2784
+ code: z6.string().min(1).max(64),
2785
+ org: z6.string().min(1).optional()
2786
+ });
2787
+ var RedeemResponseSchema = z6.object({
2788
+ slug: z6.string(),
2789
+ amount: z6.number(),
2790
+ currency: z6.string(),
2791
+ expiresAt: z6.string(),
2662
2792
  balance: BalanceSchema,
2663
2793
  /** The slug was out of credit and this put it back above zero: it may start boxes again. */
2664
- reinstated: z5.boolean()
2794
+ reinstated: z6.boolean()
2665
2795
  });
2666
2796
  var TOP_UP_AMOUNTS = [10, 25, 50, 100];
2667
- var BillingInfoSchema = z5.object({
2668
- card: z5.object({ brand: z5.string(), last4: z5.string() }).nullable(),
2669
- cardInUse: z5.boolean(),
2797
+ var BillingInfoSchema = z6.object({
2798
+ card: z6.object({ brand: z6.string(), last4: z6.string() }).nullable(),
2799
+ cardInUse: z6.boolean(),
2670
2800
  balance: BalanceSchema
2671
2801
  });
2672
- var BillingRedirectSchema = z5.object({ url: z5.string() });
2673
- var TopUpCheckoutRequestSchema = z5.object({
2674
- amount: z5.literal(TOP_UP_AMOUNTS)
2802
+ var BillingRedirectSchema = z6.object({ url: z6.string() });
2803
+ var TopUpCheckoutRequestSchema = z6.object({
2804
+ amount: z6.literal(TOP_UP_AMOUNTS)
2675
2805
  });
2676
- var TransferRequestSchema = z5.object({
2677
- org: z5.string().min(1),
2678
- amount: z5.number().positive().multipleOf(0.01, "amount is in cents at most")
2806
+ var TransferRequestSchema = z6.object({
2807
+ org: z6.string().min(1),
2808
+ amount: z6.number().positive().multipleOf(0.01, "amount is in cents at most")
2679
2809
  });
2680
- var TransferResponseSchema = z5.object({ from: BalanceSchema, to: BalanceSchema, activated: z5.boolean() });
2681
- var LoginRequestSchema = z5.object({
2682
- email: z5.string().min(1),
2683
- password: z5.string().min(1),
2684
- publicKey: z5.string().optional()
2810
+ var TransferResponseSchema = z6.object({ from: BalanceSchema, to: BalanceSchema, activated: z6.boolean() });
2811
+ var LoginRequestSchema = z6.object({
2812
+ email: z6.string().min(1),
2813
+ password: z6.string().min(1),
2814
+ publicKey: z6.string().optional()
2685
2815
  });
2686
- var SignupRequestSchema = z5.object({
2687
- username: z5.string().min(1),
2688
- name: z5.string().min(1),
2689
- email: z5.string().min(1),
2690
- password: z5.string().min(1)
2816
+ var SignupRequestSchema = z6.object({
2817
+ username: z6.string().min(1),
2818
+ name: z6.string().min(1),
2819
+ email: z6.string().min(1),
2820
+ password: z6.string().min(1)
2691
2821
  });
2692
- var LoginResponseSchema = z5.object({
2693
- token: z5.string(),
2822
+ var LoginResponseSchema = z6.object({
2823
+ token: z6.string(),
2694
2824
  user: CloudUserSchema,
2695
- sshCert: z5.string().optional(),
2696
- sshCertExpires: z5.string().optional(),
2825
+ sshCert: z6.string().optional(),
2826
+ sshCertExpires: z6.string().optional(),
2697
2827
  /** Whose boxes the certificate opens: `<slug>@<realm>` for the user and each org they are in (orgs phase 4). */
2698
- sshCertPrincipals: z5.array(z5.string()).optional()
2828
+ sshCertPrincipals: z6.array(z6.string()).optional()
2699
2829
  });
2700
- var DeviceLoginRequestSchema = z5.object({
2830
+ var DeviceLoginRequestSchema = z6.object({
2701
2831
  // Capped: anyone may open a login, and the key is stored until it expires (an RSA-16384 key is ~2.8 KB).
2702
- publicKey: z5.string().max(16384).optional(),
2703
- hostname: z5.string().max(255).optional()
2704
- });
2705
- var DeviceLoginStartSchema = z5.object({
2706
- deviceCode: z5.string(),
2707
- userCode: z5.string(),
2708
- verifyUrl: z5.string(),
2709
- expiresIn: z5.number(),
2710
- interval: z5.number()
2711
- });
2712
- var DeviceLoginPollRequestSchema = z5.object({ deviceCode: z5.string().min(1) });
2713
- var DeviceLoginPollSchema = z5.union([
2714
- z5.object({ status: z5.enum(["pending", "slow_down", "refused", "expired"]) }),
2715
- LoginResponseSchema.extend({ status: z5.literal("approved") })
2832
+ publicKey: z6.string().max(16384).optional(),
2833
+ hostname: z6.string().max(255).optional()
2834
+ });
2835
+ var DeviceLoginStartSchema = z6.object({
2836
+ deviceCode: z6.string(),
2837
+ userCode: z6.string(),
2838
+ verifyUrl: z6.string(),
2839
+ expiresIn: z6.number(),
2840
+ interval: z6.number()
2841
+ });
2842
+ var DeviceLoginPollRequestSchema = z6.object({ deviceCode: z6.string().min(1) });
2843
+ var DeviceLoginPollSchema = z6.union([
2844
+ z6.object({ status: z6.enum(["pending", "slow_down", "refused", "expired"]) }),
2845
+ LoginResponseSchema.extend({ status: z6.literal("approved") })
2716
2846
  ]);
2717
- var DeviceLoginInfoSchema = z5.object({
2718
- userCode: z5.string(),
2719
- hostname: z5.string(),
2847
+ var DeviceLoginInfoSchema = z6.object({
2848
+ userCode: z6.string(),
2849
+ hostname: z6.string(),
2720
2850
  /** The address the request came from; null when the control plane could not tell. */
2721
- ip: z5.string().nullable(),
2722
- createdAt: z5.string(),
2723
- expiresAt: z5.string()
2851
+ ip: z6.string().nullable(),
2852
+ createdAt: z6.string(),
2853
+ expiresAt: z6.string()
2724
2854
  });
2725
2855
  var API_KEY_NAME_RE = /^[a-z0-9][a-z0-9._-]{0,31}$/;
2726
- var ApiKeySchema = z5.object({
2727
- name: z5.string(),
2728
- createdAt: z5.string(),
2856
+ var ApiKeySchema = z6.object({
2857
+ name: z6.string(),
2858
+ createdAt: z6.string(),
2729
2859
  /** Last request made with it (ISO); null: never used. */
2730
- lastUsedAt: z5.string().nullable(),
2860
+ lastUsedAt: z6.string().nullable(),
2731
2861
  /** When it stops working (ISO); null: never. */
2732
- expiresAt: z5.string().nullable()
2862
+ expiresAt: z6.string().nullable()
2733
2863
  });
2734
- var CreateApiKeyRequestSchema = z5.object({
2735
- name: z5.string().regex(API_KEY_NAME_RE, "a key's name is lowercase letters, digits, '.', '_' or '-' (up to 32 characters)"),
2736
- expiresAt: z5.iso.datetime({ offset: true }).nullable().optional()
2864
+ var CreateApiKeyRequestSchema = z6.object({
2865
+ name: z6.string().regex(API_KEY_NAME_RE, "a key's name is lowercase letters, digits, '.', '_' or '-' (up to 32 characters)"),
2866
+ expiresAt: z6.iso.datetime({ offset: true }).nullable().optional()
2737
2867
  });
2738
- var CreatedApiKeySchema = ApiKeySchema.extend({ key: z5.string() });
2739
- var SshCertRequestSchema = z5.object({
2740
- publicKey: z5.string().min(1)
2868
+ var CreatedApiKeySchema = ApiKeySchema.extend({ key: z6.string() });
2869
+ var SshCertRequestSchema = z6.object({
2870
+ publicKey: z6.string().min(1)
2741
2871
  });
2742
- var SshCertResponseSchema = z5.object({
2743
- cert: z5.string(),
2744
- expires: z5.string(),
2745
- principals: z5.array(z5.string())
2872
+ var SshCertResponseSchema = z6.object({
2873
+ cert: z6.string(),
2874
+ expires: z6.string(),
2875
+ principals: z6.array(z6.string())
2746
2876
  });
2747
- var SshCaResponseSchema = z5.object({
2748
- publicKey: z5.string(),
2877
+ var SshCaResponseSchema = z6.object({
2878
+ publicKey: z6.string(),
2749
2879
  /** CAs replaced by `ca rotate` (#55), newest first; a box still holding one of these has not had `kvbox-server trust-ca` run on its host. */
2750
- retired: z5.array(z5.object({ publicKey: z5.string(), retiredAt: z5.string() })).optional()
2880
+ retired: z6.array(z6.object({ publicKey: z6.string(), retiredAt: z6.string() })).optional()
2751
2881
  });
2752
- var HostSshCaResponseSchema = z5.object({
2753
- publicKey: z5.string()
2882
+ var HostSshCaResponseSchema = z6.object({
2883
+ publicKey: z6.string()
2754
2884
  });
2755
- var CloudCaSchema = z5.object({
2756
- controlPlane: z5.string(),
2757
- publicKey: z5.string(),
2758
- fingerprint: z5.string()
2885
+ var CloudCaSchema = z6.object({
2886
+ controlPlane: z6.string(),
2887
+ publicKey: z6.string(),
2888
+ fingerprint: z6.string()
2759
2889
  });
2760
- var TrustCaRequestSchema = z5.object({
2761
- publicKey: z5.string().min(1)
2890
+ var TrustCaRequestSchema = z6.object({
2891
+ publicKey: z6.string().min(1)
2762
2892
  });
2763
- var SshKeysAppliedSchema = z5.enum(["now", "start", "wake", "resume", "later"]);
2764
- var TrustCaReportSchema = z5.object({
2765
- publicKey: z5.string(),
2766
- fingerprint: z5.string(),
2893
+ var SshKeysAppliedSchema = z6.enum(["now", "start", "wake", "resume", "later"]);
2894
+ var TrustCaReportSchema = z6.object({
2895
+ publicKey: z6.string(),
2896
+ fingerprint: z6.string(),
2767
2897
  /** The guest trusts the CA now. */
2768
- updated: z5.array(z5.string()),
2898
+ updated: z6.array(z6.string()),
2769
2899
  /** meta.json has the line; the guest gets it at `when`. */
2770
- pending: z5.array(z5.object({ box: z5.string(), when: SshKeysAppliedSchema, why: z5.string().optional() })),
2771
- failed: z5.array(z5.object({ box: z5.string(), error: z5.string() })),
2900
+ pending: z6.array(z6.object({ box: z6.string(), when: SshKeysAppliedSchema, why: z6.string().optional() })),
2901
+ failed: z6.array(z6.object({ box: z6.string(), error: z6.string() })),
2772
2902
  /** Local boxes, untouched: they trust the host's key only. */
2773
- local: z5.number().int(),
2903
+ local: z6.number().int(),
2774
2904
  /** Cloud boxes made without a CA line (a managed service's, #173), untouched: no certificate opens them. Absent from older servers. */
2775
- skipped: z5.array(z5.string()).optional()
2776
- });
2777
- var HostJoinRequestSchema = z5.object({
2778
- token: z5.string().min(1),
2779
- name: z5.string().min(1),
2780
- url: z5.string().url(),
2781
- fingerprint: z5.string().regex(/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/),
2782
- publicAddress: z5.string().min(1),
2905
+ skipped: z6.array(z6.string()).optional()
2906
+ });
2907
+ var HostJoinRequestSchema = z6.object({
2908
+ token: z6.string().min(1),
2909
+ name: z6.string().min(1),
2910
+ url: z6.string().url(),
2911
+ fingerprint: z6.string().regex(/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/),
2912
+ publicAddress: z6.string().min(1),
2783
2913
  /** Where the host is (`kvbox-server join --country`): a code or an English name. */
2784
- country: z5.string().optional()
2785
- });
2786
- var HostJoinResponseSchema = z5.object({
2787
- hostSecret: z5.string(),
2788
- controlPlane: z5.object({ name: z5.string() })
2789
- });
2790
- var CloudHostSchema = z5.object({
2791
- name: z5.string(),
2792
- url: z5.string(),
2793
- publicAddress: z5.string(),
2794
- joinedAt: z5.string(),
2795
- lastSeenAt: z5.string().nullable(),
2914
+ country: z6.string().optional()
2915
+ });
2916
+ var HostJoinResponseSchema = z6.object({
2917
+ hostSecret: z6.string(),
2918
+ controlPlane: z6.object({ name: z6.string() })
2919
+ });
2920
+ var CloudHostSchema = z6.object({
2921
+ name: z6.string(),
2922
+ url: z6.string(),
2923
+ publicAddress: z6.string(),
2924
+ joinedAt: z6.string(),
2925
+ lastSeenAt: z6.string().nullable(),
2796
2926
  capacity: CapacitySchema.nullable(),
2797
2927
  /** ISO 3166-1 alpha-2 code (`RO`), null when nobody said where the host is. */
2798
- country: z5.string().nullable(),
2928
+ country: z6.string().nullable(),
2799
2929
  /** The S3 region a storage made on this host answers to (`ro-west-1`); null: it takes no storage. */
2800
- region: z5.string().nullable(),
2930
+ region: z6.string().nullable(),
2801
2931
  /** kvbox-server's version as of the poller's last look (`capacity.version`); null before one, or for a server older than 0.5.45. */
2802
- version: z5.string().nullable()
2932
+ version: z6.string().nullable()
2803
2933
  });
2804
- var HostInfoSchema = z5.object({
2934
+ var HostInfoSchema = z6.object({
2805
2935
  host: CloudHostSchema,
2806
2936
  health: HealthSchema.nullable(),
2807
- error: z5.string().nullable()
2937
+ error: z6.string().nullable()
2808
2938
  });
2809
- var HostPatchRequest = z5.object({ country: z5.string().nullable().optional(), region: z5.string().nullable().optional() }).refine((b) => b.country !== void 0 || b.region !== void 0, { message: "give country, region or both" });
2810
- var CountrySchema = z5.object({ code: z5.string(), name: z5.string() });
2939
+ var HostPatchRequest = z6.object({ country: z6.string().nullable().optional(), region: z6.string().nullable().optional() }).refine((b) => b.country !== void 0 || b.region !== void 0, { message: "give country, region or both" });
2940
+ var CountrySchema = z6.object({ code: z6.string(), name: z6.string() });
2811
2941
 
2812
2942
  // src/core/locks.ts
2813
2943
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -2837,6 +2967,9 @@ async function withLock(key, fn) {
2837
2967
  if (tails.get(key) === tail) tails.delete(key);
2838
2968
  }
2839
2969
  }
2970
+ function outsideLocks(fn) {
2971
+ return held.exit(fn);
2972
+ }
2840
2973
  function boxBusy(ref) {
2841
2974
  return tails.has(refKey(ref));
2842
2975
  }
@@ -3438,7 +3571,11 @@ async function capacity(p = paths()) {
3438
3571
  images: await listImages(cfg, p),
3439
3572
  ...await backupStoreCapacity(p).then((store) => store ? { backupStore: store } : {}),
3440
3573
  // Backups and restores here reach a store by its certificate's pin (core/storeFetch.ts).
3441
- storeClient: true
3574
+ storeClient: true,
3575
+ // A new box on a backup's disk (#141): the control plane places `new --from-backup` only here.
3576
+ fromBackup: true,
3577
+ // A box's integrations are kept here (#205): the control plane sends a list only to such a host.
3578
+ integrations: true
3442
3579
  };
3443
3580
  }
3444
3581
  function gb(mib) {
@@ -3488,7 +3625,7 @@ async function assertRoomFor(vcpu, memMib, force, box, by, p = paths()) {
3488
3625
  // src/core/env.ts
3489
3626
  import { existsSync as existsSync7 } from "node:fs";
3490
3627
  import { copyFile, mkdir as mkdir4, readFile as readFile7, readdir as readdir4, rename as rename4, writeFile as writeFile5 } from "node:fs/promises";
3491
- import { z as z6 } from "zod";
3628
+ import { z as z7 } from "zod";
3492
3629
 
3493
3630
  // ../shared/src/env.ts
3494
3631
  var ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
@@ -3508,10 +3645,10 @@ function envValueProblem(value) {
3508
3645
  }
3509
3646
 
3510
3647
  // src/core/env.ts
3511
- var OwnerEnvSchema = z6.object({
3648
+ var OwnerEnvSchema = z7.object({
3512
3649
  /** The control plane's counter for the list; only ever grows. */
3513
- version: z6.number().int().min(0),
3514
- vars: z6.array(z6.object({ name: z6.string(), value: z6.string() }))
3650
+ version: z7.number().int().min(0),
3651
+ vars: z7.array(z7.object({ name: z7.string(), value: z7.string() }))
3515
3652
  });
3516
3653
  async function readOwnerEnv(owner, p = paths()) {
3517
3654
  try {
@@ -3532,8 +3669,8 @@ async function envForBoot(box, p = paths()) {
3532
3669
  const mine = new Set(own.map((v) => v.name));
3533
3670
  return [...(slug ?? []).filter((v) => !mine.has(v.name)), ...own.map((v) => ({ name: v.name, value: v.value }))];
3534
3671
  }
3535
- var BoxEnvFileSchema = z6.object({
3536
- vars: z6.array(z6.object({ name: z6.string(), value: z6.string(), secret: z6.boolean(), updatedAt: z6.string() }))
3672
+ var BoxEnvFileSchema = z7.object({
3673
+ vars: z7.array(z7.object({ name: z7.string(), value: z7.string(), secret: z7.boolean(), updatedAt: z7.string() }))
3537
3674
  });
3538
3675
  async function readBoxEnv(box, p = paths()) {
3539
3676
  return readBoxEnvFile(p.machine(box.owner, box.name).env);
@@ -3750,81 +3887,7 @@ function recordState(meta, state, by, p, at = (/* @__PURE__ */ new Date()).toISO
3750
3887
  }
3751
3888
  }
3752
3889
 
3753
- // src/core/machines/status.ts
3754
- import { existsSync as existsSync9 } from "node:fs";
3755
- function isHibernated(meta, p) {
3756
- return !vmAlive(meta) && existsSync9(p.machine(meta.owner, meta.name).hibernateVmstate);
3757
- }
3758
- function statusOf(meta, p = paths()) {
3759
- if (vmAlive(meta)) return meta.paused ? "standby" : "running";
3760
- return isHibernated(meta, p) ? "hibernated" : "stopped";
3761
- }
3762
- function stateMessage(ref, status) {
3763
- return `box ${shown(ref)} is ${status === "standby" ? "in standby" : status}`;
3764
- }
3765
- function assertNotHibernated(meta, p) {
3766
- if (isHibernated(meta, p)) {
3767
- throw new KvboxError(`${stateMessage(meta, "hibernated")}; its memory image was made with its current shape and base: kvbox wake ${shown(meta)} first`);
3768
- }
3769
- }
3770
-
3771
- // src/core/machines/list.ts
3772
- function toMachine(meta, p = paths()) {
3773
- const alive2 = vmAlive(meta);
3774
- if (!alive2 && meta.pid !== null) {
3775
- try {
3776
- closeOpenRun(meta.id, (/* @__PURE__ */ new Date()).toISOString(), p);
3777
- } catch (err) {
3778
- log.warn(`usage ledger: ${err.message}`);
3779
- }
3780
- }
3781
- return {
3782
- id: meta.id,
3783
- name: meta.name,
3784
- owner: meta.owner,
3785
- ip: meta.ip,
3786
- mac: meta.mac,
3787
- pid: alive2 ? meta.pid : null,
3788
- vcpu: meta.vcpu,
3789
- memMib: meta.memMib,
3790
- ...diskStats(p.machine(meta.owner, meta.name).overlay),
3791
- base: meta.base,
3792
- ...meta.image !== void 0 ? { image: meta.image } : {},
3793
- ...meta.url !== void 0 ? { url: urlFor(meta.url, meta.name) } : {},
3794
- createdAt: meta.createdAt,
3795
- source: meta.source,
3796
- status: statusOf(meta, p),
3797
- ...meta.sshPort === void 0 ? {} : { sshPort: meta.sshPort },
3798
- ...meta.ports?.length ? { ports: meta.ports.map((f) => ({ ...f })) } : {},
3799
- ...meta.autoHibernateSec ? { autoHibernateSec: meta.autoHibernateSec } : {},
3800
- ...meta.idleCheck !== void 0 ? { idleCheck: meta.idleCheck } : {},
3801
- ...meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {},
3802
- ...meta.links?.some((l) => !l.stale) ? { links: meta.links.filter((l) => !l.stale).map((l) => ({ from: linkFrom(l, meta.owner), port: l.port })) } : {}
3803
- };
3804
- }
3805
- var linkFrom = (l, owner) => l.owner === owner ? l.name : `${l.owner.split("@")[0]}/${l.name}`;
3806
- async function listMachines(scope, p = paths()) {
3807
- return (await readAllMeta(p)).filter((m) => inScope(m.owner, scope)).map((m) => toMachine(m, p));
3808
- }
3809
- async function getMachine(ref, p = paths()) {
3810
- return toMachine(await readMeta(ref, p), p);
3811
- }
3812
-
3813
- // src/core/machines/boot.ts
3814
- async function launch(spec, nic, cfg, pubkeyB64, p) {
3815
- const root = imageFileFor(spec, p);
3816
- const kernel = kernelFor(await imageManifest(root), cfg, p);
3817
- const volumes = (await placeVolumeDrives(spec, p)).map((v) => ({ id: volumeDriveId(v.name), path: volumeDriveRel(v.name) }));
3818
- return driver().vm.boot(spec, { kernel, root, volumes, pubkeyB64 }, nic, cfg, p);
3819
- }
3820
- async function loadSnapshot(spec, image, nic, cfg, p) {
3821
- return driver().vm.restore(spec, { vmstate: image.vmstate, mem: image.mem }, nic, cfg, p);
3822
- }
3823
- async function resumeVm(box, p) {
3824
- await driver().vm.resume(box, p);
3825
- }
3826
-
3827
- // src/core/machines/guest.ts
3890
+ // src/core/machines/integrations.ts
3828
3891
  import { setTimeout as sleep3 } from "node:timers/promises";
3829
3892
 
3830
3893
  // src/core/agent.ts
@@ -3897,6 +3960,9 @@ async function idle(udsPath, script, timeoutMs = 15e3) {
3897
3960
  async function runScript(udsPath, path, input, timeoutMs = 35e3) {
3898
3961
  return (await agentCall(udsPath, { op: "script", path, input: input ?? null }, timeoutMs))["output"];
3899
3962
  }
3963
+ function setIntegrations(udsPath, list, identity, timeoutMs) {
3964
+ return agentCall(udsPath, { op: "integrations", list: [...list], ...identity ? { identity } : {} }, timeoutMs);
3965
+ }
3900
3966
  async function startRun(udsPath, id, command, timeoutSec, timeoutMs = 15e3) {
3901
3967
  return (await agentCall(udsPath, { op: "run", id, command, timeoutSec }, timeoutMs))["started"] === true;
3902
3968
  }
@@ -3917,27 +3983,386 @@ async function runOutput(udsPath, id, stream, offset, limit, timeoutMs = 15e3) {
3917
3983
  if (typeof size2 !== "number" || !Number.isInteger(size2) || size2 < 0 || typeof data !== "string") throw new KvboxError("kvbox-agent sent run output this server does not understand");
3918
3984
  return { size: size2, offset, data };
3919
3985
  }
3920
- var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
3921
- var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
3922
- var isNoAgent = (err) => /vsock connect refused|vsock connection closed before the guest accepted|did not accept the vsock connection|kvbox-agent unreachable: connect (ENOENT|ECONNREFUSED)/.test(err.message ?? "");
3986
+ var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
3987
+ var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
3988
+ var isNoAgent = (err) => /vsock connect refused|vsock connection closed before the guest accepted|did not accept the vsock connection|kvbox-agent unreachable: connect (ENOENT|ECONNREFUSED)/.test(err.message ?? "");
3989
+
3990
+ // src/core/credentials.ts
3991
+ import { request as request3 } from "undici";
3992
+ var TIMEOUT_MS = 1e4;
3993
+ var PROBE_KEPT_MS = 6e4;
3994
+ var unavailable = (message) => ({ ok: false, code: "unavailable", message });
3995
+ async function ask(cp, body) {
3996
+ const res = await request3(`${cp.url}/hosts/self/integrations/credential`, {
3997
+ method: "POST",
3998
+ headers: { authorization: `Bearer ${cp.secret}`, "content-type": "application/json" },
3999
+ body: JSON.stringify(body),
4000
+ headersTimeout: TIMEOUT_MS,
4001
+ bodyTimeout: TIMEOUT_MS
4002
+ });
4003
+ const text = await res.body.text();
4004
+ try {
4005
+ return { status: res.statusCode, json: JSON.parse(text) };
4006
+ } catch {
4007
+ return { status: res.statusCode, json: null };
4008
+ }
4009
+ }
4010
+ async function askCredential(cp, box, integration) {
4011
+ let answer;
4012
+ try {
4013
+ answer = await ask(cp, { owner: box.owner, box: box.name, integration });
4014
+ } catch (err) {
4015
+ return unavailable(`${cp.name} could not be reached (${err.message}); try again shortly`);
4016
+ }
4017
+ if (answer.status === 404) return unavailable(`${cp.name} has no integrations yet`);
4018
+ const parsed = CredentialAnswerSchema.safeParse(answer.json);
4019
+ if (!parsed.success) return unavailable(`${cp.name} answered ${answer.status}; try again shortly`);
4020
+ return parsed.data;
4021
+ }
4022
+ var probes = /* @__PURE__ */ new Map();
4023
+ async function probeConnection(cp, box, integration, now = Date.now()) {
4024
+ const key = `${box.owner}/${box.name}/${integration}`;
4025
+ const kept = probes.get(key);
4026
+ if (kept && now - kept.at < PROBE_KEPT_MS) return kept.answer;
4027
+ try {
4028
+ const parsed = ConnectedAnswerSchema.safeParse((await ask(cp, { owner: box.owner, box: box.name, integration, probe: true })).json);
4029
+ if (!parsed.success) return null;
4030
+ probes.set(key, { at: now, answer: parsed.data });
4031
+ if (probes.size > 5e3) {
4032
+ for (const [k, v] of probes) if (now - v.at >= PROBE_KEPT_MS) probes.delete(k);
4033
+ }
4034
+ return parsed.data;
4035
+ } catch {
4036
+ return null;
4037
+ }
4038
+ }
4039
+
4040
+ // src/core/guestRequests.ts
4041
+ import { rm as rm5 } from "node:fs/promises";
4042
+ import { createServer } from "node:net";
4043
+ var MAX_REQUEST_BYTES = 4096;
4044
+ var REQUEST_TIMEOUT_MS = 5e3;
4045
+ var MAX_OPEN = 32;
4046
+ var listeners = /* @__PURE__ */ new Map();
4047
+ var unreadable = (message) => ({ ok: false, code: "unavailable", message });
4048
+ function serve(sock, answer, timeoutMs) {
4049
+ let buf = "";
4050
+ let taken = false;
4051
+ const reply = (body) => {
4052
+ if (!sock.destroyed) sock.end(JSON.stringify(body) + "\n");
4053
+ };
4054
+ const late = setTimeout(() => sock.destroy(), timeoutMs);
4055
+ late.unref();
4056
+ sock.once("close", () => clearTimeout(late));
4057
+ sock.on("error", () => void 0);
4058
+ sock.on("data", (chunk) => {
4059
+ if (taken) return;
4060
+ buf += chunk.toString("utf8");
4061
+ const nl = buf.indexOf("\n");
4062
+ if (nl === -1) {
4063
+ if (buf.length > MAX_REQUEST_BYTES) sock.destroy();
4064
+ return;
4065
+ }
4066
+ taken = true;
4067
+ clearTimeout(late);
4068
+ let request7;
4069
+ try {
4070
+ request7 = JSON.parse(buf.slice(0, nl));
4071
+ } catch {
4072
+ return reply(unreadable("the request is not JSON"));
4073
+ }
4074
+ answer(request7).then(reply, (err) => reply(unreadable(err.message)));
4075
+ });
4076
+ }
4077
+ async function listenGuest(path, answer, timeoutMs = REQUEST_TIMEOUT_MS) {
4078
+ await closeGuest(path);
4079
+ await rm5(path, { force: true });
4080
+ const open3 = /* @__PURE__ */ new Set();
4081
+ const server = createServer((sock) => {
4082
+ open3.add(sock);
4083
+ sock.once("close", () => open3.delete(sock));
4084
+ serve(sock, answer, timeoutMs);
4085
+ });
4086
+ server.maxConnections = MAX_OPEN;
4087
+ await new Promise((resolve3, reject) => {
4088
+ server.once("error", reject);
4089
+ server.listen(path, () => {
4090
+ server.off("error", reject);
4091
+ resolve3();
4092
+ });
4093
+ });
4094
+ server.unref();
4095
+ server.on("error", () => void 0);
4096
+ listeners.set(path, { server, open: open3 });
4097
+ }
4098
+ async function closeGuest(path) {
4099
+ const l = listeners.get(path);
4100
+ if (!l) return;
4101
+ listeners.delete(path);
4102
+ for (const sock of l.open) sock.destroy();
4103
+ await new Promise((resolve3) => l.server.close(() => resolve3()));
4104
+ await rm5(path, { force: true });
4105
+ }
4106
+ var guestListening = (path) => listeners.has(path);
4107
+
4108
+ // src/core/machines/integrations.ts
4109
+ var AGENT_REPLY_MS = 2e4;
4110
+ function socketOf(box, p) {
4111
+ try {
4112
+ return driver().vm.guestSocket(box, GUEST_REQUEST_PORT, p);
4113
+ } catch (err) {
4114
+ if (err instanceof NotImplementedError) return void 0;
4115
+ throw err;
4116
+ }
4117
+ }
4118
+ async function listenForGuest(box, p) {
4119
+ const ref = { owner: box.owner, name: box.name };
4120
+ try {
4121
+ const path = socketOf(box, p);
4122
+ if (path !== void 0) await listenGuest(path, (request7) => answerGuest(ref, request7, p));
4123
+ } catch (err) {
4124
+ log.warn(`box ${shown(ref)}: integrations will not answer in it: ${err.message}`);
4125
+ }
4126
+ }
4127
+ async function stopListeningForGuest(box, p) {
4128
+ try {
4129
+ const path = socketOf(box, p);
4130
+ if (path !== void 0) await closeGuest(path);
4131
+ } catch {
4132
+ }
4133
+ }
4134
+ async function listenForRunning(p) {
4135
+ for (const listed of await readAllMeta(p)) {
4136
+ if (!vmAlive(listed)) continue;
4137
+ await withBoxLock(listed, async () => {
4138
+ const meta = await readMachineMeta(listed, p).catch(() => null);
4139
+ if (meta !== null && vmAlive(meta)) await listenForGuest(meta, p);
4140
+ });
4141
+ }
4142
+ }
4143
+ async function closeDeadListeners(p) {
4144
+ for (const meta of await readAllMeta(p)) {
4145
+ if (vmAlive(meta)) continue;
4146
+ const path = socketOf(meta, p);
4147
+ if (path === void 0 || !guestListening(path)) continue;
4148
+ await withBoxLock(meta, async () => {
4149
+ const now = await readMachineMeta(meta, p).catch(() => null);
4150
+ if (now === null || !vmAlive(now)) await stopListeningForGuest(meta, p);
4151
+ });
4152
+ }
4153
+ }
4154
+ function forgetGuest(box) {
4155
+ asked.delete(refKey(box));
4156
+ told.delete(box.id);
4157
+ }
4158
+ var refusal = (code, message, connected) => ({ ok: false, code, message, ...connected === void 0 ? {} : { connected } });
4159
+ var asked = /* @__PURE__ */ new Map();
4160
+ function withinLimit(box, now) {
4161
+ const w = asked.get(box);
4162
+ if (!w || now - w.since >= 6e4) {
4163
+ asked.set(box, { since: now, count: 1 });
4164
+ return true;
4165
+ }
4166
+ w.count += 1;
4167
+ return w.count <= GUEST_REQUESTS_PER_MINUTE;
4168
+ }
4169
+ async function answerGuest(ref, request7, p, now = Date.now()) {
4170
+ if (!withinLimit(refKey(ref), now)) return refusal("unavailable", `this box asked more than ${GUEST_REQUESTS_PER_MINUTE} times in a minute; try again shortly`);
4171
+ const parsed = GuestRequestSchema.safeParse(request7);
4172
+ if (!parsed.success) return refusal("unavailable", "this host does not know that request; it may need updating");
4173
+ const integration = parsed.data.integration;
4174
+ let meta;
4175
+ try {
4176
+ meta = await readMachineMeta(ref, p);
4177
+ } catch {
4178
+ return refusal("unavailable", "this box is being removed");
4179
+ }
4180
+ const cp = (await loadConfig(p)).controlPlane;
4181
+ if (!cp || !isCloudBox(meta.owner)) return refusal("unavailable", "integrations are not available in a box made on the host itself");
4182
+ if (!(meta.integrations ?? []).includes(integration)) {
4183
+ const probe = await probeConnection(cp, meta, integration, now);
4184
+ return refusal("off", `${integration} is not turned on for this box`, probe?.connected);
4185
+ }
4186
+ const answer = await askCredential(cp, meta, integration);
4187
+ if (answer.ok && answer.identity && !(told.has(meta.id) && sameIdentity(told.get(meta.id), answer.identity))) {
4188
+ void tellCurrent(ref, p.machine(meta.owner, meta.name).vsock, p, answer.identity).catch(() => void 0);
4189
+ }
4190
+ return answer;
4191
+ }
4192
+ var told = /* @__PURE__ */ new Map();
4193
+ var sameIdentity = (a, b) => a?.name === b?.name && a?.email === b?.email;
4194
+ async function tellGuest(box, vsock, identity) {
4195
+ await setIntegrations(vsock, box.integrations ?? [], identity, AGENT_REPLY_MS);
4196
+ told.set(box.id, identity);
4197
+ }
4198
+ async function identityOf(box, p) {
4199
+ if (!(box.integrations ?? []).includes("github")) return void 0;
4200
+ const cp = (await loadConfig(p)).controlPlane;
4201
+ if (!cp) return void 0;
4202
+ const probe = await probeConnection(cp, box, "github");
4203
+ if (probe !== null) return probe.identity;
4204
+ return told.has(box.id) ? told.get(box.id) : null;
4205
+ }
4206
+ var sameList = (a, b) => JSON.stringify(a ?? []) === JSON.stringify(b ?? []);
4207
+ async function tellCurrent(ref, vsock, p, identity) {
4208
+ for (; ; ) {
4209
+ const asked2 = await readMachineMeta(ref, p);
4210
+ const who = identity !== void 0 && (asked2.integrations ?? []).includes("github") ? identity : await identityOf(asked2, p);
4211
+ if (who === null) return false;
4212
+ const done = await withBoxLock(ref, async () => {
4213
+ const box = await readMachineMeta(ref, p);
4214
+ if (!sameList(box.integrations, asked2.integrations)) return false;
4215
+ await tellGuest(box, vsock, who);
4216
+ return true;
4217
+ });
4218
+ if (done) return true;
4219
+ }
4220
+ }
4221
+ var outdated = (box) => `its image is from before base v${INTEGRATIONS_BASE}, which has no integrations (kvbox vm update ${shown(box)} moves it onto the current one)`;
4222
+ async function applyIntegrations(box, vsock, p) {
4223
+ if (!isCloudBox(box.owner)) return;
4224
+ try {
4225
+ const who = await identityOf(box, p);
4226
+ await tellGuest(box, vsock, who ?? void 0);
4227
+ if (who === null) {
4228
+ told.delete(box.id);
4229
+ if (box.pid !== null) void tellIntegrationsWhenUp(box, box.pid, vsock, p);
4230
+ }
4231
+ } catch (err) {
4232
+ if (!isUnknownOp(err)) return void log.warn(`box ${shown(box)} was not told its integrations: ${err.message}`);
4233
+ if ((box.integrations ?? []).length > 0) throw new KvboxError(`box ${shown(box)} cannot use integrations yet: ${outdated(box)}`);
4234
+ }
4235
+ }
4236
+ var BOOT_WAIT_MS = 12e4;
4237
+ var WHO_RETRY_MS = 3e3;
4238
+ function tellIntegrationsWhenUp(ref, pid, vsock, p, timing = { waitMs: BOOT_WAIT_MS }) {
4239
+ return outsideLocks(async () => {
4240
+ if (!isCloudBox(ref.owner)) return;
4241
+ const deadline = Date.now() + timing.waitMs;
4242
+ for (; ; ) {
4243
+ if (!pidAlive(pid)) return;
4244
+ try {
4245
+ if (await tellCurrent(ref, vsock, p)) return;
4246
+ if (Date.now() >= deadline) return void log.warn(`box ${shown(ref)} was not told who commits in it: the control plane could not be asked`);
4247
+ await sleep3(timing.retryMs ?? WHO_RETRY_MS);
4248
+ } catch (err) {
4249
+ if (!pidAlive(pid)) return;
4250
+ if (isNoAgent(err) && Date.now() < deadline) {
4251
+ await sleep3(500);
4252
+ continue;
4253
+ }
4254
+ const box = await readMachineMeta(ref, p).catch(() => null);
4255
+ if (box === null) return;
4256
+ if (!isUnknownOp(err)) log.warn(`box ${shown(ref)} was not told its integrations: ${err.message}`);
4257
+ else if ((box.integrations ?? []).length > 0) log.warn(`box ${shown(ref)} has integrations it cannot use: ${outdated(ref)}`);
4258
+ return;
4259
+ }
4260
+ }
4261
+ }).catch(() => void 0);
4262
+ }
4263
+
4264
+ // src/core/machines/status.ts
4265
+ import { existsSync as existsSync9 } from "node:fs";
4266
+ function isHibernated(meta, p) {
4267
+ return !vmAlive(meta) && existsSync9(p.machine(meta.owner, meta.name).hibernateVmstate);
4268
+ }
4269
+ function statusOf(meta, p = paths()) {
4270
+ if (vmAlive(meta)) return meta.paused ? "standby" : "running";
4271
+ return isHibernated(meta, p) ? "hibernated" : "stopped";
4272
+ }
4273
+ function stateMessage(ref, status) {
4274
+ return `box ${shown(ref)} is ${status === "standby" ? "in standby" : status}`;
4275
+ }
4276
+ function assertNotHibernated(meta, p) {
4277
+ if (isHibernated(meta, p)) {
4278
+ throw new KvboxError(`${stateMessage(meta, "hibernated")}; its memory image was made with its current shape and base: kvbox wake ${shown(meta)} first`);
4279
+ }
4280
+ }
4281
+
4282
+ // src/core/machines/list.ts
4283
+ function toMachine(meta, p = paths()) {
4284
+ const alive2 = vmAlive(meta);
4285
+ if (!alive2 && meta.pid !== null) {
4286
+ try {
4287
+ closeOpenRun(meta.id, (/* @__PURE__ */ new Date()).toISOString(), p);
4288
+ } catch (err) {
4289
+ log.warn(`usage ledger: ${err.message}`);
4290
+ }
4291
+ }
4292
+ return {
4293
+ id: meta.id,
4294
+ name: meta.name,
4295
+ owner: meta.owner,
4296
+ ip: meta.ip,
4297
+ mac: meta.mac,
4298
+ pid: alive2 ? meta.pid : null,
4299
+ vcpu: meta.vcpu,
4300
+ memMib: meta.memMib,
4301
+ ...diskStats(p.machine(meta.owner, meta.name).overlay),
4302
+ base: meta.base,
4303
+ ...meta.image !== void 0 ? { image: meta.image } : {},
4304
+ ...meta.url !== void 0 ? { url: urlFor(meta.url, meta.name) } : {},
4305
+ createdAt: meta.createdAt,
4306
+ source: meta.source,
4307
+ status: statusOf(meta, p),
4308
+ ...meta.sshPort === void 0 ? {} : { sshPort: meta.sshPort },
4309
+ ...meta.ports?.length ? { ports: meta.ports.map((f) => ({ ...f })) } : {},
4310
+ ...meta.autoHibernateSec ? { autoHibernateSec: meta.autoHibernateSec } : {},
4311
+ ...meta.idleCheck !== void 0 ? { idleCheck: meta.idleCheck } : {},
4312
+ ...meta.integrations?.length ? { integrations: [...meta.integrations] } : {},
4313
+ ...meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {},
4314
+ ...meta.links?.some((l) => !l.stale) ? { links: meta.links.filter((l) => !l.stale).map((l) => ({ from: linkFrom(l, meta.owner), port: l.port })) } : {}
4315
+ };
4316
+ }
4317
+ var linkFrom = (l, owner) => l.owner === owner ? l.name : `${l.owner.split("@")[0]}/${l.name}`;
4318
+ async function listMachines(scope, p = paths()) {
4319
+ return (await readAllMeta(p)).filter((m) => inScope(m.owner, scope)).map((m) => toMachine(m, p));
4320
+ }
4321
+ async function getMachine(ref, p = paths()) {
4322
+ return toMachine(await readMeta(ref, p), p);
4323
+ }
4324
+
4325
+ // src/core/machines/boot.ts
4326
+ async function launch(spec, nic, cfg, pubkeyB64, p) {
4327
+ const root = imageFileFor(spec, p);
4328
+ const kernel = kernelFor(await imageManifest(root), cfg, p);
4329
+ const volumes = (await placeVolumeDrives(spec, p)).map((v) => ({ id: volumeDriveId(v.name), path: volumeDriveRel(v.name) }));
4330
+ return withGuestListener(spec, p, () => driver().vm.boot(spec, { kernel, root, volumes, pubkeyB64 }, nic, cfg, p));
4331
+ }
4332
+ async function loadSnapshot(spec, image, nic, cfg, p) {
4333
+ return withGuestListener(spec, p, () => driver().vm.restore(spec, { vmstate: image.vmstate, mem: image.mem }, nic, cfg, p));
4334
+ }
4335
+ async function withGuestListener(box, p, bringUp) {
4336
+ await listenForGuest(box, p);
4337
+ try {
4338
+ return await bringUp();
4339
+ } catch (err) {
4340
+ await stopListeningForGuest(box, p);
4341
+ throw err;
4342
+ }
4343
+ }
4344
+ async function resumeVm(box, p) {
4345
+ await driver().vm.resume(box, p);
4346
+ }
3923
4347
 
3924
4348
  // src/core/machines/guest.ts
4349
+ import { setTimeout as sleep4 } from "node:timers/promises";
3925
4350
  function prefixLenOf(subnet) {
3926
4351
  return Number(subnet.split("/")[1]);
3927
4352
  }
3928
- var AGENT_REPLY_MS = 2e4;
4353
+ var AGENT_REPLY_MS2 = 2e4;
3929
4354
  async function introduce(spec, vsock, cfg, failure2) {
3930
4355
  const id = { name: spec.name, ip: spec.ip, prefixLen: prefixLenOf(cfg.subnet), gateway: cfg.gateway, mac: spec.mac, time: Math.floor(Date.now() / 1e3) };
3931
4356
  const deadline = Date.now() + 3e3;
3932
4357
  for (; ; ) {
3933
4358
  try {
3934
- await setIdentity(vsock, id, AGENT_REPLY_MS);
4359
+ await setIdentity(vsock, id, AGENT_REPLY_MS2);
3935
4360
  return;
3936
4361
  } catch (err) {
3937
4362
  const msg = err.message;
3938
4363
  const transient = /unreachable|refused|before the guest accepted/.test(msg);
3939
4364
  if (transient && Date.now() < deadline) {
3940
- await sleep3(100);
4365
+ await sleep4(100);
3941
4366
  continue;
3942
4367
  }
3943
4368
  if (transient) throw new KvboxError(`${msg}
@@ -3949,7 +4374,7 @@ async function introduce(spec, vsock, cfg, failure2) {
3949
4374
  }
3950
4375
  async function dropGuestVolumes(box, vsock) {
3951
4376
  try {
3952
- await dropVolumes(vsock, AGENT_REPLY_MS);
4377
+ await dropVolumes(vsock, AGENT_REPLY_MS2);
3953
4378
  } catch (err) {
3954
4379
  const why = isUnknownOp(err) ? `its image predates base v0.9.0, whose kvbox-agent can unmount them (kvbox vm update ${shown(box)} moves it onto the current base)` : err.message;
3955
4380
  log.warn(`box ${shown(box)} keeps the volume mounts it was frozen with, over empty disks now: ${why}`);
@@ -3959,7 +4384,7 @@ async function pushEnv(box, vsock, p) {
3959
4384
  const vars = await envForBoot(box, p);
3960
4385
  if (vars === null) return;
3961
4386
  try {
3962
- await setEnv(vsock, vars, AGENT_REPLY_MS);
4387
+ await setEnv(vsock, vars, AGENT_REPLY_MS2);
3963
4388
  } catch (err) {
3964
4389
  warnEnv(box, vars, err);
3965
4390
  }
@@ -3973,7 +4398,7 @@ function warnEnv(box, vars, err) {
3973
4398
  log.warn(`box ${shown(box)} did not get its environment variables: ${err.message}`);
3974
4399
  }
3975
4400
  var ENV_BOOT_WAIT_MS = 12e4;
3976
- function pushEnvAfterBoot(box, pid, vsock, p, timing = { replyMs: AGENT_REPLY_MS, waitMs: ENV_BOOT_WAIT_MS }) {
4401
+ function pushEnvAfterBoot(box, pid, vsock, p, timing = { replyMs: AGENT_REPLY_MS2, waitMs: ENV_BOOT_WAIT_MS }) {
3977
4402
  return (async () => {
3978
4403
  const deadline = Date.now() + timing.waitMs;
3979
4404
  for (; ; ) {
@@ -3986,7 +4411,7 @@ function pushEnvAfterBoot(box, pid, vsock, p, timing = { replyMs: AGENT_REPLY_MS
3986
4411
  } catch (err) {
3987
4412
  if (!pidAlive(pid)) return;
3988
4413
  if (isNoAgent(err) && Date.now() < deadline) {
3989
- await sleep3(500);
4414
+ await sleep4(500);
3990
4415
  continue;
3991
4416
  }
3992
4417
  warnEnv(box, vars, err);
@@ -4037,7 +4462,7 @@ function authorizedKeysB64(hostKey, extra) {
4037
4462
  }
4038
4463
  async function pushAuthorizedKeys(box, vsock, p) {
4039
4464
  try {
4040
- await setAuthorizedKeys(vsock, authorizedKeysLines(await readHostPubkey(p), box.sshKeys ?? []), AGENT_REPLY_MS);
4465
+ await setAuthorizedKeys(vsock, authorizedKeysLines(await readHostPubkey(p), box.sshKeys ?? []), AGENT_REPLY_MS2);
4041
4466
  return void 0;
4042
4467
  } catch (err) {
4043
4468
  const why = isUnknownOp(err) ? `its image predates base v0.6.0, whose kvbox-agent can replace authorized_keys (kvbox vm update ${shown(box)} moves it onto the current base)` : err.message;
@@ -4240,17 +4665,131 @@ var startMachine = locked(async function startMachine2(ref, p = paths(), force =
4240
4665
  const started = { ...meta, pid, bootId: currentBootId(), sshKeysStale: void 0, paused: void 0 };
4241
4666
  await writeMachineMeta(started, p);
4242
4667
  recordState(started, "running", "start", p);
4668
+ void tellIntegrationsWhenUp(started, pid, p.machine(meta.owner, meta.name).vsock, p);
4243
4669
  return toMachine(started, p);
4244
4670
  } catch (err) {
4245
4671
  if (pid !== void 0) killQuietly(pid);
4672
+ await stopListeningForGuest(meta, p);
4246
4673
  await closePorts(meta, cfg);
4247
4674
  await driver().net.remove(meta.id, cfg).catch(() => void 0);
4248
4675
  throw err;
4249
4676
  }
4250
4677
  });
4251
4678
 
4679
+ // src/core/machines/newbox.ts
4680
+ import { mkdir as mkdir5, rm as rm6 } from "node:fs/promises";
4681
+ var NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
4682
+ var AUTO_PREFIX = "box";
4683
+ function pickName(requested, taken) {
4684
+ if (requested !== void 0) {
4685
+ if (!NAME_RE.test(requested)) {
4686
+ throw new KvboxError(`invalid box name "${requested}": 1-12 chars, lowercase letters, digits and '-', starting with a letter or digit`);
4687
+ }
4688
+ if (taken.has(requested)) throw new KvboxError(`box ${requested} already exists`);
4689
+ return requested;
4690
+ }
4691
+ for (let i = 1; ; i++) {
4692
+ const candidate = `${AUTO_PREFIX}${i}`;
4693
+ if (!taken.has(candidate)) return candidate;
4694
+ }
4695
+ }
4696
+ function autoHibernateFor(req, cfg, manifest = {}) {
4697
+ if (req.autoHibernateSec !== void 0) return req.autoHibernateSec || void 0;
4698
+ if (manifest.autoHibernate === false) return void 0;
4699
+ if (typeof manifest.autoHibernate === "string") return parseDuration(manifest.autoHibernate) || void 0;
4700
+ return cfg.autoHibernateSec || void 0;
4701
+ }
4702
+ var integrationsOf = (list) => list && list.length > 0 ? [...list] : void 0;
4703
+ function requestedIntegrations(list) {
4704
+ assertKnownIntegrations(list, "this host's kvbox-server", "it needs updating first");
4705
+ return integrationsOf(list);
4706
+ }
4707
+ var inheritedIntegrations = (list, sourceOwner, owner) => sourceOwner === owner ? integrationsOf(list) : void 0;
4708
+ async function bootInto(box, prepare, origin, cfg, p) {
4709
+ const { id, ip, owner, name } = box;
4710
+ const keysB64 = authorizedKeysB64(await readHostPubkey(p), box.sshKeys ?? []);
4711
+ const m = p.machine(owner, name);
4712
+ await driver().net.prepare(cfg);
4713
+ await mkdir5(m.dir, { recursive: true, mode: 448 });
4714
+ let tapCreated = false;
4715
+ let pid;
4716
+ let sshPort;
4717
+ let drawn;
4718
+ try {
4719
+ drawn = isCloudBox(owner) ? await drawPorts(1, p) : void 0;
4720
+ sshPort = drawn?.ports[0];
4721
+ await prepare(m);
4722
+ const tap = await driver().net.create(box, cfg);
4723
+ tapCreated = true;
4724
+ const spec = { ...box, sshPort };
4725
+ pid = await launch(spec, tap, cfg, keysB64, p);
4726
+ await openPorts(spec, cfg, p);
4727
+ void pushEnvAfterBoot(spec, pid, m.vsock, p);
4728
+ const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin };
4729
+ await writeMachineMeta(meta, p);
4730
+ recordState(meta, "running", "new", p, meta.createdAt);
4731
+ void tellIntegrationsWhenUp(meta, pid, m.vsock, p);
4732
+ return toMachine(meta, p);
4733
+ } catch (err) {
4734
+ if (pid !== void 0) killQuietly(pid);
4735
+ await stopListeningForGuest(box, p);
4736
+ await closePorts({ id, ip, sshPort }, cfg);
4737
+ if (tapCreated) await driver().net.remove(id, cfg).catch(() => void 0);
4738
+ await rm6(m.dir, { recursive: true, force: true });
4739
+ boxListChanged();
4740
+ throw err;
4741
+ } finally {
4742
+ drawn?.release();
4743
+ }
4744
+ }
4745
+ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
4746
+ const { id, ip, owner, name } = box;
4747
+ const m = p.machine(owner, name);
4748
+ await driver().net.prepare(cfg);
4749
+ await mkdir5(m.dir, { recursive: true, mode: 448 });
4750
+ let tapCreated = false;
4751
+ let pid;
4752
+ let sshPort;
4753
+ let drawn;
4754
+ try {
4755
+ drawn = isCloudBox(owner) ? await drawPorts(1, p) : void 0;
4756
+ sshPort = drawn?.ports[0];
4757
+ const image = await prepare(m);
4758
+ const tap = await driver().net.create(box, cfg, { detached: true });
4759
+ tapCreated = true;
4760
+ const spec = { ...box, sshPort };
4761
+ pid = await loadSnapshot(spec, image, tap, cfg, p);
4762
+ await resumeVm(box, p);
4763
+ await introduce(spec, m.vsock, cfg, {
4764
+ silent: `nothing answered on the restored box's control channel for 3 s; the restored box was discarded, try again`,
4765
+ noAnswer: "the restored box was discarded. kvbox-agent inside it took the request but gave no answer; try again, and if it keeps happening look at the box's journal (kvbox exec <box> -- sudo journalctl -u kvbox-agent) on a box started from the same snapshot."
4766
+ });
4767
+ const stale = await pushAuthorizedKeys(box, m.vsock, p);
4768
+ if (stale && keysOrFail) throw new KvboxError(`${keysOrFail}: ${stale}`);
4769
+ if (image.volumes?.length) await dropGuestVolumes(box, m.vsock);
4770
+ await pushEnv(box, m.vsock, p);
4771
+ await driver().net.attach(box, cfg);
4772
+ await openPorts(spec, cfg, p);
4773
+ const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin, memSnapshots: 1, sshKeysStale: stale ? true : void 0 };
4774
+ await writeMachineMeta(meta, p);
4775
+ recordState(meta, "running", "new", p, meta.createdAt);
4776
+ void tellIntegrationsWhenUp(meta, pid, m.vsock, p);
4777
+ return toMachine(meta, p);
4778
+ } catch (err) {
4779
+ if (pid !== void 0) killQuietly(pid);
4780
+ await stopListeningForGuest(box, p);
4781
+ await closePorts({ id, ip, sshPort }, cfg);
4782
+ if (tapCreated) await driver().net.remove(id, cfg).catch(() => void 0);
4783
+ await rm6(m.dir, { recursive: true, force: true });
4784
+ boxListChanged();
4785
+ throw err;
4786
+ } finally {
4787
+ drawn?.release();
4788
+ }
4789
+ }
4790
+
4252
4791
  // src/core/machines/stop.ts
4253
- import { rm as rm5 } from "node:fs/promises";
4792
+ import { rm as rm7 } from "node:fs/promises";
4254
4793
 
4255
4794
  // src/core/machines/links.ts
4256
4795
  function linkSource(req, caller, target) {
@@ -4348,9 +4887,13 @@ async function waitDead(pid, graceMs) {
4348
4887
  }
4349
4888
  }
4350
4889
  async function cleanupProcess(meta, cfg, p) {
4351
- await closePorts(meta, cfg);
4352
- await driver().net.remove(meta.id, cfg);
4353
- await driver().vm.cleanup(meta, p);
4890
+ try {
4891
+ await closePorts(meta, cfg);
4892
+ await driver().net.remove(meta.id, cfg);
4893
+ await driver().vm.cleanup(meta, p);
4894
+ } finally {
4895
+ await stopListeningForGuest(meta, p);
4896
+ }
4354
4897
  }
4355
4898
  var stopMachine = locked(async function stopMachine2(ref, p = paths()) {
4356
4899
  const meta = await readMeta(ref, p);
@@ -4359,8 +4902,8 @@ var stopMachine = locked(async function stopMachine2(ref, p = paths()) {
4359
4902
  if (!vmAlive(meta) && !isHibernated(meta, p)) throw new KvboxError(`box ${shown(ref)} is already stopped`);
4360
4903
  await shutdown2(meta, cfg, p, 1e4);
4361
4904
  await compactDisk(m.overlay).catch((err) => log.warn(`box ${shown(ref)}: disk not compacted: ${err.message}`));
4362
- await rm5(m.hibernateDir, { recursive: true, force: true });
4363
- await rm5(m.memBase, { force: true });
4905
+ await rm7(m.hibernateDir, { recursive: true, force: true });
4906
+ await rm7(m.memBase, { force: true });
4364
4907
  const stopped = { ...meta, pid: null, memSnapshots: void 0, paused: void 0 };
4365
4908
  await writeMachineMeta(stopped, p);
4366
4909
  recordState(stopped, "stopped", "stop", p);
@@ -4379,7 +4922,8 @@ var destroyBox = locked(async function destroyBox2(ref, p = paths()) {
4379
4922
  throw err;
4380
4923
  });
4381
4924
  recordState(meta, "stopped", "rm", p);
4382
- await rm5(p.machine(ref.owner, ref.name).dir, { recursive: true, force: true });
4925
+ await rm7(p.machine(ref.owner, ref.name).dir, { recursive: true, force: true });
4926
+ forgetGuest(meta);
4383
4927
  boxListChanged();
4384
4928
  return meta;
4385
4929
  });
@@ -4389,7 +4933,7 @@ async function applyAtNextBoot(meta, changes, by, cfg, p, whileStopped) {
4389
4933
  const wasRunning = vmAlive(meta);
4390
4934
  if (wasRunning) {
4391
4935
  await shutdown2(meta, cfg, p, 1e4);
4392
- await rm6(p.machine(meta.owner, meta.name).memBase, { force: true });
4936
+ await rm8(p.machine(meta.owner, meta.name).memBase, { force: true });
4393
4937
  }
4394
4938
  const updated = { ...meta, ...changes, pid: null, memSnapshots: void 0, paused: void 0 };
4395
4939
  await writeMachineMeta(updated, p);
@@ -4454,7 +4998,7 @@ var replaceDisk = locked(async function replaceDisk2(ref, file, disk, p = paths(
4454
4998
  const currentGib = Math.round(statSync3(m.overlay).size / 1024 ** 3);
4455
4999
  const restoredGib = Math.round(statSync3(file).size / 1024 ** 3);
4456
5000
  return applyAtNextBoot(meta, { base: disk.base, image: disk.image }, "restore", cfg, p, async () => {
4457
- if (disk.vars === null) await rm6(m.env, { force: true });
5001
+ if (disk.vars === null) await rm8(m.env, { force: true });
4458
5002
  else await writeBoxEnv(ref, disk.vars, p);
4459
5003
  await rename5(file, m.overlay);
4460
5004
  if (currentGib > restoredGib) await growDisk(m.overlay, currentGib);
@@ -4465,111 +5009,16 @@ var setMachine = locked(async function setMachine2(ref, req, p = paths()) {
4465
5009
  const next = { ...meta };
4466
5010
  if (req.autoHibernateSec !== void 0) next.autoHibernateSec = req.autoHibernateSec || void 0;
4467
5011
  if (req.idleCheck !== void 0) next.idleCheck = req.idleCheck || void 0;
5012
+ if (req.integrations !== void 0) {
5013
+ next.integrations = requestedIntegrations(req.integrations);
5014
+ if (statusOf(meta, p) === "running") await applyIntegrations(next, p.machine(meta.owner, meta.name).vsock, p);
5015
+ }
4468
5016
  await writeMachineMeta(next, p);
4469
5017
  return toMachine(next, p);
4470
5018
  });
4471
5019
 
4472
- // src/core/machines/newbox.ts
4473
- import { mkdir as mkdir5, rm as rm7 } from "node:fs/promises";
4474
- var NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
4475
- var AUTO_PREFIX = "box";
4476
- function pickName(requested, taken) {
4477
- if (requested !== void 0) {
4478
- if (!NAME_RE.test(requested)) {
4479
- throw new KvboxError(`invalid box name "${requested}": 1-12 chars, lowercase letters, digits and '-', starting with a letter or digit`);
4480
- }
4481
- if (taken.has(requested)) throw new KvboxError(`box ${requested} already exists`);
4482
- return requested;
4483
- }
4484
- for (let i = 1; ; i++) {
4485
- const candidate = `${AUTO_PREFIX}${i}`;
4486
- if (!taken.has(candidate)) return candidate;
4487
- }
4488
- }
4489
- function autoHibernateFor(req, cfg, manifest = {}) {
4490
- if (req.autoHibernateSec !== void 0) return req.autoHibernateSec || void 0;
4491
- if (manifest.autoHibernate === false) return void 0;
4492
- if (typeof manifest.autoHibernate === "string") return parseDuration(manifest.autoHibernate) || void 0;
4493
- return cfg.autoHibernateSec || void 0;
4494
- }
4495
- async function bootInto(box, prepare, origin, cfg, p) {
4496
- const { id, ip, owner, name } = box;
4497
- const keysB64 = authorizedKeysB64(await readHostPubkey(p), box.sshKeys ?? []);
4498
- const m = p.machine(owner, name);
4499
- await driver().net.prepare(cfg);
4500
- await mkdir5(m.dir, { recursive: true, mode: 448 });
4501
- let tapCreated = false;
4502
- let pid;
4503
- let sshPort;
4504
- let drawn;
4505
- try {
4506
- drawn = isCloudBox(owner) ? await drawPorts(1, p) : void 0;
4507
- sshPort = drawn?.ports[0];
4508
- await prepare(m);
4509
- const tap = await driver().net.create(box, cfg);
4510
- tapCreated = true;
4511
- const spec = { ...box, sshPort };
4512
- pid = await launch(spec, tap, cfg, keysB64, p);
4513
- await openPorts(spec, cfg, p);
4514
- void pushEnvAfterBoot(spec, pid, m.vsock, p);
4515
- const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin };
4516
- await writeMachineMeta(meta, p);
4517
- recordState(meta, "running", "new", p, meta.createdAt);
4518
- return toMachine(meta, p);
4519
- } catch (err) {
4520
- if (pid !== void 0) killQuietly(pid);
4521
- await closePorts({ id, ip, sshPort }, cfg);
4522
- if (tapCreated) await driver().net.remove(id, cfg).catch(() => void 0);
4523
- await rm7(m.dir, { recursive: true, force: true });
4524
- boxListChanged();
4525
- throw err;
4526
- } finally {
4527
- drawn?.release();
4528
- }
4529
- }
4530
- async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
4531
- const { id, ip, owner, name } = box;
4532
- const m = p.machine(owner, name);
4533
- await driver().net.prepare(cfg);
4534
- await mkdir5(m.dir, { recursive: true, mode: 448 });
4535
- let tapCreated = false;
4536
- let pid;
4537
- let sshPort;
4538
- let drawn;
4539
- try {
4540
- drawn = isCloudBox(owner) ? await drawPorts(1, p) : void 0;
4541
- sshPort = drawn?.ports[0];
4542
- const image = await prepare(m);
4543
- const tap = await driver().net.create(box, cfg, { detached: true });
4544
- tapCreated = true;
4545
- const spec = { ...box, sshPort };
4546
- pid = await loadSnapshot(spec, image, tap, cfg, p);
4547
- await resumeVm(box, p);
4548
- await introduce(spec, m.vsock, cfg, {
4549
- silent: `nothing answered on the restored box's control channel for 3 s; the restored box was discarded, try again`,
4550
- noAnswer: "the restored box was discarded. kvbox-agent inside it took the request but gave no answer; try again, and if it keeps happening look at the box's journal (kvbox exec <box> -- sudo journalctl -u kvbox-agent) on a box started from the same snapshot."
4551
- });
4552
- const stale = await pushAuthorizedKeys(box, m.vsock, p);
4553
- if (stale && keysOrFail) throw new KvboxError(`${keysOrFail}: ${stale}`);
4554
- if (image.volumes?.length) await dropGuestVolumes(box, m.vsock);
4555
- await pushEnv(box, m.vsock, p);
4556
- await driver().net.attach(box, cfg);
4557
- await openPorts(spec, cfg, p);
4558
- const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin, memSnapshots: 1, sshKeysStale: stale ? true : void 0 };
4559
- await writeMachineMeta(meta, p);
4560
- recordState(meta, "running", "new", p, meta.createdAt);
4561
- return toMachine(meta, p);
4562
- } catch (err) {
4563
- if (pid !== void 0) killQuietly(pid);
4564
- await closePorts({ id, ip, sshPort }, cfg);
4565
- if (tapCreated) await driver().net.remove(id, cfg).catch(() => void 0);
4566
- await rm7(m.dir, { recursive: true, force: true });
4567
- boxListChanged();
4568
- throw err;
4569
- } finally {
4570
- drawn?.release();
4571
- }
4572
- }
5020
+ // src/core/machines/create.ts
5021
+ import { rename as rename6, stat as stat3 } from "node:fs/promises";
4573
5022
 
4574
5023
  // src/core/machines/restore.ts
4575
5024
  import { existsSync as existsSync10 } from "node:fs";
@@ -4620,7 +5069,7 @@ async function restoreFrom(from, owner, req, cfg, p) {
4620
5069
  await placeholderDrives(m.dir, snap.volumes ?? []);
4621
5070
  return { vmstate: s.vmstate, mem: s.mem, label: shown(from), volumes: snap.volumes };
4622
5071
  },
4623
- { source: `snapshot:${refKey(from)}`, autoHibernateSec: autoHibernateFor(req, cfg, manifest), idleCheck: manifest.idle, url: maskedUrl(manifest, vars) },
5072
+ { source: `snapshot:${refKey(from)}`, autoHibernateSec: autoHibernateFor(req, cfg, manifest), idleCheck: manifest.idle, url: maskedUrl(manifest, vars), integrations: req.integrations !== void 0 ? requestedIntegrations(req.integrations) : inheritedIntegrations(snap.integrations, from.owner, owner) },
4624
5073
  cfg,
4625
5074
  p
4626
5075
  );
@@ -4630,12 +5079,27 @@ async function restoreFrom(from, owner, req, cfg, p) {
4630
5079
  async function currentBaseVersion(p = paths()) {
4631
5080
  return (await currentImage(void 0, await loadConfig(p), p)).version;
4632
5081
  }
4633
- async function createMachine(req, owner, p = paths()) {
4634
- const cfg = await loadConfig(p);
4635
- if (req.from !== void 0) return restoreMachine(req.from, owner, req, cfg, p);
4636
- const sizeName = req.size ?? cfg.defaultSize;
5082
+ function sizeOf(req, defaultSize, diskBytes) {
5083
+ const sizeName = req.size ?? defaultSize;
4637
5084
  if (!isSizeName(sizeName)) throw new KvboxError(`unknown size "${sizeName}"; use one of ${Object.keys(SIZES).join(", ")}`);
4638
5085
  const size2 = SIZES[sizeName];
5086
+ if (diskBytes !== void 0 && diskBytes > size2.diskGib * 1024 ** 3) {
5087
+ const fits = SIZE_NAMES.find((n) => diskBytes <= SIZES[n].diskGib * 1024 ** 3);
5088
+ throw new KvboxError(`this backup's disk is ${Math.ceil(diskBytes / 1024 ** 3)} GB, more than a ${sizeName} box's ${size2.diskGib} GB${fits ? `; use --size ${fits}` : ""}`);
5089
+ }
5090
+ return size2;
5091
+ }
5092
+ async function checkNewBox(req, owner, diskBytes, p = paths()) {
5093
+ const cfg = await loadConfig(p);
5094
+ const size2 = sizeOf(req, cfg.defaultSize, diskBytes);
5095
+ assertAssets(cfg);
5096
+ await assertRoomFor(size2.vcpu, size2.memMib, req.force ?? false, { owner }, "new", p);
5097
+ if (req.name !== void 0) pickName(req.name, new Set((await readAllMeta(p)).filter((m) => m.owner === owner).map((m) => m.name)));
5098
+ }
5099
+ async function createMachine(req, owner, p = paths(), from) {
5100
+ const cfg = await loadConfig(p);
5101
+ if (req.from !== void 0) return restoreMachine(req.from, owner, req, cfg, p);
5102
+ const size2 = sizeOf(req, cfg.defaultSize, from ? (await stat3(from.disk)).size : void 0);
4639
5103
  assertAssets(cfg);
4640
5104
  await assertRoomFor(size2.vcpu, size2.memMib, req.force ?? false, { owner }, "new", p);
4641
5105
  const sshKeys = isCloudBox(owner) && req.sshKeys !== void 0 && req.sshKeys.length > 0 ? req.sshKeys : void 0;
@@ -4644,35 +5108,38 @@ async function createMachine(req, owner, p = paths()) {
4644
5108
  const name = pickName(req.name, new Set(existing.filter((m) => m.owner === owner).map((m) => m.name)));
4645
5109
  const id = newBoxId(idsInUse(existing));
4646
5110
  const { ip, mac } = driver().net.allocate(cfg, existing.map((m) => m.ip));
4647
- const image = imageKey(req.image);
4648
- const base = await currentImage(image, cfg, p);
5111
+ const image = imageKey(from ? from.image : req.image);
5112
+ const base = from ? { version: from.base, file: imageFile(image, from.base, p) } : await currentImage(image, cfg, p);
4649
5113
  await assertOverlayCapable(base.file, image, base.version);
4650
5114
  const manifest = await imageManifest(base.file);
4651
- const env = imageEnv(manifest, name, req.env ?? [], (await readOwnerEnv(owner, p).catch(() => null))?.vars ?? []);
5115
+ const env = from ? null : imageEnv(manifest, name, req.env ?? [], (await readOwnerEnv(owner, p).catch(() => null))?.vars ?? []);
4652
5116
  const now = (/* @__PURE__ */ new Date()).toISOString();
4653
5117
  const autoHibernateSec = autoHibernateFor(req, cfg, manifest);
4654
- const vars = env.vars.map((v) => ({ ...v, secret: env.secrets.includes(v.name), updatedAt: now }));
5118
+ const vars = env === null ? from?.vars ?? [] : env.vars.map((v) => ({ ...v, secret: env.secrets.includes(v.name), updatedAt: now }));
4655
5119
  const machine = await bootInto(
4656
5120
  { id, name, owner, ip, mac, vcpu: size2.vcpu, memMib: size2.memMib, base: base.version, image, sshKeys },
4657
5121
  // The image is shared read-only by every box; only the box's own writes land in its overlay.
4658
5122
  async (m) => {
4659
- await createOverlay(m.overlay, size2.diskGib);
5123
+ if (from) {
5124
+ await rename6(from.disk, m.overlay);
5125
+ if ((await stat3(m.overlay)).size < size2.diskGib * 1024 ** 3) await growDisk(m.overlay, size2.diskGib);
5126
+ } else await createOverlay(m.overlay, size2.diskGib);
4660
5127
  if (vars.length > 0) await writeBoxEnv({ owner, name }, vars, p);
4661
5128
  },
4662
- { source: "base", autoHibernateSec, idleCheck: manifest.idle, url: maskedUrl(manifest, vars) },
5129
+ { source: from ? `backup:${from.id}` : "base", autoHibernateSec, idleCheck: manifest.idle, url: maskedUrl(manifest, vars), integrations: requestedIntegrations(req.integrations) },
4663
5130
  cfg,
4664
5131
  p
4665
5132
  );
4666
- return env.connect === void 0 ? machine : { ...machine, connect: env.connect };
5133
+ return env?.connect === void 0 ? machine : { ...machine, connect: env.connect };
4667
5134
  }
4668
5135
 
4669
5136
  // src/core/machines/fork.ts
4670
5137
  import { statSync as statSync4 } from "node:fs";
4671
- import { rm as rm9 } from "node:fs/promises";
5138
+ import { rm as rm10 } from "node:fs/promises";
4672
5139
 
4673
5140
  // src/core/snapshots.ts
4674
5141
  import { existsSync as existsSync11 } from "node:fs";
4675
- import { link as link2, mkdir as mkdir6, readdir as readdir5, rename as rename6, rm as rm8, stat as stat3 } from "node:fs/promises";
5142
+ import { link as link2, mkdir as mkdir6, readdir as readdir5, rename as rename7, rm as rm9, stat as stat4 } from "node:fs/promises";
4676
5143
  var NAME_RE2 = /^[a-z0-9][a-z0-9._-]{0,63}$/;
4677
5144
  function toSnapshot(meta) {
4678
5145
  return {
@@ -4702,7 +5169,7 @@ async function listSnapshots(scope, p = paths()) {
4702
5169
  async function usedBytes(dir) {
4703
5170
  let total = 0;
4704
5171
  for (const entry of await readdir5(dir)) {
4705
- total += (await stat3(`${dir}/${entry}`)).blocks * 512;
5172
+ total += (await stat4(`${dir}/${entry}`)).blocks * 512;
4706
5173
  }
4707
5174
  return total;
4708
5175
  }
@@ -4733,7 +5200,7 @@ async function snapshotBox(ref, req, owner, p) {
4733
5200
  if (existsSync11(final.dir) && !req.replace) throw new KvboxError(`snapshot ${req.name} already exists (--replace retakes it)`);
4734
5201
  const s = req.replace ? p.snapshot(owner, `.${req.name}.new-${box.id}`) : final;
4735
5202
  const cfg = await loadConfig(p);
4736
- if (s !== final) await rm8(s.dir, { recursive: true, force: true });
5203
+ if (s !== final) await rm9(s.dir, { recursive: true, force: true });
4737
5204
  await mkdir6(s.dir, { recursive: true, mode: 448 });
4738
5205
  try {
4739
5206
  const volumes = await captureDrivesOf(box, p);
@@ -4741,6 +5208,7 @@ async function snapshotBox(ref, req, owner, p) {
4741
5208
  await copyBoxEnv(p.machine(box.owner, box.name).env, s.env);
4742
5209
  const meta = {
4743
5210
  ...volumes.length > 0 ? { volumes } : {},
5211
+ ...box.integrations?.length ? { integrations: [...box.integrations] } : {},
4744
5212
  name: req.name,
4745
5213
  owner,
4746
5214
  source: refKey(box),
@@ -4755,7 +5223,7 @@ async function snapshotBox(ref, req, owner, p) {
4755
5223
  if (s !== final) await swapIn({ owner, name: req.name }, s.dir, box.id, p);
4756
5224
  return toSnapshot(meta);
4757
5225
  } catch (err) {
4758
- await rm8(s.dir, { recursive: true, force: true });
5226
+ await rm9(s.dir, { recursive: true, force: true });
4759
5227
  throw err;
4760
5228
  }
4761
5229
  }
@@ -4763,17 +5231,17 @@ async function swapIn(ref, from, boxId, p) {
4763
5231
  const to = p.snapshot(ref.owner, ref.name).dir;
4764
5232
  const old = p.snapshot(ref.owner, `.${ref.name}.old-${boxId}`).dir;
4765
5233
  await withSnapshotLock(ref, async () => {
4766
- await rm8(old, { recursive: true, force: true });
5234
+ await rm9(old, { recursive: true, force: true });
4767
5235
  const hadOld = existsSync11(to);
4768
- if (hadOld) await rename6(to, old);
5236
+ if (hadOld) await rename7(to, old);
4769
5237
  try {
4770
- await rename6(from, to);
5238
+ await rename7(from, to);
4771
5239
  } catch (err) {
4772
- if (hadOld) await rename6(old, to);
5240
+ if (hadOld) await rename7(old, to);
4773
5241
  throw err;
4774
5242
  }
4775
5243
  });
4776
- await rm8(old, { recursive: true, force: true });
5244
+ await rm9(old, { recursive: true, force: true });
4777
5245
  }
4778
5246
  async function captureBox(box, to, cfg, p) {
4779
5247
  const m = p.machine(box.owner, box.name);
@@ -4802,10 +5270,10 @@ async function captureBox(box, to, cfg, p) {
4802
5270
  } else if (since > 0) {
4803
5271
  await mergeOntoPrevious(m.memBase, to.mem, cfg.snapshotEditor ?? p.snapshotEditor);
4804
5272
  }
4805
- await rm8(m.memBase, { force: true });
5273
+ await rm9(m.memBase, { force: true });
4806
5274
  await link2(to.mem, m.memBase);
4807
5275
  } catch (err) {
4808
- if (lineageTouched) await rm8(m.memBase, { force: true }).catch(() => void 0);
5276
+ if (lineageTouched) await rm9(m.memBase, { force: true }).catch(() => void 0);
4809
5277
  throw err;
4810
5278
  }
4811
5279
  }
@@ -4814,12 +5282,12 @@ async function mergeOntoPrevious(previous, diffFile, editor) {
4814
5282
  const merged = `${diffFile}.merged`;
4815
5283
  await run(["cp", "--sparse=always", "--reflink=auto", previous, merged]);
4816
5284
  await run([editor, "edit-memory", "rebase", "--memory-path", merged, "--diff-path", diffFile]);
4817
- await rename6(merged, diffFile);
5285
+ await rename7(merged, diffFile);
4818
5286
  }
4819
5287
  async function deleteSnapshot(ref, p = paths()) {
4820
5288
  const dir = p.snapshot(ref.owner, ref.name).dir;
4821
5289
  if (ref.name.startsWith(".") || !existsSync11(dir)) throw new NotFoundError(`snapshot ${shown(ref)}`);
4822
- await withSnapshotLock(ref, () => rm8(dir, { recursive: true, force: true }));
5290
+ await withSnapshotLock(ref, () => rm9(dir, { recursive: true, force: true }));
4823
5291
  }
4824
5292
 
4825
5293
  // src/core/machines/fork.ts
@@ -4854,7 +5322,7 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
4854
5322
  const { ip, mac } = driver().net.allocate(cfg, existing.map((m) => m.ip));
4855
5323
  const box = { id, name, owner, ip, mac, ...shape, base: src.base, image: src.image, sshKeys };
4856
5324
  const srcEnv = p.machine(src.owner, src.name).env;
4857
- const origin = { source: `fork:${refKey(src)}`, autoHibernateSec: (req.autoHibernateSec ?? src.autoHibernateSec) || void 0, idleCheck: src.idleCheck, url: src.url };
5325
+ const origin = { source: `fork:${refKey(src)}`, autoHibernateSec: (req.autoHibernateSec ?? src.autoHibernateSec) || void 0, idleCheck: src.idleCheck, url: src.url, integrations: inheritedIntegrations(src.integrations, src.owner, owner) };
4858
5326
  if (!warm) {
4859
5327
  return bootInto(
4860
5328
  box,
@@ -4884,12 +5352,12 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
4884
5352
  // another slug. Such a fork is discarded rather than kept stale; a cold fork boots with the new line.
4885
5353
  owner === src.owner ? void 0 : `box ${shown(ref)} was not forked into ${owner}: the copy would still let ${src.owner} in (stop the box and fork it cold, which boots with ${owner}'s keys)`
4886
5354
  );
4887
- await rm9(p.machine(owner, name).forkVmstate, { force: true });
5355
+ await rm10(p.machine(owner, name).forkVmstate, { force: true });
4888
5356
  return machine;
4889
5357
  });
4890
5358
 
4891
5359
  // src/core/machines/recovery.ts
4892
- import { rm as rm10 } from "node:fs/promises";
5360
+ import { rm as rm11 } from "node:fs/promises";
4893
5361
  var RECOVERY_CONCURRENCY = 2;
4894
5362
  async function settleDeadBoxes(p = paths()) {
4895
5363
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -4903,7 +5371,7 @@ async function settleDeadBoxes(p = paths()) {
4903
5371
  } catch (err) {
4904
5372
  log.warn(`usage ledger: ${err.message}`);
4905
5373
  }
4906
- await rm10(p.machine(meta.owner, meta.name).memBase, { force: true });
5374
+ await rm11(p.machine(meta.owner, meta.name).memBase, { force: true });
4907
5375
  if (meta.paused) {
4908
5376
  await writeMachineMeta({ ...meta, pid: null, bootId: void 0, memSnapshots: void 0, paused: void 0 }, p);
4909
5377
  leftStopped.push(refKey(meta));
@@ -4960,7 +5428,7 @@ async function bootRecovered(settled, p = paths()) {
4960
5428
 
4961
5429
  // src/core/machines/standby.ts
4962
5430
  import { existsSync as existsSync12 } from "node:fs";
4963
- import { link as link3, mkdir as mkdir7, rm as rm11 } from "node:fs/promises";
5431
+ import { link as link3, mkdir as mkdir7, rm as rm12 } from "node:fs/promises";
4964
5432
  var pauseMachine = locked(async function pauseMachine2(ref, p = paths()) {
4965
5433
  const meta = await readMeta(ref, p);
4966
5434
  const status = statusOf(meta, p);
@@ -4985,6 +5453,7 @@ var resumeMachine = locked(async function resumeMachine2(ref, p = paths()) {
4985
5453
  const running = { ...meta, paused: void 0, sshKeysStale: stale ? true : void 0 };
4986
5454
  await writeMachineMeta(running, p);
4987
5455
  recordState(running, "running", "resume", p);
5456
+ if (meta.pid !== null) void tellIntegrationsWhenUp(running, meta.pid, m.vsock, p);
4988
5457
  return toMachine(running, p);
4989
5458
  });
4990
5459
  var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(), by = "hibernate") {
@@ -4994,14 +5463,14 @@ var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(),
4994
5463
  if (status === "hibernated") throw new KvboxError(`${stateMessage(ref, status)} already`);
4995
5464
  if (status === "stopped") throw new KvboxError(`${stateMessage(ref, status)}; only a running box can be hibernated (there is no memory to keep)`);
4996
5465
  const m = p.machine(ref.owner, ref.name);
4997
- await rm11(m.hibernateDir, { recursive: true, force: true });
5466
+ await rm12(m.hibernateDir, { recursive: true, force: true });
4998
5467
  await mkdir7(m.hibernateDir, { recursive: true, mode: 448 });
4999
5468
  const vm = driver().vm;
5000
5469
  try {
5001
5470
  await vm.pause(ref, p);
5002
5471
  await vm.saveState(ref, { vmstate: m.hibernateVmstate, mem: m.hibernateMem }, "full", p);
5003
5472
  } catch (err) {
5004
- await rm11(m.hibernateDir, { recursive: true, force: true });
5473
+ await rm12(m.hibernateDir, { recursive: true, force: true });
5005
5474
  if (!meta.paused) await vm.resume(ref, p).catch(() => void 0);
5006
5475
  throw err;
5007
5476
  }
@@ -5009,7 +5478,7 @@ var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(),
5009
5478
  await waitFor(() => !pidAlive(meta.pid), 5e3, 50);
5010
5479
  await cleanupProcess(meta, cfg, p);
5011
5480
  await run(["fallocate", "--dig-holes", m.hibernateMem]);
5012
- await rm11(m.memBase, { force: true });
5481
+ await rm12(m.memBase, { force: true });
5013
5482
  const hibernated = { ...meta, pid: null, memSnapshots: void 0, paused: void 0 };
5014
5483
  await writeMachineMeta(hibernated, p);
5015
5484
  recordState(hibernated, "hibernated", by, p);
@@ -5044,22 +5513,24 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths(), force = f
5044
5513
  await openPorts(meta, cfg, p);
5045
5514
  } catch (err) {
5046
5515
  if (pid !== void 0) killQuietly(pid);
5516
+ await stopListeningForGuest(meta, p);
5047
5517
  await closePorts(meta, cfg);
5048
5518
  await driver().net.remove(meta.id, cfg).catch(() => void 0);
5049
5519
  throw err;
5050
5520
  }
5051
- await rm11(m.memBase, { force: true });
5521
+ await rm12(m.memBase, { force: true });
5052
5522
  await link3(m.hibernateMem, m.memBase);
5053
- await rm11(m.hibernateDir, { recursive: true, force: true });
5523
+ await rm12(m.hibernateDir, { recursive: true, force: true });
5054
5524
  const running = { ...meta, pid, bootId: currentBootId(), memSnapshots: 1, paused: void 0, sshKeysStale: stale ? true : void 0 };
5055
5525
  await writeMachineMeta(running, p);
5056
5526
  recordState(running, "running", "wake", p);
5527
+ void tellIntegrationsWhenUp(running, pid, m.vsock, p);
5057
5528
  return toMachine(running, p);
5058
5529
  });
5059
5530
 
5060
5531
  // src/core/machines/volumes.ts
5061
5532
  import { statSync as statSync5 } from "node:fs";
5062
- import { rename as rename7, rm as rm12 } from "node:fs/promises";
5533
+ import { rename as rename8, rm as rm13 } from "node:fs/promises";
5063
5534
  var attachVolume = locked(async function attachVolume2(ref, volume, p = paths()) {
5064
5535
  const cfg = await loadConfig(p);
5065
5536
  const claimed = await withHostLock("volumes", async () => {
@@ -5082,7 +5553,7 @@ var detachVolume = locked(async function detachVolume2(ref, volume, p = paths())
5082
5553
  if (!meta.volumes?.includes(volume.name) || volume.owner !== meta.owner) throw new KvboxError(`volume ${shown(volume)} is not attached to box ${shown(ref)}`);
5083
5554
  assertNotHibernated(meta, p);
5084
5555
  const kept = meta.volumes.filter((v) => v !== volume.name);
5085
- return applyAtNextBoot(meta, { volumes: kept.length > 0 ? kept : void 0 }, "detach", cfg, p, () => rm12(p.machine(ref.owner, ref.name).volumeDrive(volume.name), { force: true }));
5556
+ return applyAtNextBoot(meta, { volumes: kept.length > 0 ? kept : void 0 }, "detach", cfg, p, () => rm13(p.machine(ref.owner, ref.name).volumeDrive(volume.name), { force: true }));
5086
5557
  });
5087
5558
  async function resizeVolume(volume, sizeGib, p = paths()) {
5088
5559
  await assertCanGrow(volume, sizeGib, p);
@@ -5114,7 +5585,7 @@ async function replaceVolumeDisk(volume, file, p = paths()) {
5114
5585
  await grow();
5115
5586
  const swap = async () => {
5116
5587
  await grow();
5117
- await rename7(file, p.volume(volume.owner, volume.name).disk);
5588
+ await rename8(file, p.volume(volume.owner, volume.name).disk);
5118
5589
  };
5119
5590
  const holder = await attachedBox(volume, p);
5120
5591
  if (holder === null) {
@@ -5138,9 +5609,9 @@ async function replaceVolumeDisk(volume, file, p = paths()) {
5138
5609
  // src/core/backups.ts
5139
5610
  import { randomBytes as randomBytes5 } from "node:crypto";
5140
5611
  import { existsSync as existsSync13 } from "node:fs";
5141
- import { mkdir as mkdir8, open, readdir as readdir6, readFile as readFile9, rm as rm13, stat as stat4, statfs as statfs3, writeFile as writeFile7 } from "node:fs/promises";
5612
+ import { mkdir as mkdir8, open, readdir as readdir6, readFile as readFile9, rm as rm14, stat as stat5, statfs as statfs3, writeFile as writeFile7 } from "node:fs/promises";
5142
5613
  import { basename as basename2, join as join3 } from "node:path";
5143
- import { setTimeout as sleep4 } from "node:timers/promises";
5614
+ import { setTimeout as sleep5 } from "node:timers/promises";
5144
5615
 
5145
5616
  // ../shared/src/backup.ts
5146
5617
  import { createCipheriv, createDecipheriv, createHmac, randomBytes as randomBytes4 } from "node:crypto";
@@ -5282,7 +5753,7 @@ async function readBox2(ref, p) {
5282
5753
  }
5283
5754
  }
5284
5755
  async function chunkNames(file, keys) {
5285
- const { size: size2 } = await stat4(file);
5756
+ const { size: size2 } = await stat5(file);
5286
5757
  const chunks = [];
5287
5758
  const fh = await open(file, "r");
5288
5759
  try {
@@ -5310,7 +5781,7 @@ async function stageBackup(ref, req, p = paths()) {
5310
5781
  checkId(req.id);
5311
5782
  const keys = backupKeys(req.key);
5312
5783
  const s = p.backup(req.id);
5313
- await rm13(s.dir, { recursive: true, force: true });
5784
+ await rm14(s.dir, { recursive: true, force: true });
5314
5785
  await mkdir8(s.dir, { recursive: true, mode: 448 });
5315
5786
  try {
5316
5787
  const { meta, envText } = await withBoxLock(ref, async () => {
@@ -5331,10 +5802,11 @@ async function stageBackup(ref, req, p = paths()) {
5331
5802
  base: meta.base,
5332
5803
  ...meta.image !== void 0 ? { image: meta.image } : {},
5333
5804
  vcpu: meta.vcpu,
5334
- memMib: meta.memMib
5805
+ memMib: meta.memMib,
5806
+ ...meta.integrations?.length ? { integrations: [...meta.integrations] } : {}
5335
5807
  };
5336
5808
  } catch (err) {
5337
- await rm13(s.dir, { recursive: true, force: true });
5809
+ await rm14(s.dir, { recursive: true, force: true });
5338
5810
  throw err;
5339
5811
  }
5340
5812
  }
@@ -5353,7 +5825,7 @@ async function stageVolumeBackup(ref, req, p = paths()) {
5353
5825
  await readVolume(ref, p);
5354
5826
  const from = p.volume(ref.owner, ref.name).disk;
5355
5827
  const s = p.backup(req.id);
5356
- await rm13(s.dir, { recursive: true, force: true });
5828
+ await rm14(s.dir, { recursive: true, force: true });
5357
5829
  await mkdir8(s.dir, { recursive: true, mode: 448 });
5358
5830
  try {
5359
5831
  await assertRoom(s.dir, 0, `a backup of volume ${shown(ref)}`, p);
@@ -5376,7 +5848,7 @@ async function stageVolumeBackup(ref, req, p = paths()) {
5376
5848
  await writeFile7(s.chunks, JSON.stringify({ chunks }), { mode: 384 });
5377
5849
  return { id: req.id, sizeBytes, chunks };
5378
5850
  } catch (err) {
5379
- await rm13(s.dir, { recursive: true, force: true });
5851
+ await rm14(s.dir, { recursive: true, force: true });
5380
5852
  throw err;
5381
5853
  }
5382
5854
  }
@@ -5422,7 +5894,7 @@ async function uploadOnce(id, req, signal, p) {
5422
5894
  if (index === void 0) throw new KvboxError(`backup ${id} has no chunk ${name.slice(0, 12)}`);
5423
5895
  return { name, url, index };
5424
5896
  });
5425
- const { size: size2 } = await stat4(s.disk);
5897
+ const { size: size2 } = await stat5(s.disk);
5426
5898
  const fetchChunk = await chunkFetcher(req.pin, work[0]?.url, p);
5427
5899
  const fh = await open(s.disk, "r");
5428
5900
  let bytes = 0;
@@ -5441,25 +5913,25 @@ async function uploadOnce(id, req, signal, p) {
5441
5913
  } finally {
5442
5914
  await fh.close();
5443
5915
  }
5444
- await rm13(s.dir, { recursive: true, force: true });
5916
+ await rm14(s.dir, { recursive: true, force: true });
5445
5917
  return { chunks: work.length, bytes, sizes };
5446
5918
  }
5447
5919
  async function dropBackup(id, p = paths()) {
5448
5920
  checkId(id);
5449
5921
  uploads.get(id)?.abort();
5450
- await rm13(p.backup(id).dir, { recursive: true, force: true });
5922
+ await rm14(p.backup(id).dir, { recursive: true, force: true });
5451
5923
  }
5452
5924
  async function clearStagedBackups(p = paths()) {
5453
- await rm13(p.backups, { recursive: true, force: true });
5925
+ await rm14(p.backups, { recursive: true, force: true });
5454
5926
  const prefix = basename2(p.machine("x", "x").restoring);
5455
5927
  for (const ref of await listMachineRefs(p)) {
5456
5928
  const dir = p.machine(ref.owner, ref.name).dir;
5457
- for (const f of await readdir6(dir).catch(() => [])) if (f === prefix || f.startsWith(`${prefix}.`)) await rm13(join3(dir, f), { force: true });
5929
+ for (const f of await readdir6(dir).catch(() => [])) if (f === prefix || f.startsWith(`${prefix}.`)) await rm14(join3(dir, f), { force: true });
5458
5930
  }
5459
5931
  const volumePrefix = basename2(p.volume("x", "x").restoring);
5460
5932
  for (const ref of await listVolumeRefs(p)) {
5461
5933
  const dir = p.volume(ref.owner, ref.name).dir;
5462
- for (const f of await readdir6(dir).catch(() => [])) if (f.startsWith(`${volumePrefix}.`)) await rm13(join3(dir, f), { force: true });
5934
+ for (const f of await readdir6(dir).catch(() => [])) if (f.startsWith(`${volumePrefix}.`)) await rm14(join3(dir, f), { force: true });
5463
5935
  }
5464
5936
  }
5465
5937
  async function downloadDisk(file, req, p = paths()) {
@@ -5515,7 +5987,7 @@ async function restoreOnce(ref, req, p) {
5515
5987
  }
5516
5988
  const keys = backupKeys(req.key);
5517
5989
  const m = p.machine(ref.owner, ref.name);
5518
- const current2 = (await stat4(m.overlay)).size;
5990
+ const current2 = (await stat5(m.overlay)).size;
5519
5991
  if (req.sizeBytes > current2) {
5520
5992
  const gb2 = (n) => `${Math.ceil(n / 1024 ** 3)}GB`;
5521
5993
  throw new KvboxError(`this backup's disk is ${gb2(req.sizeBytes)} and box ${shown(ref)}'s is ${gb2(current2)}: kvbox vm rescale ${shown(ref)} --disk ${gb2(req.sizeBytes)} first`);
@@ -5533,9 +6005,51 @@ async function restoreOnce(ref, req, p) {
5533
6005
  await downloadDisk(file, req, p);
5534
6006
  return await replaceDisk(ref, file, { base: req.base, image: req.image, vars }, p);
5535
6007
  } finally {
5536
- await rm13(file, { force: true });
5537
- await rm13(envFile, { force: true });
6008
+ await rm14(file, { force: true });
6009
+ await rm14(envFile, { force: true });
6010
+ }
6011
+ }
6012
+ async function createFromBackup(req, owner, p = paths()) {
6013
+ const { backup, ...create } = req;
6014
+ checkId(backup.id);
6015
+ const base = await baseFor(backup, p);
6016
+ await checkNewBox(create, owner, backup.sizeBytes, p);
6017
+ const keys = backupKeys(backup.key);
6018
+ const dir = join3(p.backups, `new-${randomBytes5(4).toString("hex")}`);
6019
+ await mkdir8(dir, { recursive: true, mode: 448 });
6020
+ try {
6021
+ let vars = null;
6022
+ if (backup.env !== null) {
6023
+ const envFile = join3(dir, "env.json");
6024
+ await writeFile7(envFile, openText(keys, backup.env, `env:${backup.id}`), { mode: 384 });
6025
+ vars = await readBoxEnvFile(envFile);
6026
+ checkBoxEnv(vars);
6027
+ }
6028
+ await assertRoom(dir, backup.chunks.length * CHUNK_SIZE, `a box from backup ${backup.id}`, p);
6029
+ const disk = join3(dir, "disk.ext4");
6030
+ await downloadDisk(disk, backup, p);
6031
+ const sent = create;
6032
+ return await createMachine(sent, owner, p, { disk, base, image: backup.image, vars, id: backup.id });
6033
+ } finally {
6034
+ await rm14(dir, { recursive: true, force: true });
6035
+ }
6036
+ }
6037
+ async function baseFor(backup, p) {
6038
+ if (existsSync13(imageFile(backup.image, backup.base, p))) return backup.base;
6039
+ const current2 = (await currentImage(imageKey(backup.image), await loadConfig(p), p)).version;
6040
+ if (compareVersions(current2, backup.base) < 0) {
6041
+ throw new KvboxError(`this backup stacks on ${imageLabel(backup.image)} ${backup.base}, newer than this host's ${current2}; the host needs updating first`);
6042
+ }
6043
+ return current2;
6044
+ }
6045
+ function compareVersions(a, b) {
6046
+ const parts = (v) => v.replace(/^v/, "").split(/[.-]/).map((x2) => Number.parseInt(x2, 10) || 0);
6047
+ const [x, y] = [parts(a), parts(b)];
6048
+ for (let i = 0; i < Math.max(x.length, y.length); i++) {
6049
+ const d = (x[i] ?? 0) - (y[i] ?? 0);
6050
+ if (d !== 0) return d;
5538
6051
  }
6052
+ return 0;
5539
6053
  }
5540
6054
  async function restoreVolumeBackup(ref, req, p = paths()) {
5541
6055
  checkId(req.id);
@@ -5570,7 +6084,7 @@ async function restoreVolumeBackup(ref, req, p = paths()) {
5570
6084
  if (n > 0) holding.set(held2, n);
5571
6085
  else holding.delete(held2);
5572
6086
  }
5573
- await rm13(file, { force: true });
6087
+ await rm14(file, { force: true });
5574
6088
  }
5575
6089
  }
5576
6090
  async function pool(items, fn) {
@@ -5598,34 +6112,34 @@ async function withTries(what, fn, signal) {
5598
6112
  } catch (err) {
5599
6113
  if (signal?.aborted) throw new KvboxError(`${what}: the backup was dropped`);
5600
6114
  last = err;
5601
- await sleep4(250 * 2 ** i);
6115
+ await sleep5(250 * 2 ** i);
5602
6116
  }
5603
6117
  }
5604
6118
  throw new KvboxError(`${what} failed ${TRIES} times: ${last.message}`);
5605
6119
  }
5606
6120
 
5607
6121
  // src/core/relay.ts
5608
- import { access as access2, chmod as chmod4, mkdir as mkdir10, rm as rm14, writeFile as writeFile8 } from "node:fs/promises";
6122
+ import { access as access2, chmod as chmod4, mkdir as mkdir10, rm as rm15, writeFile as writeFile8 } from "node:fs/promises";
5609
6123
 
5610
6124
  // ../shared/src/relay.ts
5611
- import { z as z7 } from "zod";
6125
+ import { z as z8 } from "zod";
5612
6126
  var RELAY_TUNNEL_GATEWAY = "10.77.0.1";
5613
6127
  var IPV4_RE = /^(\d{1,3})(\.\d{1,3}){3}$/;
5614
6128
  var WG_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
5615
- var RelayJoinSchema = z7.object({
5616
- v: z7.literal(1),
6129
+ var RelayJoinSchema = z8.object({
6130
+ v: z8.literal(1),
5617
6131
  /** How the relay lists this host. */
5618
- name: z7.string().regex(/^[a-z0-9][a-z0-9-]{0,30}$/),
6132
+ name: z8.string().regex(/^[a-z0-9][a-z0-9-]{0,30}$/),
5619
6133
  /** `<relay-primary-ip>:<port>`, the WireGuard endpoint the host dials. */
5620
- relay: z7.string().regex(/^(\d{1,3})(\.\d{1,3}){3}:\d{1,5}$/),
6134
+ relay: z8.string().regex(/^(\d{1,3})(\.\d{1,3}){3}:\d{1,5}$/),
5621
6135
  /** The relay's WireGuard public key. */
5622
- relayKey: z7.string().regex(WG_KEY_RE),
6136
+ relayKey: z8.string().regex(WG_KEY_RE),
5623
6137
  /** This host's address inside the tunnel. */
5624
- tunnelIp: z7.string().regex(IPV4_RE),
6138
+ tunnelIp: z8.string().regex(IPV4_RE),
5625
6139
  /** This host's WireGuard private key, generated on the relay, kept nowhere else. */
5626
- privateKey: z7.string().regex(WG_KEY_RE),
6140
+ privateKey: z8.string().regex(WG_KEY_RE),
5627
6141
  /** The extra public IPv4 the relay owns for this host; what the host advertises to the control plane. */
5628
- publicIp: z7.string().regex(IPV4_RE)
6142
+ publicIp: z8.string().regex(IPV4_RE)
5629
6143
  });
5630
6144
  function decodeRelayJoin(text) {
5631
6145
  let parsed;
@@ -5642,7 +6156,7 @@ function decodeRelayJoin(text) {
5642
6156
  import { X509Certificate } from "node:crypto";
5643
6157
  import { chmod as chmod3, mkdir as mkdir9, readFile as readFile10 } from "node:fs/promises";
5644
6158
  import { hostname as osHostname } from "node:os";
5645
- import { request as request3 } from "undici";
6159
+ import { request as request4 } from "undici";
5646
6160
 
5647
6161
  // ../shared/src/country.ts
5648
6162
  var names = new Intl.DisplayNames(["en"], { type: "region", fallback: "none" });
@@ -5747,7 +6261,7 @@ async function joinControlPlane(opts, p = paths(), guessAddress = defaultAdverti
5747
6261
  const { fingerprint } = await ensureTlsCert(p);
5748
6262
  const hostUrl = `https://${advertise}:${port}`;
5749
6263
  const body = { token: opts.token, name, url: hostUrl, fingerprint, publicAddress: advertise, ...country !== void 0 ? { country } : {} };
5750
- const res = await request3(`${url}/hosts/join`, {
6264
+ const res = await request4(`${url}/hosts/join`, {
5751
6265
  method: "POST",
5752
6266
  headers: { "content-type": "application/json" },
5753
6267
  body: JSON.stringify(body),
@@ -5772,7 +6286,7 @@ async function fetchCloudCa(p = paths()) {
5772
6286
  const cfg = await loadConfig(p);
5773
6287
  const cp = cfg.controlPlane;
5774
6288
  if (!cp) throw new KvboxError("this host has not joined a control plane, so there is no CA to fetch; paste the key instead: kvbox-server trust-ca <public-key>");
5775
- const res = await request3(`${cp.url}/hosts/self/ssh-ca`, {
6289
+ const res = await request4(`${cp.url}/hosts/self/ssh-ca`, {
5776
6290
  headers: { authorization: `Bearer ${cp.secret}` },
5777
6291
  headersTimeout: 1e4,
5778
6292
  bodyTimeout: 1e4
@@ -5791,7 +6305,7 @@ async function fetchCloudName(p = paths()) {
5791
6305
  const cfg = await loadConfig(p);
5792
6306
  const cp = cfg.controlPlane;
5793
6307
  if (!cp) throw new KvboxError("this host has not joined a control plane, so there is no name to ask for; give it: kvbox-server rename-realm <name>");
5794
- const res = await request3(`${cp.url}/health`, { headersTimeout: 1e4, bodyTimeout: 1e4 }).catch((err) => {
6308
+ const res = await request4(`${cp.url}/health`, { headersTimeout: 1e4, bodyTimeout: 1e4 }).catch((err) => {
5795
6309
  throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);
5796
6310
  });
5797
6311
  const text = await res.body.text();
@@ -5804,7 +6318,7 @@ async function leaveControlPlane(p = paths()) {
5804
6318
  const cfg = await loadConfig(p);
5805
6319
  const cp = cfg.controlPlane;
5806
6320
  if (!cp) throw new KvboxError("this host has not joined a control plane");
5807
- const told = await request3(`${cp.url}/hosts/self`, {
6321
+ const told2 = await request4(`${cp.url}/hosts/self`, {
5808
6322
  method: "DELETE",
5809
6323
  headers: { authorization: `Bearer ${cp.secret}` },
5810
6324
  headersTimeout: 3e3,
@@ -5815,7 +6329,7 @@ async function leaveControlPlane(p = paths()) {
5815
6329
  }).catch(() => false);
5816
6330
  const { controlPlane: _gone, ...rest } = cfg;
5817
6331
  await saveConfig({ ...rest, ...rest.backupStore ? { backupStore: { ...rest.backupStore, registered: false } } : {} }, p);
5818
- return { controlPlane: cp.name, told };
6332
+ return { controlPlane: cp.name, told: told2 };
5819
6333
  }
5820
6334
  function jsonOrNull(text) {
5821
6335
  try {
@@ -5884,7 +6398,7 @@ async function dropRelay(p = paths()) {
5884
6398
  throw new KvboxError(`${cfg.controlPlane.name} reaches this host through the relay (${relay.publicIp}); run kvbox-server leave first`);
5885
6399
  }
5886
6400
  await driver().net.relay(cfg, ["relay", "down"]);
5887
- await rm14(p.relayConf, { force: true });
6401
+ await rm15(p.relayConf, { force: true });
5888
6402
  const { relay: _gone, ...rest } = cfg;
5889
6403
  await saveConfig(rest, p);
5890
6404
  return relay;
@@ -5914,7 +6428,7 @@ function boxHasRun(ref, now = Date.now()) {
5914
6428
  if (runs.size === 0) going.delete(keyOf(ref));
5915
6429
  return runs.size > 0;
5916
6430
  }
5917
- async function socketOf(ref, p) {
6431
+ async function socketOf2(ref, p) {
5918
6432
  const meta = await readMachineMeta(ref, p).catch((err) => {
5919
6433
  if (err.code === "ENOENT") throw new NotFoundError(`box ${shown(ref)}`);
5920
6434
  throw err;
@@ -5924,7 +6438,7 @@ async function socketOf(ref, p) {
5924
6438
  return p.machine(meta.owner, meta.name).vsock;
5925
6439
  }
5926
6440
  var OUTPUT_BASE = "v0.16.0";
5927
- var outdated = (ref, err, needs = "v0.15.0") => {
6441
+ var outdated2 = (ref, err, needs = "v0.15.0") => {
5928
6442
  if (isUnknownOp(err)) throw new BoxOutdatedError(`box ${shown(ref)} runs on an image from before ${needs === OUTPUT_BASE ? "reading a command's output" : "commands"} (it needs base ${needs} or later)`);
5929
6443
  if (isNoAgent(err)) throw new AgentNotAnsweringError(`box ${shown(ref)} did not take the request: its kvbox-agent is not answering (${err.message}); ask again`);
5930
6444
  throw err;
@@ -5935,25 +6449,25 @@ var unanswered = (ref, err, needs) => {
5935
6449
  if (isNoAgent(err) || /kvbox-agent did not answer within/.test(err.message ?? "")) {
5936
6450
  throw new AgentNotAnsweringError(`box ${shown(ref)}: its kvbox-agent is not answering (${err.message}); ask again`);
5937
6451
  }
5938
- return outdated(ref, err, needs);
6452
+ return outdated2(ref, err, needs);
5939
6453
  };
5940
6454
  async function startBoxRun(ref, req, p = paths()) {
5941
- const vsock = await socketOf(ref, p);
5942
- if (req.output) await runOutput(vsock, req.id, "stdout", 0, 0).catch((err) => outdated(ref, err, OUTPUT_BASE));
6455
+ const vsock = await socketOf2(ref, p);
6456
+ if (req.output) await runOutput(vsock, req.id, "stdout", 0, 0).catch((err) => outdated2(ref, err, OUTPUT_BASE));
5943
6457
  const had = going.get(keyOf(ref))?.has(req.id) ?? false;
5944
6458
  note(ref, req.id, Date.now() + req.timeoutSec * 1e3 + 6e4);
5945
6459
  return startRun(vsock, req.id, req.command, req.timeoutSec).catch((err) => {
5946
6460
  if (!had) note(ref, req.id, null);
5947
- return outdated(ref, err);
6461
+ return outdated2(ref, err);
5948
6462
  });
5949
6463
  }
5950
6464
  async function boxRunOutput(ref, id, stream, offset, limit, p = paths()) {
5951
- const vsock = await socketOf(ref, p);
6465
+ const vsock = await socketOf2(ref, p);
5952
6466
  const out = await runOutput(vsock, id, stream, offset, limit).catch((err) => unanswered(ref, err, OUTPUT_BASE));
5953
6467
  return { id, stream, ...out };
5954
6468
  }
5955
6469
  async function boxRunStatus(ref, id, p = paths()) {
5956
- const vsock = await socketOf(ref, p);
6470
+ const vsock = await socketOf2(ref, p);
5957
6471
  const run2 = await runStatus(vsock, id).catch((err) => unanswered(ref, err));
5958
6472
  note(ref, id, run2.state === "running" ? Date.now() + SEEN_RUNNING_MS : null);
5959
6473
  return { id, ...run2 };
@@ -6122,9 +6636,9 @@ function startRelayWatch(opts = {}) {
6122
6636
  // src/daemon.ts
6123
6637
  import { spawn as spawn3 } from "node:child_process";
6124
6638
  import { accessSync, constants as constants2, openSync as openSync5, readFileSync as readFileSync3, statSync as statSync6 } from "node:fs";
6125
- import { mkdir as mkdir11, readFile as readFile11, stat as stat5 } from "node:fs/promises";
6639
+ import { mkdir as mkdir11, readFile as readFile11, stat as stat6 } from "node:fs/promises";
6126
6640
  import { userInfo as userInfo3 } from "node:os";
6127
- import { setTimeout as sleep5 } from "node:timers/promises";
6641
+ import { setTimeout as sleep6 } from "node:timers/promises";
6128
6642
 
6129
6643
  // ../shared/src/systemd.ts
6130
6644
  import { spawnSync } from "node:child_process";
@@ -6160,7 +6674,7 @@ function startsAtBoot(p) {
6160
6674
  }
6161
6675
 
6162
6676
  // src/socketClient.ts
6163
- import { Agent as Agent3, request as request4 } from "undici";
6677
+ import { Agent as Agent3, request as request5 } from "undici";
6164
6678
  var SocketClient = class {
6165
6679
  agent;
6166
6680
  constructor(socketPath) {
@@ -6188,7 +6702,7 @@ var SocketClient = class {
6188
6702
  async call(method, path, schema, body, timeoutMs) {
6189
6703
  let res;
6190
6704
  try {
6191
- res = await request4(`http://kvbox-server${path}`, {
6705
+ res = await request5(`http://kvbox-server${path}`, {
6192
6706
  method,
6193
6707
  dispatcher: this.agent,
6194
6708
  ...timeoutMs === void 0 ? {} : { headersTimeout: timeoutMs, bodyTimeout: timeoutMs },
@@ -6259,11 +6773,11 @@ async function stopDaemon(pid, timeoutMs = 1e4) {
6259
6773
  const deadline = Date.now() + timeoutMs;
6260
6774
  while (alive(pid)) {
6261
6775
  if (Date.now() > deadline) throw new KvboxError(`kvbox-server (pid ${pid}) did not stop within ${timeoutMs / 1e3}s`);
6262
- await sleep5(100);
6776
+ await sleep6(100);
6263
6777
  }
6264
6778
  }
6265
6779
  async function answering(p = paths()) {
6266
- if (!await stat5(p.serverSock).then(() => true, () => false)) return null;
6780
+ if (!await stat6(p.serverSock).then(() => true, () => false)) return null;
6267
6781
  const probe = new SocketClient(p.serverSock);
6268
6782
  try {
6269
6783
  const health = await probe.health();
@@ -6301,7 +6815,7 @@ async function restartDaemon(p = paths()) {
6301
6815
  return startDetached(p);
6302
6816
  }
6303
6817
  async function startUnit(p, timeoutMs) {
6304
- const logFrom = await stat5(p.serverLog).then((s) => s.size, () => 0);
6818
+ const logFrom = await stat6(p.serverLog).then((s) => s.size, () => 0);
6305
6819
  const res = startUnitProcess();
6306
6820
  if (!res.ok) {
6307
6821
  const why = res.out || await lastErrorLine(p.serverLog, logFrom) || "systemctl start failed";
@@ -6322,7 +6836,7 @@ async function serving(p, timeoutMs, check) {
6322
6836
  const deadline = Date.now() + timeoutMs;
6323
6837
  while (Date.now() < deadline) {
6324
6838
  await check?.();
6325
- if (await stat5(p.serverSock).then(() => true, () => false)) {
6839
+ if (await stat6(p.serverSock).then(() => true, () => false)) {
6326
6840
  const probe = new SocketClient(p.serverSock);
6327
6841
  try {
6328
6842
  await probe.health();
@@ -6332,7 +6846,7 @@ async function serving(p, timeoutMs, check) {
6332
6846
  await probe.close();
6333
6847
  }
6334
6848
  }
6335
- await sleep5(100);
6849
+ await sleep6(100);
6336
6850
  }
6337
6851
  throw new KvboxError(`kvbox-server did not start within ${timeoutMs / 1e3}s; see ${p.serverLog}`);
6338
6852
  }
@@ -6385,7 +6899,7 @@ function groupWithMember(gid, user, groupFile) {
6385
6899
  }
6386
6900
 
6387
6901
  // src/listen.ts
6388
- import { readFile as readFile13, rm as rm15, writeFile as writeFile10 } from "node:fs/promises";
6902
+ import { readFile as readFile13, rm as rm16, writeFile as writeFile10 } from "node:fs/promises";
6389
6903
  import { createServer as createHttpsServer } from "node:https";
6390
6904
  import { createAdaptorServer } from "@hono/node-server";
6391
6905
 
@@ -6396,7 +6910,7 @@ var PROXIED_HEADER = "x-kvbox-proxied";
6396
6910
  var VISITOR_PATH_HEADER = "x-kvbox-path";
6397
6911
  var WAKE_HEADER = "x-kvbox-wake";
6398
6912
  var WAKE_WAIT_MS = 3e4;
6399
- var REQUEST_TIMEOUT_MS = 36e5;
6913
+ var REQUEST_TIMEOUT_MS2 = 36e5;
6400
6914
  var WOKE_HEADER = "x-kvbox-woke";
6401
6915
  var VISITOR_AUTH_HEADER = "x-kvbox-authorization";
6402
6916
  var NOT_FORWARDED = /* @__PURE__ */ new Set(["expect"]);
@@ -6426,7 +6940,7 @@ function versionOf(srcFileUrl, injected) {
6426
6940
  }
6427
6941
 
6428
6942
  // src/version.ts
6429
- var VERSION = versionOf(import.meta.url, true ? "0.6.11" : void 0);
6943
+ var VERSION = versionOf(import.meta.url, true ? "0.6.13" : void 0);
6430
6944
 
6431
6945
  // src/caller.ts
6432
6946
  import { createHash as createHash3, timingSafeEqual } from "node:crypto";
@@ -6537,6 +7051,11 @@ async function startUpdate(version, p = paths(), deps = {}) {
6537
7051
  import { Hono } from "hono";
6538
7052
  function backupMachineRoutes() {
6539
7053
  const r = new Hono();
7054
+ r.post("/from-backup", async (c) => {
7055
+ const body = HostFromBackupRequest.safeParse(await c.req.json().catch(() => ({})));
7056
+ if (!body.success) throw new KvboxError("from-backup: expected a new box's fields and {backup: {id, key, sizeBytes, base, env, chunks}}");
7057
+ return c.json(await createFromBackup(body.data, c.get("owner")), 201);
7058
+ });
6540
7059
  r.post("/:name/backup", async (c) => {
6541
7060
  const body = HostBackupRequest.safeParse(await c.req.json().catch(() => ({})));
6542
7061
  if (!body.success) throw new KvboxError("backup: expected {id, key}");
@@ -6598,7 +7117,7 @@ function backupStoreRoutes(opts = {}) {
6598
7117
  import { connect as connect2 } from "node:net";
6599
7118
  import { Readable } from "node:stream";
6600
7119
  import { Hono as Hono3 } from "hono";
6601
- import { request as request5 } from "undici";
7120
+ import { request as request6 } from "undici";
6602
7121
 
6603
7122
  // ../shared/src/httpHead.ts
6604
7123
  var END = "\r\n\r\n";
@@ -6743,7 +7262,7 @@ async function forward(c, wake) {
6743
7262
  raw.headers.forEach((value, name) => pairs.push([name, value]));
6744
7263
  let res;
6745
7264
  try {
6746
- res = await request5(`http://${target.ip}:${target.port}${target.path}`, {
7265
+ res = await request6(`http://${target.ip}:${target.port}${target.path}`, {
6747
7266
  method: raw.method,
6748
7267
  headers: boxHeaders(pairs, target).flat(),
6749
7268
  body: raw.body === null ? null : Readable.fromWeb(raw.body),
@@ -7024,18 +7543,18 @@ function machineRoutes() {
7024
7543
 
7025
7544
  // src/routes/runs.ts
7026
7545
  import { Hono as Hono7 } from "hono";
7027
- import { z as z8 } from "zod";
7028
- var refusal = (c, err) => {
7546
+ import { z as z9 } from "zod";
7547
+ var refusal2 = (c, err) => {
7029
7548
  if (err instanceof ProxyFailure) return c.json({ error: err.message, code: err.code }, err.status);
7030
7549
  if (err instanceof BoxOutdatedError) return c.json({ error: err.message, code: "box-outdated" }, 409);
7031
7550
  if (err instanceof AgentNotAnsweringError) return c.json({ error: err.message, code: "unreachable" }, 503);
7032
7551
  if (err instanceof NotFoundError) return c.json({ error: err.message, code: "not-found" }, 404);
7033
7552
  throw err;
7034
7553
  };
7035
- var OutputQuery = z8.object({
7036
- stream: z8.enum(RUN_STREAMS).default("stdout"),
7037
- offset: z8.coerce.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).default(0),
7038
- limit: z8.coerce.number().int().min(0).max(RUN_OUTPUT_MAX_BYTES).default(RUN_OUTPUT_MAX_BYTES)
7554
+ var OutputQuery = z9.object({
7555
+ stream: z9.enum(RUN_STREAMS).default("stdout"),
7556
+ offset: z9.coerce.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).default(0),
7557
+ limit: z9.coerce.number().int().min(0).max(RUN_OUTPUT_MAX_BYTES).default(RUN_OUTPUT_MAX_BYTES)
7039
7558
  });
7040
7559
  function runRoutes(wake = wakeBox) {
7041
7560
  const r = new Hono7();
@@ -7046,7 +7565,7 @@ function runRoutes(wake = wakeBox) {
7046
7565
  const started = await startBoxRun(ref, body);
7047
7566
  return c.json(StartRunAnswerSchema.parse({ id: body.id, started, woke }), 202);
7048
7567
  } catch (err) {
7049
- return refusal(c, err);
7568
+ return refusal2(c, err);
7050
7569
  }
7051
7570
  });
7052
7571
  r.get("/:name/runs/:id", async (c) => {
@@ -7054,7 +7573,7 @@ function runRoutes(wake = wakeBox) {
7054
7573
  const { ref } = await runningBox(c.req.param("name"), c.get("owner"), wants(c.req.header(WAKE_HEADER)) ? wake : void 0);
7055
7574
  return c.json(BoxRunSchema.parse(await boxRunStatus(ref, c.req.param("id"))));
7056
7575
  } catch (err) {
7057
- return refusal(c, err);
7576
+ return refusal2(c, err);
7058
7577
  }
7059
7578
  });
7060
7579
  r.get("/:name/runs/:id/output", async (c) => {
@@ -7067,7 +7586,7 @@ function runRoutes(wake = wakeBox) {
7067
7586
  const { ref } = await runningBox(c.req.param("name"), c.get("owner"));
7068
7587
  return c.json(RunOutputSchema.parse(await boxRunOutput(ref, id, stream, offset, limit)));
7069
7588
  } catch (err) {
7070
- return refusal(c, err);
7589
+ return refusal2(c, err);
7071
7590
  }
7072
7591
  });
7073
7592
  return r;
@@ -7229,7 +7748,7 @@ async function listen(opts = {}) {
7229
7748
  throw new KvboxError(`socket path too long for a Unix socket (${socketPath}); set KVBOX_HOME to a shorter path`);
7230
7749
  }
7231
7750
  if (socketPath === p.serverSock) await refuseSecondDaemon(p);
7232
- await rm15(socketPath, { force: true });
7751
+ await rm16(socketPath, { force: true });
7233
7752
  const server = createAdaptorServer({ fetch: createApp().fetch });
7234
7753
  await new Promise((resolve3, reject) => {
7235
7754
  server.once("error", reject);
@@ -7248,7 +7767,7 @@ async function listen(opts = {}) {
7248
7767
  fetch: createApp({ controlPlane: { name: cp.name, secret: cp.secret } }).fetch,
7249
7768
  createServer: createHttpsServer,
7250
7769
  // A body forwarded to a box may take long to arrive (a large upload through the edge, #182).
7251
- serverOptions: { key, cert, requestTimeout: REQUEST_TIMEOUT_MS }
7770
+ serverOptions: { key, cert, requestTimeout: REQUEST_TIMEOUT_MS2 }
7252
7771
  });
7253
7772
  const appListeners = httpsServer.listeners("request");
7254
7773
  httpsServer.removeAllListeners("request");
@@ -7267,8 +7786,8 @@ async function listen(opts = {}) {
7267
7786
  httpsServer.listen(port, "0.0.0.0", () => resolve3());
7268
7787
  }).catch(async (err) => {
7269
7788
  server.close();
7270
- await rm15(socketPath, { force: true });
7271
- await rm15(p.serverPid, { force: true });
7789
+ await rm16(socketPath, { force: true });
7790
+ await rm16(p.serverPid, { force: true });
7272
7791
  throw new KvboxError(`cannot listen on port ${port} for ${cp.name} (${err.message})`);
7273
7792
  });
7274
7793
  const bound = httpsServer.address().port;
@@ -7279,15 +7798,15 @@ async function listen(opts = {}) {
7279
7798
  new Promise((resolve3) => server.close(() => resolve3())),
7280
7799
  httpsServer ? new Promise((resolve3) => httpsServer.close(() => resolve3())) : void 0
7281
7800
  ]);
7282
- await rm15(socketPath, { force: true });
7283
- await rm15(p.serverPid, { force: true });
7801
+ await rm16(socketPath, { force: true });
7802
+ await rm16(p.serverPid, { force: true });
7284
7803
  };
7285
7804
  const shutdown3 = async () => {
7286
7805
  server.close();
7287
7806
  httpsServer?.close();
7288
7807
  await stopRecovery();
7289
- await rm15(socketPath, { force: true });
7290
- await rm15(p.serverPid, { force: true });
7808
+ await rm16(socketPath, { force: true });
7809
+ await rm16(p.serverPid, { force: true });
7291
7810
  process.exit(0);
7292
7811
  };
7293
7812
  process.once("SIGINT", () => void shutdown3());
@@ -7331,6 +7850,8 @@ var startCommand = new Command("start").description("run the daemon in the foreg
7331
7850
  const cfg = await loadConfig(paths());
7332
7851
  log.info(`control plane ${cfg.controlPlane?.name}: answering on ${https.url}`);
7333
7852
  }
7853
+ await listenForRunning(paths()).catch((err) => log.warn(`running boxes cannot reach their integrations: ${err.message}`));
7854
+ setInterval(() => void closeDeadListeners(paths()).catch(() => void 0), 6e4).unref();
7334
7855
  try {
7335
7856
  const cfg = await loadConfig(paths());
7336
7857
  const state = await driver().net.prepare(cfg);
@@ -7457,8 +7978,8 @@ var leaveCommand = new Command6("leave").description("take this host out from be
7457
7978
  });
7458
7979
 
7459
7980
  // src/commands/logs.ts
7460
- import { open as open2, readFile as readFile14, stat as stat6 } from "node:fs/promises";
7461
- import { setTimeout as sleep6 } from "node:timers/promises";
7981
+ import { open as open2, readFile as readFile14, stat as stat7 } from "node:fs/promises";
7982
+ import { setTimeout as sleep7 } from "node:timers/promises";
7462
7983
  import { Command as Command7 } from "commander";
7463
7984
  var logsCommand = new Command7("logs").description("show the daemon's log ($KVBOX_HOME/server.log); -f keeps printing as it grows").option("-n, --lines <n>", "how many lines to show from the end", "50").option("-f, --follow", "keep printing new lines until Ctrl-C").action(async (opts) => {
7464
7985
  const n = Number.parseInt(opts.lines, 10);
@@ -7484,9 +8005,9 @@ function tailLines(text, n) {
7484
8005
  }
7485
8006
  async function follow(path, write, opts = {}) {
7486
8007
  const intervalMs = opts.intervalMs ?? 250;
7487
- let offset = opts.from ?? await stat6(path).then((s) => s.size, () => 0);
8008
+ let offset = opts.from ?? await stat7(path).then((s) => s.size, () => 0);
7488
8009
  while (!opts.signal?.aborted) {
7489
- const size2 = await stat6(path).then((s) => s.size, () => 0);
8010
+ const size2 = await stat7(path).then((s) => s.size, () => 0);
7490
8011
  if (size2 < offset) offset = 0;
7491
8012
  if (size2 > offset) {
7492
8013
  const fh = await open2(path, "r");
@@ -7499,7 +8020,7 @@ async function follow(path, write, opts = {}) {
7499
8020
  await fh.close();
7500
8021
  }
7501
8022
  }
7502
- await sleep6(intervalMs, void 0, { signal: opts.signal }).catch(() => void 0);
8023
+ await sleep7(intervalMs, void 0, { signal: opts.signal }).catch(() => void 0);
7503
8024
  }
7504
8025
  }
7505
8026
 
@@ -7533,8 +8054,8 @@ var relayCommand = new Command9("relay").description("reach the internet through
7533
8054
  import { Command as Command11 } from "commander";
7534
8055
 
7535
8056
  // src/core/realm.ts
7536
- import { lstat as lstat2, readFile as readFile15, readdir as readdir7, readlink, rename as rename8, rm as rm16, symlink as symlink2, writeFile as writeFile11 } from "node:fs/promises";
7537
- import { z as z9 } from "zod";
8057
+ import { lstat as lstat2, readFile as readFile15, readdir as readdir7, readlink, rename as rename9, rm as rm17, symlink as symlink2, writeFile as writeFile11 } from "node:fs/promises";
8058
+ import { z as z10 } from "zod";
7538
8059
  var esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7539
8060
  async function ownersIn(root, from, suffix = "") {
7540
8061
  const entries = await readdir7(root).catch((err) => {
@@ -7598,7 +8119,7 @@ async function plan(from, to, p) {
7598
8119
  for (const oldOwner of await ownersIn(p.volumes, from)) {
7599
8120
  await clash(p.ownerVolumes(owner(oldOwner)), `volumes of ${owner(oldOwner)}`);
7600
8121
  for (const name of await namesIn2(p.ownerVolumes(oldOwner))) {
7601
- const meta = await read(p.volume(oldOwner, name).meta, VolumeMetaSchema.extend({ id: z9.string().optional() }), `volume ${oldOwner}/${name}`);
8122
+ const meta = await read(p.volume(oldOwner, name).meta, VolumeMetaSchema.extend({ id: z10.string().optional() }), `volume ${oldOwner}/${name}`);
7602
8123
  out.volumes.push({ oldOwner, name, meta: { ...meta, owner: owner(meta.owner) } });
7603
8124
  }
7604
8125
  }
@@ -7609,19 +8130,29 @@ async function countRealm(from, to, p = paths()) {
7609
8130
  const planned = await plan(from, to, p);
7610
8131
  return { boxes: planned.boxes.length, snapshots: planned.snapshots.length, volumes: planned.volumes.length };
7611
8132
  }
8133
+ async function boundSockets() {
8134
+ try {
8135
+ const lines = (await readFile15("/proc/net/unix", "utf8")).split("\n");
8136
+ return new Set(lines.map((l) => l.split(" ").slice(7).join(" ")).filter((path) => path.startsWith("/")));
8137
+ } catch {
8138
+ return null;
8139
+ }
8140
+ }
7612
8141
  async function writeJson(file, value) {
7613
8142
  const tmp = `${file}.tmp`;
7614
8143
  await writeFile11(tmp, JSON.stringify(value, null, 2) + "\n");
7615
- await rename8(tmp, file);
8144
+ await rename9(tmp, file);
7616
8145
  }
7617
8146
  async function move(entries, metaOf, ownerDir, owners, to) {
7618
8147
  for (const e of entries) await writeJson(metaOf(e.oldOwner, e.name), e.meta);
7619
- for (const o of owners) await rename8(ownerDir(o), ownerDir(to(o)));
8148
+ for (const o of owners) await rename9(ownerDir(o), ownerDir(to(o)));
7620
8149
  }
7621
8150
  async function renameRealm(from, to, p = paths()) {
7622
8151
  const planned = await plan(from, to, p);
7623
8152
  const tail = new RegExp(`@${esc(from)}$`);
7624
8153
  const owner = (o) => o.replace(tail, `@${to}`);
8154
+ const bound = await boundSockets();
8155
+ const integrationsPending = planned.boxes.filter((b) => (b.status === "running" || b.status === "standby") && (b.meta.integrations ?? []).length > 0).filter((b) => bound === null || bound.has(p.machine(b.oldOwner, b.name).vsock)).map((b) => `${b.meta.owner}/${b.name}`);
7625
8156
  await move(planned.volumes, (o, n) => p.volume(o, n).meta, p.ownerVolumes, await ownersIn(p.volumes, from), owner);
7626
8157
  await move(planned.snapshots, (o, n) => p.snapshot(o, n).meta, p.ownerSnapshots, await ownersIn(p.snapshots, from), owner);
7627
8158
  await move(planned.boxes, (o, n) => p.machine(o, n).meta, p.ownerMachines, await ownersIn(p.machines, from), owner);
@@ -7631,16 +8162,16 @@ async function renameRealm(from, to, p = paths()) {
7631
8162
  const link4 = m.volumeDrive(volume);
7632
8163
  const target = await readlink(link4).catch(() => null);
7633
8164
  if (target !== p.volume(box.oldOwner, volume).disk) continue;
7634
- await rm16(link4, { force: true });
8165
+ await rm17(link4, { force: true });
7635
8166
  await symlink2(p.volume(box.meta.owner, volume).disk, link4);
7636
8167
  }
7637
8168
  }
7638
- for (const o of planned.envOwners) await rename8(p.ownerEnv(o), p.ownerEnv(owner(o)));
8169
+ for (const o of planned.envOwners) await rename9(p.ownerEnv(o), p.ownerEnv(owner(o)));
7639
8170
  renameLedgerRealm(from, to, p);
7640
8171
  closeDb(p);
7641
8172
  const cfg = await loadConfig(p);
7642
8173
  if (cfg.controlPlane?.name === from) await saveConfig({ ...cfg, controlPlane: { ...cfg.controlPlane, name: to } }, p);
7643
- const report2 = { from, to, boxes: planned.boxes.length, snapshots: planned.snapshots.length, volumes: planned.volumes.length, keysUpdated: [], keysPending: [] };
8174
+ const report2 = { from, to, boxes: planned.boxes.length, snapshots: planned.snapshots.length, volumes: planned.volumes.length, keysUpdated: [], keysPending: [], integrationsPending };
7644
8175
  for (const box of planned.boxes) {
7645
8176
  const { meta, status } = box;
7646
8177
  if (!(meta.sshKeys ?? []).some(isCaLine)) continue;
@@ -7725,7 +8256,7 @@ var renameRealmCommand = new Command11("rename-realm").description("move this ho
7725
8256
  const to = name ?? await fetchCloudName(p);
7726
8257
  if (from === to) {
7727
8258
  if (!opts.json) console.log(`nothing to do: the control plane is called ${to} and this host's boxes are already under that name`);
7728
- else console.log(JSON.stringify({ from, to, boxes: 0, snapshots: 0, volumes: 0, keysUpdated: [], keysPending: [] }, null, 2));
8259
+ else console.log(JSON.stringify({ from, to, boxes: 0, snapshots: 0, volumes: 0, keysUpdated: [], keysPending: [], integrationsPending: [] }, null, 2));
7729
8260
  return;
7730
8261
  }
7731
8262
  const count = await countRealm(from, to, p);
@@ -7756,6 +8287,9 @@ function describe(report2, restarted) {
7756
8287
  console.log(`moved ${report2.boxes} box(es), ${report2.snapshots} snapshot(s) and ${report2.volumes} volume(s) from ${report2.from} to ${report2.to}`);
7757
8288
  for (const box of report2.keysUpdated) console.log(`box ${box} accepts SSH certificates for ${report2.to} now`);
7758
8289
  for (const k of report2.keysPending) console.log(`box ${k.box} ${WHEN2[k.when]}${k.why ? ` (${k.why})` : ""}`);
8290
+ for (const box of report2.integrationsPending) {
8291
+ console.log(`box ${box} has integrations on and cannot fetch their credentials (git, gh) until it is stopped and started, or hibernated and woken`);
8292
+ }
7759
8293
  console.log(restarted ? "kvbox-server restarted" : "kvbox-server was not running; start it with kvbox-server start -d");
7760
8294
  }
7761
8295