@kvbox/server 0.6.12 → 0.6.15

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";
@@ -1761,1067 +1781,1189 @@ function hasDiskRoom(d, sizeGib) {
1761
1781
  }
1762
1782
  var VCPU_OVERSUBSCRIPTION = 2;
1763
1783
 
1784
+ // ../shared/src/integrations.ts
1785
+ import { z as z5 } from "zod";
1786
+ var INTEGRATION_IDS = ["github", "claude"];
1787
+ var IntegrationIdSchema = z5.enum(INTEGRATION_IDS);
1788
+ var INTEGRATION_KINDS = ["oauth", "app", "api-key", "subscription"];
1789
+ var IntegrationKindSchema = z5.enum(INTEGRATION_KINDS);
1790
+ var INTEGRATION_STATUSES = ["ok", "needs-reconnect"];
1791
+ var IntegrationStatusSchema = z5.enum(INTEGRATION_STATUSES);
1792
+ var IntegrationListSchema = z5.array(z5.string().min(1).max(40)).max(20).transform((list) => [...new Set(list)]);
1793
+ function assertKnownIntegrations(list, who, hint = `the integrations are: ${INTEGRATION_IDS.join(", ")}`) {
1794
+ const unknown = (list ?? []).filter((n) => !INTEGRATION_IDS.includes(n));
1795
+ if (unknown.length > 0) throw new KvboxError(`${who} does not know the integration ${unknown.join(", ")} (${hint})`);
1796
+ }
1797
+ var IntegrationCatalogEntrySchema = z5.object({
1798
+ /** A plain string, like `integration` in a listing row: a reader may be older than the control plane. */
1799
+ id: z5.string(),
1800
+ title: z5.string(),
1801
+ description: z5.string(),
1802
+ /**
1803
+ * How Connect works: `oauth` sends the browser to the provider's consent screen; `paste` takes a credential
1804
+ * the user pastes (Claude Code's). A plain string, like `id`: a released CLI must still read a catalog with a way it does not know.
1805
+ */
1806
+ connect: z5.string(),
1807
+ /** What a user's slug and an org's may hold; an empty list: that kind of slug cannot connect it yet. */
1808
+ kinds: z5.object({ user: z5.array(IntegrationKindSchema), org: z5.array(IntegrationKindSchema) }),
1809
+ /** Whether this control plane is set up for it (a self-hosted one without a GitHub app is not). */
1810
+ available: z5.boolean(),
1811
+ /** Its guide, as a URL. */
1812
+ docs: z5.string().optional(),
1813
+ /** Where it is connected and disconnected: this control plane's web app, when it has one. */
1814
+ page: z5.string().optional()
1815
+ });
1816
+ var IntegrationSchema = z5.object({
1817
+ /** The slug it belongs to: a user's or an org's. */
1818
+ owner: z5.string(),
1819
+ /**
1820
+ * Which one (`github`). A plain string, not the ids above: this is an answer, read by every released CLI
1821
+ * and SDK, and one from before a new integration must still read the listing that has it.
1822
+ */
1823
+ integration: z5.string(),
1824
+ connected: z5.boolean(),
1825
+ /** The rest is null while not connected. */
1826
+ kind: IntegrationKindSchema.nullable(),
1827
+ /** Whose account, as shown: the GitHub login. Never a secret. */
1828
+ account: z5.string().nullable(),
1829
+ status: IntegrationStatusSchema.nullable(),
1830
+ connectedBy: z5.string().nullable(),
1831
+ connectedAt: z5.string().nullable(),
1832
+ /** The last time a box was handed the credential (to the minute). */
1833
+ lastUsedAt: z5.string().nullable(),
1834
+ /** Whether the caller may connect or disconnect it: the slug's own user, an org's owners. */
1835
+ canManage: z5.boolean()
1836
+ });
1837
+ var IntegrationConnectSchema = z5.object({ url: z5.string() });
1838
+ var IntegrationCompleteRequestSchema = z5.object({ code: z5.string().min(1), state: z5.string().min(1) });
1839
+ var ClaudeConnectRequestSchema = z5.object({
1840
+ credential: z5.string().trim().min(1).max(4096).regex(/^[A-Za-z0-9_-]+$/, "a Claude Code token or an Anthropic API key has only letters, digits, - and _: paste it again on one line, with nothing inside it")
1841
+ });
1842
+ var IntegrationIdentitySchema = z5.object({ name: z5.string(), email: z5.string() });
1843
+ var CREDENTIAL_REFUSALS = ["off", "not-connected", "needs-reconnect", "unavailable"];
1844
+ var CredentialAnswerSchema = z5.discriminatedUnion("ok", [
1845
+ z5.object({
1846
+ ok: z5.literal(true),
1847
+ kind: IntegrationKindSchema,
1848
+ token: z5.string(),
1849
+ /** When the token ends (ISO), for one that does (a GitHub App's hour). */
1850
+ expiresAt: z5.string().optional(),
1851
+ identity: IntegrationIdentitySchema.optional()
1852
+ }),
1853
+ z5.object({
1854
+ ok: z5.literal(false),
1855
+ code: z5.enum(CREDENTIAL_REFUSALS),
1856
+ message: z5.string(),
1857
+ /** With `off`: whether the slug has it connected, so the box can say how to turn it on. */
1858
+ connected: z5.boolean().optional()
1859
+ })
1860
+ ]);
1861
+ var HostCredentialRequestSchema = z5.object({ owner: z5.string().min(1), box: z5.string().min(1), integration: IntegrationIdSchema, probe: z5.boolean().optional() });
1862
+ var ConnectedAnswerSchema = z5.object({ connected: z5.boolean(), identity: IntegrationIdentitySchema.optional() });
1863
+ var GUEST_REQUEST_PORT = 53;
1864
+ var GuestRequestSchema = z5.object({ op: z5.literal("credential"), integration: IntegrationIdSchema });
1865
+ var INTEGRATIONS_BASE = "0.17.0";
1866
+ var INTEGRATION_BASES = { github: INTEGRATIONS_BASE, claude: "0.18.0" };
1867
+ function unusableOnBase(base, list) {
1868
+ const parts = (v) => v.replace(/^v/, "").split(".").map(Number);
1869
+ if (!/^v?\d+\.\d+\.\d+$/.test(base)) return [];
1870
+ const have = parts(base);
1871
+ const older = (need) => {
1872
+ const want = parts(need);
1873
+ for (let i = 0; i < 3; i++) if (have[i] !== want[i]) return have[i] < want[i];
1874
+ return false;
1875
+ };
1876
+ return list.filter((n) => {
1877
+ const need = INTEGRATION_BASES[n];
1878
+ return need !== void 0 && older(need);
1879
+ });
1880
+ }
1881
+ var GUEST_REQUESTS_PER_MINUTE = 60;
1882
+
1764
1883
  // src/core/volumes.ts
1765
1884
  import { existsSync as existsSync5, statSync } from "node:fs";
1766
1885
  import { lstat, mkdir as mkdir2, readdir as readdir3, rm as rm3, statfs, symlink, truncate, writeFile as writeFile3 } from "node:fs/promises";
1767
1886
 
1768
1887
  // ../shared/src/api.ts
1769
- 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"]);
1888
+ import { z as z6 } from "zod";
1889
+ var SizeSchema = z6.enum(SIZE_NAMES);
1890
+ var BoxStatusSchema = z6.enum(["running", "standby", "hibernated", "stopped", "unknown"]);
1891
+ var PortProtoSchema = z6.enum(["tcp", "udp"]);
1773
1892
  var MAX_BOX_PORTS = 16;
1774
- var PortForwardSchema = z5.object({
1775
- guestPort: z5.number().int().min(1).max(65535),
1776
- hostPort: z5.number().int(),
1893
+ var PortForwardSchema = z6.object({
1894
+ guestPort: z6.number().int().min(1).max(65535),
1895
+ hostPort: z6.number().int(),
1777
1896
  proto: PortProtoSchema,
1778
1897
  /** The host's public address; only the control plane fills it in, as for `ssh`. */
1779
- address: z5.string().optional(),
1898
+ address: z6.string().optional(),
1780
1899
  /**
1781
1900
  * Closed but kept (#173): nothing reaches the box through it, and the host port stays the box's, so
1782
1901
  * publishing the same box port again opens the same number. Absent: open while the box runs.
1783
1902
  */
1784
- closed: z5.literal(true).optional()
1903
+ closed: z6.literal(true).optional()
1785
1904
  });
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),
1905
+ var PortsRequest = z6.object({
1906
+ ports: z6.array(z6.object({ guestPort: z6.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS),
1788
1907
  /** `DELETE` only (#173): close the ports but keep their host ports for the box (`closed`). */
1789
- keep: z5.boolean().optional()
1908
+ keep: z6.boolean().optional()
1790
1909
  });
1791
- var BoxPortSchema = z5.number().int().min(1).max(65535);
1910
+ var BoxPortSchema = z6.number().int().min(1).max(65535);
1792
1911
  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(),
1912
+ var BoxLinkSchema = z6.object({ from: z6.string(), port: BoxPortSchema });
1913
+ var LinkRequest = z6.object({ from: z6.string().min(1), fromOwner: z6.string().optional(), port: BoxPortSchema });
1914
+ var ClaimSubdomainRequest = z6.object({ name: z6.string(), port: BoxPortSchema });
1915
+ var SubdomainPortRequest = z6.object({ port: BoxPortSchema });
1916
+ var SubdomainRouteRequest = z6.object({ name: z6.string(), port: BoxPortSchema });
1917
+ var SubdomainSchema = z6.object({
1918
+ owner: z6.string(),
1919
+ box: z6.string(),
1920
+ subdomain: z6.string(),
1802
1921
  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(),
1922
+ url: z6.string(),
1923
+ routes: z6.array(z6.object({ name: z6.string(), port: BoxPortSchema, url: z6.string() }))
1924
+ });
1925
+ var AddDomainRequest = z6.object({ domain: z6.string(), port: BoxPortSchema.optional() });
1926
+ var DomainSchema = z6.object({
1927
+ owner: z6.string(),
1928
+ box: z6.string(),
1929
+ domain: z6.string(),
1811
1930
  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()
1931
+ status: z6.enum(["pending", "live"]),
1932
+ www: z6.boolean(),
1933
+ url: z6.string(),
1934
+ error: z6.string().nullable(),
1935
+ records: z6.array(z6.object({ type: z6.enum(["A", "TXT", "CNAME"]), name: z6.string(), value: z6.string() })),
1936
+ createdAt: z6.string()
1937
+ });
1938
+ var WakeHookSchema = z6.object({
1939
+ id: z6.string(),
1940
+ owner: z6.string(),
1941
+ box: z6.string(),
1942
+ url: z6.string(),
1943
+ createdBy: z6.string().nullable(),
1944
+ createdAt: z6.string(),
1945
+ lastCalledAt: z6.string().nullable()
1946
+ });
1947
+ var CreatedWakeHookSchema = WakeHookSchema.extend({ secret: z6.string() });
1948
+ var WakeHookCallSchema = z6.object({
1949
+ box: z6.string(),
1950
+ action: z6.enum(["wake", "resume", "none"]),
1951
+ reason: z6.string().optional()
1833
1952
  });
1834
1953
  var BACKUP_STATUSES = ["running", "ready", "failed"];
1835
1954
  var BACKUP_KINDS = ["box", "volume"];
1836
- var BackupSchema = z5.object({
1837
- id: z5.string(),
1838
- owner: z5.string(),
1839
- box: z5.string(),
1955
+ var BackupSchema = z6.object({
1956
+ id: z6.string(),
1957
+ owner: z6.string(),
1958
+ box: z6.string(),
1840
1959
  /**
1841
1960
  * The box it was taken of has been removed (#141): a box called `box` now is another box, which this backup
1842
1961
  * never restores into; `kvbox new <name> --from-backup <id>` makes a box from it. Absent from a control plane
1843
1962
  * before #141.
1844
1963
  */
1845
- boxRemoved: z5.boolean().optional(),
1846
- status: z5.enum(BACKUP_STATUSES),
1964
+ boxRemoved: z6.boolean().optional(),
1965
+ status: z6.enum(BACKUP_STATUSES),
1847
1966
  /** Why it failed; null otherwise. */
1848
- error: z5.string().nullable(),
1967
+ error: z6.string().nullable(),
1849
1968
  /** The image version the disk stacks on (a restore needs it on the host), and the image (absent: base). */
1850
- base: z5.string().nullable(),
1851
- image: z5.string().optional(),
1852
- vcpu: z5.number().int().nullable(),
1853
- memMib: z5.number().int().nullable(),
1969
+ base: z6.string().nullable(),
1970
+ image: z6.string().optional(),
1971
+ vcpu: z6.number().int().nullable(),
1972
+ memMib: z6.number().int().nullable(),
1854
1973
  /** The disk's size. */
1855
- diskBytes: z5.number().int().nullable(),
1974
+ diskBytes: z6.number().int().nullable(),
1856
1975
  /** What it holds: the slots that are not all zeros. */
1857
- dataBytes: z5.number().int().nullable(),
1976
+ dataBytes: z6.number().int().nullable(),
1858
1977
  /** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
1859
- uploadedBytes: z5.number().int().nullable(),
1860
- createdBy: z5.string().nullable(),
1861
- createdAt: z5.string(),
1862
- finishedAt: z5.string().nullable()
1863
- });
1864
- var BackupLimitSchema = z5.object({
1865
- perDay: z5.number().int(),
1866
- used: z5.number().int(),
1867
- nextAt: z5.string().nullable()
1868
- });
1869
- var NamedBackupLimitSchema = BackupLimitSchema.extend({ owner: z5.string(), name: z5.string() });
1870
- var HostBackupRequest = z5.object({ id: z5.string(), key: z5.string() });
1871
- var HostBackupManifestSchema = z5.object({
1872
- id: z5.string(),
1873
- sizeBytes: z5.number().int(),
1874
- chunks: z5.array(z5.string().nullable()),
1875
- env: z5.string().nullable(),
1876
- base: z5.string(),
1877
- image: z5.string().optional(),
1878
- vcpu: z5.number().int(),
1879
- memMib: z5.number().int()
1880
- });
1881
- var HostUploadRequest = z5.object({ key: z5.string(), urls: z5.record(z5.string(), z5.string()), pin: z5.string().optional() });
1882
- var HostUploadResultSchema = z5.object({ chunks: z5.number().int(), bytes: z5.number().int(), sizes: z5.record(z5.string(), z5.number().int()) });
1883
- var HostRestoreRequest = z5.object({
1978
+ uploadedBytes: z6.number().int().nullable(),
1979
+ createdBy: z6.string().nullable(),
1980
+ createdAt: z6.string(),
1981
+ finishedAt: z6.string().nullable()
1982
+ });
1983
+ var BackupLimitSchema = z6.object({
1984
+ perDay: z6.number().int(),
1985
+ used: z6.number().int(),
1986
+ nextAt: z6.string().nullable()
1987
+ });
1988
+ var NamedBackupLimitSchema = BackupLimitSchema.extend({ owner: z6.string(), name: z6.string() });
1989
+ var HostBackupRequest = z6.object({ id: z6.string(), key: z6.string() });
1990
+ var HostBackupManifestSchema = z6.object({
1991
+ id: z6.string(),
1992
+ sizeBytes: z6.number().int(),
1993
+ chunks: z6.array(z6.string().nullable()),
1994
+ env: z6.string().nullable(),
1995
+ base: z6.string(),
1996
+ image: z6.string().optional(),
1997
+ vcpu: z6.number().int(),
1998
+ memMib: z6.number().int(),
1999
+ /** The box's integrations (#205), so a box made from the backup has them again. Absent: none, or an older host. */
2000
+ integrations: z6.array(z6.string()).optional()
2001
+ });
2002
+ var HostUploadRequest = z6.object({ key: z6.string(), urls: z6.record(z6.string(), z6.string()), pin: z6.string().optional() });
2003
+ var HostUploadResultSchema = z6.object({ chunks: z6.number().int(), bytes: z6.number().int(), sizes: z6.record(z6.string(), z6.number().int()) });
2004
+ var HostRestoreRequest = z6.object({
1884
2005
  /** The backup's id: its variables were sealed under it. */
1885
- id: z5.string(),
1886
- key: z5.string(),
1887
- sizeBytes: z5.number().int().positive(),
1888
- base: z5.string(),
1889
- image: z5.string().optional(),
1890
- env: z5.string().nullable(),
1891
- chunks: z5.array(z5.object({ index: z5.number().int().nonnegative(), hash: z5.string(), url: z5.string() })),
2006
+ id: z6.string(),
2007
+ key: z6.string(),
2008
+ sizeBytes: z6.number().int().positive(),
2009
+ base: z6.string(),
2010
+ image: z6.string().optional(),
2011
+ env: z6.string().nullable(),
2012
+ chunks: z6.array(z6.object({ index: z6.number().int().nonnegative(), hash: z6.string(), url: z6.string() })),
1892
2013
  /** The certificate fingerprint of the store the URLs point at (see HostUploadRequest). */
1893
- pin: z5.string().optional()
2014
+ pin: z6.string().optional()
1894
2015
  });
1895
- var VolumeBackupSchema = z5.object({
1896
- id: z5.string(),
1897
- owner: z5.string(),
1898
- volume: z5.string(),
1899
- status: z5.enum(BACKUP_STATUSES),
2016
+ var VolumeBackupSchema = z6.object({
2017
+ id: z6.string(),
2018
+ owner: z6.string(),
2019
+ volume: z6.string(),
2020
+ status: z6.enum(BACKUP_STATUSES),
1900
2021
  /** Why it failed; null otherwise. */
1901
- error: z5.string().nullable(),
2022
+ error: z6.string().nullable(),
1902
2023
  /** The volume's size when taken. */
1903
- diskBytes: z5.number().int().nullable(),
2024
+ diskBytes: z6.number().int().nullable(),
1904
2025
  /** What it holds: the slots that are not all zeros. */
1905
- dataBytes: z5.number().int().nullable(),
2026
+ dataBytes: z6.number().int().nullable(),
1906
2027
  /** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
1907
- uploadedBytes: z5.number().int().nullable(),
1908
- createdBy: z5.string().nullable(),
1909
- createdAt: z5.string(),
1910
- finishedAt: z5.string().nullable()
2028
+ uploadedBytes: z6.number().int().nullable(),
2029
+ createdBy: z6.string().nullable(),
2030
+ createdAt: z6.string(),
2031
+ finishedAt: z6.string().nullable()
1911
2032
  });
1912
- var BackupScheduleSchema = z5.object({
1913
- enabled: z5.boolean(),
2033
+ var BackupScheduleSchema = z6.object({
2034
+ enabled: z6.boolean(),
1914
2035
  /** 0-23, UTC. Kept while it is off, so turning it on again keeps the hour. */
1915
- hour: z5.number().int().min(0).max(23),
1916
- nextAt: z5.string().nullable(),
1917
- lastAt: z5.string().nullable(),
1918
- lastBackup: z5.string().nullable(),
1919
- lastError: z5.string().nullable()
1920
- });
1921
- var SetBackupScheduleRequest = z5.object({ enabled: z5.boolean().optional(), hour: z5.number().int().min(0).max(23).optional() });
1922
- var HostVolumeBackupManifestSchema = z5.object({ id: z5.string(), sizeBytes: z5.number().int(), chunks: z5.array(z5.string().nullable()) });
1923
- var HostVolumeRestoreRequest = z5.object({
1924
- id: z5.string(),
1925
- key: z5.string(),
1926
- sizeBytes: z5.number().int().positive(),
1927
- chunks: z5.array(z5.object({ index: z5.number().int().nonnegative(), hash: z5.string(), url: z5.string() })),
1928
- pin: z5.string().optional()
2036
+ hour: z6.number().int().min(0).max(23),
2037
+ nextAt: z6.string().nullable(),
2038
+ lastAt: z6.string().nullable(),
2039
+ lastBackup: z6.string().nullable(),
2040
+ lastError: z6.string().nullable()
2041
+ });
2042
+ var SetBackupScheduleRequest = z6.object({ enabled: z6.boolean().optional(), hour: z6.number().int().min(0).max(23).optional() });
2043
+ var HostVolumeBackupManifestSchema = z6.object({ id: z6.string(), sizeBytes: z6.number().int(), chunks: z6.array(z6.string().nullable()) });
2044
+ var HostVolumeRestoreRequest = z6.object({
2045
+ id: z6.string(),
2046
+ key: z6.string(),
2047
+ sizeBytes: z6.number().int().positive(),
2048
+ chunks: z6.array(z6.object({ index: z6.number().int().nonnegative(), hash: z6.string(), url: z6.string() })),
2049
+ pin: z6.string().optional()
1929
2050
  });
1930
2051
  var BACKUP_STORE_BUCKET = "kvbox-backups";
1931
2052
  var BACKUP_STORE_REGION = "kvbox";
1932
- var BackupStoreSetupRequest = z5.object({ path: z5.string().min(1), force: z5.boolean().optional(), newStore: z5.boolean().optional() });
1933
- var BackupStoreStatusSchema = z5.object({
1934
- path: z5.string(),
1935
- bucket: z5.string(),
1936
- accessKey: z5.string(),
2053
+ var BackupStoreSetupRequest = z6.object({ path: z6.string().min(1), force: z6.boolean().optional(), newStore: z6.boolean().optional() });
2054
+ var BackupStoreStatusSchema = z6.object({
2055
+ path: z6.string(),
2056
+ bucket: z6.string(),
2057
+ accessKey: z6.string(),
1937
2058
  /** Whether Garage is running and can store. */
1938
- running: z5.boolean(),
2059
+ running: z6.boolean(),
1939
2060
  /** The filesystem the path is on. */
1940
- totalBytes: z5.number().int(),
1941
- freeBytes: z5.number().int(),
2061
+ totalBytes: z6.number().int(),
2062
+ freeBytes: z6.number().int(),
1942
2063
  /** What the bucket holds, when Garage answers. */
1943
- objects: z5.number().int().optional(),
1944
- storedBytes: z5.number().int().optional(),
2064
+ objects: z6.number().int().optional(),
2065
+ storedBytes: z6.number().int().optional(),
1945
2066
  /** Whether the control plane took the store's registration at setup. */
1946
- registered: z5.boolean().optional()
2067
+ registered: z6.boolean().optional()
1947
2068
  });
1948
- var BackupStoreRegistration = z5.object({ bucket: z5.string().min(1), region: z5.string().min(1), accessKey: z5.string().min(1), secretKey: z5.string().min(1) });
1949
- var CloudBackupStoreSchema = z5.object({
1950
- id: z5.string(),
2069
+ var BackupStoreRegistration = z6.object({ bucket: z6.string().min(1), region: z6.string().min(1), accessKey: z6.string().min(1), secretKey: z6.string().min(1) });
2070
+ var CloudBackupStoreSchema = z6.object({
2071
+ id: z6.string(),
1951
2072
  /** Null while no host serves it (its host left; it comes back when a host registers its key and secret again). */
1952
- host: z5.string().nullable(),
1953
- endpoint: z5.string().nullable(),
1954
- bucket: z5.string(),
1955
- accessKey: z5.string(),
1956
- createdAt: z5.string(),
2073
+ host: z6.string().nullable(),
2074
+ endpoint: z6.string().nullable(),
2075
+ bucket: z6.string(),
2076
+ accessKey: z6.string(),
2077
+ createdAt: z6.string(),
1957
2078
  /** The host answered a poll in the last minute and its Garage runs. */
1958
- live: z5.boolean(),
2079
+ live: z6.boolean(),
1959
2080
  /** From the host's last poll; null when it never reported a store. */
1960
- totalBytes: z5.number().int().nullable(),
1961
- freeBytes: z5.number().int().nullable(),
2081
+ totalBytes: z6.number().int().nullable(),
2082
+ freeBytes: z6.number().int().nullable(),
1962
2083
  /** Ready backups kept here, and what their chunks take (encrypted, compressed). */
1963
- backups: z5.number().int(),
1964
- storedBytes: z5.number().int(),
2084
+ backups: z6.number().int(),
2085
+ storedBytes: z6.number().int(),
1965
2086
  /** 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). */
1966
- boxes: z5.number().int(),
1967
- volumes: z5.number().int(),
1968
- databases: z5.number().int(),
2087
+ boxes: z6.number().int(),
2088
+ volumes: z6.number().int(),
2089
+ databases: z6.number().int(),
1969
2090
  /** When the newest ready backup kept here finished; null when it keeps none. */
1970
- lastBackupAt: z5.string().nullable()
2091
+ lastBackupAt: z6.string().nullable()
1971
2092
  });
1972
- var StoredItemSchema = z5.object({
1973
- kind: z5.enum(BACKUP_KINDS),
1974
- owner: z5.string(),
2093
+ var StoredItemSchema = z6.object({
2094
+ kind: z6.enum(BACKUP_KINDS),
2095
+ owner: z6.string(),
1975
2096
  /** The box's or volume's name; a managed database's (#186) for its hidden volume. */
1976
- name: z5.string(),
2097
+ name: z6.string(),
1977
2098
  /** The managed database's kind (`postgres`) when the volume is one's (#186); null otherwise. */
1978
- managed: z5.string().nullable(),
2099
+ managed: z6.string().nullable(),
1979
2100
  /** The host the box (or volume) is on now; null when it is gone (its backups stay). */
1980
- host: z5.string().nullable(),
2101
+ host: z6.string().nullable(),
1981
2102
  /** It is on the store's own host: losing that host loses it and its backups together. */
1982
- sameHost: z5.boolean(),
2103
+ sameHost: z6.boolean(),
1983
2104
  /** Ready backups kept here, and what they added to the store together (encrypted, compressed). */
1984
- backups: z5.number().int(),
1985
- uploadedBytes: z5.number().int(),
2105
+ backups: z6.number().int(),
2106
+ uploadedBytes: z6.number().int(),
1986
2107
  /** The newest backup sent here, whatever became of it. */
1987
- latest: z5.object({ id: z5.string(), status: z5.enum(BACKUP_STATUSES), error: z5.string().nullable(), createdAt: z5.string() })
2108
+ latest: z6.object({ id: z6.string(), status: z6.enum(BACKUP_STATUSES), error: z6.string().nullable(), createdAt: z6.string() })
1988
2109
  });
1989
- var FailedBackupSchema = z5.object({
1990
- id: z5.string(),
1991
- owner: z5.string(),
2110
+ var FailedBackupSchema = z6.object({
2111
+ id: z6.string(),
2112
+ owner: z6.string(),
1992
2113
  /** What it was a backup of: a box or a volume (#168), and its name; a managed database's (#186) for its hidden volume. */
1993
- kind: z5.enum(BACKUP_KINDS),
1994
- name: z5.string(),
2114
+ kind: z6.enum(BACKUP_KINDS),
2115
+ name: z6.string(),
1995
2116
  /** The managed database's kind (`postgres`) when the volume is one's; null otherwise. */
1996
- managed: z5.string().nullable(),
1997
- error: z5.string().nullable(),
2117
+ managed: z6.string().nullable(),
2118
+ error: z6.string().nullable(),
1998
2119
  /** 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. */
1999
- host: z5.string().nullable(),
2000
- store: z5.string().nullable(),
2001
- createdAt: z5.string()
2120
+ host: z6.string().nullable(),
2121
+ store: z6.string().nullable(),
2122
+ createdAt: z6.string()
2002
2123
  });
2003
- var MachineSchema = z5.object({
2124
+ var MachineSchema = z6.object({
2004
2125
  /** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */
2005
- id: z5.string(),
2006
- name: z5.string(),
2126
+ id: z6.string(),
2127
+ name: z6.string(),
2007
2128
  /** Who the box belongs to; names are unique per owner. A bare name is local to the host, `user@control-plane` later. */
2008
- owner: z5.string(),
2009
- ip: z5.string(),
2010
- mac: z5.string(),
2011
- pid: z5.number().int().nullable(),
2012
- vcpu: z5.number().int(),
2013
- memMib: z5.number().int(),
2014
- diskBytes: z5.number().int(),
2129
+ owner: z6.string(),
2130
+ ip: z6.string(),
2131
+ mac: z6.string(),
2132
+ pid: z6.number().int().nullable(),
2133
+ vcpu: z6.number().int(),
2134
+ memMib: z6.number().int(),
2135
+ diskBytes: z6.number().int(),
2015
2136
  // the box's own writable disk, as the guest sees it
2016
- diskUsedBytes: z5.number().int(),
2137
+ diskUsedBytes: z6.number().int(),
2017
2138
  // what the box uses of it: the filesystem's own count, like the guest's `df` (#115)
2018
2139
  /** 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. */
2019
- diskHostBytes: z5.number().int().optional(),
2020
- base: z5.string(),
2140
+ diskHostBytes: z6.number().int().optional(),
2141
+ base: z6.string(),
2021
2142
  // version of the image the box's overlay stacks on
2022
2143
  /** The image (#87) when it is not the base one: `postgres`. `base` is then that image's version. */
2023
- image: z5.string().optional(),
2024
- createdAt: z5.string(),
2025
- source: z5.string(),
2144
+ image: z6.string().optional(),
2145
+ /**
2146
+ * A newer version of the box's image on its host, the one `kvbox vm update` moves it onto. Only the control
2147
+ * plane fills it in (from the host's last `/capacity`); absent while the box is on the newest one, or the host did not say.
2148
+ */
2149
+ latestBase: z6.string().optional(),
2150
+ createdAt: z6.string(),
2151
+ source: z6.string(),
2026
2152
  // "base", "snapshot:<owner/name>", "fork:<owner/name>" (#79) or "backup:<id>" (#141)
2027
2153
  status: BoxStatusSchema,
2028
2154
  /**
2029
2155
  * Public TCP port on the host that reaches the box's SSH while it runs (#49). Only boxes made
2030
2156
  * through a control plane have one; the control plane adds the host's address for `connect` (#21).
2031
2157
  */
2032
- sshPort: z5.number().int().optional(),
2158
+ sshPort: z6.number().int().optional(),
2033
2159
  /**
2034
2160
  * Where `ssh` reaches the box from outside: the host's public address and that port (#21). Only
2035
2161
  * the control plane fills it in (a host does not know its own public address); absent for a box
2036
2162
  * whose host reported no port or did not answer.
2037
2163
  */
2038
- ssh: z5.object({ host: z5.string(), port: z5.number().int(), user: z5.string() }).optional(),
2164
+ ssh: z6.object({ host: z6.string(), port: z6.number().int(), user: z6.string() }).optional(),
2039
2165
  /** Box ports published on the host (#30). Absent: none. */
2040
- ports: z5.array(PortForwardSchema).optional(),
2166
+ ports: z6.array(PortForwardSchema).optional(),
2041
2167
  /** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /machines`. */
2042
- ownerKind: z5.enum(["user", "org"]).optional(),
2168
+ ownerKind: z6.enum(["user", "org"]).optional(),
2043
2169
  /**
2044
2170
  * The name of the host the box runs on. Only the control plane fills it in, on `GET /machines`: a box
2045
2171
  * links to, and a volume attaches to, only a box on the same host.
2046
2172
  */
2047
- host: z5.string().optional(),
2173
+ host: z6.string().optional(),
2048
2174
  /** The country code of that host (`RO`, `US`), when its admin gave one. Only the control plane fills it in. */
2049
- country: z5.string().optional(),
2175
+ country: z6.string().optional(),
2050
2176
  /**
2051
2177
  * The kind of managed service the box runs (`postgres`, `redis`, `storage`). Only an admin's
2052
2178
  * `GET /machines?all=1` lists such boxes, so a host's boxes add up; every other listing hides them.
2053
2179
  */
2054
- managed: z5.string().optional(),
2180
+ managed: z6.string().optional(),
2055
2181
  /** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
2056
- autoHibernateSec: z5.number().int().positive().optional(),
2182
+ autoHibernateSec: z6.number().int().positive().optional(),
2057
2183
  /** A script inside the box that says it is idle (#102, exit 0): auto-hibernate asks it instead of watching the traffic. */
2058
- idleCheck: z5.string().optional(),
2184
+ idleCheck: z6.string().optional(),
2059
2185
  /** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */
2060
- volumes: z5.array(z5.object({ name: z5.string(), sizeGib: z5.number().int(), mountPath: z5.string() })).optional(),
2186
+ volumes: z6.array(z6.object({ name: z6.string(), sizeGib: z6.number().int(), mountPath: z6.string() })).optional(),
2061
2187
  /** Boxes that may reach this one, each on one port (#98). Absent: none. */
2062
- links: z5.array(BoxLinkSchema).optional(),
2188
+ links: z6.array(BoxLinkSchema).optional(),
2189
+ /**
2190
+ * The integrations turned on for the box (#205, `github`): names only, the credential is fetched by the box
2191
+ * each time it is needed. Absent: none. A host before integrations never sends it.
2192
+ */
2193
+ integrations: z6.array(z6.string()).optional(),
2063
2194
  /** How to reach what the box serves, its secrets masked (#87): `postgres://postgres:****@db.kvbox:5432/postgres`. */
2064
- url: z5.string().optional(),
2195
+ url: z6.string().optional(),
2065
2196
  /**
2066
2197
  * Only in what `POST /machines` answers, for an image that declares one (#87): how to reach what it
2067
2198
  * serves, e.g. `postgres://postgres:<password>@db.kvbox:5432/postgres`. Holds the box's variables.
2068
2199
  */
2069
- connect: z5.string().optional()
2200
+ connect: z6.string().optional()
2070
2201
  });
2071
- var VolumeSchema = z5.object({
2202
+ var VolumeSchema = z6.object({
2072
2203
  /** The host's 6-hex volume id (#91): the ledger's key, so a name removed and made again is two volumes. */
2073
- id: z5.string(),
2074
- name: z5.string(),
2075
- owner: z5.string(),
2076
- sizeGib: z5.number().int(),
2204
+ id: z6.string(),
2205
+ name: z6.string(),
2206
+ owner: z6.string(),
2207
+ sizeGib: z6.number().int(),
2077
2208
  /** What the sparse file really occupies on the host. */
2078
- usedBytes: z5.number().int(),
2079
- attachedTo: z5.string().nullable(),
2080
- createdAt: z5.string(),
2209
+ usedBytes: z6.number().int(),
2210
+ attachedTo: z6.string().nullable(),
2211
+ createdAt: z6.string(),
2081
2212
  /** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /volumes`. */
2082
- ownerKind: z5.enum(["user", "org"]).optional(),
2213
+ ownerKind: z6.enum(["user", "org"]).optional(),
2083
2214
  /** The name of the host the volume lives on; only the control plane fills it in. It attaches only to a box there. */
2084
- host: z5.string().optional()
2215
+ host: z6.string().optional()
2085
2216
  });
2086
2217
  var MAX_VOLUME_GIB = 4096;
2087
2218
  var VOLUME_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
2088
2219
  var VOLUME_NAME_RULE = "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit";
2089
- var CreateVolumeRequest = z5.object({
2090
- name: z5.string(),
2091
- sizeGib: z5.number().int().min(1).max(MAX_VOLUME_GIB),
2220
+ var CreateVolumeRequest = z6.object({
2221
+ name: z6.string(),
2222
+ sizeGib: z6.number().int().min(1).max(MAX_VOLUME_GIB),
2092
2223
  /**
2093
2224
  * Through a control plane (#91): the box this volume is for, so it is made on that box's host; the
2094
2225
  * control plane requires it (a volume attaches only to a box on its own host, so one made for no box
2095
2226
  * could never attach) and the CLI attaches right after. A host ignores it.
2096
2227
  */
2097
- box: z5.string().optional()
2228
+ box: z6.string().optional()
2098
2229
  });
2099
- var AttachVolumeRequest = z5.object({
2100
- box: z5.string()
2230
+ var AttachVolumeRequest = z6.object({
2231
+ box: z6.string()
2101
2232
  });
2102
- var ResizeVolumeRequest = z5.object({
2103
- sizeGib: z5.number().int().min(1).max(MAX_VOLUME_GIB)
2233
+ var ResizeVolumeRequest = z6.object({
2234
+ sizeGib: z6.number().int().min(1).max(MAX_VOLUME_GIB)
2104
2235
  });
2105
- var RunScriptRequest = z5.object({ input: z5.unknown().optional() });
2106
- var ScriptOutputSchema = z5.object({ output: z5.unknown() });
2236
+ var RunScriptRequest = z6.object({ input: z6.unknown().optional() });
2237
+ var ScriptOutputSchema = z6.object({ output: z6.unknown() });
2107
2238
  var BOX_RUN_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
2108
- var StartRunRequest = z5.object({
2109
- id: z5.string().regex(BOX_RUN_ID_RE),
2110
- command: z5.string().min(1).max(8192),
2239
+ var StartRunRequest = z6.object({
2240
+ id: z6.string().regex(BOX_RUN_ID_RE),
2241
+ command: z6.string().min(1).max(8192),
2111
2242
  /** The command and everything it started are killed after this long. */
2112
- timeoutSec: z5.number().int().min(1).max(86400),
2243
+ timeoutSec: z6.number().int().min(1).max(86400),
2113
2244
  /**
2114
2245
  * The caller will read the output back (`exec`, #188): the box's kvbox-agent must know `runOutput`
2115
2246
  * (base v0.16.0+), which the host checks before the command starts, so an older box is `box-outdated`
2116
2247
  * without having run anything.
2117
2248
  */
2118
- output: z5.boolean().optional()
2249
+ output: z6.boolean().optional()
2119
2250
  });
2120
- var StartRunAnswerSchema = z5.object({
2121
- id: z5.string(),
2251
+ var StartRunAnswerSchema = z6.object({
2252
+ id: z6.string(),
2122
2253
  /** False: a run of this id was already there. */
2123
- started: z5.boolean(),
2254
+ started: z6.boolean(),
2124
2255
  /** The box was asleep and this request woke it. */
2125
- woke: z5.boolean()
2256
+ woke: z6.boolean()
2126
2257
  });
2127
2258
  var BOX_RUN_STATES = ["running", "exited", "timeout", "unknown"];
2128
- var BoxRunSchema = z5.object({
2129
- id: z5.string(),
2130
- state: z5.enum(BOX_RUN_STATES),
2259
+ var BoxRunSchema = z6.object({
2260
+ id: z6.string(),
2261
+ state: z6.enum(BOX_RUN_STATES),
2131
2262
  /** With `exited`; 128 + the signal for a command a signal ended. */
2132
- exitCode: z5.number().int().optional(),
2263
+ exitCode: z6.number().int().optional(),
2133
2264
  /**
2134
2265
  * With `exited` and `timeout`: how long the command itself ran, by the box's own clock (base v0.15.1
2135
2266
  * and later). The asker learns of the end seconds late, so its own count is too long.
2136
2267
  */
2137
- durationMs: z5.number().int().nonnegative().optional()
2268
+ durationMs: z6.number().int().nonnegative().optional()
2138
2269
  });
2139
- var RunRefusalSchema = z5.object({ error: z5.string(), code: z5.string().optional() });
2270
+ var RunRefusalSchema = z6.object({ error: z6.string(), code: z6.string().optional() });
2140
2271
  var RUN_OUTPUT_MAX_BYTES = 1 << 20;
2141
2272
  var RUN_STREAMS = ["stdout", "stderr"];
2142
- var RunOutputSchema = z5.object({
2143
- id: z5.string(),
2144
- stream: z5.enum(RUN_STREAMS),
2145
- offset: z5.number().int().nonnegative(),
2146
- size: z5.number().int().nonnegative(),
2147
- data: z5.string()
2148
- });
2149
- var ExecRequest = z5.object({
2150
- command: z5.string().min(1).max(8192),
2273
+ var RunOutputSchema = z6.object({
2274
+ id: z6.string(),
2275
+ stream: z6.enum(RUN_STREAMS),
2276
+ offset: z6.number().int().nonnegative(),
2277
+ size: z6.number().int().nonnegative(),
2278
+ data: z6.string()
2279
+ });
2280
+ var ExecRequest = z6.object({
2281
+ command: z6.string().min(1).max(8192),
2151
2282
  /** The command and everything it started are killed after this long (default DEFAULT_EXEC_TIMEOUT_SEC). */
2152
- timeoutSec: z5.number().int().min(1).max(86400).optional()
2283
+ timeoutSec: z6.number().int().min(1).max(86400).optional()
2153
2284
  });
2154
- var ExecStartSchema = z5.object({
2155
- id: z5.string(),
2285
+ var ExecStartSchema = z6.object({
2286
+ id: z6.string(),
2156
2287
  /** The box was asleep and this request woke it. */
2157
- woke: z5.boolean()
2288
+ woke: z6.boolean()
2158
2289
  });
2159
- var ExecSchema = z5.object({
2160
- id: z5.string(),
2161
- state: z5.enum(BOX_RUN_STATES),
2290
+ var ExecSchema = z6.object({
2291
+ id: z6.string(),
2292
+ state: z6.enum(BOX_RUN_STATES),
2162
2293
  /** With `exited`; 128 + the signal for a command a signal ended. */
2163
- exitCode: z5.number().int().optional(),
2294
+ exitCode: z6.number().int().optional(),
2164
2295
  /** With `exited` and `timeout`: how long the command itself ran. */
2165
- durationMs: z5.number().int().nonnegative().optional(),
2166
- stdout: z5.string().optional(),
2167
- stderr: z5.string().optional(),
2168
- stdoutBytes: z5.number().int().nonnegative().optional(),
2169
- stderrBytes: z5.number().int().nonnegative().optional(),
2170
- truncated: z5.boolean().optional()
2171
- });
2172
- var EnvVarSchema = z5.object({
2173
- name: z5.string(),
2174
- value: z5.string().optional(),
2175
- secret: z5.boolean(),
2176
- updatedAt: z5.string()
2177
- });
2178
- var BoxEnvSchema = z5.object({
2179
- box: z5.string(),
2180
- vars: z5.array(EnvVarSchema)
2181
- });
2182
- var BoxEnvChangeSchema = z5.object({
2183
- box: z5.string(),
2184
- name: z5.string(),
2296
+ durationMs: z6.number().int().nonnegative().optional(),
2297
+ stdout: z6.string().optional(),
2298
+ stderr: z6.string().optional(),
2299
+ stdoutBytes: z6.number().int().nonnegative().optional(),
2300
+ stderrBytes: z6.number().int().nonnegative().optional(),
2301
+ truncated: z6.boolean().optional()
2302
+ });
2303
+ var EnvVarSchema = z6.object({
2304
+ name: z6.string(),
2305
+ value: z6.string().optional(),
2306
+ secret: z6.boolean(),
2307
+ updatedAt: z6.string()
2308
+ });
2309
+ var BoxEnvSchema = z6.object({
2310
+ box: z6.string(),
2311
+ vars: z6.array(EnvVarSchema)
2312
+ });
2313
+ var BoxEnvChangeSchema = z6.object({
2314
+ box: z6.string(),
2315
+ name: z6.string(),
2185
2316
  /** Whether the box is running now: the change waits for its next start. */
2186
- running: z5.boolean()
2317
+ running: z6.boolean()
2187
2318
  });
2188
- var SetEnvRequest = z5.object({
2189
- value: z5.string(),
2190
- secret: z5.boolean().optional()
2319
+ var SetEnvRequest = z6.object({
2320
+ value: z6.string(),
2321
+ secret: z6.boolean().optional()
2191
2322
  });
2192
- var EnvChangeSchema = z5.object({
2193
- owner: z5.string(),
2194
- name: z5.string(),
2195
- boxes: z5.number().int()
2323
+ var EnvChangeSchema = z6.object({
2324
+ owner: z6.string(),
2325
+ name: z6.string(),
2326
+ boxes: z6.number().int()
2196
2327
  });
2197
- var HostEnvRequest = z5.object({
2198
- version: z5.number().int().min(0),
2199
- vars: z5.array(z5.object({ name: z5.string(), value: z5.string() }))
2328
+ var HostEnvRequest = z6.object({
2329
+ version: z6.number().int().min(0),
2330
+ vars: z6.array(z6.object({ name: z6.string(), value: z6.string() }))
2200
2331
  });
2201
- var HostEnvVersionsSchema = z5.array(z5.object({ owner: z5.string(), version: z5.number().int() }));
2202
- var CreateMachineRequest = z5.object({
2203
- name: z5.string().optional(),
2332
+ var HostEnvVersionsSchema = z6.array(z6.object({ owner: z6.string(), version: z6.number().int() }));
2333
+ var CreateMachineRequest = z6.object({
2334
+ name: z6.string().optional(),
2204
2335
  /** Ignored over the local socket (the caller is the host owner); the control plane sets it over HTTPS. */
2205
- owner: z5.string().optional(),
2336
+ owner: z6.string().optional(),
2206
2337
  size: SizeSchema.optional(),
2207
- from: z5.string().optional(),
2208
- force: z5.boolean().optional(),
2338
+ from: z6.string().optional(),
2339
+ force: z6.boolean().optional(),
2209
2340
  /**
2210
2341
  * Extra authorized_keys lines for the box, on top of the host's own key: the control plane sends
2211
2342
  * its SSH CA as one `cert-authority …` line (#51). Written into the box's authorized_keys at every
2212
2343
  * boot (#49); a host older than that ignores them.
2213
2344
  */
2214
- sshKeys: z5.array(z5.string()).optional(),
2345
+ sshKeys: z6.array(z6.string()).optional(),
2215
2346
  /** Seconds without network traffic before the box is hibernated (#47); 0: never. Absent: the host's default. */
2216
- autoHibernateSec: z5.number().int().min(0).optional(),
2347
+ autoHibernateSec: z6.number().int().min(0).optional(),
2217
2348
  /**
2218
2349
  * Place the box on the host of this box (#98, `kvbox new --near`), so the two can be linked. Only the
2219
2350
  * control plane reads it; a host has one place to put a box.
2220
2351
  */
2221
- near: z5.string().optional(),
2352
+ near: z6.string().optional(),
2222
2353
  /**
2223
2354
  * Place the box on a host in this country (`kvbox new --country romania`): a code or an English name,
2224
2355
  * `@kvbox/shared/country`. Only the control plane reads it.
2225
2356
  */
2226
- country: z5.string().optional(),
2357
+ country: z6.string().optional(),
2227
2358
  /**
2228
2359
  * Place the box on the host of this name and nowhere else (`kvbox new --host kvbox2`, a hidden flag):
2229
2360
  * an admin's, to try a host out. Only the control plane reads it, and refuses it from anyone else.
2230
2361
  */
2231
- host: z5.string().optional(),
2362
+ host: z6.string().optional(),
2232
2363
  /** The image to boot (#87, `kvbox new --base postgres`). Absent: the base image. */
2233
- image: z5.string().optional(),
2364
+ image: z6.string().optional(),
2234
2365
  /** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */
2235
- env: z5.array(z5.object({ name: z5.string(), value: z5.string() })).optional(),
2366
+ env: z6.array(z6.object({ name: z6.string(), value: z6.string() })).optional(),
2236
2367
  /**
2237
2368
  * Start the box on this backup's disk (#141, `kvbox new --from-backup <id>`), a removed box's too: its image,
2238
2369
  * version and variables come from the backup, its size too unless given. Only the control plane reads it.
2239
2370
  */
2240
- fromBackup: z5.string().optional()
2371
+ fromBackup: z6.string().optional(),
2372
+ /**
2373
+ * The integrations turned on for the box (#205, `kvbox new --integration github`). Absent: none, or with
2374
+ * `from` / `fromBackup` the list the snapshot or the backup was taken with.
2375
+ */
2376
+ integrations: IntegrationListSchema.optional()
2241
2377
  });
2242
2378
  var HostFromBackupRequest = CreateMachineRequest.omit({ from: true, fromBackup: true, image: true, env: true }).extend({ backup: HostRestoreRequest });
2243
- var ForkMachineRequest = z5.object({
2244
- name: z5.string().optional(),
2379
+ var ForkMachineRequest = z6.object({
2380
+ name: z6.string().optional(),
2245
2381
  /**
2246
2382
  * The new box's slug, bare (`acme`): the control plane sends the target of `--org` here; the host
2247
2383
  * qualifies it with the caller's realm. Absent: the source's owner. A CLI leaves it out.
2248
2384
  */
2249
- owner: z5.string().optional(),
2385
+ owner: z6.string().optional(),
2250
2386
  /** A cold fork only: a warm one keeps the source's vCPU and memory. */
2251
2387
  size: SizeSchema.optional(),
2252
- force: z5.boolean().optional(),
2388
+ force: z6.boolean().optional(),
2253
2389
  /** As in CreateMachineRequest: the control plane's CA line for the new box's owner. */
2254
- sshKeys: z5.array(z5.string()).optional(),
2255
- autoHibernateSec: z5.number().int().min(0).optional()
2390
+ sshKeys: z6.array(z6.string()).optional(),
2391
+ autoHibernateSec: z6.number().int().min(0).optional()
2256
2392
  });
2257
- var SetSshKeysRequest = z5.object({
2258
- sshKeys: z5.array(z5.string())
2393
+ var SetSshKeysRequest = z6.object({
2394
+ sshKeys: z6.array(z6.string())
2259
2395
  });
2260
- var RescaleMachineRequest = z5.object({
2396
+ var RescaleMachineRequest = z6.object({
2261
2397
  size: SizeSchema.optional(),
2262
- vcpu: z5.number().int().min(1).max(64).optional(),
2263
- memMib: z5.number().int().min(256).optional(),
2264
- diskGib: z5.number().int().min(1).optional(),
2398
+ vcpu: z6.number().int().min(1).max(64).optional(),
2399
+ memMib: z6.number().int().min(256).optional(),
2400
+ diskGib: z6.number().int().min(1).optional(),
2265
2401
  /** Skip the capacity guard when a running box grows (#37). */
2266
- force: z5.boolean().optional()
2402
+ force: z6.boolean().optional()
2267
2403
  });
2268
- var StartMachineRequest = z5.object({
2269
- force: z5.boolean().optional()
2404
+ var StartMachineRequest = z6.object({
2405
+ force: z6.boolean().optional()
2270
2406
  });
2271
- var SetMachineRequest = z5.object({
2407
+ var SetMachineRequest = z6.object({
2272
2408
  /** Seconds without network traffic before the box is hibernated (#47); 0: never. */
2273
- autoHibernateSec: z5.number().int().min(0).optional(),
2409
+ autoHibernateSec: z6.number().int().min(0).optional(),
2274
2410
  /** The box's idle check (#102): an absolute path to a script inside the box, exit 0 = idle; "": none, back to network traffic. */
2275
- idleCheck: z5.union([z5.literal(""), z5.string().max(255).regex(/^\/[^\0\n]*$/, "an absolute path inside the box")]).optional()
2276
- });
2277
- var SnapshotSchema = z5.object({
2278
- name: z5.string(),
2279
- owner: z5.string(),
2280
- source: z5.string(),
2411
+ idleCheck: z6.union([z6.literal(""), z6.string().max(255).regex(/^\/[^\0\n]*$/, "an absolute path inside the box")]).optional(),
2412
+ /** The box's integrations (#205), the whole list: `[]` turns every one off. Applies at once, in any state. */
2413
+ integrations: IntegrationListSchema.optional()
2414
+ });
2415
+ var SnapshotSchema = z6.object({
2416
+ name: z6.string(),
2417
+ owner: z6.string(),
2418
+ source: z6.string(),
2281
2419
  // the box it was taken from, as owner/name
2282
- base: z5.string(),
2420
+ base: z6.string(),
2283
2421
  // version of the image the overlay stacks on; a restore needs the same one
2284
2422
  /** As in MachineSchema: the image when it is not the base one (#87). */
2285
- image: z5.string().optional(),
2286
- vcpu: z5.number().int(),
2287
- memMib: z5.number().int(),
2288
- sizeBytes: z5.number().int(),
2423
+ image: z6.string().optional(),
2424
+ vcpu: z6.number().int(),
2425
+ memMib: z6.number().int(),
2426
+ sizeBytes: z6.number().int(),
2289
2427
  // what vmstate + mem + overlay really occupy on the host
2290
- createdAt: z5.string()
2428
+ createdAt: z6.string()
2291
2429
  });
2292
- var CreateSnapshotRequest = z5.object({
2293
- box: z5.string(),
2294
- name: z5.string(),
2430
+ var CreateSnapshotRequest = z6.object({
2431
+ box: z6.string(),
2432
+ name: z6.string(),
2295
2433
  /** Retake a snapshot under a name that exists (#83): the old one goes only once the new one is complete. */
2296
- replace: z5.boolean().optional()
2297
- });
2298
- var DiskCapacitySchema = z5.object({
2299
- totalGib: z5.number().int(),
2300
- freeGib: z5.number().int(),
2301
- volumesGib: z5.number().int(),
2302
- volumesUsedGib: z5.number().int(),
2303
- headroomGib: z5.number().int()
2304
- });
2305
- var CapacitySchema = z5.object({
2306
- hostMemMib: z5.number().int(),
2307
- hostCores: z5.number().int(),
2308
- reservedMemMib: z5.number().int(),
2309
- reservedVcpu: z5.number().int(),
2310
- running: z5.number().int(),
2434
+ replace: z6.boolean().optional()
2435
+ });
2436
+ var DiskCapacitySchema = z6.object({
2437
+ totalGib: z6.number().int(),
2438
+ freeGib: z6.number().int(),
2439
+ volumesGib: z6.number().int(),
2440
+ volumesUsedGib: z6.number().int(),
2441
+ headroomGib: z6.number().int()
2442
+ });
2443
+ var CapacitySchema = z6.object({
2444
+ hostMemMib: z6.number().int(),
2445
+ hostCores: z6.number().int(),
2446
+ reservedMemMib: z6.number().int(),
2447
+ reservedVcpu: z6.number().int(),
2448
+ running: z6.number().int(),
2311
2449
  /**
2312
2450
  * MiB of RAM the host keeps back from its boxes (config.json `memHeadroomMib`). Absent on a kvbox-server
2313
2451
  * from before the setting, which keeps 2 GB (`OLD_HOST_MEM_HEADROOM_MIB`).
2314
2452
  */
2315
- memHeadroomMib: z5.number().int().optional(),
2453
+ memHeadroomMib: z6.number().int().optional(),
2316
2454
  /** Absent on a host from before volumes (#91): it cannot take one. */
2317
2455
  disk: DiskCapacitySchema.optional(),
2318
2456
  /**
2319
2457
  * The images a new box can be made from here (#87), with the version `new` uses; the base is `base`.
2320
2458
  * Absent on a host from before images: it has only the base.
2321
2459
  */
2322
- images: z5.array(z5.object({ name: z5.string(), version: z5.string() })).optional(),
2460
+ images: z6.array(z6.object({ name: z6.string(), version: z6.string() })).optional(),
2323
2461
  /** kvbox-server's version, so the control plane's host list shows it without a call per host. Older servers omit it. */
2324
- version: z5.string().optional(),
2462
+ version: z6.string().optional(),
2325
2463
  /** Present on a host set up as a backup store: the disk its Garage keeps chunks on, and whether Garage runs. */
2326
- backupStore: z5.object({ totalBytes: z5.number().int(), freeBytes: z5.number().int(), running: z5.boolean() }).optional(),
2464
+ backupStore: z6.object({ totalBytes: z6.number().int(), freeBytes: z6.number().int(), running: z6.boolean() }).optional(),
2327
2465
  /** 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. */
2328
- storeClient: z5.boolean().optional(),
2466
+ storeClient: z6.boolean().optional(),
2329
2467
  /** True on a kvbox-server with `POST /machines/from-backup` (#141, `kvbox new --from-backup`); older ones omit it. */
2330
- fromBackup: z5.boolean().optional()
2331
- });
2332
- var ImageSchema = z5.object({ name: z5.string(), version: z5.string().nullable() });
2333
- var ImageIndexSchema = z5.object({
2334
- updatedAt: z5.string(),
2335
- images: z5.record(z5.string(), z5.object({ version: z5.string().min(1), minServer: z5.string().min(1).optional() }))
2336
- });
2337
- var LatestImagesSchema = z5.object({
2338
- updatedAt: z5.string().nullable(),
2468
+ fromBackup: z6.boolean().optional(),
2469
+ /** True on a kvbox-server that keeps a box's `integrations` (#205); an older one drops the field without a word. */
2470
+ integrations: z6.boolean().optional(),
2471
+ /** The integrations this kvbox-server knows (`hostKnowsIntegrations`). Absent with `integrations`: the first one's, `github` alone. */
2472
+ integrationIds: z6.array(z6.string()).optional()
2473
+ });
2474
+ var ImageSchema = z6.object({ name: z6.string(), version: z6.string().nullable() });
2475
+ var ImageIndexSchema = z6.object({
2476
+ updatedAt: z6.string(),
2477
+ images: z6.record(z6.string(), z6.object({ version: z6.string().min(1), minServer: z6.string().min(1).optional() }))
2478
+ });
2479
+ var LatestImagesSchema = z6.object({
2480
+ updatedAt: z6.string().nullable(),
2339
2481
  images: ImageIndexSchema.shape.images,
2340
- checkedAt: z5.string().nullable()
2341
- });
2342
- var RecoveryReportSchema = z5.object({
2343
- at: z5.string(),
2344
- booted: z5.array(z5.string()),
2345
- leftStopped: z5.array(z5.string()),
2346
- failed: z5.array(z5.object({ box: z5.string(), error: z5.string() }))
2347
- });
2348
- var HostUpdateSchema = z5.object({
2349
- state: z5.enum(["running", "done", "failed"]),
2350
- startedAt: z5.string(),
2351
- finishedAt: z5.string().nullable(),
2482
+ checkedAt: z6.string().nullable()
2483
+ });
2484
+ var RecoveryReportSchema = z6.object({
2485
+ at: z6.string(),
2486
+ booted: z6.array(z6.string()),
2487
+ leftStopped: z6.array(z6.string()),
2488
+ failed: z6.array(z6.object({ box: z6.string(), error: z6.string() }))
2489
+ });
2490
+ var HostUpdateSchema = z6.object({
2491
+ state: z6.enum(["running", "done", "failed"]),
2492
+ startedAt: z6.string(),
2493
+ finishedAt: z6.string().nullable(),
2352
2494
  /** kvbox-server's version when the update started, and when it ended (null while running or when it failed before). */
2353
- from: z5.string(),
2354
- to: z5.string().nullable(),
2355
- error: z5.string().nullable(),
2356
- needsManual: z5.array(z5.string())
2357
- });
2358
- var HealthSchema = z5.object({
2359
- ok: z5.literal(true),
2360
- version: z5.string(),
2361
- pid: z5.number().int(),
2495
+ from: z6.string(),
2496
+ to: z6.string().nullable(),
2497
+ error: z6.string().nullable(),
2498
+ needsManual: z6.array(z6.string())
2499
+ });
2500
+ var HealthSchema = z6.object({
2501
+ ok: z6.literal(true),
2502
+ version: z6.string(),
2503
+ pid: z6.number().int(),
2362
2504
  /** Base image version new boxes get (null when the host has no usable base image yet). */
2363
- base: z5.string().nullable(),
2505
+ base: z6.string().nullable(),
2364
2506
  /** Owner that boxes made over the local socket get (the Unix user running the server). */
2365
- owner: z5.string(),
2507
+ owner: z6.string(),
2366
2508
  /** The control plane this host joined (null when none). */
2367
- controlPlane: z5.object({
2509
+ controlPlane: z6.object({
2368
2510
  /** Realm name, e.g. kvbox.sh. */
2369
- name: z5.string(),
2370
- url: z5.string(),
2511
+ name: z6.string(),
2512
+ url: z6.string(),
2371
2513
  /** Where this host answers the control plane. */
2372
- hostUrl: z5.string()
2514
+ hostUrl: z6.string()
2373
2515
  }).nullable(),
2374
2516
  /** The relay this host reaches the internet through (#50); null when it has its own public address. Older servers omit it. */
2375
- relay: z5.object({
2376
- name: z5.string(),
2517
+ relay: z6.object({
2518
+ name: z6.string(),
2377
2519
  /** The public IP the relay owns for this host. */
2378
- publicIp: z5.string(),
2520
+ publicIp: z6.string(),
2379
2521
  /** The relay's WireGuard endpoint the tunnel dials. */
2380
- endpoint: z5.string(),
2522
+ endpoint: z6.string(),
2381
2523
  /** Times the server redialed the tunnel since it started, because the relay stopped answering. Older servers omit them. */
2382
- restarts: z5.number().int().optional(),
2383
- lastRestartAt: z5.string().nullable().optional()
2524
+ restarts: z6.number().int().optional(),
2525
+ lastRestartAt: z6.string().nullable().optional()
2384
2526
  }).nullable().optional(),
2385
2527
  /** Boxes brought back at the server's last start; null when there were none or it is still at it. Older servers omit it. */
2386
2528
  recovery: RecoveryReportSchema.nullable().optional(),
2387
2529
  /** The last self-update; null when none ran. Older servers omit it. */
2388
2530
  update: HostUpdateSchema.nullable().optional()
2389
2531
  });
2390
- var MachineUsageSchema = z5.object({
2391
- name: z5.string(),
2392
- owner: z5.string(),
2532
+ var MachineUsageSchema = z6.object({
2533
+ name: z6.string(),
2534
+ owner: z6.string(),
2393
2535
  status: BoxStatusSchema,
2394
- window: z5.object({ from: z5.string(), to: z5.string() }),
2395
- seconds: z5.object({
2396
- running: z5.number().int(),
2397
- standby: z5.number().int(),
2398
- hibernated: z5.number().int(),
2399
- stopped: z5.number().int()
2536
+ window: z6.object({ from: z6.string(), to: z6.string() }),
2537
+ seconds: z6.object({
2538
+ running: z6.number().int(),
2539
+ standby: z6.number().int(),
2540
+ hibernated: z6.number().int(),
2541
+ stopped: z6.number().int()
2400
2542
  }),
2401
- vcpuHours: z5.number(),
2402
- ramGibHours: z5.number(),
2403
- diskGibHours: z5.number(),
2404
- cost: z5.object({ amount: z5.number(), currency: z5.string() }).optional(),
2543
+ vcpuHours: z6.number(),
2544
+ ramGibHours: z6.number(),
2545
+ diskGibHours: z6.number(),
2546
+ cost: z6.object({ amount: z6.number(), currency: z6.string() }).optional(),
2405
2547
  /** Stops the server did not witness (Firecracker died, host rebooted) and dated to when it noticed. */
2406
- estimatedStops: z5.number().int(),
2407
- historyFrom: z5.string().nullable()
2548
+ estimatedStops: z6.number().int(),
2549
+ historyFrom: z6.string().nullable()
2408
2550
  });
2409
- var GuestStatsSchema = z5.object({
2551
+ var GuestStatsSchema = z6.object({
2410
2552
  /** Load average over 1, 5 and 15 minutes. */
2411
- load: z5.tuple([z5.number(), z5.number(), z5.number()]),
2412
- cpus: z5.number().int(),
2413
- memTotalMib: z5.number().int(),
2553
+ load: z6.tuple([z6.number(), z6.number(), z6.number()]),
2554
+ cpus: z6.number().int(),
2555
+ memTotalMib: z6.number().int(),
2414
2556
  /** Total minus available: page cache counts as free. */
2415
- memUsedMib: z5.number().int(),
2557
+ memUsedMib: z6.number().int(),
2416
2558
  /** The box's root, which is its overlay disk: the box's own writes, not the shared base. */
2417
- diskTotalBytes: z5.number().int(),
2418
- diskUsedBytes: z5.number().int(),
2419
- uptimeSec: z5.number().int()
2559
+ diskTotalBytes: z6.number().int(),
2560
+ diskUsedBytes: z6.number().int(),
2561
+ uptimeSec: z6.number().int()
2420
2562
  });
2421
- var MachineStatsSchema = z5.object({
2422
- name: z5.string(),
2423
- owner: z5.string(),
2563
+ var MachineStatsSchema = z6.object({
2564
+ name: z6.string(),
2565
+ owner: z6.string(),
2424
2566
  stats: GuestStatsSchema.nullable()
2425
2567
  });
2426
- var UsageStatusSchema = z5.enum([...BoxStatusSchema.options, "removed"]);
2568
+ var UsageStatusSchema = z6.enum([...BoxStatusSchema.options, "removed"]);
2427
2569
  var BoxUsageSchema = MachineUsageSchema.omit({ window: true, status: true }).extend({
2428
2570
  /** The host's box id; a name removed and recreated appears twice, with two ids. */
2429
- id: z5.string(),
2571
+ id: z6.string(),
2430
2572
  status: UsageStatusSchema,
2431
2573
  /** Through a control plane: whether the owner slug is a user's or an org's (what `kvbox ls` shows). */
2432
- ownerKind: z5.enum(["user", "org"]).optional(),
2574
+ ownerKind: z6.enum(["user", "org"]).optional(),
2433
2575
  /**
2434
2576
  * Through a control plane: the username that made the box (#60), absent when the box is gone from
2435
2577
  * the index (removed), was found by reconcile, or its maker was deleted. The ledger does not record it.
2436
2578
  */
2437
- createdBy: z5.string().optional()
2579
+ createdBy: z6.string().optional()
2438
2580
  });
2439
- var VolumeUsageSchema = z5.object({
2581
+ var VolumeUsageSchema = z6.object({
2440
2582
  /** The host's volume id; a name removed and made again appears twice, with two ids. */
2441
- id: z5.string(),
2442
- name: z5.string(),
2443
- owner: z5.string(),
2444
- ownerKind: z5.enum(["user", "org"]).optional(),
2583
+ id: z6.string(),
2584
+ name: z6.string(),
2585
+ owner: z6.string(),
2586
+ ownerKind: z6.enum(["user", "org"]).optional(),
2445
2587
  /** The size at the end of the window (or when removed). */
2446
- sizeGib: z5.number().int(),
2447
- status: z5.enum(["present", "removed"]),
2448
- volumeHours: z5.number(),
2449
- volumeGibHours: z5.number(),
2450
- cost: z5.object({ amount: z5.number(), currency: z5.string() }).optional(),
2451
- historyFrom: z5.string().nullable()
2452
- });
2453
- var CronUsageSchema = z5.object({
2454
- id: z5.string(),
2455
- name: z5.string(),
2456
- owner: z5.string(),
2457
- ownerKind: z5.enum(["user", "org"]).optional(),
2458
- status: z5.enum(["present", "removed"]),
2459
- hours: z5.number(),
2460
- cost: z5.object({ amount: z5.number(), currency: z5.string() }).optional(),
2588
+ sizeGib: z6.number().int(),
2589
+ status: z6.enum(["present", "removed"]),
2590
+ volumeHours: z6.number(),
2591
+ volumeGibHours: z6.number(),
2592
+ cost: z6.object({ amount: z6.number(), currency: z6.string() }).optional(),
2593
+ historyFrom: z6.string().nullable()
2594
+ });
2595
+ var CronUsageSchema = z6.object({
2596
+ id: z6.string(),
2597
+ name: z6.string(),
2598
+ owner: z6.string(),
2599
+ ownerKind: z6.enum(["user", "org"]).optional(),
2600
+ status: z6.enum(["present", "removed"]),
2601
+ hours: z6.number(),
2602
+ cost: z6.object({ amount: z6.number(), currency: z6.string() }).optional(),
2461
2603
  /** When it was made. */
2462
- historyFrom: z5.string().nullable()
2463
- });
2464
- var BackupUsageSchema = z5.object({
2465
- id: z5.string(),
2466
- kind: z5.string(),
2467
- name: z5.string(),
2468
- owner: z5.string(),
2469
- ownerKind: z5.enum(["user", "org"]).optional(),
2604
+ historyFrom: z6.string().nullable()
2605
+ });
2606
+ var BackupUsageSchema = z6.object({
2607
+ id: z6.string(),
2608
+ kind: z6.string(),
2609
+ name: z6.string(),
2610
+ owner: z6.string(),
2611
+ ownerKind: z6.enum(["user", "org"]).optional(),
2470
2612
  /** How many paid backups turned ready in the window. */
2471
- count: z5.number().int(),
2472
- cost: z5.object({ amount: z5.number(), currency: z5.string() })
2613
+ count: z6.number().int(),
2614
+ cost: z6.object({ amount: z6.number(), currency: z6.string() })
2473
2615
  });
2474
- var UsageDayItemSchema = z5.object({
2475
- id: z5.string(),
2476
- name: z5.string(),
2477
- owner: z5.string(),
2616
+ var UsageDayItemSchema = z6.object({
2617
+ id: z6.string(),
2618
+ name: z6.string(),
2619
+ owner: z6.string(),
2478
2620
  /** Removed by the end of the report's window. */
2479
- removed: z5.boolean(),
2480
- cost: z5.number()
2621
+ removed: z6.boolean(),
2622
+ cost: z6.number()
2481
2623
  });
2482
- var UsageDaySchema = z5.object({
2624
+ var UsageDaySchema = z6.object({
2483
2625
  /** `YYYY-MM-DD`, UTC. */
2484
- date: z5.string(),
2485
- from: z5.string(),
2486
- to: z5.string(),
2487
- cost: z5.number(),
2488
- currency: z5.string(),
2489
- boxes: z5.array(UsageDayItemSchema),
2490
- volumes: z5.array(UsageDayItemSchema),
2626
+ date: z6.string(),
2627
+ from: z6.string(),
2628
+ to: z6.string(),
2629
+ cost: z6.number(),
2630
+ currency: z6.string(),
2631
+ boxes: z6.array(UsageDayItemSchema),
2632
+ volumes: z6.array(UsageDayItemSchema),
2491
2633
  /** Object storage that existed that day (#182); absent on a day without any. */
2492
- storage: z5.array(UsageDayItemSchema).optional(),
2634
+ storage: z6.array(UsageDayItemSchema).optional(),
2493
2635
  /** Cron services that existed that day (#190); absent on a day without any. */
2494
- cron: z5.array(UsageDayItemSchema).optional(),
2636
+ cron: z6.array(UsageDayItemSchema).optional(),
2495
2637
  /** Paid backups that turned ready that day, summed per thing backed up (`id` is `<owner>/<kind>:<name>`); absent on a day without any. */
2496
- backups: z5.array(UsageDayItemSchema).optional()
2638
+ backups: z6.array(UsageDayItemSchema).optional()
2497
2639
  });
2498
- var UsageReportSchema = z5.object({
2499
- window: z5.object({ from: z5.string(), to: z5.string() }),
2500
- boxes: z5.array(BoxUsageSchema),
2640
+ var UsageReportSchema = z6.object({
2641
+ window: z6.object({ from: z6.string(), to: z6.string() }),
2642
+ boxes: z6.array(BoxUsageSchema),
2501
2643
  /** Absent from a side older than #91. */
2502
- volumes: z5.array(VolumeUsageSchema).optional(),
2644
+ volumes: z6.array(VolumeUsageSchema).optional(),
2503
2645
  /**
2504
2646
  * Object storage (#182, control plane only): one row per storage a slug has or had, shaped like a
2505
2647
  * volume's. `volumeHours` are the hours it existed, `volumeGibHours` those of the GiB beyond the
2506
2648
  * included ones, `sizeGib` its whole size. Absent when there is none.
2507
2649
  */
2508
- storage: z5.array(VolumeUsageSchema).optional(),
2650
+ storage: z6.array(VolumeUsageSchema).optional(),
2509
2651
  /** Cron services (#190, control plane only): one row per service a slug has or had. Absent when there is none. */
2510
- cron: z5.array(CronUsageSchema).optional(),
2652
+ cron: z6.array(CronUsageSchema).optional(),
2511
2653
  /** Paid backups (control plane only): one row per box, volume or service backed up by hand in the window. Absent when there is none. */
2512
- backups: z5.array(BackupUsageSchema).optional(),
2654
+ backups: z6.array(BackupUsageSchema).optional(),
2513
2655
  /** With `?by=day` only, oldest day first. */
2514
- days: z5.array(UsageDaySchema).optional(),
2515
- totals: z5.object({
2656
+ days: z6.array(UsageDaySchema).optional(),
2657
+ totals: z6.object({
2516
2658
  seconds: MachineUsageSchema.shape.seconds,
2517
- vcpuHours: z5.number(),
2518
- ramGibHours: z5.number(),
2519
- diskGibHours: z5.number(),
2520
- volumeHours: z5.number().optional(),
2521
- volumeGibHours: z5.number().optional(),
2659
+ vcpuHours: z6.number(),
2660
+ ramGibHours: z6.number(),
2661
+ diskGibHours: z6.number(),
2662
+ volumeHours: z6.number().optional(),
2663
+ volumeGibHours: z6.number().optional(),
2522
2664
  /** Boxes, volumes, object storage, cron services and paid backups together. */
2523
- cost: z5.object({ amount: z5.number(), currency: z5.string() }).optional()
2665
+ cost: z6.object({ amount: z6.number(), currency: z6.string() }).optional()
2524
2666
  })
2525
2667
  });
2526
- var UsageEventRowSchema = z5.object({
2527
- id: z5.number().int(),
2528
- boxId: z5.string(),
2529
- owner: z5.string(),
2530
- name: z5.string(),
2531
- at: z5.string(),
2532
- state: z5.enum(["running", "standby", "hibernated", "stopped"]),
2533
- vcpu: z5.number().int(),
2534
- memMib: z5.number().int(),
2535
- diskGib: z5.number().int(),
2536
- by: z5.string()
2537
- });
2538
- var UsageEventsResponseSchema = z5.object({
2539
- ledger: z5.string().min(1),
2540
- events: z5.array(UsageEventRowSchema),
2541
- next: z5.number().int()
2542
- });
2543
- var VolumeEventRowSchema = z5.object({
2544
- id: z5.number().int(),
2545
- volumeId: z5.string(),
2546
- owner: z5.string(),
2547
- name: z5.string(),
2548
- at: z5.string(),
2549
- sizeGib: z5.number().int(),
2550
- by: z5.enum(["create", "resize", "rm"])
2551
- });
2552
- var VolumeEventsResponseSchema = z5.object({
2553
- ledger: z5.string().min(1),
2554
- events: z5.array(VolumeEventRowSchema),
2555
- next: z5.number().int()
2668
+ var UsageEventRowSchema = z6.object({
2669
+ id: z6.number().int(),
2670
+ boxId: z6.string(),
2671
+ owner: z6.string(),
2672
+ name: z6.string(),
2673
+ at: z6.string(),
2674
+ state: z6.enum(["running", "standby", "hibernated", "stopped"]),
2675
+ vcpu: z6.number().int(),
2676
+ memMib: z6.number().int(),
2677
+ diskGib: z6.number().int(),
2678
+ by: z6.string()
2679
+ });
2680
+ var UsageEventsResponseSchema = z6.object({
2681
+ ledger: z6.string().min(1),
2682
+ events: z6.array(UsageEventRowSchema),
2683
+ next: z6.number().int()
2684
+ });
2685
+ var VolumeEventRowSchema = z6.object({
2686
+ id: z6.number().int(),
2687
+ volumeId: z6.string(),
2688
+ owner: z6.string(),
2689
+ name: z6.string(),
2690
+ at: z6.string(),
2691
+ sizeGib: z6.number().int(),
2692
+ by: z6.enum(["create", "resize", "rm"])
2693
+ });
2694
+ var VolumeEventsResponseSchema = z6.object({
2695
+ ledger: z6.string().min(1),
2696
+ events: z6.array(VolumeEventRowSchema),
2697
+ next: z6.number().int()
2556
2698
  });
2557
2699
  var API_ERROR_CODES = ["account-inactive", "org-inactive", "out-of-credit", "box-outdated", "storage-outdated", "object-exists", "storage-waking"];
2558
- var ApiErrorCodeSchema = z5.enum(API_ERROR_CODES);
2559
- var ApiErrorSchema = z5.object({
2560
- error: z5.string(),
2700
+ var ApiErrorCodeSchema = z6.enum(API_ERROR_CODES);
2701
+ var ApiErrorSchema = z6.object({
2702
+ error: z6.string(),
2561
2703
  code: ApiErrorCodeSchema.optional()
2562
2704
  });
2563
2705
  var ACTIVATED_BY = ["card", "admin"];
2564
- var ActivatedBySchema = z5.enum(ACTIVATED_BY);
2565
- var CloudUserSchema = z5.object({
2706
+ var ActivatedBySchema = z6.enum(ACTIVATED_BY);
2707
+ var CloudUserSchema = z6.object({
2566
2708
  /** The handle: what hosts file boxes under (`<username>@<control plane>`). Lowercase, no `@` or `/`. */
2567
- username: z5.string(),
2709
+ username: z6.string(),
2568
2710
  /** Display name, free text ("Alexandru Ghiura"). */
2569
- name: z5.string(),
2711
+ name: z6.string(),
2570
2712
  /** Login identity, unique. */
2571
- email: z5.string(),
2572
- role: z5.enum(["admin", "user"]),
2573
- createdAt: z5.string(),
2713
+ email: z6.string(),
2714
+ role: z6.enum(["admin", "user"]),
2715
+ createdAt: z6.string(),
2574
2716
  /**
2575
2717
  * False until a card is on file or an admin activates the account (#74): then only `/me` and
2576
2718
  * `/logout` answer. Admins are never gated. A control plane older than #74 does not send these and
2577
2719
  * gates nobody, hence the defaults: a newer CLI must still parse its answers.
2578
2720
  */
2579
- active: z5.boolean().default(true),
2721
+ active: z6.boolean().default(true),
2580
2722
  activatedBy: ActivatedBySchema.nullable().default(null),
2581
2723
  /** When too many wrong passwords locked the account (#161); null when it is not locked. Older control planes omit it. */
2582
- lockedAt: z5.string().nullable().default(null)
2724
+ lockedAt: z6.string().nullable().default(null)
2583
2725
  });
2584
2726
  var ORG_ROLES = ["owner", "admin", "member"];
2585
- var OrgRoleSchema = z5.enum(ORG_ROLES);
2586
- var CloudOrgSchema = z5.object({
2587
- slug: z5.string(),
2727
+ var OrgRoleSchema = z6.enum(ORG_ROLES);
2728
+ var CloudOrgSchema = z6.object({
2729
+ slug: z6.string(),
2588
2730
  /** Display name; the slug never changes, this may. */
2589
- name: z5.string(),
2590
- createdAt: z5.string(),
2731
+ name: z6.string(),
2732
+ createdAt: z6.string(),
2591
2733
  /** 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. */
2592
- active: z5.boolean().default(true),
2734
+ active: z6.boolean().default(true),
2593
2735
  activatedBy: ActivatedBySchema.nullable().default(null)
2594
2736
  });
2595
2737
  var OrgMembershipSchema = CloudOrgSchema.extend({ role: OrgRoleSchema });
2596
- var OrgMemberSchema = z5.object({
2597
- username: z5.string(),
2598
- name: z5.string(),
2738
+ var OrgMemberSchema = z6.object({
2739
+ username: z6.string(),
2740
+ name: z6.string(),
2599
2741
  role: OrgRoleSchema,
2600
- addedAt: z5.string()
2742
+ addedAt: z6.string()
2601
2743
  });
2602
- var OrgDetailSchema = CloudOrgSchema.extend({ members: z5.array(OrgMemberSchema) });
2603
- var CreateOrgRequestSchema = z5.object({
2604
- slug: z5.string().min(1),
2605
- name: z5.string().min(1)
2744
+ var OrgDetailSchema = CloudOrgSchema.extend({ members: z6.array(OrgMemberSchema) });
2745
+ var CreateOrgRequestSchema = z6.object({
2746
+ slug: z6.string().min(1),
2747
+ name: z6.string().min(1)
2606
2748
  });
2607
- var RenameOrgRequestSchema = z5.object({ name: z5.string().min(1) });
2608
- var AddMemberRequestSchema = z5.object({
2609
- username: z5.string().min(1),
2749
+ var RenameOrgRequestSchema = z6.object({ name: z6.string().min(1) });
2750
+ var AddMemberRequestSchema = z6.object({
2751
+ username: z6.string().min(1),
2610
2752
  role: OrgRoleSchema.default("member")
2611
2753
  });
2612
- var SetRoleRequestSchema = z5.object({ role: OrgRoleSchema });
2613
- var MeResponseSchema = CloudUserSchema.extend({ orgs: z5.array(OrgMembershipSchema) });
2614
- var BalanceSchema = z5.object({
2615
- slug: z5.string(),
2616
- balance: z5.number(),
2617
- currency: z5.string(),
2618
- topUps: z5.number(),
2619
- spent: z5.number(),
2754
+ var SetRoleRequestSchema = z6.object({ role: OrgRoleSchema });
2755
+ var MeResponseSchema = CloudUserSchema.extend({ orgs: z6.array(OrgMembershipSchema) });
2756
+ var BalanceSchema = z6.object({
2757
+ slug: z6.string(),
2758
+ balance: z6.number(),
2759
+ currency: z6.string(),
2760
+ topUps: z6.number(),
2761
+ spent: z6.number(),
2620
2762
  /** The first moment usage counts from: the slug's first top-up or redeemed code; null when it has none. */
2621
- since: z5.string().nullable(),
2763
+ since: z6.string().nullable(),
2622
2764
  /** 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. */
2623
- suspendedAt: z5.string().nullable().default(null),
2765
+ suspendedAt: z6.string().nullable().default(null),
2624
2766
  /** Promo credit left (#163), already counted in `balance`; 0 with none. Absent from a control plane older than this field. */
2625
- promo: z5.number().default(0),
2767
+ promo: z6.number().default(0),
2626
2768
  /** When the next promo credit expires; null with none left. */
2627
- promoExpiresAt: z5.string().nullable().default(null)
2769
+ promoExpiresAt: z6.string().nullable().default(null)
2628
2770
  });
2629
- var TopUpRequestSchema = z5.object({
2630
- slug: z5.string().min(1),
2771
+ var TopUpRequestSchema = z6.object({
2772
+ slug: z6.string().min(1),
2631
2773
  /** In the control plane's currency; negative corrects a mistake. */
2632
- amount: z5.number().finite(),
2633
- note: z5.string().max(200).optional()
2634
- });
2635
- var TopUpSchema = z5.object({
2636
- id: z5.string(),
2637
- slug: z5.string(),
2638
- amount: z5.number(),
2639
- currency: z5.string(),
2774
+ amount: z6.number().finite(),
2775
+ note: z6.string().max(200).optional()
2776
+ });
2777
+ var TopUpSchema = z6.object({
2778
+ id: z6.string(),
2779
+ slug: z6.string(),
2780
+ amount: z6.number(),
2781
+ currency: z6.string(),
2640
2782
  /** `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. */
2641
- source: z5.enum(["admin", "card", "trial", "transfer"]),
2642
- note: z5.string().nullable(),
2643
- at: z5.string()
2783
+ source: z6.enum(["admin", "card", "trial", "transfer"]),
2784
+ note: z6.string().nullable(),
2785
+ at: z6.string()
2644
2786
  });
2645
- var CreateCodeRequestSchema = z5.object({
2787
+ var CreateCodeRequestSchema = z6.object({
2646
2788
  /** In the control plane's currency, cents at most. */
2647
- amount: z5.number().positive().multipleOf(0.01, "amount is in cents at most"),
2789
+ amount: z6.number().positive().multipleOf(0.01, "amount is in cents at most"),
2648
2790
  /** 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. */
2649
- expiresAt: z5.string().min(1),
2650
- note: z5.string().max(200).optional()
2651
- });
2652
- var CreditCodeSchema = z5.object({
2653
- code: z5.string(),
2654
- amount: z5.number(),
2655
- currency: z5.string(),
2656
- expiresAt: z5.string(),
2657
- note: z5.string().nullable(),
2658
- status: z5.enum(["unused", "redeemed", "expired", "revoked"]),
2659
- createdBy: z5.string(),
2660
- createdAt: z5.string(),
2791
+ expiresAt: z6.string().min(1),
2792
+ note: z6.string().max(200).optional()
2793
+ });
2794
+ var CreditCodeSchema = z6.object({
2795
+ code: z6.string(),
2796
+ amount: z6.number(),
2797
+ currency: z6.string(),
2798
+ expiresAt: z6.string(),
2799
+ note: z6.string().nullable(),
2800
+ status: z6.enum(["unused", "redeemed", "expired", "revoked"]),
2801
+ createdBy: z6.string(),
2802
+ createdAt: z6.string(),
2661
2803
  /** Who redeemed it and the slug the credit went to (their own, or an org they own). */
2662
- redeemedBy: z5.string().nullable(),
2663
- redeemedSlug: z5.string().nullable(),
2664
- redeemedAt: z5.string().nullable(),
2665
- revokedAt: z5.string().nullable()
2666
- });
2667
- var RedeemRequestSchema = z5.object({
2668
- code: z5.string().min(1).max(64),
2669
- org: z5.string().min(1).optional()
2670
- });
2671
- var RedeemResponseSchema = z5.object({
2672
- slug: z5.string(),
2673
- amount: z5.number(),
2674
- currency: z5.string(),
2675
- expiresAt: z5.string(),
2804
+ redeemedBy: z6.string().nullable(),
2805
+ redeemedSlug: z6.string().nullable(),
2806
+ redeemedAt: z6.string().nullable(),
2807
+ revokedAt: z6.string().nullable()
2808
+ });
2809
+ var RedeemRequestSchema = z6.object({
2810
+ code: z6.string().min(1).max(64),
2811
+ org: z6.string().min(1).optional()
2812
+ });
2813
+ var RedeemResponseSchema = z6.object({
2814
+ slug: z6.string(),
2815
+ amount: z6.number(),
2816
+ currency: z6.string(),
2817
+ expiresAt: z6.string(),
2676
2818
  balance: BalanceSchema,
2677
2819
  /** The slug was out of credit and this put it back above zero: it may start boxes again. */
2678
- reinstated: z5.boolean()
2820
+ reinstated: z6.boolean()
2679
2821
  });
2680
2822
  var TOP_UP_AMOUNTS = [10, 25, 50, 100];
2681
- var BillingInfoSchema = z5.object({
2682
- card: z5.object({ brand: z5.string(), last4: z5.string() }).nullable(),
2683
- cardInUse: z5.boolean(),
2823
+ var BillingInfoSchema = z6.object({
2824
+ card: z6.object({ brand: z6.string(), last4: z6.string() }).nullable(),
2825
+ cardInUse: z6.boolean(),
2684
2826
  balance: BalanceSchema
2685
2827
  });
2686
- var BillingRedirectSchema = z5.object({ url: z5.string() });
2687
- var TopUpCheckoutRequestSchema = z5.object({
2688
- amount: z5.literal(TOP_UP_AMOUNTS)
2828
+ var BillingRedirectSchema = z6.object({ url: z6.string() });
2829
+ var TopUpCheckoutRequestSchema = z6.object({
2830
+ amount: z6.literal(TOP_UP_AMOUNTS)
2689
2831
  });
2690
- var TransferRequestSchema = z5.object({
2691
- org: z5.string().min(1),
2692
- amount: z5.number().positive().multipleOf(0.01, "amount is in cents at most")
2832
+ var TransferRequestSchema = z6.object({
2833
+ org: z6.string().min(1),
2834
+ amount: z6.number().positive().multipleOf(0.01, "amount is in cents at most")
2693
2835
  });
2694
- var TransferResponseSchema = z5.object({ from: BalanceSchema, to: BalanceSchema, activated: z5.boolean() });
2695
- var LoginRequestSchema = z5.object({
2696
- email: z5.string().min(1),
2697
- password: z5.string().min(1),
2698
- publicKey: z5.string().optional()
2836
+ var TransferResponseSchema = z6.object({ from: BalanceSchema, to: BalanceSchema, activated: z6.boolean() });
2837
+ var LoginRequestSchema = z6.object({
2838
+ email: z6.string().min(1),
2839
+ password: z6.string().min(1),
2840
+ publicKey: z6.string().optional()
2699
2841
  });
2700
- var SignupRequestSchema = z5.object({
2701
- username: z5.string().min(1),
2702
- name: z5.string().min(1),
2703
- email: z5.string().min(1),
2704
- password: z5.string().min(1)
2842
+ var SignupRequestSchema = z6.object({
2843
+ username: z6.string().min(1),
2844
+ name: z6.string().min(1),
2845
+ email: z6.string().min(1),
2846
+ password: z6.string().min(1)
2705
2847
  });
2706
- var LoginResponseSchema = z5.object({
2707
- token: z5.string(),
2848
+ var LoginResponseSchema = z6.object({
2849
+ token: z6.string(),
2708
2850
  user: CloudUserSchema,
2709
- sshCert: z5.string().optional(),
2710
- sshCertExpires: z5.string().optional(),
2851
+ sshCert: z6.string().optional(),
2852
+ sshCertExpires: z6.string().optional(),
2711
2853
  /** Whose boxes the certificate opens: `<slug>@<realm>` for the user and each org they are in (orgs phase 4). */
2712
- sshCertPrincipals: z5.array(z5.string()).optional()
2854
+ sshCertPrincipals: z6.array(z6.string()).optional()
2713
2855
  });
2714
- var DeviceLoginRequestSchema = z5.object({
2856
+ var DeviceLoginRequestSchema = z6.object({
2715
2857
  // Capped: anyone may open a login, and the key is stored until it expires (an RSA-16384 key is ~2.8 KB).
2716
- publicKey: z5.string().max(16384).optional(),
2717
- hostname: z5.string().max(255).optional()
2718
- });
2719
- var DeviceLoginStartSchema = z5.object({
2720
- deviceCode: z5.string(),
2721
- userCode: z5.string(),
2722
- verifyUrl: z5.string(),
2723
- expiresIn: z5.number(),
2724
- interval: z5.number()
2725
- });
2726
- var DeviceLoginPollRequestSchema = z5.object({ deviceCode: z5.string().min(1) });
2727
- var DeviceLoginPollSchema = z5.union([
2728
- z5.object({ status: z5.enum(["pending", "slow_down", "refused", "expired"]) }),
2729
- LoginResponseSchema.extend({ status: z5.literal("approved") })
2858
+ publicKey: z6.string().max(16384).optional(),
2859
+ hostname: z6.string().max(255).optional()
2860
+ });
2861
+ var DeviceLoginStartSchema = z6.object({
2862
+ deviceCode: z6.string(),
2863
+ userCode: z6.string(),
2864
+ verifyUrl: z6.string(),
2865
+ expiresIn: z6.number(),
2866
+ interval: z6.number()
2867
+ });
2868
+ var DeviceLoginPollRequestSchema = z6.object({ deviceCode: z6.string().min(1) });
2869
+ var DeviceLoginPollSchema = z6.union([
2870
+ z6.object({ status: z6.enum(["pending", "slow_down", "refused", "expired"]) }),
2871
+ LoginResponseSchema.extend({ status: z6.literal("approved") })
2730
2872
  ]);
2731
- var DeviceLoginInfoSchema = z5.object({
2732
- userCode: z5.string(),
2733
- hostname: z5.string(),
2873
+ var DeviceLoginInfoSchema = z6.object({
2874
+ userCode: z6.string(),
2875
+ hostname: z6.string(),
2734
2876
  /** The address the request came from; null when the control plane could not tell. */
2735
- ip: z5.string().nullable(),
2736
- createdAt: z5.string(),
2737
- expiresAt: z5.string()
2877
+ ip: z6.string().nullable(),
2878
+ createdAt: z6.string(),
2879
+ expiresAt: z6.string()
2738
2880
  });
2739
2881
  var API_KEY_NAME_RE = /^[a-z0-9][a-z0-9._-]{0,31}$/;
2740
- var ApiKeySchema = z5.object({
2741
- name: z5.string(),
2742
- createdAt: z5.string(),
2882
+ var ApiKeySchema = z6.object({
2883
+ name: z6.string(),
2884
+ createdAt: z6.string(),
2743
2885
  /** Last request made with it (ISO); null: never used. */
2744
- lastUsedAt: z5.string().nullable(),
2886
+ lastUsedAt: z6.string().nullable(),
2745
2887
  /** When it stops working (ISO); null: never. */
2746
- expiresAt: z5.string().nullable()
2888
+ expiresAt: z6.string().nullable()
2747
2889
  });
2748
- var CreateApiKeyRequestSchema = z5.object({
2749
- name: z5.string().regex(API_KEY_NAME_RE, "a key's name is lowercase letters, digits, '.', '_' or '-' (up to 32 characters)"),
2750
- expiresAt: z5.iso.datetime({ offset: true }).nullable().optional()
2890
+ var CreateApiKeyRequestSchema = z6.object({
2891
+ name: z6.string().regex(API_KEY_NAME_RE, "a key's name is lowercase letters, digits, '.', '_' or '-' (up to 32 characters)"),
2892
+ expiresAt: z6.iso.datetime({ offset: true }).nullable().optional()
2751
2893
  });
2752
- var CreatedApiKeySchema = ApiKeySchema.extend({ key: z5.string() });
2753
- var SshCertRequestSchema = z5.object({
2754
- publicKey: z5.string().min(1)
2894
+ var CreatedApiKeySchema = ApiKeySchema.extend({ key: z6.string() });
2895
+ var SshCertRequestSchema = z6.object({
2896
+ publicKey: z6.string().min(1)
2755
2897
  });
2756
- var SshCertResponseSchema = z5.object({
2757
- cert: z5.string(),
2758
- expires: z5.string(),
2759
- principals: z5.array(z5.string())
2898
+ var SshCertResponseSchema = z6.object({
2899
+ cert: z6.string(),
2900
+ expires: z6.string(),
2901
+ principals: z6.array(z6.string())
2760
2902
  });
2761
- var SshCaResponseSchema = z5.object({
2762
- publicKey: z5.string(),
2903
+ var SshCaResponseSchema = z6.object({
2904
+ publicKey: z6.string(),
2763
2905
  /** 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. */
2764
- retired: z5.array(z5.object({ publicKey: z5.string(), retiredAt: z5.string() })).optional()
2906
+ retired: z6.array(z6.object({ publicKey: z6.string(), retiredAt: z6.string() })).optional()
2765
2907
  });
2766
- var HostSshCaResponseSchema = z5.object({
2767
- publicKey: z5.string()
2908
+ var HostSshCaResponseSchema = z6.object({
2909
+ publicKey: z6.string()
2768
2910
  });
2769
- var CloudCaSchema = z5.object({
2770
- controlPlane: z5.string(),
2771
- publicKey: z5.string(),
2772
- fingerprint: z5.string()
2911
+ var CloudCaSchema = z6.object({
2912
+ controlPlane: z6.string(),
2913
+ publicKey: z6.string(),
2914
+ fingerprint: z6.string()
2773
2915
  });
2774
- var TrustCaRequestSchema = z5.object({
2775
- publicKey: z5.string().min(1)
2916
+ var TrustCaRequestSchema = z6.object({
2917
+ publicKey: z6.string().min(1)
2776
2918
  });
2777
- var SshKeysAppliedSchema = z5.enum(["now", "start", "wake", "resume", "later"]);
2778
- var TrustCaReportSchema = z5.object({
2779
- publicKey: z5.string(),
2780
- fingerprint: z5.string(),
2919
+ var SshKeysAppliedSchema = z6.enum(["now", "start", "wake", "resume", "later"]);
2920
+ var TrustCaReportSchema = z6.object({
2921
+ publicKey: z6.string(),
2922
+ fingerprint: z6.string(),
2781
2923
  /** The guest trusts the CA now. */
2782
- updated: z5.array(z5.string()),
2924
+ updated: z6.array(z6.string()),
2783
2925
  /** meta.json has the line; the guest gets it at `when`. */
2784
- pending: z5.array(z5.object({ box: z5.string(), when: SshKeysAppliedSchema, why: z5.string().optional() })),
2785
- failed: z5.array(z5.object({ box: z5.string(), error: z5.string() })),
2926
+ pending: z6.array(z6.object({ box: z6.string(), when: SshKeysAppliedSchema, why: z6.string().optional() })),
2927
+ failed: z6.array(z6.object({ box: z6.string(), error: z6.string() })),
2786
2928
  /** Local boxes, untouched: they trust the host's key only. */
2787
- local: z5.number().int(),
2929
+ local: z6.number().int(),
2788
2930
  /** Cloud boxes made without a CA line (a managed service's, #173), untouched: no certificate opens them. Absent from older servers. */
2789
- skipped: z5.array(z5.string()).optional()
2790
- });
2791
- var HostJoinRequestSchema = z5.object({
2792
- token: z5.string().min(1),
2793
- name: z5.string().min(1),
2794
- url: z5.string().url(),
2795
- fingerprint: z5.string().regex(/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/),
2796
- publicAddress: z5.string().min(1),
2931
+ skipped: z6.array(z6.string()).optional()
2932
+ });
2933
+ var HostJoinRequestSchema = z6.object({
2934
+ token: z6.string().min(1),
2935
+ name: z6.string().min(1),
2936
+ url: z6.string().url(),
2937
+ fingerprint: z6.string().regex(/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/),
2938
+ publicAddress: z6.string().min(1),
2797
2939
  /** Where the host is (`kvbox-server join --country`): a code or an English name. */
2798
- country: z5.string().optional()
2799
- });
2800
- var HostJoinResponseSchema = z5.object({
2801
- hostSecret: z5.string(),
2802
- controlPlane: z5.object({ name: z5.string() })
2803
- });
2804
- var CloudHostSchema = z5.object({
2805
- name: z5.string(),
2806
- url: z5.string(),
2807
- publicAddress: z5.string(),
2808
- joinedAt: z5.string(),
2809
- lastSeenAt: z5.string().nullable(),
2940
+ country: z6.string().optional()
2941
+ });
2942
+ var HostJoinResponseSchema = z6.object({
2943
+ hostSecret: z6.string(),
2944
+ controlPlane: z6.object({ name: z6.string() })
2945
+ });
2946
+ var CloudHostSchema = z6.object({
2947
+ name: z6.string(),
2948
+ url: z6.string(),
2949
+ publicAddress: z6.string(),
2950
+ joinedAt: z6.string(),
2951
+ lastSeenAt: z6.string().nullable(),
2810
2952
  capacity: CapacitySchema.nullable(),
2811
2953
  /** ISO 3166-1 alpha-2 code (`RO`), null when nobody said where the host is. */
2812
- country: z5.string().nullable(),
2954
+ country: z6.string().nullable(),
2813
2955
  /** The S3 region a storage made on this host answers to (`ro-west-1`); null: it takes no storage. */
2814
- region: z5.string().nullable(),
2956
+ region: z6.string().nullable(),
2815
2957
  /** 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. */
2816
- version: z5.string().nullable()
2958
+ version: z6.string().nullable()
2817
2959
  });
2818
- var HostInfoSchema = z5.object({
2960
+ var HostInfoSchema = z6.object({
2819
2961
  host: CloudHostSchema,
2820
2962
  health: HealthSchema.nullable(),
2821
- error: z5.string().nullable()
2963
+ error: z6.string().nullable()
2822
2964
  });
2823
- 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" });
2824
- var CountrySchema = z5.object({ code: z5.string(), name: z5.string() });
2965
+ 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" });
2966
+ var CountrySchema = z6.object({ code: z6.string(), name: z6.string() });
2825
2967
 
2826
2968
  // src/core/locks.ts
2827
2969
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -2851,6 +2993,9 @@ async function withLock(key, fn) {
2851
2993
  if (tails.get(key) === tail) tails.delete(key);
2852
2994
  }
2853
2995
  }
2996
+ function outsideLocks(fn) {
2997
+ return held.exit(fn);
2998
+ }
2854
2999
  function boxBusy(ref) {
2855
3000
  return tails.has(refKey(ref));
2856
3001
  }
@@ -3454,7 +3599,11 @@ async function capacity(p = paths()) {
3454
3599
  // Backups and restores here reach a store by its certificate's pin (core/storeFetch.ts).
3455
3600
  storeClient: true,
3456
3601
  // A new box on a backup's disk (#141): the control plane places `new --from-backup` only here.
3457
- fromBackup: true
3602
+ fromBackup: true,
3603
+ // A box's integrations are kept here (#205): the control plane sends a list only to such a host.
3604
+ integrations: true,
3605
+ // ...and which (the control plane places a box with `claude` only on a host that names it).
3606
+ integrationIds: [...INTEGRATION_IDS]
3458
3607
  };
3459
3608
  }
3460
3609
  function gb(mib) {
@@ -3504,7 +3653,7 @@ async function assertRoomFor(vcpu, memMib, force, box, by, p = paths()) {
3504
3653
  // src/core/env.ts
3505
3654
  import { existsSync as existsSync7 } from "node:fs";
3506
3655
  import { copyFile, mkdir as mkdir4, readFile as readFile7, readdir as readdir4, rename as rename4, writeFile as writeFile5 } from "node:fs/promises";
3507
- import { z as z6 } from "zod";
3656
+ import { z as z7 } from "zod";
3508
3657
 
3509
3658
  // ../shared/src/env.ts
3510
3659
  var ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
@@ -3524,10 +3673,10 @@ function envValueProblem(value) {
3524
3673
  }
3525
3674
 
3526
3675
  // src/core/env.ts
3527
- var OwnerEnvSchema = z6.object({
3676
+ var OwnerEnvSchema = z7.object({
3528
3677
  /** The control plane's counter for the list; only ever grows. */
3529
- version: z6.number().int().min(0),
3530
- vars: z6.array(z6.object({ name: z6.string(), value: z6.string() }))
3678
+ version: z7.number().int().min(0),
3679
+ vars: z7.array(z7.object({ name: z7.string(), value: z7.string() }))
3531
3680
  });
3532
3681
  async function readOwnerEnv(owner, p = paths()) {
3533
3682
  try {
@@ -3548,8 +3697,8 @@ async function envForBoot(box, p = paths()) {
3548
3697
  const mine = new Set(own.map((v) => v.name));
3549
3698
  return [...(slug ?? []).filter((v) => !mine.has(v.name)), ...own.map((v) => ({ name: v.name, value: v.value }))];
3550
3699
  }
3551
- var BoxEnvFileSchema = z6.object({
3552
- vars: z6.array(z6.object({ name: z6.string(), value: z6.string(), secret: z6.boolean(), updatedAt: z6.string() }))
3700
+ var BoxEnvFileSchema = z7.object({
3701
+ vars: z7.array(z7.object({ name: z7.string(), value: z7.string(), secret: z7.boolean(), updatedAt: z7.string() }))
3553
3702
  });
3554
3703
  async function readBoxEnv(box, p = paths()) {
3555
3704
  return readBoxEnvFile(p.machine(box.owner, box.name).env);
@@ -3766,81 +3915,7 @@ function recordState(meta, state, by, p, at = (/* @__PURE__ */ new Date()).toISO
3766
3915
  }
3767
3916
  }
3768
3917
 
3769
- // src/core/machines/status.ts
3770
- import { existsSync as existsSync9 } from "node:fs";
3771
- function isHibernated(meta, p) {
3772
- return !vmAlive(meta) && existsSync9(p.machine(meta.owner, meta.name).hibernateVmstate);
3773
- }
3774
- function statusOf(meta, p = paths()) {
3775
- if (vmAlive(meta)) return meta.paused ? "standby" : "running";
3776
- return isHibernated(meta, p) ? "hibernated" : "stopped";
3777
- }
3778
- function stateMessage(ref, status) {
3779
- return `box ${shown(ref)} is ${status === "standby" ? "in standby" : status}`;
3780
- }
3781
- function assertNotHibernated(meta, p) {
3782
- if (isHibernated(meta, p)) {
3783
- throw new KvboxError(`${stateMessage(meta, "hibernated")}; its memory image was made with its current shape and base: kvbox wake ${shown(meta)} first`);
3784
- }
3785
- }
3786
-
3787
- // src/core/machines/list.ts
3788
- function toMachine(meta, p = paths()) {
3789
- const alive2 = vmAlive(meta);
3790
- if (!alive2 && meta.pid !== null) {
3791
- try {
3792
- closeOpenRun(meta.id, (/* @__PURE__ */ new Date()).toISOString(), p);
3793
- } catch (err) {
3794
- log.warn(`usage ledger: ${err.message}`);
3795
- }
3796
- }
3797
- return {
3798
- id: meta.id,
3799
- name: meta.name,
3800
- owner: meta.owner,
3801
- ip: meta.ip,
3802
- mac: meta.mac,
3803
- pid: alive2 ? meta.pid : null,
3804
- vcpu: meta.vcpu,
3805
- memMib: meta.memMib,
3806
- ...diskStats(p.machine(meta.owner, meta.name).overlay),
3807
- base: meta.base,
3808
- ...meta.image !== void 0 ? { image: meta.image } : {},
3809
- ...meta.url !== void 0 ? { url: urlFor(meta.url, meta.name) } : {},
3810
- createdAt: meta.createdAt,
3811
- source: meta.source,
3812
- status: statusOf(meta, p),
3813
- ...meta.sshPort === void 0 ? {} : { sshPort: meta.sshPort },
3814
- ...meta.ports?.length ? { ports: meta.ports.map((f) => ({ ...f })) } : {},
3815
- ...meta.autoHibernateSec ? { autoHibernateSec: meta.autoHibernateSec } : {},
3816
- ...meta.idleCheck !== void 0 ? { idleCheck: meta.idleCheck } : {},
3817
- ...meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {},
3818
- ...meta.links?.some((l) => !l.stale) ? { links: meta.links.filter((l) => !l.stale).map((l) => ({ from: linkFrom(l, meta.owner), port: l.port })) } : {}
3819
- };
3820
- }
3821
- var linkFrom = (l, owner) => l.owner === owner ? l.name : `${l.owner.split("@")[0]}/${l.name}`;
3822
- async function listMachines(scope, p = paths()) {
3823
- return (await readAllMeta(p)).filter((m) => inScope(m.owner, scope)).map((m) => toMachine(m, p));
3824
- }
3825
- async function getMachine(ref, p = paths()) {
3826
- return toMachine(await readMeta(ref, p), p);
3827
- }
3828
-
3829
- // src/core/machines/boot.ts
3830
- async function launch(spec, nic, cfg, pubkeyB64, p) {
3831
- const root = imageFileFor(spec, p);
3832
- const kernel = kernelFor(await imageManifest(root), cfg, p);
3833
- const volumes = (await placeVolumeDrives(spec, p)).map((v) => ({ id: volumeDriveId(v.name), path: volumeDriveRel(v.name) }));
3834
- return driver().vm.boot(spec, { kernel, root, volumes, pubkeyB64 }, nic, cfg, p);
3835
- }
3836
- async function loadSnapshot(spec, image, nic, cfg, p) {
3837
- return driver().vm.restore(spec, { vmstate: image.vmstate, mem: image.mem }, nic, cfg, p);
3838
- }
3839
- async function resumeVm(box, p) {
3840
- await driver().vm.resume(box, p);
3841
- }
3842
-
3843
- // src/core/machines/guest.ts
3918
+ // src/core/machines/integrations.ts
3844
3919
  import { setTimeout as sleep3 } from "node:timers/promises";
3845
3920
 
3846
3921
  // src/core/agent.ts
@@ -3913,47 +3988,432 @@ async function idle(udsPath, script, timeoutMs = 15e3) {
3913
3988
  async function runScript(udsPath, path, input, timeoutMs = 35e3) {
3914
3989
  return (await agentCall(udsPath, { op: "script", path, input: input ?? null }, timeoutMs))["output"];
3915
3990
  }
3916
- async function startRun(udsPath, id, command, timeoutSec, timeoutMs = 15e3) {
3917
- return (await agentCall(udsPath, { op: "run", id, command, timeoutSec }, timeoutMs))["started"] === true;
3991
+ async function setIntegrations(udsPath, list, identity, timeoutMs) {
3992
+ const reply = await agentCall(udsPath, { op: "integrations", list: [...list], ...identity ? { identity } : {} }, timeoutMs);
3993
+ const known = reply["known"];
3994
+ return { known: Array.isArray(known) ? known.filter((n) => typeof n === "string") : ["github"] };
3995
+ }
3996
+ async function startRun(udsPath, id, command, timeoutSec, timeoutMs = 15e3) {
3997
+ return (await agentCall(udsPath, { op: "run", id, command, timeoutSec }, timeoutMs))["started"] === true;
3998
+ }
3999
+ async function runStatus(udsPath, id, timeoutMs) {
4000
+ const reply = await agentCall(udsPath, { op: "runStatus", id }, timeoutMs);
4001
+ const state = reply["state"];
4002
+ if (state !== "running" && state !== "exited" && state !== "timeout" && state !== "unknown") throw new KvboxError("kvbox-agent sent a run state this server does not know");
4003
+ const durationMs = reply["durationMs"];
4004
+ return {
4005
+ state,
4006
+ ...typeof reply["exitCode"] === "number" ? { exitCode: reply["exitCode"] } : {},
4007
+ ...typeof durationMs === "number" && Number.isInteger(durationMs) && durationMs >= 0 ? { durationMs } : {}
4008
+ };
4009
+ }
4010
+ async function runOutput(udsPath, id, stream, offset, limit, timeoutMs = 15e3) {
4011
+ const reply = await agentCall(udsPath, { op: "runOutput", id, stream, offset, limit }, timeoutMs);
4012
+ const { size: size2, data } = reply;
4013
+ 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");
4014
+ return { size: size2, offset, data };
4015
+ }
4016
+ var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
4017
+ var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
4018
+ 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 ?? "");
4019
+
4020
+ // src/core/credentials.ts
4021
+ import { request as request3 } from "undici";
4022
+ var TIMEOUT_MS = 1e4;
4023
+ var PROBE_KEPT_MS = 6e4;
4024
+ var unavailable = (message) => ({ ok: false, code: "unavailable", message });
4025
+ async function ask(cp, body) {
4026
+ const res = await request3(`${cp.url}/hosts/self/integrations/credential`, {
4027
+ method: "POST",
4028
+ headers: { authorization: `Bearer ${cp.secret}`, "content-type": "application/json" },
4029
+ body: JSON.stringify(body),
4030
+ headersTimeout: TIMEOUT_MS,
4031
+ bodyTimeout: TIMEOUT_MS
4032
+ });
4033
+ const text = await res.body.text();
4034
+ try {
4035
+ return { status: res.statusCode, json: JSON.parse(text) };
4036
+ } catch {
4037
+ return { status: res.statusCode, json: null };
4038
+ }
4039
+ }
4040
+ async function askCredential(cp, box, integration) {
4041
+ let answer;
4042
+ try {
4043
+ answer = await ask(cp, { owner: box.owner, box: box.name, integration });
4044
+ } catch (err) {
4045
+ return unavailable(`${cp.name} could not be reached (${err.message}); try again shortly`);
4046
+ }
4047
+ if (answer.status === 404) return unavailable(`${cp.name} has no integrations yet`);
4048
+ const parsed = CredentialAnswerSchema.safeParse(answer.json);
4049
+ if (!parsed.success) return unavailable(`${cp.name} answered ${answer.status}; try again shortly`);
4050
+ return parsed.data;
4051
+ }
4052
+ var probes = /* @__PURE__ */ new Map();
4053
+ async function probeConnection(cp, box, integration, now = Date.now()) {
4054
+ const key = `${box.owner}/${box.name}/${integration}`;
4055
+ const kept = probes.get(key);
4056
+ if (kept && now - kept.at < PROBE_KEPT_MS) return kept.answer;
4057
+ try {
4058
+ const parsed = ConnectedAnswerSchema.safeParse((await ask(cp, { owner: box.owner, box: box.name, integration, probe: true })).json);
4059
+ if (!parsed.success) return null;
4060
+ probes.set(key, { at: now, answer: parsed.data });
4061
+ if (probes.size > 5e3) {
4062
+ for (const [k, v] of probes) if (now - v.at >= PROBE_KEPT_MS) probes.delete(k);
4063
+ }
4064
+ return parsed.data;
4065
+ } catch {
4066
+ return null;
4067
+ }
4068
+ }
4069
+
4070
+ // src/core/guestRequests.ts
4071
+ import { rm as rm5 } from "node:fs/promises";
4072
+ import { createServer } from "node:net";
4073
+ var MAX_REQUEST_BYTES = 4096;
4074
+ var REQUEST_TIMEOUT_MS = 5e3;
4075
+ var MAX_OPEN = 32;
4076
+ var listeners = /* @__PURE__ */ new Map();
4077
+ var unreadable = (message) => ({ ok: false, code: "unavailable", message });
4078
+ function serve(sock, answer, timeoutMs) {
4079
+ let buf = "";
4080
+ let taken = false;
4081
+ const reply = (body) => {
4082
+ if (!sock.destroyed) sock.end(JSON.stringify(body) + "\n");
4083
+ };
4084
+ const late = setTimeout(() => sock.destroy(), timeoutMs);
4085
+ late.unref();
4086
+ sock.once("close", () => clearTimeout(late));
4087
+ sock.on("error", () => void 0);
4088
+ sock.on("data", (chunk) => {
4089
+ if (taken) return;
4090
+ buf += chunk.toString("utf8");
4091
+ const nl = buf.indexOf("\n");
4092
+ if (nl === -1) {
4093
+ if (buf.length > MAX_REQUEST_BYTES) sock.destroy();
4094
+ return;
4095
+ }
4096
+ taken = true;
4097
+ clearTimeout(late);
4098
+ let request7;
4099
+ try {
4100
+ request7 = JSON.parse(buf.slice(0, nl));
4101
+ } catch {
4102
+ return reply(unreadable("the request is not JSON"));
4103
+ }
4104
+ answer(request7).then(reply, (err) => reply(unreadable(err.message)));
4105
+ });
4106
+ }
4107
+ async function listenGuest(path, answer, timeoutMs = REQUEST_TIMEOUT_MS) {
4108
+ await closeGuest(path);
4109
+ await rm5(path, { force: true });
4110
+ const open3 = /* @__PURE__ */ new Set();
4111
+ const server = createServer((sock) => {
4112
+ open3.add(sock);
4113
+ sock.once("close", () => open3.delete(sock));
4114
+ serve(sock, answer, timeoutMs);
4115
+ });
4116
+ server.maxConnections = MAX_OPEN;
4117
+ await new Promise((resolve3, reject) => {
4118
+ server.once("error", reject);
4119
+ server.listen(path, () => {
4120
+ server.off("error", reject);
4121
+ resolve3();
4122
+ });
4123
+ });
4124
+ server.unref();
4125
+ server.on("error", () => void 0);
4126
+ listeners.set(path, { server, open: open3 });
4127
+ }
4128
+ async function closeGuest(path) {
4129
+ const l = listeners.get(path);
4130
+ if (!l) return;
4131
+ listeners.delete(path);
4132
+ for (const sock of l.open) sock.destroy();
4133
+ await new Promise((resolve3) => l.server.close(() => resolve3()));
4134
+ await rm5(path, { force: true });
4135
+ }
4136
+ var guestListening = (path) => listeners.has(path);
4137
+
4138
+ // src/core/machines/integrations.ts
4139
+ var AGENT_REPLY_MS = 2e4;
4140
+ function socketOf(box, p) {
4141
+ try {
4142
+ return driver().vm.guestSocket(box, GUEST_REQUEST_PORT, p);
4143
+ } catch (err) {
4144
+ if (err instanceof NotImplementedError) return void 0;
4145
+ throw err;
4146
+ }
4147
+ }
4148
+ async function listenForGuest(box, p) {
4149
+ const ref = { owner: box.owner, name: box.name };
4150
+ try {
4151
+ const path = socketOf(box, p);
4152
+ if (path !== void 0) await listenGuest(path, (request7) => answerGuest(ref, request7, p));
4153
+ } catch (err) {
4154
+ log.warn(`box ${shown(ref)}: integrations will not answer in it: ${err.message}`);
4155
+ }
4156
+ }
4157
+ async function stopListeningForGuest(box, p) {
4158
+ try {
4159
+ const path = socketOf(box, p);
4160
+ if (path !== void 0) await closeGuest(path);
4161
+ } catch {
4162
+ }
4163
+ }
4164
+ async function listenForRunning(p) {
4165
+ for (const listed of await readAllMeta(p)) {
4166
+ if (!vmAlive(listed)) continue;
4167
+ await withBoxLock(listed, async () => {
4168
+ const meta = await readMachineMeta(listed, p).catch(() => null);
4169
+ if (meta !== null && vmAlive(meta)) await listenForGuest(meta, p);
4170
+ });
4171
+ }
4172
+ }
4173
+ async function closeDeadListeners(p) {
4174
+ for (const meta of await readAllMeta(p)) {
4175
+ if (vmAlive(meta)) continue;
4176
+ const path = socketOf(meta, p);
4177
+ if (path === void 0 || !guestListening(path)) continue;
4178
+ await withBoxLock(meta, async () => {
4179
+ const now = await readMachineMeta(meta, p).catch(() => null);
4180
+ if (now === null || !vmAlive(now)) await stopListeningForGuest(meta, p);
4181
+ });
4182
+ }
4183
+ }
4184
+ function forgetGuest(box) {
4185
+ asked.delete(refKey(box));
4186
+ told.delete(box.id);
4187
+ }
4188
+ var refusal = (code, message, connected) => ({ ok: false, code, message, ...connected === void 0 ? {} : { connected } });
4189
+ var asked = /* @__PURE__ */ new Map();
4190
+ function withinLimit(box, now) {
4191
+ const w = asked.get(box);
4192
+ if (!w || now - w.since >= 6e4) {
4193
+ asked.set(box, { since: now, count: 1 });
4194
+ return true;
4195
+ }
4196
+ w.count += 1;
4197
+ return w.count <= GUEST_REQUESTS_PER_MINUTE;
4198
+ }
4199
+ async function answerGuest(ref, request7, p, now = Date.now()) {
4200
+ if (!withinLimit(refKey(ref), now)) return refusal("unavailable", `this box asked more than ${GUEST_REQUESTS_PER_MINUTE} times in a minute; try again shortly`);
4201
+ const parsed = GuestRequestSchema.safeParse(request7);
4202
+ if (!parsed.success) return refusal("unavailable", "this host does not know that request; it may need updating");
4203
+ const integration = parsed.data.integration;
4204
+ let meta;
4205
+ try {
4206
+ meta = await readMachineMeta(ref, p);
4207
+ } catch {
4208
+ return refusal("unavailable", "this box is being removed");
4209
+ }
4210
+ const cp = (await loadConfig(p)).controlPlane;
4211
+ if (!cp || !isCloudBox(meta.owner)) return refusal("unavailable", "integrations are not available in a box made on the host itself");
4212
+ if (!(meta.integrations ?? []).includes(integration)) {
4213
+ const probe = await probeConnection(cp, meta, integration, now);
4214
+ return refusal("off", `${integration} is not turned on for this box`, probe?.connected);
4215
+ }
4216
+ const answer = await askCredential(cp, meta, integration);
4217
+ if (answer.ok && answer.identity && !(told.has(meta.id) && sameIdentity(told.get(meta.id), answer.identity))) {
4218
+ void tellCurrent(ref, p.machine(meta.owner, meta.name).vsock, p, answer.identity).catch(() => void 0);
4219
+ }
4220
+ return answer;
4221
+ }
4222
+ var told = /* @__PURE__ */ new Map();
4223
+ var sameIdentity = (a, b) => a?.name === b?.name && a?.email === b?.email;
4224
+ async function tellGuest(box, vsock, identity) {
4225
+ const { known } = await setIntegrations(vsock, box.integrations ?? [], identity, AGENT_REPLY_MS);
4226
+ told.set(box.id, identity);
4227
+ return (box.integrations ?? []).filter((n) => !known.includes(n));
4228
+ }
4229
+ var tooOldFor = (box, names2) => `its image is from before base v${names2.map((n) => INTEGRATION_BASES[n] ?? INTEGRATIONS_BASE).sort().at(-1)}, which cannot use ${names2.join(", ")} (kvbox vm update ${shown(box)} moves it onto the current one)`;
4230
+ async function identityOf(box, p) {
4231
+ if (!(box.integrations ?? []).includes("github")) return void 0;
4232
+ const cp = (await loadConfig(p)).controlPlane;
4233
+ if (!cp) return void 0;
4234
+ const probe = await probeConnection(cp, box, "github");
4235
+ if (probe !== null) return probe.identity;
4236
+ return told.has(box.id) ? told.get(box.id) : null;
4237
+ }
4238
+ var sameList = (a, b) => JSON.stringify(a ?? []) === JSON.stringify(b ?? []);
4239
+ async function tellCurrent(ref, vsock, p, identity) {
4240
+ for (; ; ) {
4241
+ const asked2 = await readMachineMeta(ref, p);
4242
+ const who = identity !== void 0 && (asked2.integrations ?? []).includes("github") ? identity : await identityOf(asked2, p);
4243
+ if (who === null) return false;
4244
+ const done = await withBoxLock(ref, async () => {
4245
+ const box = await readMachineMeta(ref, p);
4246
+ if (!sameList(box.integrations, asked2.integrations)) return false;
4247
+ const unusable = await tellGuest(box, vsock, who);
4248
+ if (unusable.length > 0) log.warn(`box ${shown(box)} has integrations it cannot use: ${tooOldFor(box, unusable)}`);
4249
+ return true;
4250
+ });
4251
+ if (done) return true;
4252
+ }
4253
+ }
4254
+ function assertImageCanUse(box, list, before) {
4255
+ if (box.image !== void 0) return;
4256
+ const unusable = unusableOnBase(box.base, (list ?? []).filter((n) => !(before ?? []).includes(n)));
4257
+ if (unusable.length > 0) throw new KvboxError(`box ${shown(box)} cannot use ${unusable.join(", ")} yet: ${tooOldFor(box, unusable)}`);
4258
+ }
4259
+ 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)`;
4260
+ async function applyIntegrations(box, vsock, p, before) {
4261
+ if (!isCloudBox(box.owner)) return;
4262
+ let unusable;
4263
+ try {
4264
+ const prior = told.has(box.id) ? { who: told.get(box.id) } : null;
4265
+ const who = await identityOf(box, p);
4266
+ unusable = await tellGuest(box, vsock, who ?? void 0);
4267
+ let unsure = who === null;
4268
+ if (unusable.length > 0) {
4269
+ if (prior) told.set(box.id, prior.who);
4270
+ else told.delete(box.id);
4271
+ const kept = { ...box, integrations: before && before.length > 0 ? [...before] : void 0 };
4272
+ const keptWho = await identityOf(kept, p);
4273
+ unsure = keptWho === null;
4274
+ await tellGuest(kept, vsock, keptWho ?? void 0).catch(() => unsure = true);
4275
+ }
4276
+ if (unsure) {
4277
+ told.delete(box.id);
4278
+ if (box.pid !== null) void tellIntegrationsWhenUp(box, box.pid, vsock, p);
4279
+ }
4280
+ } catch (err) {
4281
+ if (!isUnknownOp(err)) return void log.warn(`box ${shown(box)} was not told its integrations: ${err.message}`);
4282
+ if ((box.integrations ?? []).length > 0) throw new KvboxError(`box ${shown(box)} cannot use integrations yet: ${outdated(box)}`);
4283
+ return;
4284
+ }
4285
+ if (unusable.length > 0) throw new KvboxError(`box ${shown(box)} cannot use ${unusable.join(", ")} yet: ${tooOldFor(box, unusable)}`);
4286
+ }
4287
+ var BOOT_WAIT_MS = 12e4;
4288
+ var WHO_RETRY_MS = 3e3;
4289
+ function tellIntegrationsWhenUp(ref, pid, vsock, p, timing = { waitMs: BOOT_WAIT_MS }) {
4290
+ return outsideLocks(async () => {
4291
+ if (!isCloudBox(ref.owner)) return;
4292
+ const deadline = Date.now() + timing.waitMs;
4293
+ for (; ; ) {
4294
+ if (!pidAlive(pid)) return;
4295
+ try {
4296
+ if (await tellCurrent(ref, vsock, p)) return;
4297
+ 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`);
4298
+ await sleep3(timing.retryMs ?? WHO_RETRY_MS);
4299
+ } catch (err) {
4300
+ if (!pidAlive(pid)) return;
4301
+ if (isNoAgent(err) && Date.now() < deadline) {
4302
+ await sleep3(500);
4303
+ continue;
4304
+ }
4305
+ const box = await readMachineMeta(ref, p).catch(() => null);
4306
+ if (box === null) return;
4307
+ if (!isUnknownOp(err)) log.warn(`box ${shown(ref)} was not told its integrations: ${err.message}`);
4308
+ else if ((box.integrations ?? []).length > 0) log.warn(`box ${shown(ref)} has integrations it cannot use: ${outdated(ref)}`);
4309
+ return;
4310
+ }
4311
+ }
4312
+ }).catch(() => void 0);
4313
+ }
4314
+
4315
+ // src/core/machines/status.ts
4316
+ import { existsSync as existsSync9 } from "node:fs";
4317
+ function isHibernated(meta, p) {
4318
+ return !vmAlive(meta) && existsSync9(p.machine(meta.owner, meta.name).hibernateVmstate);
4319
+ }
4320
+ function statusOf(meta, p = paths()) {
4321
+ if (vmAlive(meta)) return meta.paused ? "standby" : "running";
4322
+ return isHibernated(meta, p) ? "hibernated" : "stopped";
4323
+ }
4324
+ function stateMessage(ref, status) {
4325
+ return `box ${shown(ref)} is ${status === "standby" ? "in standby" : status}`;
4326
+ }
4327
+ function assertNotHibernated(meta, p) {
4328
+ if (isHibernated(meta, p)) {
4329
+ throw new KvboxError(`${stateMessage(meta, "hibernated")}; its memory image was made with its current shape and base: kvbox wake ${shown(meta)} first`);
4330
+ }
4331
+ }
4332
+
4333
+ // src/core/machines/list.ts
4334
+ function toMachine(meta, p = paths()) {
4335
+ const alive2 = vmAlive(meta);
4336
+ if (!alive2 && meta.pid !== null) {
4337
+ try {
4338
+ closeOpenRun(meta.id, (/* @__PURE__ */ new Date()).toISOString(), p);
4339
+ } catch (err) {
4340
+ log.warn(`usage ledger: ${err.message}`);
4341
+ }
4342
+ }
4343
+ return {
4344
+ id: meta.id,
4345
+ name: meta.name,
4346
+ owner: meta.owner,
4347
+ ip: meta.ip,
4348
+ mac: meta.mac,
4349
+ pid: alive2 ? meta.pid : null,
4350
+ vcpu: meta.vcpu,
4351
+ memMib: meta.memMib,
4352
+ ...diskStats(p.machine(meta.owner, meta.name).overlay),
4353
+ base: meta.base,
4354
+ ...meta.image !== void 0 ? { image: meta.image } : {},
4355
+ ...meta.url !== void 0 ? { url: urlFor(meta.url, meta.name) } : {},
4356
+ createdAt: meta.createdAt,
4357
+ source: meta.source,
4358
+ status: statusOf(meta, p),
4359
+ ...meta.sshPort === void 0 ? {} : { sshPort: meta.sshPort },
4360
+ ...meta.ports?.length ? { ports: meta.ports.map((f) => ({ ...f })) } : {},
4361
+ ...meta.autoHibernateSec ? { autoHibernateSec: meta.autoHibernateSec } : {},
4362
+ ...meta.idleCheck !== void 0 ? { idleCheck: meta.idleCheck } : {},
4363
+ ...meta.integrations?.length ? { integrations: [...meta.integrations] } : {},
4364
+ ...meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {},
4365
+ ...meta.links?.some((l) => !l.stale) ? { links: meta.links.filter((l) => !l.stale).map((l) => ({ from: linkFrom(l, meta.owner), port: l.port })) } : {}
4366
+ };
4367
+ }
4368
+ var linkFrom = (l, owner) => l.owner === owner ? l.name : `${l.owner.split("@")[0]}/${l.name}`;
4369
+ async function listMachines(scope, p = paths()) {
4370
+ return (await readAllMeta(p)).filter((m) => inScope(m.owner, scope)).map((m) => toMachine(m, p));
4371
+ }
4372
+ async function getMachine(ref, p = paths()) {
4373
+ return toMachine(await readMeta(ref, p), p);
4374
+ }
4375
+
4376
+ // src/core/machines/boot.ts
4377
+ async function launch(spec, nic, cfg, pubkeyB64, p) {
4378
+ const root = imageFileFor(spec, p);
4379
+ const kernel = kernelFor(await imageManifest(root), cfg, p);
4380
+ const volumes = (await placeVolumeDrives(spec, p)).map((v) => ({ id: volumeDriveId(v.name), path: volumeDriveRel(v.name) }));
4381
+ return withGuestListener(spec, p, () => driver().vm.boot(spec, { kernel, root, volumes, pubkeyB64 }, nic, cfg, p));
4382
+ }
4383
+ async function loadSnapshot(spec, image, nic, cfg, p) {
4384
+ return withGuestListener(spec, p, () => driver().vm.restore(spec, { vmstate: image.vmstate, mem: image.mem }, nic, cfg, p));
3918
4385
  }
3919
- async function runStatus(udsPath, id, timeoutMs) {
3920
- const reply = await agentCall(udsPath, { op: "runStatus", id }, timeoutMs);
3921
- const state = reply["state"];
3922
- if (state !== "running" && state !== "exited" && state !== "timeout" && state !== "unknown") throw new KvboxError("kvbox-agent sent a run state this server does not know");
3923
- const durationMs = reply["durationMs"];
3924
- return {
3925
- state,
3926
- ...typeof reply["exitCode"] === "number" ? { exitCode: reply["exitCode"] } : {},
3927
- ...typeof durationMs === "number" && Number.isInteger(durationMs) && durationMs >= 0 ? { durationMs } : {}
3928
- };
4386
+ async function withGuestListener(box, p, bringUp) {
4387
+ await listenForGuest(box, p);
4388
+ try {
4389
+ return await bringUp();
4390
+ } catch (err) {
4391
+ await stopListeningForGuest(box, p);
4392
+ throw err;
4393
+ }
3929
4394
  }
3930
- async function runOutput(udsPath, id, stream, offset, limit, timeoutMs = 15e3) {
3931
- const reply = await agentCall(udsPath, { op: "runOutput", id, stream, offset, limit }, timeoutMs);
3932
- const { size: size2, data } = reply;
3933
- 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");
3934
- return { size: size2, offset, data };
4395
+ async function resumeVm(box, p) {
4396
+ await driver().vm.resume(box, p);
3935
4397
  }
3936
- var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
3937
- var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
3938
- 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 ?? "");
3939
4398
 
3940
4399
  // src/core/machines/guest.ts
4400
+ import { setTimeout as sleep4 } from "node:timers/promises";
3941
4401
  function prefixLenOf(subnet) {
3942
4402
  return Number(subnet.split("/")[1]);
3943
4403
  }
3944
- var AGENT_REPLY_MS = 2e4;
4404
+ var AGENT_REPLY_MS2 = 2e4;
3945
4405
  async function introduce(spec, vsock, cfg, failure2) {
3946
4406
  const id = { name: spec.name, ip: spec.ip, prefixLen: prefixLenOf(cfg.subnet), gateway: cfg.gateway, mac: spec.mac, time: Math.floor(Date.now() / 1e3) };
3947
4407
  const deadline = Date.now() + 3e3;
3948
4408
  for (; ; ) {
3949
4409
  try {
3950
- await setIdentity(vsock, id, AGENT_REPLY_MS);
4410
+ await setIdentity(vsock, id, AGENT_REPLY_MS2);
3951
4411
  return;
3952
4412
  } catch (err) {
3953
4413
  const msg = err.message;
3954
4414
  const transient = /unreachable|refused|before the guest accepted/.test(msg);
3955
4415
  if (transient && Date.now() < deadline) {
3956
- await sleep3(100);
4416
+ await sleep4(100);
3957
4417
  continue;
3958
4418
  }
3959
4419
  if (transient) throw new KvboxError(`${msg}
@@ -3965,7 +4425,7 @@ async function introduce(spec, vsock, cfg, failure2) {
3965
4425
  }
3966
4426
  async function dropGuestVolumes(box, vsock) {
3967
4427
  try {
3968
- await dropVolumes(vsock, AGENT_REPLY_MS);
4428
+ await dropVolumes(vsock, AGENT_REPLY_MS2);
3969
4429
  } catch (err) {
3970
4430
  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;
3971
4431
  log.warn(`box ${shown(box)} keeps the volume mounts it was frozen with, over empty disks now: ${why}`);
@@ -3975,7 +4435,7 @@ async function pushEnv(box, vsock, p) {
3975
4435
  const vars = await envForBoot(box, p);
3976
4436
  if (vars === null) return;
3977
4437
  try {
3978
- await setEnv(vsock, vars, AGENT_REPLY_MS);
4438
+ await setEnv(vsock, vars, AGENT_REPLY_MS2);
3979
4439
  } catch (err) {
3980
4440
  warnEnv(box, vars, err);
3981
4441
  }
@@ -3989,7 +4449,7 @@ function warnEnv(box, vars, err) {
3989
4449
  log.warn(`box ${shown(box)} did not get its environment variables: ${err.message}`);
3990
4450
  }
3991
4451
  var ENV_BOOT_WAIT_MS = 12e4;
3992
- function pushEnvAfterBoot(box, pid, vsock, p, timing = { replyMs: AGENT_REPLY_MS, waitMs: ENV_BOOT_WAIT_MS }) {
4452
+ function pushEnvAfterBoot(box, pid, vsock, p, timing = { replyMs: AGENT_REPLY_MS2, waitMs: ENV_BOOT_WAIT_MS }) {
3993
4453
  return (async () => {
3994
4454
  const deadline = Date.now() + timing.waitMs;
3995
4455
  for (; ; ) {
@@ -4002,7 +4462,7 @@ function pushEnvAfterBoot(box, pid, vsock, p, timing = { replyMs: AGENT_REPLY_MS
4002
4462
  } catch (err) {
4003
4463
  if (!pidAlive(pid)) return;
4004
4464
  if (isNoAgent(err) && Date.now() < deadline) {
4005
- await sleep3(500);
4465
+ await sleep4(500);
4006
4466
  continue;
4007
4467
  }
4008
4468
  warnEnv(box, vars, err);
@@ -4053,7 +4513,7 @@ function authorizedKeysB64(hostKey, extra) {
4053
4513
  }
4054
4514
  async function pushAuthorizedKeys(box, vsock, p) {
4055
4515
  try {
4056
- await setAuthorizedKeys(vsock, authorizedKeysLines(await readHostPubkey(p), box.sshKeys ?? []), AGENT_REPLY_MS);
4516
+ await setAuthorizedKeys(vsock, authorizedKeysLines(await readHostPubkey(p), box.sshKeys ?? []), AGENT_REPLY_MS2);
4057
4517
  return void 0;
4058
4518
  } catch (err) {
4059
4519
  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;
@@ -4256,17 +4716,132 @@ var startMachine = locked(async function startMachine2(ref, p = paths(), force =
4256
4716
  const started = { ...meta, pid, bootId: currentBootId(), sshKeysStale: void 0, paused: void 0 };
4257
4717
  await writeMachineMeta(started, p);
4258
4718
  recordState(started, "running", "start", p);
4719
+ void tellIntegrationsWhenUp(started, pid, p.machine(meta.owner, meta.name).vsock, p);
4259
4720
  return toMachine(started, p);
4260
4721
  } catch (err) {
4261
4722
  if (pid !== void 0) killQuietly(pid);
4723
+ await stopListeningForGuest(meta, p);
4262
4724
  await closePorts(meta, cfg);
4263
4725
  await driver().net.remove(meta.id, cfg).catch(() => void 0);
4264
4726
  throw err;
4265
4727
  }
4266
4728
  });
4267
4729
 
4730
+ // src/core/machines/newbox.ts
4731
+ import { mkdir as mkdir5, rm as rm6 } from "node:fs/promises";
4732
+ var NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
4733
+ var AUTO_PREFIX = "box";
4734
+ function pickName(requested, taken) {
4735
+ if (requested !== void 0) {
4736
+ if (!NAME_RE.test(requested)) {
4737
+ throw new KvboxError(`invalid box name "${requested}": 1-12 chars, lowercase letters, digits and '-', starting with a letter or digit`);
4738
+ }
4739
+ if (taken.has(requested)) throw new KvboxError(`box ${requested} already exists`);
4740
+ return requested;
4741
+ }
4742
+ for (let i = 1; ; i++) {
4743
+ const candidate = `${AUTO_PREFIX}${i}`;
4744
+ if (!taken.has(candidate)) return candidate;
4745
+ }
4746
+ }
4747
+ function autoHibernateFor(req, cfg, manifest = {}) {
4748
+ if (req.autoHibernateSec !== void 0) return req.autoHibernateSec || void 0;
4749
+ if (manifest.autoHibernate === false) return void 0;
4750
+ if (typeof manifest.autoHibernate === "string") return parseDuration(manifest.autoHibernate) || void 0;
4751
+ return cfg.autoHibernateSec || void 0;
4752
+ }
4753
+ var integrationsOf = (list) => list && list.length > 0 ? [...list] : void 0;
4754
+ function requestedIntegrations(list, on) {
4755
+ assertKnownIntegrations(list, "this host's kvbox-server", "it needs updating first");
4756
+ if (on) assertImageCanUse(on, list);
4757
+ return integrationsOf(list);
4758
+ }
4759
+ var inheritedIntegrations = (list, sourceOwner, owner) => sourceOwner === owner ? integrationsOf(list) : void 0;
4760
+ async function bootInto(box, prepare, origin, cfg, p) {
4761
+ const { id, ip, owner, name } = box;
4762
+ const keysB64 = authorizedKeysB64(await readHostPubkey(p), box.sshKeys ?? []);
4763
+ const m = p.machine(owner, name);
4764
+ await driver().net.prepare(cfg);
4765
+ await mkdir5(m.dir, { recursive: true, mode: 448 });
4766
+ let tapCreated = false;
4767
+ let pid;
4768
+ let sshPort;
4769
+ let drawn;
4770
+ try {
4771
+ drawn = isCloudBox(owner) ? await drawPorts(1, p) : void 0;
4772
+ sshPort = drawn?.ports[0];
4773
+ await prepare(m);
4774
+ const tap = await driver().net.create(box, cfg);
4775
+ tapCreated = true;
4776
+ const spec = { ...box, sshPort };
4777
+ pid = await launch(spec, tap, cfg, keysB64, p);
4778
+ await openPorts(spec, cfg, p);
4779
+ void pushEnvAfterBoot(spec, pid, m.vsock, p);
4780
+ const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin };
4781
+ await writeMachineMeta(meta, p);
4782
+ recordState(meta, "running", "new", p, meta.createdAt);
4783
+ void tellIntegrationsWhenUp(meta, pid, m.vsock, p);
4784
+ return toMachine(meta, p);
4785
+ } catch (err) {
4786
+ if (pid !== void 0) killQuietly(pid);
4787
+ await stopListeningForGuest(box, p);
4788
+ await closePorts({ id, ip, sshPort }, cfg);
4789
+ if (tapCreated) await driver().net.remove(id, cfg).catch(() => void 0);
4790
+ await rm6(m.dir, { recursive: true, force: true });
4791
+ boxListChanged();
4792
+ throw err;
4793
+ } finally {
4794
+ drawn?.release();
4795
+ }
4796
+ }
4797
+ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
4798
+ const { id, ip, owner, name } = box;
4799
+ const m = p.machine(owner, name);
4800
+ await driver().net.prepare(cfg);
4801
+ await mkdir5(m.dir, { recursive: true, mode: 448 });
4802
+ let tapCreated = false;
4803
+ let pid;
4804
+ let sshPort;
4805
+ let drawn;
4806
+ try {
4807
+ drawn = isCloudBox(owner) ? await drawPorts(1, p) : void 0;
4808
+ sshPort = drawn?.ports[0];
4809
+ const image = await prepare(m);
4810
+ const tap = await driver().net.create(box, cfg, { detached: true });
4811
+ tapCreated = true;
4812
+ const spec = { ...box, sshPort };
4813
+ pid = await loadSnapshot(spec, image, tap, cfg, p);
4814
+ await resumeVm(box, p);
4815
+ await introduce(spec, m.vsock, cfg, {
4816
+ silent: `nothing answered on the restored box's control channel for 3 s; the restored box was discarded, try again`,
4817
+ 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."
4818
+ });
4819
+ const stale = await pushAuthorizedKeys(box, m.vsock, p);
4820
+ if (stale && keysOrFail) throw new KvboxError(`${keysOrFail}: ${stale}`);
4821
+ if (image.volumes?.length) await dropGuestVolumes(box, m.vsock);
4822
+ await pushEnv(box, m.vsock, p);
4823
+ await driver().net.attach(box, cfg);
4824
+ await openPorts(spec, cfg, p);
4825
+ const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin, memSnapshots: 1, sshKeysStale: stale ? true : void 0 };
4826
+ await writeMachineMeta(meta, p);
4827
+ recordState(meta, "running", "new", p, meta.createdAt);
4828
+ void tellIntegrationsWhenUp(meta, pid, m.vsock, p);
4829
+ return toMachine(meta, p);
4830
+ } catch (err) {
4831
+ if (pid !== void 0) killQuietly(pid);
4832
+ await stopListeningForGuest(box, p);
4833
+ await closePorts({ id, ip, sshPort }, cfg);
4834
+ if (tapCreated) await driver().net.remove(id, cfg).catch(() => void 0);
4835
+ await rm6(m.dir, { recursive: true, force: true });
4836
+ boxListChanged();
4837
+ throw err;
4838
+ } finally {
4839
+ drawn?.release();
4840
+ }
4841
+ }
4842
+
4268
4843
  // src/core/machines/stop.ts
4269
- import { rm as rm5 } from "node:fs/promises";
4844
+ import { rm as rm7 } from "node:fs/promises";
4270
4845
 
4271
4846
  // src/core/machines/links.ts
4272
4847
  function linkSource(req, caller, target) {
@@ -4364,9 +4939,13 @@ async function waitDead(pid, graceMs) {
4364
4939
  }
4365
4940
  }
4366
4941
  async function cleanupProcess(meta, cfg, p) {
4367
- await closePorts(meta, cfg);
4368
- await driver().net.remove(meta.id, cfg);
4369
- await driver().vm.cleanup(meta, p);
4942
+ try {
4943
+ await closePorts(meta, cfg);
4944
+ await driver().net.remove(meta.id, cfg);
4945
+ await driver().vm.cleanup(meta, p);
4946
+ } finally {
4947
+ await stopListeningForGuest(meta, p);
4948
+ }
4370
4949
  }
4371
4950
  var stopMachine = locked(async function stopMachine2(ref, p = paths()) {
4372
4951
  const meta = await readMeta(ref, p);
@@ -4375,8 +4954,8 @@ var stopMachine = locked(async function stopMachine2(ref, p = paths()) {
4375
4954
  if (!vmAlive(meta) && !isHibernated(meta, p)) throw new KvboxError(`box ${shown(ref)} is already stopped`);
4376
4955
  await shutdown2(meta, cfg, p, 1e4);
4377
4956
  await compactDisk(m.overlay).catch((err) => log.warn(`box ${shown(ref)}: disk not compacted: ${err.message}`));
4378
- await rm5(m.hibernateDir, { recursive: true, force: true });
4379
- await rm5(m.memBase, { force: true });
4957
+ await rm7(m.hibernateDir, { recursive: true, force: true });
4958
+ await rm7(m.memBase, { force: true });
4380
4959
  const stopped = { ...meta, pid: null, memSnapshots: void 0, paused: void 0 };
4381
4960
  await writeMachineMeta(stopped, p);
4382
4961
  recordState(stopped, "stopped", "stop", p);
@@ -4395,7 +4974,8 @@ var destroyBox = locked(async function destroyBox2(ref, p = paths()) {
4395
4974
  throw err;
4396
4975
  });
4397
4976
  recordState(meta, "stopped", "rm", p);
4398
- await rm5(p.machine(ref.owner, ref.name).dir, { recursive: true, force: true });
4977
+ await rm7(p.machine(ref.owner, ref.name).dir, { recursive: true, force: true });
4978
+ forgetGuest(meta);
4399
4979
  boxListChanged();
4400
4980
  return meta;
4401
4981
  });
@@ -4405,7 +4985,7 @@ async function applyAtNextBoot(meta, changes, by, cfg, p, whileStopped) {
4405
4985
  const wasRunning = vmAlive(meta);
4406
4986
  if (wasRunning) {
4407
4987
  await shutdown2(meta, cfg, p, 1e4);
4408
- await rm6(p.machine(meta.owner, meta.name).memBase, { force: true });
4988
+ await rm8(p.machine(meta.owner, meta.name).memBase, { force: true });
4409
4989
  }
4410
4990
  const updated = { ...meta, ...changes, pid: null, memSnapshots: void 0, paused: void 0 };
4411
4991
  await writeMachineMeta(updated, p);
@@ -4470,7 +5050,7 @@ var replaceDisk = locked(async function replaceDisk2(ref, file, disk, p = paths(
4470
5050
  const currentGib = Math.round(statSync3(m.overlay).size / 1024 ** 3);
4471
5051
  const restoredGib = Math.round(statSync3(file).size / 1024 ** 3);
4472
5052
  return applyAtNextBoot(meta, { base: disk.base, image: disk.image }, "restore", cfg, p, async () => {
4473
- if (disk.vars === null) await rm6(m.env, { force: true });
5053
+ if (disk.vars === null) await rm8(m.env, { force: true });
4474
5054
  else await writeBoxEnv(ref, disk.vars, p);
4475
5055
  await rename5(file, m.overlay);
4476
5056
  if (currentGib > restoredGib) await growDisk(m.overlay, currentGib);
@@ -4481,6 +5061,11 @@ var setMachine = locked(async function setMachine2(ref, req, p = paths()) {
4481
5061
  const next = { ...meta };
4482
5062
  if (req.autoHibernateSec !== void 0) next.autoHibernateSec = req.autoHibernateSec || void 0;
4483
5063
  if (req.idleCheck !== void 0) next.idleCheck = req.idleCheck || void 0;
5064
+ if (req.integrations !== void 0) {
5065
+ next.integrations = requestedIntegrations(req.integrations);
5066
+ if (statusOf(meta, p) === "running") await applyIntegrations(next, p.machine(meta.owner, meta.name).vsock, p, meta.integrations);
5067
+ else assertImageCanUse(meta, next.integrations, meta.integrations);
5068
+ }
4484
5069
  await writeMachineMeta(next, p);
4485
5070
  return toMachine(next, p);
4486
5071
  });
@@ -4488,108 +5073,6 @@ var setMachine = locked(async function setMachine2(ref, req, p = paths()) {
4488
5073
  // src/core/machines/create.ts
4489
5074
  import { rename as rename6, stat as stat3 } from "node:fs/promises";
4490
5075
 
4491
- // src/core/machines/newbox.ts
4492
- import { mkdir as mkdir5, rm as rm7 } from "node:fs/promises";
4493
- var NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
4494
- var AUTO_PREFIX = "box";
4495
- function pickName(requested, taken) {
4496
- if (requested !== void 0) {
4497
- if (!NAME_RE.test(requested)) {
4498
- throw new KvboxError(`invalid box name "${requested}": 1-12 chars, lowercase letters, digits and '-', starting with a letter or digit`);
4499
- }
4500
- if (taken.has(requested)) throw new KvboxError(`box ${requested} already exists`);
4501
- return requested;
4502
- }
4503
- for (let i = 1; ; i++) {
4504
- const candidate = `${AUTO_PREFIX}${i}`;
4505
- if (!taken.has(candidate)) return candidate;
4506
- }
4507
- }
4508
- function autoHibernateFor(req, cfg, manifest = {}) {
4509
- if (req.autoHibernateSec !== void 0) return req.autoHibernateSec || void 0;
4510
- if (manifest.autoHibernate === false) return void 0;
4511
- if (typeof manifest.autoHibernate === "string") return parseDuration(manifest.autoHibernate) || void 0;
4512
- return cfg.autoHibernateSec || void 0;
4513
- }
4514
- async function bootInto(box, prepare, origin, cfg, p) {
4515
- const { id, ip, owner, name } = box;
4516
- const keysB64 = authorizedKeysB64(await readHostPubkey(p), box.sshKeys ?? []);
4517
- const m = p.machine(owner, name);
4518
- await driver().net.prepare(cfg);
4519
- await mkdir5(m.dir, { recursive: true, mode: 448 });
4520
- let tapCreated = false;
4521
- let pid;
4522
- let sshPort;
4523
- let drawn;
4524
- try {
4525
- drawn = isCloudBox(owner) ? await drawPorts(1, p) : void 0;
4526
- sshPort = drawn?.ports[0];
4527
- await prepare(m);
4528
- const tap = await driver().net.create(box, cfg);
4529
- tapCreated = true;
4530
- const spec = { ...box, sshPort };
4531
- pid = await launch(spec, tap, cfg, keysB64, p);
4532
- await openPorts(spec, cfg, p);
4533
- void pushEnvAfterBoot(spec, pid, m.vsock, p);
4534
- const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin };
4535
- await writeMachineMeta(meta, p);
4536
- recordState(meta, "running", "new", p, meta.createdAt);
4537
- return toMachine(meta, p);
4538
- } catch (err) {
4539
- if (pid !== void 0) killQuietly(pid);
4540
- await closePorts({ id, ip, sshPort }, cfg);
4541
- if (tapCreated) await driver().net.remove(id, cfg).catch(() => void 0);
4542
- await rm7(m.dir, { recursive: true, force: true });
4543
- boxListChanged();
4544
- throw err;
4545
- } finally {
4546
- drawn?.release();
4547
- }
4548
- }
4549
- async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
4550
- const { id, ip, owner, name } = box;
4551
- const m = p.machine(owner, name);
4552
- await driver().net.prepare(cfg);
4553
- await mkdir5(m.dir, { recursive: true, mode: 448 });
4554
- let tapCreated = false;
4555
- let pid;
4556
- let sshPort;
4557
- let drawn;
4558
- try {
4559
- drawn = isCloudBox(owner) ? await drawPorts(1, p) : void 0;
4560
- sshPort = drawn?.ports[0];
4561
- const image = await prepare(m);
4562
- const tap = await driver().net.create(box, cfg, { detached: true });
4563
- tapCreated = true;
4564
- const spec = { ...box, sshPort };
4565
- pid = await loadSnapshot(spec, image, tap, cfg, p);
4566
- await resumeVm(box, p);
4567
- await introduce(spec, m.vsock, cfg, {
4568
- silent: `nothing answered on the restored box's control channel for 3 s; the restored box was discarded, try again`,
4569
- 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."
4570
- });
4571
- const stale = await pushAuthorizedKeys(box, m.vsock, p);
4572
- if (stale && keysOrFail) throw new KvboxError(`${keysOrFail}: ${stale}`);
4573
- if (image.volumes?.length) await dropGuestVolumes(box, m.vsock);
4574
- await pushEnv(box, m.vsock, p);
4575
- await driver().net.attach(box, cfg);
4576
- await openPorts(spec, cfg, p);
4577
- const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin, memSnapshots: 1, sshKeysStale: stale ? true : void 0 };
4578
- await writeMachineMeta(meta, p);
4579
- recordState(meta, "running", "new", p, meta.createdAt);
4580
- return toMachine(meta, p);
4581
- } catch (err) {
4582
- if (pid !== void 0) killQuietly(pid);
4583
- await closePorts({ id, ip, sshPort }, cfg);
4584
- if (tapCreated) await driver().net.remove(id, cfg).catch(() => void 0);
4585
- await rm7(m.dir, { recursive: true, force: true });
4586
- boxListChanged();
4587
- throw err;
4588
- } finally {
4589
- drawn?.release();
4590
- }
4591
- }
4592
-
4593
5076
  // src/core/machines/restore.ts
4594
5077
  import { existsSync as existsSync10 } from "node:fs";
4595
5078
  import { link } from "node:fs/promises";
@@ -4639,7 +5122,7 @@ async function restoreFrom(from, owner, req, cfg, p) {
4639
5122
  await placeholderDrives(m.dir, snap.volumes ?? []);
4640
5123
  return { vmstate: s.vmstate, mem: s.mem, label: shown(from), volumes: snap.volumes };
4641
5124
  },
4642
- { source: `snapshot:${refKey(from)}`, autoHibernateSec: autoHibernateFor(req, cfg, manifest), idleCheck: manifest.idle, url: maskedUrl(manifest, vars) },
5125
+ { source: `snapshot:${refKey(from)}`, autoHibernateSec: autoHibernateFor(req, cfg, manifest), idleCheck: manifest.idle, url: maskedUrl(manifest, vars), integrations: req.integrations !== void 0 ? requestedIntegrations(req.integrations, { owner, name, base: snap.base, image: snap.image }) : inheritedIntegrations(snap.integrations, from.owner, owner) },
4643
5126
  cfg,
4644
5127
  p
4645
5128
  );
@@ -4696,7 +5179,7 @@ async function createMachine(req, owner, p = paths(), from) {
4696
5179
  } else await createOverlay(m.overlay, size2.diskGib);
4697
5180
  if (vars.length > 0) await writeBoxEnv({ owner, name }, vars, p);
4698
5181
  },
4699
- { source: from ? `backup:${from.id}` : "base", autoHibernateSec, idleCheck: manifest.idle, url: maskedUrl(manifest, vars) },
5182
+ { source: from ? `backup:${from.id}` : "base", autoHibernateSec, idleCheck: manifest.idle, url: maskedUrl(manifest, vars), integrations: requestedIntegrations(req.integrations, { owner, name, base: base.version, image }) },
4700
5183
  cfg,
4701
5184
  p
4702
5185
  );
@@ -4705,11 +5188,11 @@ async function createMachine(req, owner, p = paths(), from) {
4705
5188
 
4706
5189
  // src/core/machines/fork.ts
4707
5190
  import { statSync as statSync4 } from "node:fs";
4708
- import { rm as rm9 } from "node:fs/promises";
5191
+ import { rm as rm10 } from "node:fs/promises";
4709
5192
 
4710
5193
  // src/core/snapshots.ts
4711
5194
  import { existsSync as existsSync11 } from "node:fs";
4712
- import { link as link2, mkdir as mkdir6, readdir as readdir5, rename as rename7, rm as rm8, stat as stat4 } from "node:fs/promises";
5195
+ import { link as link2, mkdir as mkdir6, readdir as readdir5, rename as rename7, rm as rm9, stat as stat4 } from "node:fs/promises";
4713
5196
  var NAME_RE2 = /^[a-z0-9][a-z0-9._-]{0,63}$/;
4714
5197
  function toSnapshot(meta) {
4715
5198
  return {
@@ -4770,7 +5253,7 @@ async function snapshotBox(ref, req, owner, p) {
4770
5253
  if (existsSync11(final.dir) && !req.replace) throw new KvboxError(`snapshot ${req.name} already exists (--replace retakes it)`);
4771
5254
  const s = req.replace ? p.snapshot(owner, `.${req.name}.new-${box.id}`) : final;
4772
5255
  const cfg = await loadConfig(p);
4773
- if (s !== final) await rm8(s.dir, { recursive: true, force: true });
5256
+ if (s !== final) await rm9(s.dir, { recursive: true, force: true });
4774
5257
  await mkdir6(s.dir, { recursive: true, mode: 448 });
4775
5258
  try {
4776
5259
  const volumes = await captureDrivesOf(box, p);
@@ -4778,6 +5261,7 @@ async function snapshotBox(ref, req, owner, p) {
4778
5261
  await copyBoxEnv(p.machine(box.owner, box.name).env, s.env);
4779
5262
  const meta = {
4780
5263
  ...volumes.length > 0 ? { volumes } : {},
5264
+ ...box.integrations?.length ? { integrations: [...box.integrations] } : {},
4781
5265
  name: req.name,
4782
5266
  owner,
4783
5267
  source: refKey(box),
@@ -4792,7 +5276,7 @@ async function snapshotBox(ref, req, owner, p) {
4792
5276
  if (s !== final) await swapIn({ owner, name: req.name }, s.dir, box.id, p);
4793
5277
  return toSnapshot(meta);
4794
5278
  } catch (err) {
4795
- await rm8(s.dir, { recursive: true, force: true });
5279
+ await rm9(s.dir, { recursive: true, force: true });
4796
5280
  throw err;
4797
5281
  }
4798
5282
  }
@@ -4800,7 +5284,7 @@ async function swapIn(ref, from, boxId, p) {
4800
5284
  const to = p.snapshot(ref.owner, ref.name).dir;
4801
5285
  const old = p.snapshot(ref.owner, `.${ref.name}.old-${boxId}`).dir;
4802
5286
  await withSnapshotLock(ref, async () => {
4803
- await rm8(old, { recursive: true, force: true });
5287
+ await rm9(old, { recursive: true, force: true });
4804
5288
  const hadOld = existsSync11(to);
4805
5289
  if (hadOld) await rename7(to, old);
4806
5290
  try {
@@ -4810,7 +5294,7 @@ async function swapIn(ref, from, boxId, p) {
4810
5294
  throw err;
4811
5295
  }
4812
5296
  });
4813
- await rm8(old, { recursive: true, force: true });
5297
+ await rm9(old, { recursive: true, force: true });
4814
5298
  }
4815
5299
  async function captureBox(box, to, cfg, p) {
4816
5300
  const m = p.machine(box.owner, box.name);
@@ -4839,10 +5323,10 @@ async function captureBox(box, to, cfg, p) {
4839
5323
  } else if (since > 0) {
4840
5324
  await mergeOntoPrevious(m.memBase, to.mem, cfg.snapshotEditor ?? p.snapshotEditor);
4841
5325
  }
4842
- await rm8(m.memBase, { force: true });
5326
+ await rm9(m.memBase, { force: true });
4843
5327
  await link2(to.mem, m.memBase);
4844
5328
  } catch (err) {
4845
- if (lineageTouched) await rm8(m.memBase, { force: true }).catch(() => void 0);
5329
+ if (lineageTouched) await rm9(m.memBase, { force: true }).catch(() => void 0);
4846
5330
  throw err;
4847
5331
  }
4848
5332
  }
@@ -4856,7 +5340,7 @@ async function mergeOntoPrevious(previous, diffFile, editor) {
4856
5340
  async function deleteSnapshot(ref, p = paths()) {
4857
5341
  const dir = p.snapshot(ref.owner, ref.name).dir;
4858
5342
  if (ref.name.startsWith(".") || !existsSync11(dir)) throw new NotFoundError(`snapshot ${shown(ref)}`);
4859
- await withSnapshotLock(ref, () => rm8(dir, { recursive: true, force: true }));
5343
+ await withSnapshotLock(ref, () => rm9(dir, { recursive: true, force: true }));
4860
5344
  }
4861
5345
 
4862
5346
  // src/core/machines/fork.ts
@@ -4891,7 +5375,7 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
4891
5375
  const { ip, mac } = driver().net.allocate(cfg, existing.map((m) => m.ip));
4892
5376
  const box = { id, name, owner, ip, mac, ...shape, base: src.base, image: src.image, sshKeys };
4893
5377
  const srcEnv = p.machine(src.owner, src.name).env;
4894
- const origin = { source: `fork:${refKey(src)}`, autoHibernateSec: (req.autoHibernateSec ?? src.autoHibernateSec) || void 0, idleCheck: src.idleCheck, url: src.url };
5378
+ 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) };
4895
5379
  if (!warm) {
4896
5380
  return bootInto(
4897
5381
  box,
@@ -4921,12 +5405,12 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
4921
5405
  // another slug. Such a fork is discarded rather than kept stale; a cold fork boots with the new line.
4922
5406
  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)`
4923
5407
  );
4924
- await rm9(p.machine(owner, name).forkVmstate, { force: true });
5408
+ await rm10(p.machine(owner, name).forkVmstate, { force: true });
4925
5409
  return machine;
4926
5410
  });
4927
5411
 
4928
5412
  // src/core/machines/recovery.ts
4929
- import { rm as rm10 } from "node:fs/promises";
5413
+ import { rm as rm11 } from "node:fs/promises";
4930
5414
  var RECOVERY_CONCURRENCY = 2;
4931
5415
  async function settleDeadBoxes(p = paths()) {
4932
5416
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -4940,7 +5424,7 @@ async function settleDeadBoxes(p = paths()) {
4940
5424
  } catch (err) {
4941
5425
  log.warn(`usage ledger: ${err.message}`);
4942
5426
  }
4943
- await rm10(p.machine(meta.owner, meta.name).memBase, { force: true });
5427
+ await rm11(p.machine(meta.owner, meta.name).memBase, { force: true });
4944
5428
  if (meta.paused) {
4945
5429
  await writeMachineMeta({ ...meta, pid: null, bootId: void 0, memSnapshots: void 0, paused: void 0 }, p);
4946
5430
  leftStopped.push(refKey(meta));
@@ -4997,7 +5481,7 @@ async function bootRecovered(settled, p = paths()) {
4997
5481
 
4998
5482
  // src/core/machines/standby.ts
4999
5483
  import { existsSync as existsSync12 } from "node:fs";
5000
- import { link as link3, mkdir as mkdir7, rm as rm11 } from "node:fs/promises";
5484
+ import { link as link3, mkdir as mkdir7, rm as rm12 } from "node:fs/promises";
5001
5485
  var pauseMachine = locked(async function pauseMachine2(ref, p = paths()) {
5002
5486
  const meta = await readMeta(ref, p);
5003
5487
  const status = statusOf(meta, p);
@@ -5022,6 +5506,7 @@ var resumeMachine = locked(async function resumeMachine2(ref, p = paths()) {
5022
5506
  const running = { ...meta, paused: void 0, sshKeysStale: stale ? true : void 0 };
5023
5507
  await writeMachineMeta(running, p);
5024
5508
  recordState(running, "running", "resume", p);
5509
+ if (meta.pid !== null) void tellIntegrationsWhenUp(running, meta.pid, m.vsock, p);
5025
5510
  return toMachine(running, p);
5026
5511
  });
5027
5512
  var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(), by = "hibernate") {
@@ -5031,14 +5516,14 @@ var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(),
5031
5516
  if (status === "hibernated") throw new KvboxError(`${stateMessage(ref, status)} already`);
5032
5517
  if (status === "stopped") throw new KvboxError(`${stateMessage(ref, status)}; only a running box can be hibernated (there is no memory to keep)`);
5033
5518
  const m = p.machine(ref.owner, ref.name);
5034
- await rm11(m.hibernateDir, { recursive: true, force: true });
5519
+ await rm12(m.hibernateDir, { recursive: true, force: true });
5035
5520
  await mkdir7(m.hibernateDir, { recursive: true, mode: 448 });
5036
5521
  const vm = driver().vm;
5037
5522
  try {
5038
5523
  await vm.pause(ref, p);
5039
5524
  await vm.saveState(ref, { vmstate: m.hibernateVmstate, mem: m.hibernateMem }, "full", p);
5040
5525
  } catch (err) {
5041
- await rm11(m.hibernateDir, { recursive: true, force: true });
5526
+ await rm12(m.hibernateDir, { recursive: true, force: true });
5042
5527
  if (!meta.paused) await vm.resume(ref, p).catch(() => void 0);
5043
5528
  throw err;
5044
5529
  }
@@ -5046,7 +5531,7 @@ var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(),
5046
5531
  await waitFor(() => !pidAlive(meta.pid), 5e3, 50);
5047
5532
  await cleanupProcess(meta, cfg, p);
5048
5533
  await run(["fallocate", "--dig-holes", m.hibernateMem]);
5049
- await rm11(m.memBase, { force: true });
5534
+ await rm12(m.memBase, { force: true });
5050
5535
  const hibernated = { ...meta, pid: null, memSnapshots: void 0, paused: void 0 };
5051
5536
  await writeMachineMeta(hibernated, p);
5052
5537
  recordState(hibernated, "hibernated", by, p);
@@ -5081,22 +5566,24 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths(), force = f
5081
5566
  await openPorts(meta, cfg, p);
5082
5567
  } catch (err) {
5083
5568
  if (pid !== void 0) killQuietly(pid);
5569
+ await stopListeningForGuest(meta, p);
5084
5570
  await closePorts(meta, cfg);
5085
5571
  await driver().net.remove(meta.id, cfg).catch(() => void 0);
5086
5572
  throw err;
5087
5573
  }
5088
- await rm11(m.memBase, { force: true });
5574
+ await rm12(m.memBase, { force: true });
5089
5575
  await link3(m.hibernateMem, m.memBase);
5090
- await rm11(m.hibernateDir, { recursive: true, force: true });
5576
+ await rm12(m.hibernateDir, { recursive: true, force: true });
5091
5577
  const running = { ...meta, pid, bootId: currentBootId(), memSnapshots: 1, paused: void 0, sshKeysStale: stale ? true : void 0 };
5092
5578
  await writeMachineMeta(running, p);
5093
5579
  recordState(running, "running", "wake", p);
5580
+ void tellIntegrationsWhenUp(running, pid, m.vsock, p);
5094
5581
  return toMachine(running, p);
5095
5582
  });
5096
5583
 
5097
5584
  // src/core/machines/volumes.ts
5098
5585
  import { statSync as statSync5 } from "node:fs";
5099
- import { rename as rename8, rm as rm12 } from "node:fs/promises";
5586
+ import { rename as rename8, rm as rm13 } from "node:fs/promises";
5100
5587
  var attachVolume = locked(async function attachVolume2(ref, volume, p = paths()) {
5101
5588
  const cfg = await loadConfig(p);
5102
5589
  const claimed = await withHostLock("volumes", async () => {
@@ -5119,7 +5606,7 @@ var detachVolume = locked(async function detachVolume2(ref, volume, p = paths())
5119
5606
  if (!meta.volumes?.includes(volume.name) || volume.owner !== meta.owner) throw new KvboxError(`volume ${shown(volume)} is not attached to box ${shown(ref)}`);
5120
5607
  assertNotHibernated(meta, p);
5121
5608
  const kept = meta.volumes.filter((v) => v !== volume.name);
5122
- 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 }));
5609
+ 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 }));
5123
5610
  });
5124
5611
  async function resizeVolume(volume, sizeGib, p = paths()) {
5125
5612
  await assertCanGrow(volume, sizeGib, p);
@@ -5175,9 +5662,9 @@ async function replaceVolumeDisk(volume, file, p = paths()) {
5175
5662
  // src/core/backups.ts
5176
5663
  import { randomBytes as randomBytes5 } from "node:crypto";
5177
5664
  import { existsSync as existsSync13 } from "node:fs";
5178
- import { mkdir as mkdir8, open, readdir as readdir6, readFile as readFile9, rm as rm13, stat as stat5, statfs as statfs3, writeFile as writeFile7 } from "node:fs/promises";
5665
+ 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";
5179
5666
  import { basename as basename2, join as join3 } from "node:path";
5180
- import { setTimeout as sleep4 } from "node:timers/promises";
5667
+ import { setTimeout as sleep5 } from "node:timers/promises";
5181
5668
 
5182
5669
  // ../shared/src/backup.ts
5183
5670
  import { createCipheriv, createDecipheriv, createHmac, randomBytes as randomBytes4 } from "node:crypto";
@@ -5347,7 +5834,7 @@ async function stageBackup(ref, req, p = paths()) {
5347
5834
  checkId(req.id);
5348
5835
  const keys = backupKeys(req.key);
5349
5836
  const s = p.backup(req.id);
5350
- await rm13(s.dir, { recursive: true, force: true });
5837
+ await rm14(s.dir, { recursive: true, force: true });
5351
5838
  await mkdir8(s.dir, { recursive: true, mode: 448 });
5352
5839
  try {
5353
5840
  const { meta, envText } = await withBoxLock(ref, async () => {
@@ -5368,10 +5855,11 @@ async function stageBackup(ref, req, p = paths()) {
5368
5855
  base: meta.base,
5369
5856
  ...meta.image !== void 0 ? { image: meta.image } : {},
5370
5857
  vcpu: meta.vcpu,
5371
- memMib: meta.memMib
5858
+ memMib: meta.memMib,
5859
+ ...meta.integrations?.length ? { integrations: [...meta.integrations] } : {}
5372
5860
  };
5373
5861
  } catch (err) {
5374
- await rm13(s.dir, { recursive: true, force: true });
5862
+ await rm14(s.dir, { recursive: true, force: true });
5375
5863
  throw err;
5376
5864
  }
5377
5865
  }
@@ -5390,7 +5878,7 @@ async function stageVolumeBackup(ref, req, p = paths()) {
5390
5878
  await readVolume(ref, p);
5391
5879
  const from = p.volume(ref.owner, ref.name).disk;
5392
5880
  const s = p.backup(req.id);
5393
- await rm13(s.dir, { recursive: true, force: true });
5881
+ await rm14(s.dir, { recursive: true, force: true });
5394
5882
  await mkdir8(s.dir, { recursive: true, mode: 448 });
5395
5883
  try {
5396
5884
  await assertRoom(s.dir, 0, `a backup of volume ${shown(ref)}`, p);
@@ -5413,7 +5901,7 @@ async function stageVolumeBackup(ref, req, p = paths()) {
5413
5901
  await writeFile7(s.chunks, JSON.stringify({ chunks }), { mode: 384 });
5414
5902
  return { id: req.id, sizeBytes, chunks };
5415
5903
  } catch (err) {
5416
- await rm13(s.dir, { recursive: true, force: true });
5904
+ await rm14(s.dir, { recursive: true, force: true });
5417
5905
  throw err;
5418
5906
  }
5419
5907
  }
@@ -5478,25 +5966,25 @@ async function uploadOnce(id, req, signal, p) {
5478
5966
  } finally {
5479
5967
  await fh.close();
5480
5968
  }
5481
- await rm13(s.dir, { recursive: true, force: true });
5969
+ await rm14(s.dir, { recursive: true, force: true });
5482
5970
  return { chunks: work.length, bytes, sizes };
5483
5971
  }
5484
5972
  async function dropBackup(id, p = paths()) {
5485
5973
  checkId(id);
5486
5974
  uploads.get(id)?.abort();
5487
- await rm13(p.backup(id).dir, { recursive: true, force: true });
5975
+ await rm14(p.backup(id).dir, { recursive: true, force: true });
5488
5976
  }
5489
5977
  async function clearStagedBackups(p = paths()) {
5490
- await rm13(p.backups, { recursive: true, force: true });
5978
+ await rm14(p.backups, { recursive: true, force: true });
5491
5979
  const prefix = basename2(p.machine("x", "x").restoring);
5492
5980
  for (const ref of await listMachineRefs(p)) {
5493
5981
  const dir = p.machine(ref.owner, ref.name).dir;
5494
- for (const f of await readdir6(dir).catch(() => [])) if (f === prefix || f.startsWith(`${prefix}.`)) await rm13(join3(dir, f), { force: true });
5982
+ for (const f of await readdir6(dir).catch(() => [])) if (f === prefix || f.startsWith(`${prefix}.`)) await rm14(join3(dir, f), { force: true });
5495
5983
  }
5496
5984
  const volumePrefix = basename2(p.volume("x", "x").restoring);
5497
5985
  for (const ref of await listVolumeRefs(p)) {
5498
5986
  const dir = p.volume(ref.owner, ref.name).dir;
5499
- for (const f of await readdir6(dir).catch(() => [])) if (f.startsWith(`${volumePrefix}.`)) await rm13(join3(dir, f), { force: true });
5987
+ for (const f of await readdir6(dir).catch(() => [])) if (f.startsWith(`${volumePrefix}.`)) await rm14(join3(dir, f), { force: true });
5500
5988
  }
5501
5989
  }
5502
5990
  async function downloadDisk(file, req, p = paths()) {
@@ -5570,8 +6058,8 @@ async function restoreOnce(ref, req, p) {
5570
6058
  await downloadDisk(file, req, p);
5571
6059
  return await replaceDisk(ref, file, { base: req.base, image: req.image, vars }, p);
5572
6060
  } finally {
5573
- await rm13(file, { force: true });
5574
- await rm13(envFile, { force: true });
6061
+ await rm14(file, { force: true });
6062
+ await rm14(envFile, { force: true });
5575
6063
  }
5576
6064
  }
5577
6065
  async function createFromBackup(req, owner, p = paths()) {
@@ -5596,7 +6084,7 @@ async function createFromBackup(req, owner, p = paths()) {
5596
6084
  const sent = create;
5597
6085
  return await createMachine(sent, owner, p, { disk, base, image: backup.image, vars, id: backup.id });
5598
6086
  } finally {
5599
- await rm13(dir, { recursive: true, force: true });
6087
+ await rm14(dir, { recursive: true, force: true });
5600
6088
  }
5601
6089
  }
5602
6090
  async function baseFor(backup, p) {
@@ -5649,7 +6137,7 @@ async function restoreVolumeBackup(ref, req, p = paths()) {
5649
6137
  if (n > 0) holding.set(held2, n);
5650
6138
  else holding.delete(held2);
5651
6139
  }
5652
- await rm13(file, { force: true });
6140
+ await rm14(file, { force: true });
5653
6141
  }
5654
6142
  }
5655
6143
  async function pool(items, fn) {
@@ -5677,34 +6165,34 @@ async function withTries(what, fn, signal) {
5677
6165
  } catch (err) {
5678
6166
  if (signal?.aborted) throw new KvboxError(`${what}: the backup was dropped`);
5679
6167
  last = err;
5680
- await sleep4(250 * 2 ** i);
6168
+ await sleep5(250 * 2 ** i);
5681
6169
  }
5682
6170
  }
5683
6171
  throw new KvboxError(`${what} failed ${TRIES} times: ${last.message}`);
5684
6172
  }
5685
6173
 
5686
6174
  // src/core/relay.ts
5687
- import { access as access2, chmod as chmod4, mkdir as mkdir10, rm as rm14, writeFile as writeFile8 } from "node:fs/promises";
6175
+ import { access as access2, chmod as chmod4, mkdir as mkdir10, rm as rm15, writeFile as writeFile8 } from "node:fs/promises";
5688
6176
 
5689
6177
  // ../shared/src/relay.ts
5690
- import { z as z7 } from "zod";
6178
+ import { z as z8 } from "zod";
5691
6179
  var RELAY_TUNNEL_GATEWAY = "10.77.0.1";
5692
6180
  var IPV4_RE = /^(\d{1,3})(\.\d{1,3}){3}$/;
5693
6181
  var WG_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
5694
- var RelayJoinSchema = z7.object({
5695
- v: z7.literal(1),
6182
+ var RelayJoinSchema = z8.object({
6183
+ v: z8.literal(1),
5696
6184
  /** How the relay lists this host. */
5697
- name: z7.string().regex(/^[a-z0-9][a-z0-9-]{0,30}$/),
6185
+ name: z8.string().regex(/^[a-z0-9][a-z0-9-]{0,30}$/),
5698
6186
  /** `<relay-primary-ip>:<port>`, the WireGuard endpoint the host dials. */
5699
- relay: z7.string().regex(/^(\d{1,3})(\.\d{1,3}){3}:\d{1,5}$/),
6187
+ relay: z8.string().regex(/^(\d{1,3})(\.\d{1,3}){3}:\d{1,5}$/),
5700
6188
  /** The relay's WireGuard public key. */
5701
- relayKey: z7.string().regex(WG_KEY_RE),
6189
+ relayKey: z8.string().regex(WG_KEY_RE),
5702
6190
  /** This host's address inside the tunnel. */
5703
- tunnelIp: z7.string().regex(IPV4_RE),
6191
+ tunnelIp: z8.string().regex(IPV4_RE),
5704
6192
  /** This host's WireGuard private key, generated on the relay, kept nowhere else. */
5705
- privateKey: z7.string().regex(WG_KEY_RE),
6193
+ privateKey: z8.string().regex(WG_KEY_RE),
5706
6194
  /** The extra public IPv4 the relay owns for this host; what the host advertises to the control plane. */
5707
- publicIp: z7.string().regex(IPV4_RE)
6195
+ publicIp: z8.string().regex(IPV4_RE)
5708
6196
  });
5709
6197
  function decodeRelayJoin(text) {
5710
6198
  let parsed;
@@ -5721,7 +6209,7 @@ function decodeRelayJoin(text) {
5721
6209
  import { X509Certificate } from "node:crypto";
5722
6210
  import { chmod as chmod3, mkdir as mkdir9, readFile as readFile10 } from "node:fs/promises";
5723
6211
  import { hostname as osHostname } from "node:os";
5724
- import { request as request3 } from "undici";
6212
+ import { request as request4 } from "undici";
5725
6213
 
5726
6214
  // ../shared/src/country.ts
5727
6215
  var names = new Intl.DisplayNames(["en"], { type: "region", fallback: "none" });
@@ -5826,7 +6314,7 @@ async function joinControlPlane(opts, p = paths(), guessAddress = defaultAdverti
5826
6314
  const { fingerprint } = await ensureTlsCert(p);
5827
6315
  const hostUrl = `https://${advertise}:${port}`;
5828
6316
  const body = { token: opts.token, name, url: hostUrl, fingerprint, publicAddress: advertise, ...country !== void 0 ? { country } : {} };
5829
- const res = await request3(`${url}/hosts/join`, {
6317
+ const res = await request4(`${url}/hosts/join`, {
5830
6318
  method: "POST",
5831
6319
  headers: { "content-type": "application/json" },
5832
6320
  body: JSON.stringify(body),
@@ -5851,7 +6339,7 @@ async function fetchCloudCa(p = paths()) {
5851
6339
  const cfg = await loadConfig(p);
5852
6340
  const cp = cfg.controlPlane;
5853
6341
  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>");
5854
- const res = await request3(`${cp.url}/hosts/self/ssh-ca`, {
6342
+ const res = await request4(`${cp.url}/hosts/self/ssh-ca`, {
5855
6343
  headers: { authorization: `Bearer ${cp.secret}` },
5856
6344
  headersTimeout: 1e4,
5857
6345
  bodyTimeout: 1e4
@@ -5870,7 +6358,7 @@ async function fetchCloudName(p = paths()) {
5870
6358
  const cfg = await loadConfig(p);
5871
6359
  const cp = cfg.controlPlane;
5872
6360
  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>");
5873
- const res = await request3(`${cp.url}/health`, { headersTimeout: 1e4, bodyTimeout: 1e4 }).catch((err) => {
6361
+ const res = await request4(`${cp.url}/health`, { headersTimeout: 1e4, bodyTimeout: 1e4 }).catch((err) => {
5874
6362
  throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);
5875
6363
  });
5876
6364
  const text = await res.body.text();
@@ -5883,7 +6371,7 @@ async function leaveControlPlane(p = paths()) {
5883
6371
  const cfg = await loadConfig(p);
5884
6372
  const cp = cfg.controlPlane;
5885
6373
  if (!cp) throw new KvboxError("this host has not joined a control plane");
5886
- const told = await request3(`${cp.url}/hosts/self`, {
6374
+ const told2 = await request4(`${cp.url}/hosts/self`, {
5887
6375
  method: "DELETE",
5888
6376
  headers: { authorization: `Bearer ${cp.secret}` },
5889
6377
  headersTimeout: 3e3,
@@ -5894,7 +6382,7 @@ async function leaveControlPlane(p = paths()) {
5894
6382
  }).catch(() => false);
5895
6383
  const { controlPlane: _gone, ...rest } = cfg;
5896
6384
  await saveConfig({ ...rest, ...rest.backupStore ? { backupStore: { ...rest.backupStore, registered: false } } : {} }, p);
5897
- return { controlPlane: cp.name, told };
6385
+ return { controlPlane: cp.name, told: told2 };
5898
6386
  }
5899
6387
  function jsonOrNull(text) {
5900
6388
  try {
@@ -5963,7 +6451,7 @@ async function dropRelay(p = paths()) {
5963
6451
  throw new KvboxError(`${cfg.controlPlane.name} reaches this host through the relay (${relay.publicIp}); run kvbox-server leave first`);
5964
6452
  }
5965
6453
  await driver().net.relay(cfg, ["relay", "down"]);
5966
- await rm14(p.relayConf, { force: true });
6454
+ await rm15(p.relayConf, { force: true });
5967
6455
  const { relay: _gone, ...rest } = cfg;
5968
6456
  await saveConfig(rest, p);
5969
6457
  return relay;
@@ -5993,7 +6481,7 @@ function boxHasRun(ref, now = Date.now()) {
5993
6481
  if (runs.size === 0) going.delete(keyOf(ref));
5994
6482
  return runs.size > 0;
5995
6483
  }
5996
- async function socketOf(ref, p) {
6484
+ async function socketOf2(ref, p) {
5997
6485
  const meta = await readMachineMeta(ref, p).catch((err) => {
5998
6486
  if (err.code === "ENOENT") throw new NotFoundError(`box ${shown(ref)}`);
5999
6487
  throw err;
@@ -6003,7 +6491,7 @@ async function socketOf(ref, p) {
6003
6491
  return p.machine(meta.owner, meta.name).vsock;
6004
6492
  }
6005
6493
  var OUTPUT_BASE = "v0.16.0";
6006
- var outdated = (ref, err, needs = "v0.15.0") => {
6494
+ var outdated2 = (ref, err, needs = "v0.15.0") => {
6007
6495
  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)`);
6008
6496
  if (isNoAgent(err)) throw new AgentNotAnsweringError(`box ${shown(ref)} did not take the request: its kvbox-agent is not answering (${err.message}); ask again`);
6009
6497
  throw err;
@@ -6014,25 +6502,25 @@ var unanswered = (ref, err, needs) => {
6014
6502
  if (isNoAgent(err) || /kvbox-agent did not answer within/.test(err.message ?? "")) {
6015
6503
  throw new AgentNotAnsweringError(`box ${shown(ref)}: its kvbox-agent is not answering (${err.message}); ask again`);
6016
6504
  }
6017
- return outdated(ref, err, needs);
6505
+ return outdated2(ref, err, needs);
6018
6506
  };
6019
6507
  async function startBoxRun(ref, req, p = paths()) {
6020
- const vsock = await socketOf(ref, p);
6021
- if (req.output) await runOutput(vsock, req.id, "stdout", 0, 0).catch((err) => outdated(ref, err, OUTPUT_BASE));
6508
+ const vsock = await socketOf2(ref, p);
6509
+ if (req.output) await runOutput(vsock, req.id, "stdout", 0, 0).catch((err) => outdated2(ref, err, OUTPUT_BASE));
6022
6510
  const had = going.get(keyOf(ref))?.has(req.id) ?? false;
6023
6511
  note(ref, req.id, Date.now() + req.timeoutSec * 1e3 + 6e4);
6024
6512
  return startRun(vsock, req.id, req.command, req.timeoutSec).catch((err) => {
6025
6513
  if (!had) note(ref, req.id, null);
6026
- return outdated(ref, err);
6514
+ return outdated2(ref, err);
6027
6515
  });
6028
6516
  }
6029
6517
  async function boxRunOutput(ref, id, stream, offset, limit, p = paths()) {
6030
- const vsock = await socketOf(ref, p);
6518
+ const vsock = await socketOf2(ref, p);
6031
6519
  const out = await runOutput(vsock, id, stream, offset, limit).catch((err) => unanswered(ref, err, OUTPUT_BASE));
6032
6520
  return { id, stream, ...out };
6033
6521
  }
6034
6522
  async function boxRunStatus(ref, id, p = paths()) {
6035
- const vsock = await socketOf(ref, p);
6523
+ const vsock = await socketOf2(ref, p);
6036
6524
  const run2 = await runStatus(vsock, id).catch((err) => unanswered(ref, err));
6037
6525
  note(ref, id, run2.state === "running" ? Date.now() + SEEN_RUNNING_MS : null);
6038
6526
  return { id, ...run2 };
@@ -6203,7 +6691,7 @@ import { spawn as spawn3 } from "node:child_process";
6203
6691
  import { accessSync, constants as constants2, openSync as openSync5, readFileSync as readFileSync3, statSync as statSync6 } from "node:fs";
6204
6692
  import { mkdir as mkdir11, readFile as readFile11, stat as stat6 } from "node:fs/promises";
6205
6693
  import { userInfo as userInfo3 } from "node:os";
6206
- import { setTimeout as sleep5 } from "node:timers/promises";
6694
+ import { setTimeout as sleep6 } from "node:timers/promises";
6207
6695
 
6208
6696
  // ../shared/src/systemd.ts
6209
6697
  import { spawnSync } from "node:child_process";
@@ -6239,7 +6727,7 @@ function startsAtBoot(p) {
6239
6727
  }
6240
6728
 
6241
6729
  // src/socketClient.ts
6242
- import { Agent as Agent3, request as request4 } from "undici";
6730
+ import { Agent as Agent3, request as request5 } from "undici";
6243
6731
  var SocketClient = class {
6244
6732
  agent;
6245
6733
  constructor(socketPath) {
@@ -6267,7 +6755,7 @@ var SocketClient = class {
6267
6755
  async call(method, path, schema, body, timeoutMs) {
6268
6756
  let res;
6269
6757
  try {
6270
- res = await request4(`http://kvbox-server${path}`, {
6758
+ res = await request5(`http://kvbox-server${path}`, {
6271
6759
  method,
6272
6760
  dispatcher: this.agent,
6273
6761
  ...timeoutMs === void 0 ? {} : { headersTimeout: timeoutMs, bodyTimeout: timeoutMs },
@@ -6338,7 +6826,7 @@ async function stopDaemon(pid, timeoutMs = 1e4) {
6338
6826
  const deadline = Date.now() + timeoutMs;
6339
6827
  while (alive(pid)) {
6340
6828
  if (Date.now() > deadline) throw new KvboxError(`kvbox-server (pid ${pid}) did not stop within ${timeoutMs / 1e3}s`);
6341
- await sleep5(100);
6829
+ await sleep6(100);
6342
6830
  }
6343
6831
  }
6344
6832
  async function answering(p = paths()) {
@@ -6411,7 +6899,7 @@ async function serving(p, timeoutMs, check) {
6411
6899
  await probe.close();
6412
6900
  }
6413
6901
  }
6414
- await sleep5(100);
6902
+ await sleep6(100);
6415
6903
  }
6416
6904
  throw new KvboxError(`kvbox-server did not start within ${timeoutMs / 1e3}s; see ${p.serverLog}`);
6417
6905
  }
@@ -6464,7 +6952,7 @@ function groupWithMember(gid, user, groupFile) {
6464
6952
  }
6465
6953
 
6466
6954
  // src/listen.ts
6467
- import { readFile as readFile13, rm as rm15, writeFile as writeFile10 } from "node:fs/promises";
6955
+ import { readFile as readFile13, rm as rm16, writeFile as writeFile10 } from "node:fs/promises";
6468
6956
  import { createServer as createHttpsServer } from "node:https";
6469
6957
  import { createAdaptorServer } from "@hono/node-server";
6470
6958
 
@@ -6475,7 +6963,7 @@ var PROXIED_HEADER = "x-kvbox-proxied";
6475
6963
  var VISITOR_PATH_HEADER = "x-kvbox-path";
6476
6964
  var WAKE_HEADER = "x-kvbox-wake";
6477
6965
  var WAKE_WAIT_MS = 3e4;
6478
- var REQUEST_TIMEOUT_MS = 36e5;
6966
+ var REQUEST_TIMEOUT_MS2 = 36e5;
6479
6967
  var WOKE_HEADER = "x-kvbox-woke";
6480
6968
  var VISITOR_AUTH_HEADER = "x-kvbox-authorization";
6481
6969
  var NOT_FORWARDED = /* @__PURE__ */ new Set(["expect"]);
@@ -6505,7 +6993,7 @@ function versionOf(srcFileUrl, injected) {
6505
6993
  }
6506
6994
 
6507
6995
  // src/version.ts
6508
- var VERSION = versionOf(import.meta.url, true ? "0.6.12" : void 0);
6996
+ var VERSION = versionOf(import.meta.url, true ? "0.6.15" : void 0);
6509
6997
 
6510
6998
  // src/caller.ts
6511
6999
  import { createHash as createHash3, timingSafeEqual } from "node:crypto";
@@ -6682,7 +7170,7 @@ function backupStoreRoutes(opts = {}) {
6682
7170
  import { connect as connect2 } from "node:net";
6683
7171
  import { Readable } from "node:stream";
6684
7172
  import { Hono as Hono3 } from "hono";
6685
- import { request as request5 } from "undici";
7173
+ import { request as request6 } from "undici";
6686
7174
 
6687
7175
  // ../shared/src/httpHead.ts
6688
7176
  var END = "\r\n\r\n";
@@ -6827,7 +7315,7 @@ async function forward(c, wake) {
6827
7315
  raw.headers.forEach((value, name) => pairs.push([name, value]));
6828
7316
  let res;
6829
7317
  try {
6830
- res = await request5(`http://${target.ip}:${target.port}${target.path}`, {
7318
+ res = await request6(`http://${target.ip}:${target.port}${target.path}`, {
6831
7319
  method: raw.method,
6832
7320
  headers: boxHeaders(pairs, target).flat(),
6833
7321
  body: raw.body === null ? null : Readable.fromWeb(raw.body),
@@ -7108,18 +7596,18 @@ function machineRoutes() {
7108
7596
 
7109
7597
  // src/routes/runs.ts
7110
7598
  import { Hono as Hono7 } from "hono";
7111
- import { z as z8 } from "zod";
7112
- var refusal = (c, err) => {
7599
+ import { z as z9 } from "zod";
7600
+ var refusal2 = (c, err) => {
7113
7601
  if (err instanceof ProxyFailure) return c.json({ error: err.message, code: err.code }, err.status);
7114
7602
  if (err instanceof BoxOutdatedError) return c.json({ error: err.message, code: "box-outdated" }, 409);
7115
7603
  if (err instanceof AgentNotAnsweringError) return c.json({ error: err.message, code: "unreachable" }, 503);
7116
7604
  if (err instanceof NotFoundError) return c.json({ error: err.message, code: "not-found" }, 404);
7117
7605
  throw err;
7118
7606
  };
7119
- var OutputQuery = z8.object({
7120
- stream: z8.enum(RUN_STREAMS).default("stdout"),
7121
- offset: z8.coerce.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).default(0),
7122
- limit: z8.coerce.number().int().min(0).max(RUN_OUTPUT_MAX_BYTES).default(RUN_OUTPUT_MAX_BYTES)
7607
+ var OutputQuery = z9.object({
7608
+ stream: z9.enum(RUN_STREAMS).default("stdout"),
7609
+ offset: z9.coerce.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).default(0),
7610
+ limit: z9.coerce.number().int().min(0).max(RUN_OUTPUT_MAX_BYTES).default(RUN_OUTPUT_MAX_BYTES)
7123
7611
  });
7124
7612
  function runRoutes(wake = wakeBox) {
7125
7613
  const r = new Hono7();
@@ -7130,7 +7618,7 @@ function runRoutes(wake = wakeBox) {
7130
7618
  const started = await startBoxRun(ref, body);
7131
7619
  return c.json(StartRunAnswerSchema.parse({ id: body.id, started, woke }), 202);
7132
7620
  } catch (err) {
7133
- return refusal(c, err);
7621
+ return refusal2(c, err);
7134
7622
  }
7135
7623
  });
7136
7624
  r.get("/:name/runs/:id", async (c) => {
@@ -7138,7 +7626,7 @@ function runRoutes(wake = wakeBox) {
7138
7626
  const { ref } = await runningBox(c.req.param("name"), c.get("owner"), wants(c.req.header(WAKE_HEADER)) ? wake : void 0);
7139
7627
  return c.json(BoxRunSchema.parse(await boxRunStatus(ref, c.req.param("id"))));
7140
7628
  } catch (err) {
7141
- return refusal(c, err);
7629
+ return refusal2(c, err);
7142
7630
  }
7143
7631
  });
7144
7632
  r.get("/:name/runs/:id/output", async (c) => {
@@ -7151,7 +7639,7 @@ function runRoutes(wake = wakeBox) {
7151
7639
  const { ref } = await runningBox(c.req.param("name"), c.get("owner"));
7152
7640
  return c.json(RunOutputSchema.parse(await boxRunOutput(ref, id, stream, offset, limit)));
7153
7641
  } catch (err) {
7154
- return refusal(c, err);
7642
+ return refusal2(c, err);
7155
7643
  }
7156
7644
  });
7157
7645
  return r;
@@ -7313,7 +7801,7 @@ async function listen(opts = {}) {
7313
7801
  throw new KvboxError(`socket path too long for a Unix socket (${socketPath}); set KVBOX_HOME to a shorter path`);
7314
7802
  }
7315
7803
  if (socketPath === p.serverSock) await refuseSecondDaemon(p);
7316
- await rm15(socketPath, { force: true });
7804
+ await rm16(socketPath, { force: true });
7317
7805
  const server = createAdaptorServer({ fetch: createApp().fetch });
7318
7806
  await new Promise((resolve3, reject) => {
7319
7807
  server.once("error", reject);
@@ -7332,7 +7820,7 @@ async function listen(opts = {}) {
7332
7820
  fetch: createApp({ controlPlane: { name: cp.name, secret: cp.secret } }).fetch,
7333
7821
  createServer: createHttpsServer,
7334
7822
  // A body forwarded to a box may take long to arrive (a large upload through the edge, #182).
7335
- serverOptions: { key, cert, requestTimeout: REQUEST_TIMEOUT_MS }
7823
+ serverOptions: { key, cert, requestTimeout: REQUEST_TIMEOUT_MS2 }
7336
7824
  });
7337
7825
  const appListeners = httpsServer.listeners("request");
7338
7826
  httpsServer.removeAllListeners("request");
@@ -7351,8 +7839,8 @@ async function listen(opts = {}) {
7351
7839
  httpsServer.listen(port, "0.0.0.0", () => resolve3());
7352
7840
  }).catch(async (err) => {
7353
7841
  server.close();
7354
- await rm15(socketPath, { force: true });
7355
- await rm15(p.serverPid, { force: true });
7842
+ await rm16(socketPath, { force: true });
7843
+ await rm16(p.serverPid, { force: true });
7356
7844
  throw new KvboxError(`cannot listen on port ${port} for ${cp.name} (${err.message})`);
7357
7845
  });
7358
7846
  const bound = httpsServer.address().port;
@@ -7363,15 +7851,15 @@ async function listen(opts = {}) {
7363
7851
  new Promise((resolve3) => server.close(() => resolve3())),
7364
7852
  httpsServer ? new Promise((resolve3) => httpsServer.close(() => resolve3())) : void 0
7365
7853
  ]);
7366
- await rm15(socketPath, { force: true });
7367
- await rm15(p.serverPid, { force: true });
7854
+ await rm16(socketPath, { force: true });
7855
+ await rm16(p.serverPid, { force: true });
7368
7856
  };
7369
7857
  const shutdown3 = async () => {
7370
7858
  server.close();
7371
7859
  httpsServer?.close();
7372
7860
  await stopRecovery();
7373
- await rm15(socketPath, { force: true });
7374
- await rm15(p.serverPid, { force: true });
7861
+ await rm16(socketPath, { force: true });
7862
+ await rm16(p.serverPid, { force: true });
7375
7863
  process.exit(0);
7376
7864
  };
7377
7865
  process.once("SIGINT", () => void shutdown3());
@@ -7415,6 +7903,8 @@ var startCommand = new Command("start").description("run the daemon in the foreg
7415
7903
  const cfg = await loadConfig(paths());
7416
7904
  log.info(`control plane ${cfg.controlPlane?.name}: answering on ${https.url}`);
7417
7905
  }
7906
+ await listenForRunning(paths()).catch((err) => log.warn(`running boxes cannot reach their integrations: ${err.message}`));
7907
+ setInterval(() => void closeDeadListeners(paths()).catch(() => void 0), 6e4).unref();
7418
7908
  try {
7419
7909
  const cfg = await loadConfig(paths());
7420
7910
  const state = await driver().net.prepare(cfg);
@@ -7542,7 +8032,7 @@ var leaveCommand = new Command6("leave").description("take this host out from be
7542
8032
 
7543
8033
  // src/commands/logs.ts
7544
8034
  import { open as open2, readFile as readFile14, stat as stat7 } from "node:fs/promises";
7545
- import { setTimeout as sleep6 } from "node:timers/promises";
8035
+ import { setTimeout as sleep7 } from "node:timers/promises";
7546
8036
  import { Command as Command7 } from "commander";
7547
8037
  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) => {
7548
8038
  const n = Number.parseInt(opts.lines, 10);
@@ -7583,7 +8073,7 @@ async function follow(path, write, opts = {}) {
7583
8073
  await fh.close();
7584
8074
  }
7585
8075
  }
7586
- await sleep6(intervalMs, void 0, { signal: opts.signal }).catch(() => void 0);
8076
+ await sleep7(intervalMs, void 0, { signal: opts.signal }).catch(() => void 0);
7587
8077
  }
7588
8078
  }
7589
8079
 
@@ -7617,8 +8107,8 @@ var relayCommand = new Command9("relay").description("reach the internet through
7617
8107
  import { Command as Command11 } from "commander";
7618
8108
 
7619
8109
  // src/core/realm.ts
7620
- import { lstat as lstat2, readFile as readFile15, readdir as readdir7, readlink, rename as rename9, rm as rm16, symlink as symlink2, writeFile as writeFile11 } from "node:fs/promises";
7621
- import { z as z9 } from "zod";
8110
+ 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";
8111
+ import { z as z10 } from "zod";
7622
8112
  var esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7623
8113
  async function ownersIn(root, from, suffix = "") {
7624
8114
  const entries = await readdir7(root).catch((err) => {
@@ -7682,7 +8172,7 @@ async function plan(from, to, p) {
7682
8172
  for (const oldOwner of await ownersIn(p.volumes, from)) {
7683
8173
  await clash(p.ownerVolumes(owner(oldOwner)), `volumes of ${owner(oldOwner)}`);
7684
8174
  for (const name of await namesIn2(p.ownerVolumes(oldOwner))) {
7685
- const meta = await read(p.volume(oldOwner, name).meta, VolumeMetaSchema.extend({ id: z9.string().optional() }), `volume ${oldOwner}/${name}`);
8175
+ const meta = await read(p.volume(oldOwner, name).meta, VolumeMetaSchema.extend({ id: z10.string().optional() }), `volume ${oldOwner}/${name}`);
7686
8176
  out.volumes.push({ oldOwner, name, meta: { ...meta, owner: owner(meta.owner) } });
7687
8177
  }
7688
8178
  }
@@ -7693,6 +8183,14 @@ async function countRealm(from, to, p = paths()) {
7693
8183
  const planned = await plan(from, to, p);
7694
8184
  return { boxes: planned.boxes.length, snapshots: planned.snapshots.length, volumes: planned.volumes.length };
7695
8185
  }
8186
+ async function boundSockets() {
8187
+ try {
8188
+ const lines = (await readFile15("/proc/net/unix", "utf8")).split("\n");
8189
+ return new Set(lines.map((l) => l.split(" ").slice(7).join(" ")).filter((path) => path.startsWith("/")));
8190
+ } catch {
8191
+ return null;
8192
+ }
8193
+ }
7696
8194
  async function writeJson(file, value) {
7697
8195
  const tmp = `${file}.tmp`;
7698
8196
  await writeFile11(tmp, JSON.stringify(value, null, 2) + "\n");
@@ -7706,6 +8204,8 @@ async function renameRealm(from, to, p = paths()) {
7706
8204
  const planned = await plan(from, to, p);
7707
8205
  const tail = new RegExp(`@${esc(from)}$`);
7708
8206
  const owner = (o) => o.replace(tail, `@${to}`);
8207
+ const bound = await boundSockets();
8208
+ 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}`);
7709
8209
  await move(planned.volumes, (o, n) => p.volume(o, n).meta, p.ownerVolumes, await ownersIn(p.volumes, from), owner);
7710
8210
  await move(planned.snapshots, (o, n) => p.snapshot(o, n).meta, p.ownerSnapshots, await ownersIn(p.snapshots, from), owner);
7711
8211
  await move(planned.boxes, (o, n) => p.machine(o, n).meta, p.ownerMachines, await ownersIn(p.machines, from), owner);
@@ -7715,7 +8215,7 @@ async function renameRealm(from, to, p = paths()) {
7715
8215
  const link4 = m.volumeDrive(volume);
7716
8216
  const target = await readlink(link4).catch(() => null);
7717
8217
  if (target !== p.volume(box.oldOwner, volume).disk) continue;
7718
- await rm16(link4, { force: true });
8218
+ await rm17(link4, { force: true });
7719
8219
  await symlink2(p.volume(box.meta.owner, volume).disk, link4);
7720
8220
  }
7721
8221
  }
@@ -7724,7 +8224,7 @@ async function renameRealm(from, to, p = paths()) {
7724
8224
  closeDb(p);
7725
8225
  const cfg = await loadConfig(p);
7726
8226
  if (cfg.controlPlane?.name === from) await saveConfig({ ...cfg, controlPlane: { ...cfg.controlPlane, name: to } }, p);
7727
- const report2 = { from, to, boxes: planned.boxes.length, snapshots: planned.snapshots.length, volumes: planned.volumes.length, keysUpdated: [], keysPending: [] };
8227
+ const report2 = { from, to, boxes: planned.boxes.length, snapshots: planned.snapshots.length, volumes: planned.volumes.length, keysUpdated: [], keysPending: [], integrationsPending };
7728
8228
  for (const box of planned.boxes) {
7729
8229
  const { meta, status } = box;
7730
8230
  if (!(meta.sshKeys ?? []).some(isCaLine)) continue;
@@ -7809,7 +8309,7 @@ var renameRealmCommand = new Command11("rename-realm").description("move this ho
7809
8309
  const to = name ?? await fetchCloudName(p);
7810
8310
  if (from === to) {
7811
8311
  if (!opts.json) console.log(`nothing to do: the control plane is called ${to} and this host's boxes are already under that name`);
7812
- else console.log(JSON.stringify({ from, to, boxes: 0, snapshots: 0, volumes: 0, keysUpdated: [], keysPending: [] }, null, 2));
8312
+ else console.log(JSON.stringify({ from, to, boxes: 0, snapshots: 0, volumes: 0, keysUpdated: [], keysPending: [], integrationsPending: [] }, null, 2));
7813
8313
  return;
7814
8314
  }
7815
8315
  const count = await countRealm(from, to, p);
@@ -7840,6 +8340,9 @@ function describe(report2, restarted) {
7840
8340
  console.log(`moved ${report2.boxes} box(es), ${report2.snapshots} snapshot(s) and ${report2.volumes} volume(s) from ${report2.from} to ${report2.to}`);
7841
8341
  for (const box of report2.keysUpdated) console.log(`box ${box} accepts SSH certificates for ${report2.to} now`);
7842
8342
  for (const k of report2.keysPending) console.log(`box ${k.box} ${WHEN2[k.when]}${k.why ? ` (${k.why})` : ""}`);
8343
+ for (const box of report2.integrationsPending) {
8344
+ console.log(`box ${box} has integrations on and cannot fetch their credentials (git, gh) until it is stopped and started, or hibernated and woken`);
8345
+ }
7843
8346
  console.log(restarted ? "kvbox-server restarted" : "kvbox-server was not running; start it with kvbox-server start -d");
7844
8347
  }
7845
8348