@kvbox/cli 0.5.21 → 0.5.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/kvbox.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../shared/src/errors.ts","../src/output.ts","../src/program.ts","../../shared/src/version.ts","../src/version.ts","../src/commands/vm/index.ts","../src/commands/vm/connect.ts","../src/cert.ts","../../shared/src/paths.ts","../src/session.ts","../src/client.ts","../../shared/src/api.ts","../../shared/src/sizes.ts","../src/kvm.ts","../src/systemd.ts","../src/commands/vm/new.ts","../src/commands/vm/exec.ts","../src/commands/vm/fork.ts","../src/commands/vm/hibernate.ts","../src/commands/vm/ls.ts","../src/commands/vm/pause.ts","../src/commands/vm/proxy/claim.ts","../../shared/src/names.ts","../src/commands/vm/proxy/shared.ts","../src/commands/vm/proxy/index.ts","../src/commands/vm/proxy/add.ts","../src/commands/vm/proxy/ls.ts","../src/commands/vm/proxy/release.ts","../src/commands/vm/proxy/rm.ts","../src/commands/vm/proxy/set-port.ts","../src/commands/vm/rescale.ts","../src/commands/vm/resume.ts","../src/commands/vm/rm.ts","../src/commands/vm/set.ts","../src/commands/vm/start.ts","../src/commands/vm/stop.ts","../src/commands/vm/top.ts","../src/commands/vm/update.ts","../src/commands/vm/usage.ts","../src/commands/vm/wake.ts","../src/commands/server/index.ts","../src/commands/server/join.ts","../src/commands/server/daemon.ts","../src/commands/server/leave.ts","../src/commands/server/relay.ts","../src/commands/server/start.ts","../src/commands/server/status.ts","../src/commands/server/stop.ts","../src/commands/server/trust-ca.ts","../src/commands/login.ts","../src/prompt.ts","../src/commands/logout.ts","../src/commands/whoami.ts","../src/commands/snapshots/index.ts","../src/commands/snapshots/ls.ts","../src/commands/snapshots/new.ts","../src/commands/snapshots/rm.ts","../src/commands/org/index.ts","../src/commands/org/ls.ts","../src/commands/org/context.ts","../src/commands/org/members.ts","../src/commands/org/new.ts","../src/commands/org/rm.ts","../src/commands/org/role.ts","../src/commands/usage.ts","../../shared/src/usage.ts","../src/commands/credit.ts","../src/commands/deploy/index.ts","../src/commands/deploy/config.ts","../src/commands/deploy/templates/pm.ts","../src/commands/deploy/templates/nextjs.ts","../src/commands/deploy/templates/react.ts","../src/commands/deploy/templates/index.ts","../src/commands/deploy/ship.ts","../src/index.ts"],"sourcesContent":["/** Errors with an exit code; the entry point prints `message` and exits with `exitCode`. */\nexport class KvboxError extends Error {\n constructor(\n message: string,\n public readonly exitCode: number = 1,\n ) {\n super(message);\n this.name = \"KvboxError\";\n }\n}\n\nexport class NotImplementedError extends KvboxError {\n constructor(what: string) {\n super(`${what}: not implemented yet`, 2);\n this.name = \"NotImplementedError\";\n }\n}\n\n/** The named box/snapshot/host does not exist: HTTP 404, exit 1. */\nexport class NotFoundError extends KvboxError {\n constructor(what: string) {\n super(`${what}: not found`, 1);\n this.name = \"NotFoundError\";\n }\n}\n\n/** The caller is known but the rule says no (an org member outside their role): HTTP 403, exit 1. */\nexport class ForbiddenError extends KvboxError {\n constructor(message: string) {\n super(message, 1);\n this.name = \"ForbiddenError\";\n }\n}\n\n/** A bare name that is in more than one of the caller's orgs (#68); the CLI and the control plane say it the same way. */\nexport class AmbiguousRefError extends KvboxError {\n /** `orgFlag` false: `--org` names something else on this command (a fork's target), so only `slug/name` is offered. */\n constructor(kind: string, name: string, slugs: readonly string[], orgFlag = true) {\n const way = orgFlag ? `--org ${slugs[0]} or ${slugs[0]}/${name}` : `${slugs[0]}/${name}`;\n super(`${kind} ${name} exists in ${slugs.slice(0, -1).join(\", \")} and ${slugs.at(-1)}; say which with ${way}`, 1);\n this.name = \"AmbiguousRefError\";\n }\n}\n","/** Printing: tables for humans, `--json` for agents, colors only on a TTY. */\nimport { AmbiguousRefError } from \"@kvbox/shared/errors\";\nimport pc from \"picocolors\";\n\nexport const color = pc.createColors(process.stdout.isTTY === true && !process.env[\"NO_COLOR\"]);\n\nexport function json(value: unknown): void {\n process.stdout.write(JSON.stringify(value, null, 2) + \"\\n\");\n}\n\n// eslint-disable-next-line no-control-regex\nconst ANSI = /\\x1b\\[[0-9;]*m/g;\n/** Printed width of a cell: color codes take no columns. */\nconst width = (s: string) => s.replace(ANSI, \"\").length;\n\n/** Cells may carry color codes; alignment uses the visible text. */\nexport function table(rows: Record<string, string | number | null | undefined>[], columns?: string[]): void {\n if (rows.length === 0) return;\n const cols = columns ?? Object.keys(rows[0]!);\n const cells = rows.map((r) => cols.map((c) => String(r[c] ?? \"\")));\n const widths = cols.map((c, i) => Math.max(c.length, ...cells.map((r) => width(r[i]!))));\n const line = (parts: string[]) =>\n parts.map((p, i) => p + \" \".repeat(Math.max(0, widths[i]! - width(p)))).join(\" \").trimEnd();\n process.stdout.write(color.dim(line(cols.map((c) => c.toUpperCase()))) + \"\\n\");\n for (const row of cells) process.stdout.write(line(row) + \"\\n\");\n}\n\nexport function info(msg: string): void {\n process.stderr.write(msg + \"\\n\");\n}\n\nexport function warn(msg: string): void {\n process.stderr.write(color.yellow(msg) + \"\\n\");\n}\n\nexport function notImplemented(command: string): never {\n process.stderr.write(color.yellow(`kvbox ${command}: not implemented yet\\n`));\n process.exit(2);\n}\n\n/** y/N prompt on a TTY; requires `-y` otherwise (boxd's rule for destructive commands). */\nexport async function confirm(question: string, yes: boolean): Promise<boolean> {\n if (yes) return true;\n if (!process.stdin.isTTY) {\n warn(\"refusing without -y when stdin is not a terminal\");\n return false;\n }\n const { createInterface } = await import(\"node:readline/promises\");\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n try {\n const answer = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();\n return answer === \"y\" || answer === \"yes\";\n } finally {\n rl.close();\n }\n}\n\n/** Bytes for humans: 4 GiB -> \"4 GB\", 3.4 GiB -> \"3.4 GB\", under 1 GiB -> \"640 MB\". */\nexport function gb(bytes: number): string {\n const g = bytes / 1024 ** 3;\n if (g >= 1) return `${Number.isInteger(g) ? g : g.toFixed(1)} GB`;\n return `${Math.round(bytes / 1024 ** 2)} MB`;\n}\n\n/** Compact byte count for a table cell: \"4GB\", \"3.4GB\", \"640MB\". */\nexport function gbShort(bytes: number): string {\n return gb(bytes).replace(\" \", \"\");\n}\n\n/** \"2×4GB · 8GB disk\": the shape of a box in one cell. */\nexport function shape(vcpu: number, memMib: number, diskBytes?: number): string {\n const cpuRam = `${vcpu}×${gbShort(memMib * 1024 ** 2)}`;\n return diskBytes === undefined ? cpuRam : `${cpuRam} · ${gbShort(diskBytes)} disk`;\n}\n\n/** Box name as it appears in every table: one color, so the eye finds it first. */\nexport function boxName(name: string): string {\n return color.cyan(name);\n}\n\n/** Status word, colored: running green, asleep (standby, hibernated) yellow, anything else dim. */\nexport function status(s: string): string {\n if (s === \"running\") return color.green(s);\n if (s === \"standby\" || s === \"hibernated\") return color.yellow(s);\n return color.dim(s);\n}\n\n/** How long ago an ISO timestamp was, in docker's style: \"just now\", \"5m ago\", \"2h ago\", \"3d ago\". */\nexport function age(iso: string, now = Date.now()): string {\n const sec = Math.max(0, Math.floor((now - Date.parse(iso)) / 1000));\n if (sec < 60) return \"just now\";\n const min = Math.floor(sec / 60);\n if (min < 60) return `${min}m ago`;\n const hr = Math.floor(min / 60);\n if (hr < 24) return `${hr}h ago`;\n const day = Math.floor(hr / 24);\n if (day < 30) return `${day}d ago`;\n const month = Math.floor(day / 30);\n if (month < 12) return `${month}mo ago`;\n return `${Math.floor(day / 365)}y ago`;\n}\n\n/** Seconds for humans, the two biggest units: \"1d 6h\", \"20h 14m\", \"5m 3s\", \"52s\"; \"-\" for none. */\nexport function duration(seconds: number): string {\n const s = Math.max(0, Math.round(seconds));\n if (s === 0) return \"-\";\n const d = Math.floor(s / 86400);\n const h = Math.floor((s % 86400) / 3600);\n const m = Math.floor((s % 3600) / 60);\n const sec = s % 60;\n if (d > 0) return `${d}d ${h}h`;\n if (h > 0) return `${h}h ${m}m`;\n if (m > 0) return `${m}m ${sec}s`;\n return `${sec}s`;\n}\n\n/** Resource-hours for humans: one decimal under 100 (\"40.5\"), whole above (\"118\"). */\nexport function hours(h: number): string {\n return h < 100 ? String(Math.round(h * 10) / 10) : String(Math.round(h));\n}\n\n/** The bare slug of an owner: `acme@kvbox.sh` → `acme`; a local owner is already bare. */\nexport function slugOf(owner: string): string {\n const at = owner.indexOf(\"@\");\n return at === -1 ? owner : owner.slice(0, at);\n}\n\n/**\n * The item the user named in a listing (#68): `acme/lab1` (the owner's slug) or the full\n * `acme@kvbox.sh/lab1` is explicit; a bare `lab1` is the user's own (`me`) when they have one, else\n * the single org item of that name, else an error naming the candidates. Another user's private\n * box (an admin lists those) is never a bare name's. Undefined when nothing matches.\n */\nexport function pickRef<T extends { name: string; owner: string; ownerKind?: \"user\" | \"org\" | undefined }>(items: T[], text: string, me: string | undefined, kind = \"box\"): T | undefined {\n if (text.includes(\"/\")) return items.find((i) => text === `${slugOf(i.owner)}/${i.name}` || text === `${i.owner}/${i.name}`);\n const named = items.filter((i) => i.name === text);\n const own = named.find((i) => slugOf(i.owner) === me);\n if (own) return own;\n const orgs = me === undefined ? named : named.filter((i) => i.ownerKind !== \"user\"); // no user: this machine's socket, one owner\n if (orgs.length <= 1) return orgs[0];\n throw new AmbiguousRefError(kind, text, orgs.map((i) => slugOf(i.owner)));\n}\n\n/** `owner/name` with the owner dropped when it is the same person as `owner`: what a reader needs to see. */\nexport function shortRef(ref: string, owner: string): string {\n return ref.startsWith(`${owner}/`) ? ref.slice(owner.length + 1) : ref;\n}\n\nconst SPINNER_FRAMES = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\n/** Nothing is drawn before this: a 0.2 s pause/resume never shows a spinner, a 15 s hibernate does. */\nconst SPINNER_DELAY_MS = 150;\nconst SPINNER_FRAME_MS = 80;\n\nexport interface SpinOptions {\n /** Where the spinner is drawn and whether it is a terminal; defaults to stderr. */\n stream?: NodeJS.WriteStream;\n /** Milliseconds before the first frame (default 150). */\n delayMs?: number;\n}\n\n/**\n * Run `work` with a spinner on stderr: \"⠋ hibernating lab1…\" redrawn in place until the promise settles,\n * then the line is cleared so the command's own ✓ line takes its place. Off a terminal (pipes, agents,\n * `--json` captured by a script) nothing is written at all; the result and errors pass through untouched.\n */\nexport async function spin<T>(message: string, work: Promise<T> | (() => Promise<T>), opts: SpinOptions = {}): Promise<T> {\n const stream = opts.stream ?? process.stderr;\n const promise = typeof work === \"function\" ? work() : work;\n if (stream.isTTY !== true) return promise;\n\n let frame = 0;\n let drawn = false;\n const draw = () => {\n stream.write(`\\r\\x1b[K${color.cyan(SPINNER_FRAMES[frame % SPINNER_FRAMES.length]!)} ${message}`);\n frame += 1;\n drawn = true;\n };\n let interval: NodeJS.Timeout | undefined;\n const delay = setTimeout(() => {\n draw();\n interval = setInterval(draw, SPINNER_FRAME_MS);\n }, opts.delayMs ?? SPINNER_DELAY_MS);\n try {\n return await promise;\n } finally {\n clearTimeout(delay);\n if (interval !== undefined) clearInterval(interval);\n if (drawn) stream.write(\"\\r\\x1b[K\");\n }\n}\n","/** Builds the commander tree. Importable without side effects (tests); src/index.ts runs it. */\nimport { Command } from \"commander\";\nimport { VERSION } from \"./version.js\";\nimport { vmAliases, vmCommand } from \"./commands/vm/index.js\";\nimport { serverCommand } from \"./commands/server/index.js\";\nimport { loginCommand } from \"./commands/login.js\";\nimport { logoutCommand } from \"./commands/logout.js\";\nimport { whoamiCommand } from \"./commands/whoami.js\";\nimport { snapshotsCommand } from \"./commands/snapshots/index.js\";\nimport { orgCommand } from \"./commands/org/index.js\";\nimport { usageCommand } from \"./commands/usage.js\";\nimport { creditCommand } from \"./commands/credit.js\";\nimport { deployCommand } from \"./commands/deploy/index.js\";\n\nexport function buildProgram(): Command {\n const program = new Command(\"kvbox\")\n .description(\"self-hosted Firecracker microVMs with Docker-like ergonomics\")\n .version(VERSION, \"-v, --version\")\n .option(\"--local\", \"use this machine's kvbox-server over its socket, ignoring kvbox login\")\n .option(\"--org <slug>\", \"the org: where kvbox new creates, and which box a name means when it is not one of yours; before the command here, or after it\")\n .showHelpAfterError()\n .enablePositionalOptions();\n\n program.addCommand(vmCommand);\n program.addCommand(snapshotsCommand);\n program.addCommand(serverCommand);\n program.addCommand(loginCommand);\n program.addCommand(logoutCommand);\n program.addCommand(whoamiCommand);\n program.addCommand(orgCommand);\n program.addCommand(usageCommand);\n program.addCommand(creditCommand);\n program.addCommand(deployCommand);\n // Top-level shortcuts: the same Command objects as under `vm`.\n for (const cmd of vmAliases) program.addCommand(cmd);\n\n return program;\n}\n","/**\n * Each binary's version comes from its own package.json: tsup injects\n * `__KVBOX_VERSION__` at build time; the dev path (tsx) reads the file.\n * Usage in a package: `versionOf(import.meta.url)` from its `src/version.ts`.\n */\nimport { createRequire } from \"node:module\";\n\nexport function versionOf(srcFileUrl: string, injected?: string): string {\n if (typeof injected === \"string\") return injected;\n try {\n const require = createRequire(srcFileUrl);\n return (require(\"../package.json\") as { version: string }).version;\n } catch {\n return \"0.0.0-dev\";\n }\n}\n","import { versionOf } from \"@kvbox/shared/version\";\n\ndeclare const __KVBOX_VERSION__: string | undefined;\n\nexport const VERSION: string = versionOf(import.meta.url, typeof __KVBOX_VERSION__ === \"string\" ? __KVBOX_VERSION__ : undefined);\n","import { Command } from \"commander\";\nimport { connectCommand } from \"./connect.js\";\nimport { execCommand } from \"./exec.js\";\nimport { forkCommand } from \"./fork.js\";\nimport { hibernateCommand } from \"./hibernate.js\";\nimport { lsCommand } from \"./ls.js\";\nimport { newCommand } from \"./new.js\";\nimport { pauseCommand } from \"./pause.js\";\nimport { claimCommand } from \"./proxy/claim.js\";\nimport { proxyCommand } from \"./proxy/index.js\";\nimport { rescaleCommand } from \"./rescale.js\";\nimport { resumeCommand } from \"./resume.js\";\nimport { rmCommand } from \"./rm.js\";\nimport { setCommand } from \"./set.js\";\nimport { startCommand } from \"./start.js\";\nimport { stopCommand } from \"./stop.js\";\nimport { topCommand } from \"./top.js\";\nimport { updateCommand } from \"./update.js\";\nimport { usageCommand } from \"./usage.js\";\nimport { wakeCommand } from \"./wake.js\";\n\nexport const vmCommand = new Command(\"vm\")\n .enablePositionalOptions()\n .description(\"manage boxes (each one is a Firecracker microVM)\")\n .addCommand(newCommand)\n .addCommand(forkCommand)\n .addCommand(lsCommand)\n .addCommand(connectCommand)\n .addCommand(execCommand)\n .addCommand(stopCommand)\n .addCommand(startCommand)\n .addCommand(pauseCommand)\n .addCommand(resumeCommand)\n .addCommand(hibernateCommand)\n .addCommand(wakeCommand)\n .addCommand(updateCommand)\n .addCommand(rescaleCommand)\n .addCommand(setCommand)\n .addCommand(usageCommand)\n .addCommand(topCommand)\n .addCommand(proxyCommand)\n .addCommand(rmCommand);\n\n/** `--org` goes after the command like every other flag (the root's `--org` must come before it); the leaf's value wins. */\nfor (const cmd of vmCommand.commands) if (cmd !== proxyCommand) cmd.option(\"--org <slug>\", \"act in this org (- for your personal boxes)\");\n\n/**\n * The same Command objects, added again at the top level so they cannot drift. Only the daily\n * ones: a new vm command gets a shortcut when people type it every day, not by default\n * (fork, update, rescale, set, usage, top and proxy stay under `kvbox vm`, so the top level does not fill up).\n * `claim` is the one proxy command with a shortcut: giving a box its HTTPS address is the daily step.\n */\nexport const vmAliases = [newCommand, lsCommand, connectCommand, execCommand, stopCommand, startCommand, pauseCommand, resumeCommand, hibernateCommand, wakeCommand, rmCommand, claimCommand];\n","import { spawnSync } from \"node:child_process\";\nimport { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { ensureCert, renewAfterRefusal } from \"../../cert.js\";\nimport { boxesFor, clientFor, me, sshArgs, sshEndpoint, waitForSsh, wakeUp, type SshEndpoint } from \"../../client.js\";\nimport { info, pickRef, spin } from \"../../output.js\";\nimport { displayName } from \"./new.js\";\n\n/** ssh's own status when it could not connect or was refused. */\nconst SSH_FAILED = 255;\n\n/**\n * kvbox vm connect <name> [-- cmd...] — ssh into the box with the kvbox key; a shell, or run a command.\n * On this machine that is the box's ip; through the control plane its host's public address and port (#21).\n * A stopped box is started first, a sleeping one resumed or woken: \"connect\" means \"get me in\", not\n * \"fail because I forgot start\".\n */\nexport const connectCommand = new Command(\"connect\")\n .alias(\"cn\")\n .description(\"open a shell in a box over SSH (or run a command: kvbox connect <name> -- <cmd>)\")\n .argument(\"<name>\", \"box name\")\n .argument(\"[cmd...]\", \"command to run instead of a shell\")\n .passThroughOptions()\n .action(async (name: string, cmdArgs: string[], _opts: unknown, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n let ep: SshEndpoint;\n let cert: \"local\" | \"kept\" | \"renewed\";\n let owner: string;\n try {\n let box = pickRef(await boxesFor(client, name), name, me(client));\n if (!box) throw new KvboxError(`box ${name}: not found (kvbox ls)`);\n // The box trusts the CA for its owner (#51, orgs phase 4): settle the certificate first, so a\n // refusal does not leave a box it woke or booted (and bills) behind.\n cert = await ensureCert(client, undefined, undefined, { owner: box.owner });\n owner = box.owner;\n const wasRunning = box.status === \"running\";\n if (!wasRunning) box = await wakeUp(client, box, displayName(box, me(client)));\n ep = sshEndpoint(box, client.target);\n if (!wasRunning) await spin(`waiting for ${name} to accept SSH…`, waitForSsh(ep));\n } finally {\n await client.close();\n }\n let res = spawnSync(\"ssh\", [...sshArgs(ep), ...cmdArgs], { stdio: \"inherit\" });\n if (res.error) throw new KvboxError(`could not run ssh: ${res.error.message}`);\n if (res.status === SSH_FAILED) {\n // Refused with a certificate that was fine yesterday: the box may trust a new CA (#55). Renew once, try again.\n const again = await clientFor(cmd.optsWithGlobals());\n const retry = await renewAfterRefusal(again, cert, owner).finally(() => again.close());\n if (retry) {\n info(\"renewed your SSH certificate, trying again…\");\n res = spawnSync(\"ssh\", [...sshArgs(ep), ...cmdArgs], { stdio: \"inherit\" });\n if (res.error) throw new KvboxError(`could not run ssh: ${res.error.message}`);\n }\n }\n process.exit(res.status ?? 1);\n });\n","/**\n * The SSH certificate for this machine's key (#51). `kvbox login` gets one from the control\n * plane and writes it next to the key (`id_ed25519-cert.pub`), where ssh loads it by itself.\n * It lives one day and names the slugs it opens (the user's and their orgs', orgs phase 4);\n * before connecting to a cloud box the CLI renews it when it is missing, about to expire, or\n * does not name the box's owner yet (the user just joined that org), so the user never sees\n * a box refuse a stale certificate.\n */\nimport { readFile, rm, writeFile } from \"node:fs/promises\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport type { ServerClient } from \"./client.js\";\nimport { readSession, writeSession } from \"./session.js\";\n\n/** Renew when less than this is left: one hour, longer than any ssh session takes to start. */\nexport const RENEW_BEFORE_MS = 60 * 60 * 1000;\n\nexport async function writeCert(cert: string, p: Paths = paths()): Promise<void> {\n await writeFile(p.sshCert, cert.trim() + \"\\n\", { mode: 0o644 });\n}\n\n/**\n * ssh exited 255 against a cloud box: the box may have stopped trusting the CA that signed the\n * certificate on disk (`kvbox server trust-ca` after a rotation, #55). When the certificate was\n * simply kept, renew it once and say so, and the caller tries again; a certificate renewed this\n * very run is as good as it gets, so false.\n */\nexport async function renewAfterRefusal(client: ServerClient, kept: \"local\" | \"kept\" | \"renewed\", owner: string, p: Paths = paths()): Promise<boolean> {\n if (kept !== \"kept\") return false;\n await ensureCert(client, p, Date.now(), { owner, force: true });\n return true;\n}\n\nexport async function removeCert(p: Paths = paths()): Promise<void> {\n await rm(p.sshCert, { force: true });\n}\n\nexport interface EnsureCertOptions {\n /** The box's `owner` (`<slug>@<realm>`): renew unless the certificate is known to name it. */\n owner?: string;\n /** Renew whatever the state (`kvbox org use`: the new org must be on the certificate). */\n force?: boolean;\n}\n\n/**\n * Make sure a usable certificate is on disk before ssh runs against a cloud box. A local target\n * needs none (the box trusts the host's key directly). Renews through `POST /ssh/cert`; a failure\n * there is reported, never swallowed: without the certificate the box would refuse the key.\n */\nexport async function ensureCert(client: ServerClient, p: Paths = paths(), now: number = Date.now(), opts: EnsureCertOptions = {}): Promise<\"local\" | \"kept\" | \"renewed\"> {\n if (client.target.kind !== \"cloud\") return \"local\";\n const session = await readSession(p);\n if (!session) return \"local\";\n const expires = session.sshCertExpires ? new Date(session.sshCertExpires).getTime() : 0;\n const onDisk = await readFile(p.sshCert, \"utf8\").then(() => true, () => false);\n // Whether the certificate is known to open the box: the owner must be among the stored principals.\n const names = opts.owner === undefined || (session.sshCertPrincipals ?? []).includes(opts.owner);\n if (onDisk && expires - now > RENEW_BEFORE_MS && names && !opts.force) return \"kept\";\n const publicKey = await readFile(`${p.sshKey}.pub`, \"utf8\").catch(() => null);\n if (publicKey === null) throw new KvboxError(`could not renew your SSH certificate: no key at ${p.sshKey}.pub; run: kvbox login`);\n let signed;\n try {\n signed = await client.sshCert({ publicKey: publicKey.trim() });\n } catch (err) {\n throw new KvboxError(`could not renew your SSH certificate: ${(err as Error).message}`);\n }\n await writeCert(signed.cert, p);\n await writeSession({ ...session, sshCertExpires: signed.expires, sshCertPrincipals: signed.principals }, p);\n // Renewed and still not named: the user is not in that org (a membership the session remembered is gone, or\n // a platform admin reaching over the API). Say so here; ssh would only say \"Permission denied\".\n if (opts.owner !== undefined && !signed.principals.includes(opts.owner)) {\n const slug = opts.owner.split(\"@\")[0]!;\n const sameSlugElsewhere = signed.principals.find((pr) => pr.split(\"@\")[0] === slug && pr !== opts.owner);\n const why = sameSlugElsewhere\n ? `the control plane signs for ${sameSlugElsewhere} but the box's host qualifies its owner as ${opts.owner}: the control plane's name (KVBOX_CLOUD_NAME) changed after the host joined`\n : `you are not a member of ${slug} (a platform admin reaches org boxes over the API, not over SSH)`;\n throw new KvboxError(`your SSH certificate does not name ${opts.owner}: ${why}`);\n }\n return \"renewed\";\n}\n","/**\n * Host state layout. The filesystem is the database and `~/.kvbox` is its root.\n * This module is dependency-free so both the CLI (socket path, cli.json)\n * and core (everything else) can use it without crossing the layer boundary.\n *\n * `KVBOX_HOME` overrides the root, mainly for tests.\n */\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport function kvboxHome(): string {\n return process.env[\"KVBOX_HOME\"] ?? join(homedir(), \".kvbox\");\n}\n\nexport function paths(home: string = kvboxHome()) {\n return {\n home,\n config: join(home, \"config.json\"),\n /** The host's ledgers (SQLite via node:sqlite): usage events today. Boxes and snapshots stay files; see server core/db.ts. */\n db: join(home, \"kvbox.db\"),\n serverSock: join(home, \"server.sock\"),\n serverPid: join(home, \"server.pid\"),\n serverLog: join(home, \"server.log\"),\n /** The CLI's login to the control plane (`kvbox login`): url, bearer token, user. Mode 600. */\n cli: join(home, \"cli.json\"),\n ssh: join(home, \"ssh\"),\n sshKey: join(home, \"ssh\", \"id_ed25519\"),\n /** The device key signed by the control plane's CA (#51); ssh loads it by itself next to `-i id_ed25519`. */\n sshCert: join(home, \"ssh\", \"id_ed25519-cert.pub\"),\n /** Host keys of the cloud boxes this laptop connected to, one entry per box (`connect`, #21). */\n sshKnownHosts: join(home, \"ssh\", \"known_hosts\"),\n /** The host's self-signed TLS identity for the control plane (`kvbox-server join`): pinned there by fingerprint. */\n tls: join(home, \"tls\"),\n tlsKey: join(home, \"tls\", \"key.pem\"),\n tlsCert: join(home, \"tls\", \"cert.pem\"),\n /** The host's WireGuard tunnel to its relay (`kvbox server relay`, #50): the conf net-setup.sh installs for wg-quick. Mode 600. */\n relay: join(home, \"relay\"),\n relayConf: join(home, \"relay\", \"kvbox.conf\"),\n bin: join(home, \"bin\"),\n firecracker: join(home, \"bin\", \"firecracker\"),\n /** Firecracker's snapshot-editor, from the same release: merges a diff snapshot onto a full memory image. */\n snapshotEditor: join(home, \"bin\", \"snapshot-editor\"),\n assets: join(home, \"assets\"),\n kernel: join(home, \"assets\", \"vmlinux\"),\n /** Symlink to the current base image, assets/rootfs-<version>.ext4; boxes keep using the version they were made from. */\n rootfs: join(home, \"assets\", \"rootfs.ext4\"),\n baseImage: (version: string) => join(home, \"assets\", `rootfs-${version}.ext4`),\n machines: join(home, \"machines\"),\n snapshots: join(home, \"snapshots\"),\n /** Boxes and snapshots are filed by owner: machines/<owner>/<name>. The owner is part of a box's identity. */\n ownerMachines: (owner: string) => join(home, \"machines\", owner),\n ownerSnapshots: (owner: string) => join(home, \"snapshots\", owner),\n machine: (owner: string, name: string) => {\n const dir = join(home, \"machines\", owner, name);\n return {\n dir,\n meta: join(dir, \"meta.json\"),\n /** The box's writable layer, stacked on the read-only base image inside the guest. */\n overlay: join(dir, \"overlay.ext4\"),\n /**\n * The box's memory as of its last snapshot (a hard link to that snapshot's `mem`, never modified).\n * The next snapshot is a diff of the pages dirtied since, merged onto this. Absent after a boot.\n */\n memBase: join(dir, \"mem.base\"),\n /** `kvbox vm fork` (#79): the source's VM state, captured here and gone once the box runs. Its memory is `memBase`. */\n forkVmstate: join(dir, \"fork.vmstate\"),\n /** `kvbox hibernate`: the box's memory image and VM state while it is hibernated; gone again after `wake` or `stop`. */\n hibernateDir: join(dir, \"hibernate\"),\n hibernateVmstate: join(dir, \"hibernate\", \"vmstate\"),\n hibernateMem: join(dir, \"hibernate\", \"mem\"),\n sock: join(dir, \"fc.sock\"),\n /** Firecracker's vsock endpoint: the host connects here to reach kvbox-agent inside the box (core/agent.ts). */\n vsock: join(dir, \"vsock.sock\"),\n log: join(dir, \"fc.log\"),\n };\n },\n snapshot: (owner: string, name: string) => {\n const dir = join(home, \"snapshots\", owner, name);\n return {\n dir,\n meta: join(dir, \"meta.json\"),\n vmstate: join(dir, \"vmstate\"),\n mem: join(dir, \"mem\"),\n /** Copy of the box's overlay at the moment of the snapshot; the base image is referenced by version in meta.json. */\n overlay: join(dir, \"overlay.ext4\"),\n };\n },\n } as const;\n}\n\nexport type Paths = ReturnType<typeof paths>;\n","/**\n * The CLI's login: `~/.kvbox/cli.json` holds the control plane URL, the bearer token `kvbox login`\n * got, the user name and the SSH certificate's expiry, mode 600 (it is a credential). Present →\n * every command targets the control plane; absent → the local Unix socket. `kvbox logout` removes it.\n */\nimport { chmod, mkdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\n\nexport const SessionSchema = z.object({\n url: z.string(),\n token: z.string(),\n user: z.string(),\n /** When the SSH certificate at paths().sshCert stops being accepted (ISO); absent before the first login with a key. */\n sshCertExpires: z.string().optional(),\n /** Whose boxes that certificate opens (`<slug>@<realm>`, the user and their orgs); absent with `sshCertExpires`. */\n sshCertPrincipals: z.array(z.string()).optional(),\n});\nexport type Session = z.infer<typeof SessionSchema>;\n\nexport async function readSession(p: Paths = paths()): Promise<Session | null> {\n let text: string;\n try {\n text = await readFile(p.cli, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw err;\n }\n try {\n return SessionSchema.parse(JSON.parse(text));\n } catch {\n throw new KvboxError(`${p.cli} is unreadable; run: kvbox logout (then log in again)`);\n }\n}\n\nexport async function writeSession(session: Session, p: Paths = paths()): Promise<void> {\n await mkdir(p.home, { recursive: true });\n await writeFile(p.cli, JSON.stringify(session, null, 2) + \"\\n\", { mode: 0o600 });\n await chmod(p.cli, 0o600); // the mode above only applies when the file is created\n}\n\nexport async function clearSession(p: Paths = paths()): Promise<void> {\n await rm(p.cli, { force: true });\n}\n\n/** \"https://api.kvbox.sh/\" → \"api.kvbox.sh\"; \"http://localhost:18080\" → \"localhost:18080\". For messages. */\nexport function hostOf(url: string): string {\n try {\n return new URL(url).host;\n } catch {\n return url;\n }\n}\n\nfunction isLoopback(hostname: string): boolean {\n return hostname === \"localhost\" || hostname.startsWith(\"127.\") || hostname === \"[::1]\";\n}\n\n/** What the user typed as a control plane URL: \"api.kvbox.sh/\" → \"https://api.kvbox.sh\". */\nexport function normalizeUrl(input: string): string {\n const withScheme = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(input) ? input : `https://${input}`;\n let url: URL;\n try {\n url = new URL(withScheme);\n } catch {\n throw new KvboxError(`not a URL: ${input}`);\n }\n if (!/^https?:$/.test(url.protocol) || url.hostname === \"\" || /\\s/.test(input)) throw new KvboxError(`not a URL: ${input}`);\n // The password and then the token travel on this URL: plain http only to this machine (a dev control plane).\n if (url.protocol === \"http:\" && !isLoopback(url.hostname)) {\n throw new KvboxError(`${input}: use https (plain http is only allowed for localhost)`);\n }\n return url.origin + url.pathname.replace(/\\/+$/, \"\");\n}\n","/**\n * ServerClient: one method per route of the kvbox API, over undici.\n * Target resolution: `--local` -> the local Unix socket; else a `kvbox login` session (cli.json) ->\n * the control plane with its bearer token; else the local socket, auto-starting kvbox-server when\n * nothing listens (`startLocalServer`).\n */\nimport { spawn } from \"node:child_process\";\nimport { openSync } from \"node:fs\";\nimport { mkdir, readFile, stat } from \"node:fs/promises\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { Agent, request, type Dispatcher } from \"undici\";\nimport { z } from \"zod\";\nimport {\n type AddMemberRequest,\n ApiErrorSchema,\n BalanceSchema,\n BOX_SSH_USER,\n CapacitySchema,\n type ClaimSubdomainRequest,\n CloudCaSchema,\n CloudOrgSchema,\n type CreateMachineRequest,\n type ForkMachineRequest,\n type CreateOrgRequest,\n type CreateSnapshotRequest,\n HealthSchema,\n type LoginRequest,\n LoginResponseSchema,\n type Machine,\n MachineSchema,\n MachineStatsSchema,\n MachineUsageSchema,\n MeResponseSchema,\n OrgDetailSchema,\n OrgMembershipSchema,\n type OrgRole,\n type PortsRequest,\n type RescaleMachineRequest,\n type SetMachineRequest,\n SnapshotSchema,\n SshCaResponseSchema,\n type SshCertRequest,\n SshCertResponseSchema,\n type SubdomainPortRequest,\n type SubdomainRouteRequest,\n SubdomainSchema,\n TrustCaReportSchema,\n type TrustCaRequest,\n UsageReportSchema,\n} from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { info, spin } from \"./output.js\";\nimport { serverLauncher } from \"./kvm.js\";\nimport { hasUnitFor, startUnitProcess, unitActive, UNIT } from \"./systemd.js\";\nimport { hostOf, readSession } from \"./session.js\";\n\n/**\n * `cloud` with an empty token is the unauthenticated client `kvbox login` itself uses. `org` is the\n * slug bare box names belong to (sent as `X-Kvbox-Org`); absent: the user's own. `user` is the\n * logged-in username, for messages that say whose a box is.\n */\nexport type Target = { kind: \"local\"; socketPath: string } | { kind: \"cloud\"; url: string; token: string; org?: string; user?: string };\n\n/** The root command's global options. */\nexport interface GlobalOptions {\n local?: boolean;\n /** `--org <slug>`: where `kvbox new` creates, and which org a bare name means when the user's own slug has no such box (#68). Nothing is stored. */\n org?: string;\n}\n\nexport const ORG_SLUG_RE = /^[a-z0-9][a-z0-9._-]{0,31}$/;\n\n/** `--org` for this command, checked; undefined when not given (an empty value is not given). */\nexport function orgOption(opts: GlobalOptions): string | undefined {\n if (opts.org === undefined || opts.org === \"\") return undefined;\n if (!ORG_SLUG_RE.test(opts.org)) throw new KvboxError(`${opts.org}: not an org slug (lowercase letters, digits, '.', '_' or '-')`);\n return opts.org;\n}\n\nexport async function resolveTarget(opts: GlobalOptions, p: Paths = paths()): Promise<Target> {\n if (!opts.local) {\n const session = await readSession(p);\n if (session) {\n const org = orgOption(opts);\n return { kind: \"cloud\", url: session.url, token: session.token, user: session.user, ...(org === undefined ? {} : { org }) };\n }\n }\n return { kind: \"local\", socketPath: p.serverSock };\n}\n\nexport interface ClientOptions {\n /** Spawn `kvbox-server` when the local socket does not answer (default true; the start probe turns it off). */\n autoStart?: boolean;\n}\n\n/** A listing's scope: `org` names one slug (default: `--org`'s), `all` asks for the whole platform. */\nexport interface ListOptions {\n org?: string | undefined;\n all?: boolean | undefined;\n}\n\nconst allQuery = (opts: ListOptions): string => (opts.all ? \"?all=1\" : \"\");\n\nexport class ServerClient {\n private readonly dispatcher: Dispatcher;\n private readonly base: string;\n private readonly autoStart: boolean;\n private startedOnce = false;\n\n constructor(\n readonly target: Target,\n opts: ClientOptions = {},\n ) {\n this.autoStart = opts.autoStart ?? true;\n if (target.kind === \"local\") {\n this.dispatcher = new Agent({ connect: { socketPath: target.socketPath } });\n this.base = \"http://kvbox\";\n } else {\n this.dispatcher = new Agent();\n this.base = target.url;\n }\n }\n\n private async call<T>(\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n path: string,\n schema: z.ZodType<T>,\n body?: unknown,\n org: string | undefined = this.target.kind === \"cloud\" ? this.target.org : undefined,\n ): Promise<T> {\n const headers: Record<string, string> = {};\n if (body !== undefined) headers[\"content-type\"] = \"application/json\";\n if (this.target.kind === \"cloud\" && this.target.token !== \"\") headers[\"authorization\"] = `Bearer ${this.target.token}`;\n if (this.target.kind === \"cloud\" && org !== undefined) headers[\"x-kvbox-org\"] = org;\n let res;\n try {\n res = await request(this.base + path, {\n dispatcher: this.dispatcher,\n method,\n headers,\n body: body === undefined ? null : JSON.stringify(body),\n });\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code ?? (err as Error).cause;\n if (this.target.kind === \"local\") {\n // Nothing listens locally: start the daemon once and retry (architecture: \"auto-start\").\n if (this.autoStart && !this.startedOnce) {\n this.startedOnce = true;\n await spin(\"starting kvbox-server…\", startLocalServer(paths(), 5000));\n return this.call(method, path, schema, body);\n }\n throw new KvboxError(`kvbox-server is not running (${String(code)}); start it with: kvbox server start`);\n }\n throw new KvboxError(cloudDown(this.target.url, String(code)));\n }\n const text = await res.body.text();\n const where = this.target.kind === \"cloud\" ? hostOf(this.target.url) : \"kvbox-server\";\n if (res.statusCode >= 300) {\n const parsed = ApiErrorSchema.safeParse(safeJson(text) ?? {});\n // Not our JSON: a reverse proxy's page while the cloud is down, or anything else in the way.\n if (!parsed.success) throw new KvboxError(`${where} answered ${res.statusCode}`);\n if (this.target.kind === \"cloud\" && this.target.token !== \"\") {\n // A logged-in call: the token was revoked or expired.\n if (res.statusCode === 401) throw new KvboxError(\"session expired: kvbox login\");\n // The --org org does not know the user (removed, left, or the org is gone).\n if (res.statusCode === 404 && this.target.org !== undefined && parsed.data.error === `org ${this.target.org}: not found`) {\n throw new KvboxError(`${parsed.data.error} (you are not in it, or it is gone)`);\n }\n }\n throw new KvboxError(parsed.data.error, res.statusCode === 501 ? 2 : 1);\n }\n if (text === \"\") return schema.parse(undefined);\n const json = safeJson(text);\n if (json === undefined) throw new KvboxError(`${where} answered ${res.statusCode} with something that is not JSON`);\n return schema.parse(json);\n }\n\n health() {\n return this.call(\"GET\", \"/health\", HealthSchema);\n }\n\n capacity() {\n return this.call(\"GET\", \"/capacity\", CapacitySchema);\n }\n\n /**\n * Through a control plane: the user's boxes and their orgs', the `--org` org's, or `org`'s;\n * `all`: every box on the platform (platform admins only, #78).\n */\n listMachines(opts: ListOptions = {}) {\n return this.call(\"GET\", `/machines${allQuery(opts)}`, z.array(MachineSchema), undefined, opts.org);\n }\n\n createMachine(req: CreateMachineRequest) {\n return this.call(\"POST\", \"/machines\", MachineSchema, req);\n }\n\n /** `kvbox vm fork` (#79): `name` is the source; the copy goes to the `--org` slug, else the caller's own. */\n forkMachine(name: string, req: ForkMachineRequest) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/fork`, MachineSchema, req);\n }\n\n stopMachine(name: string) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/stop`, MachineSchema);\n }\n\n startMachine(name: string) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/start`, MachineSchema);\n }\n\n pauseMachine(name: string) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/pause`, MachineSchema);\n }\n\n resumeMachine(name: string) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/resume`, MachineSchema);\n }\n\n hibernateMachine(name: string) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/hibernate`, MachineSchema);\n }\n\n wakeMachine(name: string) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/wake`, MachineSchema);\n }\n\n updateMachine(name: string) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/update`, MachineSchema);\n }\n\n rescaleMachine(name: string, req: RescaleMachineRequest) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/rescale`, MachineSchema, req);\n }\n\n setMachine(name: string, req: SetMachineRequest) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/set`, MachineSchema, req);\n }\n\n /** Publish box ports on the host (#30); the answer is the box with every port it publishes. */\n addPorts(name: string, req: PortsRequest) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/ports`, MachineSchema, req);\n }\n\n /** Stop publishing them (#30). */\n removePorts(name: string, req: PortsRequest) {\n return this.call(\"DELETE\", `/machines/${encodeURIComponent(name)}/ports`, MachineSchema, req);\n }\n\n /** HTTPS names (#31), the control plane's only: the box's subdomain, claimed for its default port. */\n claimSubdomain(name: string, req: ClaimSubdomainRequest) {\n return this.call(\"PUT\", `/machines/${encodeURIComponent(name)}/subdomain`, SubdomainSchema, req);\n }\n\n setSubdomainPort(name: string, req: SubdomainPortRequest) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/subdomain/port`, SubdomainSchema, req);\n }\n\n releaseSubdomain(name: string) {\n return this.call(\"DELETE\", `/machines/${encodeURIComponent(name)}/subdomain`, SubdomainSchema);\n }\n\n /** `<route>.<sub>`: a named port under the box's subdomain. */\n addSubdomainRoute(name: string, req: SubdomainRouteRequest) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/subdomain/routes`, SubdomainSchema, req);\n }\n\n removeSubdomainRoute(name: string, route: string) {\n return this.call(\"DELETE\", `/machines/${encodeURIComponent(name)}/subdomain/routes/${encodeURIComponent(route)}`, SubdomainSchema);\n }\n\n /** Every readable box's subdomain. */\n listSubdomains() {\n return this.call(\"GET\", \"/subdomains\", z.array(SubdomainSchema));\n }\n\n /** A running box's own load, memory and disk, asked of its guest (#67). */\n machineStats(name: string) {\n return this.call(\"GET\", `/machines/${encodeURIComponent(name)}/stats`, MachineStatsSchema);\n }\n\n /** `since`: an ISO date, already validated; the server counts from the box's creation without it. */\n machineUsage(name: string, since?: string) {\n const query = since === undefined ? \"\" : `?since=${encodeURIComponent(since)}`;\n return this.call(\"GET\", `/machines/${encodeURIComponent(name)}/usage${query}`, MachineUsageSchema);\n }\n\n /** Every box of the caller over the window (#41 on a host, #42 through a control plane); dates as the user wrote them. */\n usageReport(since?: string, until?: string, all = false) {\n const q = new URLSearchParams();\n if (all) q.set(\"all\", \"1\");\n if (since !== undefined) q.set(\"since\", since);\n if (until !== undefined) q.set(\"until\", until);\n const query = q.size === 0 ? \"\" : `?${q.toString()}`;\n return this.call(\"GET\", `/usage${query}`, UsageReportSchema);\n }\n\n /** The prepaid balance of the caller's slug, or of `org` (default: `--org`'s) (#76); a control plane only. */\n balance(org?: string) {\n return this.call(\"GET\", \"/billing/balance\", BalanceSchema, undefined, org);\n }\n\n deleteMachine(name: string) {\n return this.call(\"DELETE\", `/machines/${encodeURIComponent(name)}`, z.undefined());\n }\n\n /** Like `listMachines`, for snapshots. */\n listSnapshots(opts: ListOptions = {}) {\n return this.call(\"GET\", `/snapshots${allQuery(opts)}`, z.array(SnapshotSchema), undefined, opts.org);\n }\n\n createSnapshot(req: CreateSnapshotRequest) {\n return this.call(\"POST\", \"/snapshots\", SnapshotSchema, req);\n }\n\n deleteSnapshot(name: string) {\n return this.call(\"DELETE\", `/snapshots/${encodeURIComponent(name)}`, z.undefined());\n }\n\n // ---- control plane only (`kvbox login`, `logout`, `whoami`) ----\n\n login(req: LoginRequest) {\n return this.call(\"POST\", \"/login\", LoginResponseSchema, req);\n }\n\n logout() {\n return this.call(\"POST\", \"/logout\", z.unknown()).then(() => undefined);\n }\n\n me() {\n return this.call(\"GET\", \"/me\", MeResponseSchema);\n }\n\n // ---- orgs (`kvbox org …`) ----\n\n listOrgs() {\n return this.call(\"GET\", \"/orgs\", z.array(OrgMembershipSchema));\n }\n\n createOrg(req: CreateOrgRequest) {\n return this.call(\"POST\", \"/orgs\", CloudOrgSchema, req);\n }\n\n getOrg(slug: string) {\n return this.call(\"GET\", `/orgs/${encodeURIComponent(slug)}`, OrgDetailSchema);\n }\n\n deleteOrg(slug: string) {\n return this.call(\"DELETE\", `/orgs/${encodeURIComponent(slug)}`, z.undefined());\n }\n\n addMember(slug: string, req: AddMemberRequest) {\n return this.call(\"POST\", `/orgs/${encodeURIComponent(slug)}/members`, z.undefined(), req);\n }\n\n setRole(slug: string, username: string, role: OrgRole) {\n return this.call(\"PATCH\", `/orgs/${encodeURIComponent(slug)}/members/${encodeURIComponent(username)}`, z.unknown(), { role }).then(() => undefined);\n }\n\n removeMember(slug: string, username: string) {\n return this.call(\"DELETE\", `/orgs/${encodeURIComponent(slug)}/members/${encodeURIComponent(username)}`, z.undefined());\n }\n\n /** Sign this machine's key again (#51); the key must be one the user logged in with. */\n sshCert(req: SshCertRequest) {\n return this.call(\"POST\", \"/ssh/cert\", SshCertResponseSchema, req);\n }\n\n sshCa() {\n return this.call(\"GET\", \"/ssh/ca\", SshCaResponseSchema);\n }\n\n /** This host's socket only (#55): the CA its control plane says boxes should trust. */\n cloudCa() {\n return this.call(\"GET\", \"/ssh/cloud-ca\", CloudCaSchema);\n }\n\n /** This host's socket only (#55): make every cloud box on it trust this CA. */\n trustCa(req: TrustCaRequest) {\n return this.call(\"POST\", \"/ssh/trust-ca\", TrustCaReportSchema, req);\n }\n\n async close() {\n await this.dispatcher.close();\n }\n}\n\n/**\n * The control plane did not answer. kvbox.sh has a status page; a dev control plane does not, so that\n * message points at the way back to this machine instead.\n */\nexport function cloudDown(url: string, code: string): string {\n const host = hostOf(url);\n const hint = host.endsWith(\"kvbox.sh\") ? \"check status.kvbox.sh\" : \"use --local for this machine, or kvbox logout\";\n return `${host} is not available or is down (${code}). You are logged in there, so kvbox talks to it instead of this machine; ${hint}`;\n}\n\nfunction safeJson(text: string): unknown {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Bring a box that is not running to running the way its state asks for: start a stopped one, resume\n * one in standby, wake a hibernated one. Says what it is doing. Returns the box as the server sees it now.\n */\nexport async function wakeUp(client: ServerClient, box: Machine, name: string): Promise<Machine> {\n switch (box.status) {\n case \"standby\":\n info(`box ${name} is in standby; resuming it`);\n return spin(`resuming ${name}…`, client.resumeMachine(name));\n case \"hibernated\":\n info(`box ${name} is hibernated; waking it`);\n return spin(`waking ${name} (loading its memory from disk)…`, client.wakeMachine(name));\n case \"stopped\":\n info(`box ${name} is stopped; starting it`);\n return spin(`booting ${name}…`, client.startMachine(name));\n default:\n return box;\n }\n}\n\n/**\n * The listing a box is picked from (`pickRef`): `slug/name` through a control plane lists that slug\n * alone, so a box outside the default listing (a platform admin's reach, #78) is still found.\n */\nexport function boxesFor(client: ServerClient, text: string): Promise<Machine[]> {\n const slash = text.indexOf(\"/\");\n if (slash === -1 || client.target.kind !== \"cloud\") return client.listMachines();\n return client.listMachines({ org: text.slice(0, slash).split(\"@\")[0] });\n}\n\n/** The logged-in user's slug, for telling their own boxes from an org's in a listing; undefined on this machine. */\nexport const me = (client: ServerClient): string | undefined => (client.target.kind === \"cloud\" ? client.target.user : undefined);\n\n/** Build a client from the root command's global options (`--local`). */\nexport async function clientFor(opts: { local?: boolean }, client: ClientOptions = {}): Promise<ServerClient> {\n return new ServerClient(await resolveTarget(opts), client);\n}\n\n/** Where `ssh` reaches a box, and under what name its host key is remembered. */\nexport interface SshEndpoint {\n host: string;\n port: number;\n user: string;\n /**\n * known_hosts name for a cloud box: the box's id on its host. Public ports get reused by later\n * boxes, so keying the host key by `[host]:port` would make the next box look like an impostor;\n * keyed by box, a new box is simply a new entry. Absent for a local box (no known_hosts at all).\n */\n alias?: string;\n}\n\n/**\n * How to reach a box over ssh from here (#21). On this machine: its private ip on the host's\n * bridge. Through the control plane: the host's public address and the port the host opened for\n * the box, which the control plane adds to every box it answers with.\n */\nexport function sshEndpoint(box: Machine, target: Target): SshEndpoint {\n if (target.kind === \"local\") return { host: box.ip, port: 22, user: BOX_SSH_USER };\n if (box.ssh === undefined) throw new KvboxError(`box ${box.name} has no public SSH port`);\n return { ...box.ssh, alias: `${box.id}.${box.ssh.host}` };\n}\n\n/**\n * `ssh` argv for a box. A local box's host key is not checked: keys are per box and ips get\n * reused. A cloud box's is remembered on first use under its alias (see SshEndpoint) in kvbox's\n * own known_hosts, so a changed key is refused like ssh always does. SetEnv pins the locale\n * because the image only ships C.UTF-8 (#24).\n */\nexport function sshArgs(ep: SshEndpoint, p: Paths = paths()): string[] {\n const hostKey =\n ep.alias === undefined\n ? [\"-o\", \"StrictHostKeyChecking=no\", \"-o\", \"UserKnownHostsFile=/dev/null\"]\n : [\"-o\", \"StrictHostKeyChecking=accept-new\", \"-o\", `UserKnownHostsFile=${p.sshKnownHosts}`, \"-o\", `HostKeyAlias=${ep.alias}`];\n return [\n \"-i\", p.sshKey,\n \"-p\", String(ep.port),\n ...hostKey,\n \"-o\", \"LogLevel=ERROR\",\n // A quiet open session still moves a few bytes a minute, so the host's auto-hibernate (#47) sees it.\n \"-o\", \"ServerAliveInterval=60\",\n \"-o\", \"SetEnv=LC_ALL=C.UTF-8\",\n `${ep.user}@${ep.host}`,\n ];\n}\n\n/**\n * Resolve once something accepts a TCP connection on the endpoint, or reject after `timeoutMs`.\n * A freshly started box takes a second or two before sshd listens; ssh itself would just fail.\n */\nexport async function waitForSsh(ep: Pick<SshEndpoint, \"host\" | \"port\">, timeoutMs = 30_000): Promise<void> {\n const { connect } = await import(\"node:net\");\n const deadline = Date.now() + timeoutMs;\n const attempt = () =>\n new Promise<boolean>((resolve) => {\n const sock = connect({ host: ep.host, port: ep.port, timeout: 1000 });\n sock.once(\"connect\", () => { sock.destroy(); resolve(true); });\n sock.once(\"timeout\", () => { sock.destroy(); resolve(false); });\n sock.once(\"error\", () => resolve(false));\n });\n while (Date.now() < deadline) {\n if (await attempt()) return;\n await new Promise((r) => setTimeout(r, 250));\n }\n throw new KvboxError(`box at ${ep.host}:${ep.port} did not answer within ${Math.round(timeoutMs / 1000)}s`);\n}\n\nexport const NOT_A_HOST_HINT =\n \"kvbox-server is not installed, so this machine is not a kvbox host. \" +\n \"Set it up with install-server.sh, or log in to the cloud with: kvbox login\";\n\n/**\n * The last `error: …` line of server.log, which is why a daemon that just died did not come up.\n * `from`: only what was written past that byte offset (this start's lines, not an earlier run's).\n */\nasync function lastErrorLine(logPath: string, from = 0): Promise<string | undefined> {\n const { readFile } = await import(\"node:fs/promises\");\n const text = (await readFile(logPath).catch(() => Buffer.alloc(0))).subarray(from).toString(\"utf8\");\n const lines = text.trimEnd().split(\"\\n\").slice(-20).reverse();\n return lines.find((l) => l.startsWith(\"error: \"))?.slice(\"error: \".length);\n}\n\n/**\n * Spawn `kvbox-server start` from PATH, detached, stdio to ~/.kvbox/server.log,\n * and resolve once its socket accepts a /health call (or reject after `timeoutMs`).\n * Where install-server.sh set up the systemd unit for this home (#29), systemd does the spawning\n * instead, so the server running is the one it keeps and brings back at boot.\n * When this process cannot open /dev/kvm but the user is in its group, the daemon is started\n * through `sg <group>` so it can (#61, `serverLauncher`); the pid is then read from server.pid,\n * which the daemon writes itself, since the child here would be sg.\n */\nexport async function startLocalServer(p: Paths = paths(), timeoutMs = 5000): Promise<{ pid: number; socketPath: string; viaGroup: string | undefined }> {\n await mkdir(p.home, { recursive: true });\n if (hasUnitFor(p)) return startUnit(p, timeoutMs);\n const log = openSync(p.serverLog, \"a\");\n const launcher = serverLauncher();\n const child = spawn(launcher.cmd, launcher.args, { detached: true, stdio: [\"ignore\", log, log] });\n\n const failed = new Promise<never>((_, reject) => {\n child.once(\"error\", (err: NodeJS.ErrnoException) => {\n reject(new KvboxError(err.code === \"ENOENT\" && launcher.viaGroup === undefined ? NOT_A_HOST_HINT : `could not start kvbox-server: ${err.message}`));\n });\n child.once(\"exit\", (code) => {\n void lastErrorLine(p.serverLog).then((why) => {\n reject(new KvboxError(why === undefined ? `kvbox-server exited with code ${String(code)} before listening; see ${p.serverLog}` : `kvbox-server could not start: ${why}`));\n });\n });\n });\n\n await Promise.race([serving(p, timeoutMs), failed]);\n child.removeAllListeners(\"exit\");\n child.unref();\n const pid = Number.parseInt(await readFile(p.serverPid, \"utf8\").catch(() => \"\"), 10);\n return { pid: Number.isNaN(pid) ? (child.pid ?? -1) : pid, socketPath: p.serverSock, viaGroup: launcher.viaGroup };\n}\n\n/** `systemctl start kvbox-server`, then the same wait for the socket, giving up early if the server exits. */\nasync function startUnit(p: Paths, timeoutMs: number): Promise<{ pid: number; socketPath: string; viaGroup: undefined }> {\n const logFrom = await stat(p.serverLog).then((s) => s.size, () => 0);\n const res = startUnitProcess();\n if (!res.ok) {\n const why = res.out || (await lastErrorLine(p.serverLog, logFrom)) || \"systemctl start failed\";\n throw new KvboxError(`kvbox-server could not start: ${why} (journalctl -u ${UNIT}; rerun install-server.sh if sudo asked for a password)`);\n }\n await serving(p, timeoutMs, async () => {\n if (unitActive()) return;\n const why = (await lastErrorLine(p.serverLog, logFrom)) ?? \"it exited right after starting\";\n throw new KvboxError(`kvbox-server could not start: ${why} (journalctl -u ${UNIT})`);\n });\n const pid = Number.parseInt(await readFile(p.serverPid, \"utf8\").catch(() => \"\"), 10);\n return { pid: Number.isNaN(pid) ? -1 : pid, socketPath: p.serverSock, viaGroup: undefined };\n}\n\n/** Resolve once the socket answers /health; reject after `timeoutMs`, or when `check` throws (polled while waiting). */\nasync function serving(p: Paths, timeoutMs: number, check?: () => Promise<void>): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n await check?.();\n if (await stat(p.serverSock).then(() => true, () => false)) {\n const probe = new ServerClient({ kind: \"local\", socketPath: p.serverSock }, { autoStart: false });\n try {\n await probe.health();\n return;\n } catch {\n // socket exists but not serving yet\n } finally {\n await probe.close();\n }\n }\n await sleep(100);\n }\n throw new KvboxError(`kvbox-server did not start within ${timeoutMs / 1000}s; see ${p.serverLog}`);\n}\n","/**\n * Wire shapes of the kvbox HTTP API, shared by the client (src/cli) and the\n * server (src/server). Validated with zod on both sides because the client\n * may be talking to an older or newer server.\n */\nimport { z } from \"zod\";\nimport { SIZE_NAMES } from \"./sizes.js\";\n\nexport const SizeSchema = z.enum(SIZE_NAMES as [string, ...string[]]);\n\n/** The guest account every box has; `ssh` logs in as it. */\nexport const BOX_SSH_USER = \"kvbox\";\n\n/**\n * A box's state. `running`: Firecracker up, guest executing. `standby`: Firecracker up but frozen (kvbox\n * pause): memory and processes kept, no CPU. `hibernated`: no process; memory dumped to the box's dir\n * (kvbox hibernate), wake continues where it left off. `stopped`: no process, memory gone, next start boots.\n * `unknown`: only from the control plane, for a box whose host did not answer in time (#20).\n */\nexport const BoxStatusSchema = z.enum([\"running\", \"standby\", \"hibernated\", \"stopped\", \"unknown\"]);\nexport type BoxStatus = z.infer<typeof BoxStatusSchema>;\n\n/** A published box port's protocol (#30). */\nexport const PortProtoSchema = z.enum([\"tcp\", \"udp\"]);\nexport type PortProto = z.infer<typeof PortProtoSchema>;\n\n/** At most this many published ports per box (#30): room for a lab of services, not for draining the host's range. */\nexport const MAX_BOX_PORTS = 16;\n\n/**\n * A box port published on the host's public address (#30, `kvbox vm proxy`): `hostPort` on the\n * host reaches `guestPort` in the box. The host port is drawn at random and stays the box's.\n */\nexport const PortForwardSchema = z.object({\n guestPort: z.number().int().min(1).max(65535),\n hostPort: z.number().int(),\n proto: PortProtoSchema,\n /** The host's public address; only the control plane fills it in, as for `ssh`. */\n address: z.string().optional(),\n});\nexport type PortForward = z.infer<typeof PortForwardSchema>;\n\n/** `POST /machines/:name/ports` adds these, `DELETE` removes them; the answer is the box. */\nexport const PortsRequest = z.object({\n ports: z.array(z.object({ guestPort: z.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS),\n});\nexport type PortsRequest = z.infer<typeof PortsRequest>;\n\nconst BoxPortSchema = z.number().int().min(1).max(65535);\n\n/** `PUT /machines/:name/subdomain` (#31): claim `<name>.kvbox.app` for the box, serving `port`. */\nexport const ClaimSubdomainRequest = z.object({ name: z.string(), port: BoxPortSchema });\nexport type ClaimSubdomainRequest = z.infer<typeof ClaimSubdomainRequest>;\n\n/** `POST /machines/:name/subdomain/port`: the default port changes. */\nexport const SubdomainPortRequest = z.object({ port: BoxPortSchema });\nexport type SubdomainPortRequest = z.infer<typeof SubdomainPortRequest>;\n\n/** `POST /machines/:name/subdomain/routes`: `<name>.<sub>.kvbox.app` serves `port`. */\nexport const SubdomainRouteRequest = z.object({ name: z.string(), port: BoxPortSchema });\nexport type SubdomainRouteRequest = z.infer<typeof SubdomainRouteRequest>;\n\n/**\n * A box's HTTPS subdomain (#31): `url` serves the box's `port`, each route's `url` its own port.\n * `owner` is the box's slug (a user's or an org's), `box` its name.\n */\nexport const SubdomainSchema = z.object({\n owner: z.string(),\n box: z.string(),\n subdomain: z.string(),\n port: BoxPortSchema,\n url: z.string(),\n routes: z.array(z.object({ name: z.string(), port: BoxPortSchema, url: z.string() })),\n});\nexport type Subdomain = z.infer<typeof SubdomainSchema>;\n\nexport const MachineSchema = z.object({\n /** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */\n id: z.string(),\n name: z.string(),\n /** Who the box belongs to; names are unique per owner. A bare name is local to the host, `user@control-plane` later. */\n owner: z.string(),\n ip: z.string(),\n mac: z.string(),\n pid: z.number().int().nullable(),\n vcpu: z.number().int(),\n memMib: z.number().int(),\n diskBytes: z.number().int(), // the box's own writable disk, as the guest sees it\n diskUsedBytes: z.number().int(), // what that sparse file really occupies on the host\n base: z.string(), // base image version the box's overlay stacks on\n createdAt: z.string(),\n source: z.string(), // \"base\", \"snapshot:<owner/name>\" or \"fork:<owner/name>\" (#79)\n status: BoxStatusSchema,\n /**\n * Public TCP port on the host that reaches the box's SSH while it runs (#49). Only boxes made\n * through a control plane have one; the control plane adds the host's address for `connect` (#21).\n */\n sshPort: z.number().int().optional(),\n /**\n * Where `ssh` reaches the box from outside: the host's public address and that port (#21). Only\n * the control plane fills it in (a host does not know its own public address); absent for a box\n * whose host reported no port or did not answer.\n */\n ssh: z.object({ host: z.string(), port: z.number().int(), user: z.string() }).optional(),\n /** Box ports published on the host (#30). Absent: none. */\n ports: z.array(PortForwardSchema).optional(),\n /** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /machines`. */\n ownerKind: z.enum([\"user\", \"org\"]).optional(),\n /** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */\n autoHibernateSec: z.number().int().positive().optional(),\n});\nexport type Machine = z.infer<typeof MachineSchema>;\n\nexport const CreateMachineRequest = z.object({\n name: z.string().optional(),\n /** Ignored over the local socket (the caller is the host owner); the control plane sets it over HTTPS. */\n owner: z.string().optional(),\n size: SizeSchema.optional(),\n from: z.string().optional(),\n force: z.boolean().optional(),\n /**\n * Extra authorized_keys lines for the box, on top of the host's own key: the control plane sends\n * its SSH CA as one `cert-authority …` line (#51). Written into the box's authorized_keys at every\n * boot (#49); a host older than that ignores them.\n */\n sshKeys: z.array(z.string()).optional(),\n /** Seconds without network traffic before the box is hibernated (#47); 0: never. Absent: the host's default. */\n autoHibernateSec: z.number().int().min(0).optional(),\n});\nexport type CreateMachineRequest = z.infer<typeof CreateMachineRequest>;\n\n/**\n * `POST /machines/:name/fork` (#79): a new box from `:name` as it is right now. A running or paused\n * source is copied warm (memory and disk, processes keep running); a stopped one cold (its disk, then a\n * fresh boot). Absent fields come from the source: its size and its auto-hibernate.\n */\nexport const ForkMachineRequest = z.object({\n name: z.string().optional(),\n /**\n * The new box's slug, bare (`acme`): the control plane sends the target of `--org` here; the host\n * qualifies it with the caller's realm. Absent: the source's owner. A CLI leaves it out.\n */\n owner: z.string().optional(),\n /** A cold fork only: a warm one keeps the source's vCPU and memory. */\n size: SizeSchema.optional(),\n force: z.boolean().optional(),\n /** As in CreateMachineRequest: the control plane's CA line for the new box's owner. */\n sshKeys: z.array(z.string()).optional(),\n autoHibernateSec: z.number().int().min(0).optional(),\n});\nexport type ForkMachineRequest = z.infer<typeof ForkMachineRequest>;\n\n/**\n * `POST /machines/:name/ssh-keys` on a host (orgs phase 4): replace the authorized_keys lines the box\n * gets on top of the host's own key. Takes effect at the box's next boot (kvbox-init rewrites the\n * file from the kernel command line); a running or hibernated box keeps its current file until then.\n */\nexport const SetSshKeysRequest = z.object({\n sshKeys: z.array(z.string()),\n});\nexport type SetSshKeysRequest = z.infer<typeof SetSshKeysRequest>;\n\n/** `kvbox vm rescale`: a preset and/or explicit values; explicit ones win. Anything omitted stays as it is. */\nexport const RescaleMachineRequest = z.object({\n size: SizeSchema.optional(),\n vcpu: z.number().int().min(1).max(64).optional(),\n memMib: z.number().int().min(256).optional(),\n diskGib: z.number().int().min(1).optional(),\n});\nexport type RescaleMachineRequest = z.infer<typeof RescaleMachineRequest>;\n\n/** `kvbox vm set`: settings that change nothing in the running VM. Anything omitted stays as it is. */\nexport const SetMachineRequest = z.object({\n /** Seconds without network traffic before the box is hibernated (#47); 0: never. */\n autoHibernateSec: z.number().int().min(0).optional(),\n});\nexport type SetMachineRequest = z.infer<typeof SetMachineRequest>;\n\nexport const SnapshotSchema = z.object({\n name: z.string(),\n owner: z.string(),\n source: z.string(), // the box it was taken from, as owner/name\n base: z.string(), // base image version the overlay stacks on; a restore needs the same one\n vcpu: z.number().int(),\n memMib: z.number().int(),\n sizeBytes: z.number().int(), // what vmstate + mem + overlay really occupy on the host\n createdAt: z.string(),\n});\nexport type Snapshot = z.infer<typeof SnapshotSchema>;\n\nexport const CreateSnapshotRequest = z.object({\n box: z.string(),\n name: z.string(),\n});\nexport type CreateSnapshotRequest = z.infer<typeof CreateSnapshotRequest>;\n\nexport const CapacitySchema = z.object({\n hostMemMib: z.number().int(),\n hostCores: z.number().int(),\n reservedMemMib: z.number().int(),\n reservedVcpu: z.number().int(),\n running: z.number().int(),\n});\nexport type Capacity = z.infer<typeof CapacitySchema>;\n\n/**\n * What the server did at its last start about boxes whose Firecracker had died (host reboot or crash,\n * #29). Boxes are `owner/name`. `leftStopped`: they were in standby, their memory went with the process.\n */\nexport const RecoveryReportSchema = z.object({\n at: z.string(),\n booted: z.array(z.string()),\n leftStopped: z.array(z.string()),\n failed: z.array(z.object({ box: z.string(), error: z.string() })),\n});\nexport type RecoveryReport = z.infer<typeof RecoveryReportSchema>;\n\nexport const HealthSchema = z.object({\n ok: z.literal(true),\n version: z.string(),\n pid: z.number().int(),\n /** Base image version new boxes get (null when the host has no usable base image yet). */\n base: z.string().nullable(),\n /** Owner that boxes made over the local socket get (the Unix user running the server). */\n owner: z.string(),\n /** The control plane this host joined (null when none). */\n controlPlane: z\n .object({\n /** Realm name, e.g. kvbox.sh. */\n name: z.string(),\n url: z.string(),\n /** Where this host answers the control plane. */\n hostUrl: z.string(),\n })\n .nullable(),\n /** The relay this host reaches the internet through (#50); null when it has its own public address. Older servers omit it. */\n relay: z\n .object({\n name: z.string(),\n /** The public IP the relay owns for this host. */\n publicIp: z.string(),\n /** The relay's WireGuard endpoint the tunnel dials. */\n endpoint: z.string(),\n /** Times the server redialed the tunnel since it started, because the relay stopped answering. Older servers omit them. */\n restarts: z.number().int().optional(),\n lastRestartAt: z.string().nullable().optional(),\n })\n .nullable()\n .optional(),\n /** Boxes brought back at the server's last start; null when there were none or it is still at it. Older servers omit it. */\n recovery: RecoveryReportSchema.nullable().optional(),\n});\nexport type Health = z.infer<typeof HealthSchema>;\n\n/**\n * `kvbox vm usage <box>`: how long the box spent in each state over a window and what that adds up\n * to. Hours are fractional; the CLI rounds. `cost` is present only when the host prices usage.\n * `historyFrom` is the first recorded moment, null when nothing is recorded yet.\n */\nexport const MachineUsageSchema = z.object({\n name: z.string(),\n owner: z.string(),\n status: BoxStatusSchema,\n window: z.object({ from: z.string(), to: z.string() }),\n seconds: z.object({\n running: z.number().int(),\n standby: z.number().int(),\n hibernated: z.number().int(),\n stopped: z.number().int(),\n }),\n vcpuHours: z.number(),\n ramGibHours: z.number(),\n diskGibHours: z.number(),\n cost: z.object({ amount: z.number(), currency: z.string() }).optional(),\n /** Stops the server did not witness (Firecracker died, host rebooted) and dated to when it noticed. */\n estimatedStops: z.number().int(),\n historyFrom: z.string().nullable(),\n});\nexport type MachineUsage = z.infer<typeof MachineUsageSchema>;\n\n/** What a running box says about itself through kvbox-agent's `stats` (base v0.7.0 and later). */\nexport const GuestStatsSchema = z.object({\n /** Load average over 1, 5 and 15 minutes. */\n load: z.tuple([z.number(), z.number(), z.number()]),\n cpus: z.number().int(),\n memTotalMib: z.number().int(),\n /** Total minus available: page cache counts as free. */\n memUsedMib: z.number().int(),\n /** The box's root, which is its overlay disk: the box's own writes, not the shared base. */\n diskTotalBytes: z.number().int(),\n diskUsedBytes: z.number().int(),\n uptimeSec: z.number().int(),\n});\nexport type GuestStats = z.infer<typeof GuestStatsSchema>;\n\n/** `GET /machines/:name/stats` (#67): `stats` is null when the box's image predates the request. */\nexport const MachineStatsSchema = z.object({\n name: z.string(),\n owner: z.string(),\n stats: GuestStatsSchema.nullable(),\n});\nexport type MachineStats = z.infer<typeof MachineStatsSchema>;\n\n/** A box's state as the usage ledger tells it: a box status, or `removed` when its last row is the `rm`. */\nexport const UsageStatusSchema = z.enum([...BoxStatusSchema.options, \"removed\"]);\nexport type UsageStatus = z.infer<typeof UsageStatusSchema>;\n\n/** One box's share of a `GET /usage` report (#41, #42): the same figures as `MachineUsage`, over the report's window. */\nexport const BoxUsageSchema = MachineUsageSchema.omit({ window: true, status: true }).extend({\n /** The host's box id; a name removed and recreated appears twice, with two ids. */\n id: z.string(),\n status: UsageStatusSchema,\n /** Through a control plane: whether the owner slug is a user's or an org's (what `kvbox ls` shows). */\n ownerKind: z.enum([\"user\", \"org\"]).optional(),\n /**\n * Through a control plane: the username that made the box (#60), absent when the box is gone from\n * the index (removed), was found by reconcile, or its maker was deleted. The ledger does not record it.\n */\n createdBy: z.string().optional(),\n});\nexport type BoxUsage = z.infer<typeof BoxUsageSchema>;\n\n/**\n * `GET /usage?since=&until=`: every box of the caller over the window (removed ones included) and\n * the totals. On a host over its socket: the host owner's boxes; through a control plane: every slug\n * the user can read (`X-Kvbox-Org` narrows to one). `cost` is present when the answering side prices usage.\n */\nexport const UsageReportSchema = z.object({\n window: z.object({ from: z.string(), to: z.string() }),\n boxes: z.array(BoxUsageSchema),\n totals: z.object({\n seconds: MachineUsageSchema.shape.seconds,\n vcpuHours: z.number(),\n ramGibHours: z.number(),\n diskGibHours: z.number(),\n cost: z.object({ amount: z.number(), currency: z.string() }).optional(),\n }),\n});\nexport type UsageReport = z.infer<typeof UsageReportSchema>;\n\n/**\n * `GET /usage/events?after=<id>&limit=<n>` on a host (#42): the ledger rows after `after`, oldest\n * first, as the control plane pulls them. `next` is the last row's id (the cursor to store), equal\n * to `after` when there was nothing new. Over HTTPS only rows of the caller's realm come back.\n * `ledger` names the host's ledger: row ids are unique only within it, and a new one restarts at 1.\n */\nexport const UsageEventRowSchema = z.object({\n id: z.number().int(),\n boxId: z.string(),\n owner: z.string(),\n name: z.string(),\n at: z.string(),\n state: z.enum([\"running\", \"standby\", \"hibernated\", \"stopped\"]),\n vcpu: z.number().int(),\n memMib: z.number().int(),\n diskGib: z.number().int(),\n by: z.string(),\n});\nexport type UsageEventRow = z.infer<typeof UsageEventRowSchema>;\n\nexport const UsageEventsResponseSchema = z.object({\n ledger: z.string().min(1),\n events: z.array(UsageEventRowSchema),\n next: z.number().int(),\n});\nexport type UsageEventsResponse = z.infer<typeof UsageEventsResponseSchema>;\n\nexport const ApiErrorSchema = z.object({\n error: z.string(),\n});\n\n// ---- control plane (kvbox-cloud) ----\n\n/** Where `kvbox login` goes without a URL, and the control plane's own public URL by default. */\nexport const DEFAULT_CLOUD_URL = \"https://api.kvbox.sh\";\n\n/**\n * Who turned a slug (a user or an org) on: a card on file (`card`, #75) or an admin by hand\n * (`admin`, #74). Until one of them does, the account only logs in and looks: every other route\n * answers 402 (decision \"Signup is email + password… inactive until a card is on file\").\n */\nexport const ACTIVATED_BY = [\"card\", \"admin\"] as const;\nexport const ActivatedBySchema = z.enum(ACTIVATED_BY);\nexport type ActivatedBy = z.infer<typeof ActivatedBySchema>;\n\n/** A user account on the control plane; returned by `GET /me`, `GET /users` (#48). */\nexport const CloudUserSchema = z.object({\n /** The handle: what hosts file boxes under (`<username>@<control plane>`). Lowercase, no `@` or `/`. */\n username: z.string(),\n /** Display name, free text (\"Alexandru Ghiura\"). */\n name: z.string(),\n /** Login identity, unique. */\n email: z.string(),\n role: z.enum([\"admin\", \"user\"]),\n createdAt: z.string(),\n /**\n * False until a card is on file or an admin activates the account (#74): then only `/me` and\n * `/logout` answer. Admins are never gated. A control plane older than #74 does not send these and\n * gates nobody, hence the defaults: a newer CLI must still parse its answers.\n */\n active: z.boolean().default(true),\n activatedBy: ActivatedBySchema.nullable().default(null),\n});\nexport type CloudUser = z.infer<typeof CloudUserSchema>;\n\n// ---- orgs (plan \"Orgs, slugs and roles\") ----\n\nexport const ORG_ROLES = [\"owner\", \"admin\", \"member\"] as const;\nexport const OrgRoleSchema = z.enum(ORG_ROLES);\nexport type OrgRole = z.infer<typeof OrgRoleSchema>;\n\n/** An org as the API shows it; its slug owns boxes the way a username does. */\nexport const CloudOrgSchema = z.object({\n slug: z.string(),\n /** Display name; the slug never changes, this may. */\n name: z.string(),\n createdAt: z.string(),\n /** 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. */\n active: z.boolean().default(true),\n activatedBy: ActivatedBySchema.nullable().default(null),\n});\nexport type CloudOrg = z.infer<typeof CloudOrgSchema>;\n\n/** One of the caller's orgs with their role in it (`GET /orgs`, `GET /me`). */\nexport const OrgMembershipSchema = CloudOrgSchema.extend({ role: OrgRoleSchema });\nexport type OrgMembership = z.infer<typeof OrgMembershipSchema>;\n\nexport const OrgMemberSchema = z.object({\n username: z.string(),\n name: z.string(),\n role: OrgRoleSchema,\n addedAt: z.string(),\n});\nexport type OrgMember = z.infer<typeof OrgMemberSchema>;\n\n/** `GET /orgs/:slug`: the org and its members (members and up see it). */\nexport const OrgDetailSchema = CloudOrgSchema.extend({ members: z.array(OrgMemberSchema) });\nexport type OrgDetail = z.infer<typeof OrgDetailSchema>;\n\n/** `POST /orgs`: the caller becomes the org's owner. */\nexport const CreateOrgRequestSchema = z.object({\n slug: z.string().min(1),\n name: z.string().min(1),\n});\nexport type CreateOrgRequest = z.infer<typeof CreateOrgRequestSchema>;\n\n/** `PATCH /orgs/:slug` (owner): the display name. */\nexport const RenameOrgRequestSchema = z.object({ name: z.string().min(1) });\n\n/** `POST /orgs/:slug/members` (admin, owner): an existing user joins, as a member unless said otherwise. */\nexport const AddMemberRequestSchema = z.object({\n username: z.string().min(1),\n role: OrgRoleSchema.default(\"member\"),\n});\nexport type AddMemberRequest = z.infer<typeof AddMemberRequestSchema>;\n\n/** `PATCH /orgs/:slug/members/:username` (owner). */\nexport const SetRoleRequestSchema = z.object({ role: OrgRoleSchema });\n\n/** `GET /me`: the account plus the orgs it belongs to. */\nexport const MeResponseSchema = CloudUserSchema.extend({ orgs: z.array(OrgMembershipSchema) });\nexport type MeResponse = z.infer<typeof MeResponseSchema>;\n\n// ---- prepaid credit (#76) ----\n\n/**\n * `GET /billing/balance`: what a slug (the caller's own, or `X-Kvbox-Org`'s) has left. `balance` is\n * every top-up minus what the usage ledger says its boxes cost since `since`, the slug's first top-up\n * (null: it never had any); at or below zero the slug cannot start or create anything (402).\n * `topUps` and `spent` are the two sides of it.\n */\nexport const BalanceSchema = z.object({\n slug: z.string(),\n balance: z.number(),\n currency: z.string(),\n topUps: z.number(),\n spent: z.number(),\n /** The first moment usage counts from: the slug's first top-up; null when it has none. */\n since: z.string().nullable(),\n /** 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. */\n suspendedAt: z.string().nullable().default(null),\n});\nexport type Balance = z.infer<typeof BalanceSchema>;\n\n/** `POST /admin/billing/top-ups` (platform admin): give a slug money by hand. */\nexport const TopUpRequestSchema = z.object({\n slug: z.string().min(1),\n /** In the control plane's currency; negative corrects a mistake. */\n amount: z.number().finite(),\n note: z.string().max(200).optional(),\n});\nexport type TopUpRequest = z.infer<typeof TopUpRequestSchema>;\n\n/** One top-up as recorded, answered by `POST /admin/billing/top-ups`. */\nexport const TopUpSchema = z.object({\n id: z.string(),\n slug: z.string(),\n amount: z.number(),\n currency: z.string(),\n source: z.enum([\"admin\", \"card\", \"trial\"]),\n note: z.string().nullable(),\n at: z.string(),\n});\nexport type TopUp = z.infer<typeof TopUpSchema>;\n\n/** `POST /login` body from `kvbox login` (#48); `publicKey` is the user's SSH key to inject into new boxes. */\nexport const LoginRequestSchema = z.object({\n email: z.string().min(1),\n password: z.string().min(1),\n publicKey: z.string().optional(),\n});\nexport type LoginRequest = z.infer<typeof LoginRequestSchema>;\n\n/** `POST /signup` body from the website: a new account with the `user` role; answers like `/login` (logged in at once). */\nexport const SignupRequestSchema = z.object({\n username: z.string().min(1),\n name: z.string().min(1),\n email: z.string().min(1),\n password: z.string().min(1),\n});\nexport type SignupRequest = z.infer<typeof SignupRequestSchema>;\n\n/**\n * `POST /login` answer: the bearer token the CLI stores (#48). With a `publicKey` in the request,\n * also that key signed by the control plane's SSH CA (#51): the `-cert.pub` text and when it expires (ISO).\n */\nexport const LoginResponseSchema = z.object({\n token: z.string(),\n user: CloudUserSchema,\n sshCert: z.string().optional(),\n sshCertExpires: z.string().optional(),\n /** Whose boxes the certificate opens: `<slug>@<realm>` for the user and each org they are in (orgs phase 4). */\n sshCertPrincipals: z.array(z.string()).optional(),\n});\nexport type LoginResponse = z.infer<typeof LoginResponseSchema>;\n\n/** `POST /ssh/cert` body: one of the caller's uploaded keys to sign again (#51). */\nexport const SshCertRequestSchema = z.object({\n publicKey: z.string().min(1),\n});\nexport type SshCertRequest = z.infer<typeof SshCertRequestSchema>;\n\n/** `POST /ssh/cert` answer: the certificate text, its expiry (ISO) and its principals. */\nexport const SshCertResponseSchema = z.object({\n cert: z.string(),\n expires: z.string(),\n principals: z.array(z.string()),\n});\nexport type SshCertResponse = z.infer<typeof SshCertResponseSchema>;\n\n/** `GET /ssh/ca` answer: the CA's public key, the line boxes trust after `cert-authority `. */\nexport const SshCaResponseSchema = z.object({\n publicKey: z.string(),\n /** 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. */\n retired: z.array(z.object({ publicKey: z.string(), retiredAt: z.string() })).optional(),\n});\nexport type SshCaResponse = z.infer<typeof SshCaResponseSchema>;\n\n/** `GET /hosts/self/ssh-ca` on the control plane, by the host secret: the CA every box should trust (`kvbox server trust-ca --from-cloud`, #55). */\nexport const HostSshCaResponseSchema = z.object({\n publicKey: z.string(),\n});\n\n/** `GET /ssh/cloud-ca` on a host's socket: what its control plane says the CA is, with the fingerprint to confirm. */\nexport const CloudCaSchema = z.object({\n controlPlane: z.string(),\n publicKey: z.string(),\n fingerprint: z.string(),\n});\nexport type CloudCa = z.infer<typeof CloudCaSchema>;\n\n/** `POST /ssh/trust-ca` on a host's socket (#55): the CA public key (a pasted `cert-authority …` line is accepted too). */\nexport const TrustCaRequestSchema = z.object({\n publicKey: z.string().min(1),\n});\nexport type TrustCaRequest = z.infer<typeof TrustCaRequestSchema>;\n\n/**\n * When a box's new authorized_keys reach the guest: `now` (pushed through kvbox-agent), or at its\n * next `start` (stopped: kvbox-init writes the file at boot), `wake` (hibernated), `resume`\n * (standby), or `later` (running, but its agent could not take them: the next stop and start).\n */\nexport const SshKeysAppliedSchema = z.enum([\"now\", \"start\", \"wake\", \"resume\", \"later\"]);\nexport type SshKeysApplied = z.infer<typeof SshKeysAppliedSchema>;\n\n/** `POST /ssh/trust-ca` answer: every cloud box on the host, by what happened to it. Boxes are `owner/name`. */\nexport const TrustCaReportSchema = z.object({\n publicKey: z.string(),\n fingerprint: z.string(),\n /** The guest trusts the CA now. */\n updated: z.array(z.string()),\n /** meta.json has the line; the guest gets it at `when`. */\n pending: z.array(z.object({ box: z.string(), when: SshKeysAppliedSchema, why: z.string().optional() })),\n failed: z.array(z.object({ box: z.string(), error: z.string() })),\n /** Local boxes, untouched: they trust the host's key only. */\n local: z.number().int(),\n});\nexport type TrustCaReport = z.infer<typeof TrustCaReportSchema>;\n\n/** `POST /hosts/join` body from `kvbox-server join` (#18); `fingerprint` is the host's TLS cert sha256, colon-separated. */\nexport const HostJoinRequestSchema = z.object({\n token: z.string().min(1),\n name: z.string().min(1),\n url: z.string().url(),\n fingerprint: z.string().regex(/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/),\n publicAddress: z.string().min(1),\n});\nexport type HostJoinRequest = z.infer<typeof HostJoinRequestSchema>;\n\n/** `POST /hosts/join` answer: the secret the control plane will present to the host from now on (#18). */\nexport const HostJoinResponseSchema = z.object({\n hostSecret: z.string(),\n controlPlane: z.object({ name: z.string() }),\n});\nexport type HostJoinResponse = z.infer<typeof HostJoinResponseSchema>;\n\n/** A host as the control plane knows it; returned by `GET /hosts` (admin). */\nexport const CloudHostSchema = z.object({\n name: z.string(),\n url: z.string(),\n publicAddress: z.string(),\n joinedAt: z.string(),\n lastSeenAt: z.string().nullable(),\n capacity: CapacitySchema.nullable(),\n});\nexport type CloudHost = z.infer<typeof CloudHostSchema>;\n","/**\n * Fixed box sizes. Firecracker backs guest memory lazily and the disk is a sparse overlay on the\n * shared base image, so a box only costs what the guest actually touches.\n */\nexport const SIZES = {\n xs: { vcpu: 1, memMib: 2048, diskGib: 8 },\n s: { vcpu: 2, memMib: 4096, diskGib: 8 },\n m: { vcpu: 4, memMib: 8192, diskGib: 16 },\n l: { vcpu: 8, memMib: 16384, diskGib: 32 },\n} as const;\n\nexport type SizeName = keyof typeof SIZES;\nexport const SIZE_NAMES = Object.keys(SIZES) as SizeName[];\nexport const DEFAULT_SIZE: SizeName = \"s\";\n\nexport function isSizeName(value: string): value is SizeName {\n return value in SIZES;\n}\n\n/**\n * \"16GB\", \"16G\", \"16\", \"4096MB\", \"4096M\", \"0.5GB\" -> MiB. A bare number is GB: that is how\n * people say it (\"16gb\", \"4 vcpu 16gb\"). Returns undefined when it is not a size.\n */\nexport function parseMib(text: string): number | undefined {\n const m = /^\\s*(\\d+(?:\\.\\d+)?)\\s*([gm]i?b?)?\\s*$/i.exec(text);\n if (!m) return undefined;\n const n = Number(m[1]);\n const unit = (m[2] ?? \"g\").toLowerCase();\n const mib = unit.startsWith(\"m\") ? n : n * 1024;\n return Number.isInteger(mib) && mib > 0 ? mib : undefined;\n}\n","/**\n * How to launch `kvbox-server` so it can open /dev/kvm (#61). A shell that logged in (or a tmux\n * server that started) before the user was added to the kvm group hands that stale group list to\n * every process it spawns, the daemon included; firecracker then fails with \"Permission denied\".\n * When this process cannot open the device but /etc/group says the user belongs to its group,\n * the daemon is started through `sg <group>`, which grants a group the user already holds without\n * a password. Everything else (device missing, user not in the group) is left to kvbox-server's own\n * check, which explains the situation in plain words.\n */\nimport { accessSync, constants, readFileSync, statSync } from \"node:fs\";\nimport { userInfo } from \"node:os\";\n\nexport const KVM_DEVICE = \"/dev/kvm\";\n\nexport interface Launcher {\n cmd: string;\n args: string[];\n /** The group `sg` switches to, undefined for a plain spawn. */\n viaGroup?: string;\n}\n\nexport interface LauncherOptions {\n device?: string;\n groupFile?: string;\n user?: string;\n}\n\n/** The argv that runs `kvbox-server start`: plain, or through `sg <group>` when that is what makes /dev/kvm openable. */\nexport function serverLauncher(opts: LauncherOptions = {}): Launcher {\n const device = opts.device ?? KVM_DEVICE;\n const plain: Launcher = { cmd: \"kvbox-server\", args: [\"start\"] };\n try {\n accessSync(device, constants.R_OK | constants.W_OK);\n return plain;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== \"EACCES\" && code !== \"EPERM\") return plain;\n }\n let gid: number;\n try {\n gid = statSync(device).gid;\n } catch {\n return plain;\n }\n const group = groupWithMember(gid, opts.user ?? userInfo().username, opts.groupFile ?? \"/etc/group\");\n if (group === undefined) return plain;\n // sg runs a shell string; the command is a fixed literal, no user input reaches it.\n return { cmd: \"sg\", args: [group, \"-c\", \"kvbox-server start\"], viaGroup: group };\n}\n\n/** The name of the group with this gid when the group file lists `user` among its members, else undefined. */\nexport function groupWithMember(gid: number, user: string, groupFile: string): string | undefined {\n let text: string;\n try {\n text = readFileSync(groupFile, \"utf8\");\n } catch {\n return undefined;\n }\n for (const line of text.split(\"\\n\")) {\n const [name, , id, members = \"\"] = line.split(\":\");\n if (name === undefined || id === undefined || Number.parseInt(id, 10) !== gid) continue;\n return members.split(\",\").includes(user) ? name : undefined;\n }\n return undefined;\n}\n","/**\n * The systemd unit install-server.sh writes so kvbox-server starts at boot (#29): a system unit that\n * runs the server as the installing user. When it serves this KVBOX_HOME, the CLI starts the daemon\n * through it (`sudo -n`, the sudoers rule allows exactly that) instead of spawning one beside it.\n */\nimport { spawnSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport type { Paths } from \"@kvbox/shared/paths\";\n\nexport const UNIT = \"kvbox-server\";\nexport const UNIT_FILE = `/etc/systemd/system/${UNIT}.service`;\n\n/** True when the unit exists and runs the server on `p.home` (a dev or test KVBOX_HOME has none). */\nexport function hasUnitFor(p: Paths, file = UNIT_FILE): boolean {\n let text: string;\n try {\n text = readFileSync(file, \"utf8\");\n } catch {\n return false;\n }\n const home = /^Environment=\"?KVBOX_HOME=([^\"\\n]+)\"?$/m.exec(text)?.[1];\n return home !== undefined && resolve(home) === resolve(p.home);\n}\n\n/** `sudo -n systemctl start kvbox-server`; what it said when it failed. */\nexport function startUnitProcess(): { ok: boolean; out: string } {\n const res = spawnSync(\"sudo\", [\"-n\", \"systemctl\", \"start\", UNIT], { encoding: \"utf8\" });\n return { ok: res.status === 0, out: `${res.stdout ?? \"\"}${res.stderr ?? \"\"}`.trim() };\n}\n\n/**\n * False once the unit's server has exited: systemd then shows it waiting to restart (\"activating\")\n * or given up (\"failed\"). `systemctl start` returns as soon as a Type=simple unit forks, so this is\n * how a server that dies right away is told apart from one still coming up.\n */\nexport function unitActive(): boolean {\n const res = spawnSync(\"systemctl\", [\"is-active\", UNIT], { encoding: \"utf8\" });\n return (res.stdout ?? \"\").trim() === \"active\";\n}\n\n/** Whether the server comes back by itself after a reboot: the unit serves this home and is enabled. */\nexport function startsAtBoot(p: Paths): boolean {\n return hasUnitFor(p) && spawnSync(\"systemctl\", [\"is-enabled\", \"--quiet\", UNIT]).status === 0;\n}\n","import { Command, Option } from \"commander\";\nimport type { Machine } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { SIZE_NAMES } from \"@kvbox/shared/sizes\";\nimport { clientFor } from \"../../client.js\";\nimport { color, duration, gb, info, json, shortRef, slugOf, spin, warn } from \"../../output.js\";\n\n/**\n * kvbox vm new [name] [--size xs|s|m|l] [--from <snapshot>] [--auto-hibernate <duration>|off] [--force] [--json]\n * --json output: the Machine object (see packages/shared/src/api.ts).\n */\nexport const newCommand = new Command(\"new\")\n .description(\"boot a new box from the base image or a snapshot\")\n .argument(\"[name]\", \"box name (box1, box2, … when omitted)\")\n .addOption(new Option(\"-s, --size <size>\", \"box size (default: server config, s)\").choices(SIZE_NAMES))\n .option(\"-f, --from <snapshot>\", \"start from a snapshot instead of the base image\")\n .option(\"--auto-hibernate <duration>\", \"hibernate the box after this long without network traffic (30m, 4h, 1d; off: never; default: server config, off)\")\n .option(\"--force\", \"skip the capacity guard\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string | undefined, opts: { size?: string; from?: string; autoHibernate?: string; force?: boolean; json?: boolean }, cmd: Command) => {\n const autoHibernateSec = opts.autoHibernate === undefined ? undefined : parseIdleTimeout(opts.autoHibernate);\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const what = opts.from !== undefined ? `restoring ${name ?? \"a new box\"} from snapshot ${opts.from}…` : `booting ${name ?? \"a new box\"}…`;\n const box = await spin(what, client.createMachine({\n ...(name !== undefined ? { name } : {}),\n ...(opts.size !== undefined ? { size: opts.size } : {}),\n ...(opts.from !== undefined ? { from: opts.from } : {}),\n ...(autoHibernateSec !== undefined ? { autoHibernateSec } : {}),\n ...(opts.force ? { force: true } : {}),\n }));\n // A host from before #47 drops the field without a word.\n if (autoHibernateSec && !box.autoHibernateSec) warn(`box ${name ?? box.name}: its host runs a kvbox-server too old for auto-hibernate; it will not hibernate on its own`);\n if (opts.json) {\n json(box);\n return;\n }\n const user = client.target.kind === \"cloud\" ? client.target.user : undefined;\n process.stdout.write(`${box.name}\\n`);\n info(`${color.green(\"✓\")} ${describe(box, user)}`);\n if (opts.from !== undefined) info(` connect with: kvbox connect ${displayName(box, user)} (already up: everything that ran in the snapshot is running)`);\n else info(` connect with: kvbox connect ${displayName(box, user)} (SSH is up a couple of seconds after boot)`);\n if (box.autoHibernateSec) info(` it ${autoHibernateText(box.autoHibernateSec)}`);\n } finally {\n await client.close();\n }\n });\n\n/** `user`: the caller's own slug; a box of any other slug is named `slug/name` so nobody misses where it went, and that name works in every context. */\nexport function displayName(box: Machine, user: string | undefined): string {\n return user !== undefined && slugOf(box.owner) !== user ? `${slugOf(box.owner)}/${box.name}` : box.name;\n}\n\nexport function describe(box: Machine, user?: string): string {\n const from = box.source.startsWith(\"snapshot:\")\n ? ` from snapshot ${shortRef(box.source.slice(\"snapshot:\".length), box.owner)}`\n : box.source.startsWith(\"fork:\")\n ? `, a fork of ${shortRef(box.source.slice(\"fork:\".length), box.owner)}`\n : \"\";\n return `box ${color.bold(displayName(box, user))} is ${box.status} at ${box.ip}${from}: ${box.vcpu} vCPU, ${gb(box.memMib * 1024 ** 2)} RAM, ${gb(box.diskBytes)} disk`;\n}\n\n/** What a box does when its network goes quiet, in words. */\nexport function autoHibernateText(sec: number | undefined): string {\n return sec ? `hibernates after ${duration(sec)} without network traffic (kvbox connect wakes it)` : \"never hibernates on its own\";\n}\n\nconst UNIT_SEC: Record<string, number> = { m: 60, h: 3600, d: 86400 };\n\n/** \"30m\", \"4h\", \"1d\", \"1h30m\" -> seconds; \"off\", \"never\" or \"0\" -> 0. The server checks once a minute, so minutes are the unit. */\nexport function parseIdleTimeout(text: string): number {\n const t = text.trim().toLowerCase();\n if (t === \"off\" || t === \"never\" || t === \"0\") return 0;\n if (!/^(\\d+[mhd])+$/.test(t)) throw new KvboxError(`--auto-hibernate ${text}: give a duration like 30m, 4h or 1d, or off`);\n let sec = 0;\n for (const [, n, unit] of t.matchAll(/(\\d+)([mhd])/g)) sec += Number(n) * UNIT_SEC[unit!]!;\n return sec;\n}\n","import { spawn } from \"node:child_process\";\nimport { Command, InvalidArgumentError } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { pickRef, spin } from \"../../output.js\";\nimport { ensureCert, renewAfterRefusal } from \"../../cert.js\";\nimport { boxesFor, clientFor, me, sshArgs, sshEndpoint, waitForSsh, wakeUp, type SshEndpoint } from \"../../client.js\";\nimport { displayName } from \"./new.js\";\n\n/** POSIX single-quote a string for the guest's shell. */\nexport function shellQuote(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/**\n * The one string handed to the guest's login shell: the words after `--` joined with spaces\n * (so `'cd /app && npm test'` and `cd /app '&&' npm test` both work), preceded by `export`s\n * for `--env` so the shell itself expands `$VAR` in the command. SSH SetEnv is not an option:\n * the image's sshd does not AcceptEnv (#24).\n */\nexport function remoteCommand(cmdArgs: string[], env: string[]): string {\n const cmd = cmdArgs.join(\" \");\n if (env.length === 0) return cmd;\n const assignments = env.map((entry) => {\n const eq = entry.indexOf(\"=\");\n const key = eq > 0 ? entry.slice(0, eq) : \"\";\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) throw new KvboxError(`--env ${entry}: expected KEY=VALUE`);\n return `${key}=${shellQuote(entry.slice(eq + 1))}`;\n });\n return `export ${assignments.join(\" \")}; ${cmd}`;\n}\n\n/** `timeout(1)`'s exit status when the command was killed. */\nconst TIMEOUT_EXIT = 124;\n/** ssh's own status when it could not connect or the session broke. */\nconst SSH_FAILED = 255;\n\nfunction collect(value: string, previous: string[] | undefined): string[] {\n return [...(previous ?? []), value];\n}\n\nfunction positiveSeconds(value: string): number {\n const n = Number(value);\n if (!Number.isFinite(n) || n <= 0) throw new InvalidArgumentError(\"expected a number of seconds > 0\");\n return n;\n}\n\ninterface ExecOptions {\n env?: string[];\n timeout?: number;\n tty?: boolean;\n json?: boolean;\n}\n\n/** One ssh run: its exit status, what it printed (captured only with --json), whether --timeout cut it short. */\nasync function runSsh(ssh: string[], opts: ExecOptions): Promise<{ status: number; chunks: Buffer[]; timedOut: boolean }> {\n const child = spawn(\"ssh\", ssh, { stdio: [\"inherit\", opts.json ? \"pipe\" : \"inherit\", opts.json ? \"pipe\" : \"inherit\"] });\n const chunks: Buffer[] = [];\n child.stdout?.on(\"data\", (c: Buffer) => chunks.push(c));\n child.stderr?.on(\"data\", (c: Buffer) => chunks.push(c));\n\n let timedOut = false;\n const timer =\n opts.timeout === undefined\n ? undefined\n : setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGTERM\");\n }, opts.timeout * 1000);\n\n const status = await new Promise<number>((resolve, reject) => {\n child.once(\"error\", (err) => reject(new KvboxError(`could not run ssh: ${err.message}`)));\n child.once(\"close\", (code, signal) => {\n if (timedOut) resolve(TIMEOUT_EXIT);\n else if (code !== null) resolve(code);\n else resolve(signal === \"SIGINT\" ? 130 : 1);\n });\n }).finally(() => clearTimeout(timer));\n return { status, chunks, timedOut };\n}\n\n/** kvbox vm exec <name> [-e K=V]... [--timeout N] [--tty] [--json] -- <cmd...> */\nexport const execCommand = new Command(\"exec\")\n .description(\"run a command in a box and exit with its status (kvbox exec <name> -- <cmd>)\")\n .argument(\"<name>\", \"box name\")\n .argument(\"<cmd...>\", \"command, passed to the box's shell as one string (pipes, &&, cd work)\")\n .option(\"-e, --env <KEY=VALUE>\", \"set an environment variable for the command (repeatable)\", collect)\n .option(\"--timeout <seconds>\", \"kill the command after N seconds and exit 124\", positiveSeconds)\n .option(\"--tty\", \"allocate a pseudo-terminal (for interactive tools like htop)\")\n .option(\"--json\", 'capture output and print {\"output\": \"...\", \"exit_code\": N}')\n // No passThroughOptions: flags come after the box name, `--` ends them, the rest is the command.\n .action(async (name: string, cmdArgs: string[], opts: ExecOptions, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n let ep: SshEndpoint;\n let cert: \"local\" | \"kept\" | \"renewed\";\n let owner: string;\n try {\n let box = pickRef(await boxesFor(client, name), name, me(client));\n if (!box) throw new KvboxError(`box ${name}: not found (kvbox ls)`);\n if (box.status === \"stopped\") throw new KvboxError(`box ${name} is stopped (kvbox start ${name})`);\n // The box trusts the CA for its owner (#51, orgs phase 4): settle the certificate before waking anything.\n cert = await ensureCert(client, undefined, undefined, { owner: box.owner });\n owner = box.owner;\n const wasRunning = box.status === \"running\";\n // Asleep, not off: the processes are still there, so the command can run as if nothing happened.\n if (!wasRunning) box = await wakeUp(client, box, displayName(box, me(client)));\n ep = sshEndpoint(box, client.target);\n if (!wasRunning) await spin(`waiting for ${name} to accept SSH…`, waitForSsh(ep));\n } finally {\n await client.close();\n }\n\n const remote = remoteCommand(cmdArgs, opts.env ?? []);\n const stdinIsTty = process.stdin.isTTY === true;\n const ssh = [\n ...(opts.tty ? [\"-t\"] : []),\n // With a terminal on stdin nothing is sent (the command would otherwise wait on it);\n // from a pipe or file, stdin is forwarded and its EOF reaches the command.\n ...(stdinIsTty && !opts.tty ? [\"-n\"] : []),\n ...sshArgs(ep),\n // ssh joins everything after the host into the remote command line.\n remote,\n ];\n\n let { status, chunks, timedOut } = await runSsh(ssh, opts);\n if (status === SSH_FAILED && !timedOut) {\n // Refused with a certificate that was fine yesterday: the box may trust a new CA (#55). Renew once, try again.\n const again = await clientFor(cmd.optsWithGlobals());\n if (await renewAfterRefusal(again, cert, owner).finally(() => again.close())) {\n if (opts.json) process.stderr.write(Buffer.concat(chunks));\n process.stderr.write(\"renewed your SSH certificate, trying again…\\n\");\n ({ status, chunks, timedOut } = await runSsh(ssh, opts));\n }\n }\n if (status === SSH_FAILED && !timedOut) {\n if (opts.json) process.stderr.write(Buffer.concat(chunks));\n throw new KvboxError(`box ${name}: could not run the command over SSH (box still booting?)`, SSH_FAILED);\n }\n if (opts.json) {\n process.stdout.write(JSON.stringify({ output: Buffer.concat(chunks).toString(\"utf8\"), exit_code: status }) + \"\\n\");\n }\n process.exit(status);\n });\n","import { Command, Option } from \"commander\";\nimport { SIZE_NAMES } from \"@kvbox/shared/sizes\";\nimport { clientFor, me } from \"../../client.js\";\nimport { color, info, json, spin } from \"../../output.js\";\nimport { autoHibernateText, describe, displayName, parseIdleTimeout } from \"./new.js\";\n\n/**\n * kvbox vm fork <box> [name] [--org <slug>] [--size xs|s|m|l] [--auto-hibernate <duration>|off] [--force] [--json]\n * --json output: the new box, a Machine object (see packages/shared/src/api.ts); its `source` is `fork:<owner>/<box>`.\n * A running or paused box is copied warm (its memory too: what ran in it runs in the copy), a stopped one\n * cold (its disk, then a fresh boot); a hibernated one is refused. `--org` names the slug the copy goes\n * to; the source is named as anywhere else (`acme/web` for an org's). No snapshot is left behind.\n */\nexport const forkCommand = new Command(\"fork\")\n .description(\"copy a box, running or stopped, into a new one on the same host (--org: into an org)\")\n .argument(\"<box>\", \"the box to copy\")\n .argument(\"[name]\", \"the copy's name (box1, box2, … when omitted)\")\n .addOption(new Option(\"-s, --size <size>\", \"the copy's size, for a stopped box only (default: the box's)\").choices(SIZE_NAMES))\n .option(\"--auto-hibernate <duration>\", \"hibernate the copy after this long without network traffic (30m, 4h, 1d; off: never; default: the box's)\")\n .option(\"--force\", \"skip the capacity guard\")\n .option(\"--json\", \"print the new box as JSON\")\n .action(async (source: string, name: string | undefined, opts: { size?: string; autoHibernate?: string; force?: boolean; json?: boolean }, cmd: Command) => {\n const autoHibernateSec = opts.autoHibernate === undefined ? undefined : parseIdleTimeout(opts.autoHibernate);\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const box = await spin(`forking ${source}…`, client.forkMachine(source, {\n ...(name !== undefined ? { name } : {}),\n ...(opts.size !== undefined ? { size: opts.size } : {}),\n ...(autoHibernateSec !== undefined ? { autoHibernateSec } : {}),\n ...(opts.force ? { force: true } : {}),\n }));\n if (opts.json) {\n json(box);\n return;\n }\n const user = me(client);\n process.stdout.write(`${box.name}\\n`);\n info(`${color.green(\"✓\")} ${describe(box, user)}`);\n info(` connect with: kvbox connect ${displayName(box, user)}`);\n info(` it ${autoHibernateText(box.autoHibernateSec)}; published ports and HTTPS names stay with ${source}`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { clientFor } from \"../../client.js\";\nimport { color, info, json, spin } from \"../../output.js\";\n\n/** kvbox vm hibernate <name> [--json] — --json output: the Machine object */\nexport const hibernateCommand = new Command(\"hibernate\")\n .description(\"save a box's memory to disk and free its RAM (kvbox wake continues it where it left off)\")\n .argument(\"<name>\", \"box name\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string, opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const box = await spin(`hibernating ${name} (saving its memory to disk)…`, client.hibernateMachine(name));\n if (opts.json) json(box);\n else info(`${color.green(\"✓\")} box ${name} hibernated (memory saved to disk, RAM freed; kvbox wake ${name} continues it where it left off)`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport type { Machine } from \"@kvbox/shared/api\";\nimport { clientFor } from \"../../client.js\";\nimport { age, boxName, color, gbShort, info, json, shape, slugOf, spin, status, table } from \"../../output.js\";\n\n/**\n * The OWNER cell: `private` for the user's own box, else the slug tagged with what it is (`acme org`,\n * or `bob user` for what a platform admin sees with --all); a control plane that does not say the\n * kind leaves the bare slug.\n */\nexport function ownerCell(b: Pick<Machine, \"owner\" | \"ownerKind\">, me: string | undefined): string {\n const slug = slugOf(b.owner);\n if (slug === me) return \"private\";\n return b.ownerKind === undefined ? slug : `${slug} ${color.dim(b.ownerKind)}`;\n}\n\n/**\n * The box's address: its host's public one through the control plane (#21; no port, a box can publish\n * several and the ssh one is `connect`'s business), its ip on this machine, `-` when unknown.\n */\nexport function addressOf(b: Machine): string {\n if (b.ssh !== undefined) return b.ssh.host;\n return b.ip === \"\" ? \"-\" : b.ip;\n}\n\n/**\n * kvbox vm ls [--all] [--json] — the user's boxes (and each of their orgs' through a control plane;\n * `--org <slug>` narrows to that org, `--all` lists the whole platform for a platform admin, #78). --json output: Machine[] (each item carries its `owner`, and\n * through a control plane `ownerKind`: \"user\" or \"org\")\n */\nexport const lsCommand = new Command(\"ls\")\n .description(\"list boxes with status and address (yours and your orgs'; --org <slug> for one org)\")\n .option(\"-a, --all\", \"every box on the platform (platform admins only)\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { all?: boolean; json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n // a control plane still asks a host live for a box it has not described lately: a slow host shows as a spinner, not a hang\n const boxes = await spin(\"listing boxes…\", client.listMachines({ all: opts.all }));\n if (opts.json) {\n json(boxes);\n return;\n }\n const org = client.target.kind === \"cloud\" ? client.target.org : undefined;\n if (boxes.length === 0) {\n info(org === undefined ? \"no boxes yet; create one with: kvbox new\" : `no boxes in ${org} yet; create one with: kvbox new --org ${org}`);\n return;\n }\n if (org !== undefined) info(`boxes of ${org}`);\n table(lsRows(boxes, client.target.kind === \"cloud\" ? { me: client.target.user } : undefined));\n } finally {\n await client.close();\n }\n });\n\n/**\n * Five columns, an OWNER one first through a control plane (`cloud` set, with the logged-in user as\n * `me`); cpu/ram/disk/source details stay in --json. A box whose host did not answer the control\n * plane comes back as `unknown` with no ip or size (#20).\n */\nexport function lsRows(boxes: Machine[], cloud?: { me?: string | undefined }): Record<string, string>[] {\n return boxes.map((b) => ({\n ...(cloud ? { owner: ownerCell(b, cloud.me) } : {}),\n name: boxName(b.name),\n status: status(b.status),\n address: addressOf(b),\n size: b.status === \"unknown\" ? \"-\" : `${shape(b.vcpu, b.memMib, b.diskBytes)} ${color.dim(`(${gbShort(b.diskUsedBytes)} used)`)}`,\n created: age(b.createdAt),\n }));\n}\n","import { Command } from \"commander\";\nimport { clientFor } from \"../../client.js\";\nimport { color, info, json, spin } from \"../../output.js\";\n\n/** kvbox vm pause <name> [--json] — --json output: the Machine object */\nexport const pauseCommand = new Command(\"pause\")\n .description(\"freeze a box in place (memory and processes kept, no CPU used; kvbox resume continues it instantly)\")\n .argument(\"<name>\", \"box name\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string, opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const box = await spin(`pausing ${name}…`, client.pauseMachine(name));\n if (opts.json) json(box);\n else info(`${color.green(\"✓\")} box ${name} is in standby (frozen in place; kvbox resume ${name} continues it)`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { assertSubdomain } from \"@kvbox/shared/names\";\nimport { clientFor, me } from \"../../../client.js\";\nimport { color, info, json, spin } from \"../../../output.js\";\nimport { displayName } from \"../new.js\";\nimport { findBox, parsePorts, requireCloud, subdomainJson } from \"./shared.js\";\n\n/**\n * kvbox vm proxy claim <box> <subdomain> --port <port> [--json]\n * --json output: {box, subdomain, port, url, routes: [{name, port, url}]} (#31), `box` bare for the\n * caller's own box, `slug/name` otherwise.\n */\nexport const claimCommand = new Command(\"claim\")\n .description(\"give a box its HTTPS address, https://<subdomain>.kvbox.app, serving one of its ports\")\n .argument(\"<box>\", \"box name\")\n .argument(\"<subdomain>\", \"3-63 lowercase letters, digits and '-'; must be free\")\n .requiredOption(\"--port <port>\", \"the box port the address serves\")\n .option(\"--json\", \"print the subdomain as JSON\")\n .action(async (name: string, subdomain: string, opts: { port: string; json?: boolean }, cmd: Command) => {\n assertSubdomain(subdomain);\n const [port] = parsePorts([opts.port]);\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n requireCloud(client);\n const user = me(client);\n const found = await findBox(client, name);\n const box = displayName(found, user);\n const sub = await spin(`claiming ${subdomain}…`, client.claimSubdomain(box, { name: subdomain, port: port! }));\n if (opts.json) {\n json(subdomainJson(sub, me(client)));\n return;\n }\n info(`${color.green(\"✓\")} ${color.bold(sub.url)} → box ${color.bold(box)} port ${sub.port}`);\n info(` more ports under it: kvbox vm proxy add ${box} <port> --name <name> → https://<name>.${sub.url.replace(/^https:\\/\\//, \"\")}`);\n if (found.status !== \"running\") info(` box ${box} is ${found.status}: the address answers once it runs`);\n } finally {\n await client.close();\n }\n });\n","/**\n * HTTPS names for boxes (#31, decision \"A box claims one subdomain\"): a box claims one subdomain\n * `<sub>.kvbox.app` with a default port, and named ports nest under it as `<name>.<sub>.kvbox.app`.\n * Both are single DNS labels. The CLI checks them before calling; the control plane checks again.\n */\nimport { createHmac } from \"node:crypto\";\nimport { KvboxError } from \"./errors.js\";\n\n/** Where box URLs live (decision d2cb4d88's domain); the control plane and the edge can be told otherwise. */\nexport const DEFAULT_PROXY_DOMAIN = \"kvbox.app\";\n\n/** A domain box names may live under (`kvbox.app`): the control plane's and the edge's must match. */\nexport function assertProxyDomain(text: string, key: string): string {\n if (!/^[a-z0-9-]+(\\.[a-z0-9-]+)+$/.test(text)) throw new KvboxError(`${key} must be a domain like ${DEFAULT_PROXY_DOMAIN}: ${text}`);\n return text;\n}\n\n/** One DNS label: lowercase letters, digits and `-`, never at either end. */\nconst LABEL_RE = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;\n\n/** Subdomains nobody may claim: the platform's own names, and ones that would read as ours. */\nexport const RESERVED_SUBDOMAINS: ReadonlySet<string> = new Set([\n \"admin\",\n \"api\",\n \"app\",\n \"assets\",\n \"auth\",\n \"billing\",\n \"blog\",\n \"cdn\",\n \"dashboard\",\n \"dev\",\n \"docs\",\n \"edge\",\n \"help\",\n \"install\",\n \"kvbox\",\n \"login\",\n \"mail\",\n \"relay\",\n \"root\",\n \"smtp\",\n \"static\",\n \"status\",\n \"support\",\n \"www\",\n]);\n\n/** Why `text` cannot be a claimed subdomain, or null when it can. */\nexport function subdomainProblem(text: string): string | null {\n if (text.length < 3 || text.length > 63) return `\"${text}\" must be 3 to 63 characters`;\n if (!LABEL_RE.test(text)) return `\"${text}\" may hold only lowercase letters, digits and '-', not at either end`;\n if (RESERVED_SUBDOMAINS.has(text)) return `\"${text}\" is reserved; pick another name`;\n return null;\n}\n\n/** Why `text` cannot be a name under a subdomain (`<name>.<sub>`), or null when it can. */\nexport function routeNameProblem(text: string): string | null {\n if (text.length < 1 || text.length > 63) return `\"${text}\" must be 1 to 63 characters`;\n if (!LABEL_RE.test(text)) return `\"${text}\" may hold only lowercase letters, digits and '-', not at either end`;\n return null;\n}\n\nexport function assertSubdomain(text: string): string {\n const problem = subdomainProblem(text);\n if (problem) throw new KvboxError(`subdomain ${problem}`);\n return text;\n}\n\nexport function assertRouteName(text: string): string {\n const problem = routeNameProblem(text);\n if (problem) throw new KvboxError(`name ${problem}`);\n return text;\n}\n\n/** `https://<sub>.<domain>`, or `https://<name>.<sub>.<domain>` for a named port. */\nexport function subdomainUrl(domain: string, sub: string, name?: string): string {\n return `https://${name === undefined ? \"\" : `${name}.`}${sub}.${domain}`;\n}\n\n/**\n * What a request's `Host` names under `domain`: the subdomain and, for `<name>.<sub>`, the name.\n * Null for anything else (the bare domain, deeper names, another domain).\n */\nexport function parseProxyHost(host: string, domain: string): { sub: string; name?: string } | null {\n const bare = host.toLowerCase().replace(/:\\d+$/, \"\").replace(/\\.$/, \"\");\n const suffix = `.${domain}`;\n if (!bare.endsWith(suffix)) return null;\n const labels = bare.slice(0, -suffix.length).split(\".\");\n if (labels.some((l) => !LABEL_RE.test(l))) return null;\n if (labels.length === 1) return { sub: labels[0]! };\n if (labels.length === 2) return { sub: labels[1]!, name: labels[0]! };\n return null;\n}\n\n/**\n * How the edge and a host carry a visitor's request to a box (#31). The host's answers of its own\n * (no such box, box not running, nothing listening) carry `PROXY_ERROR_HEADER`, and the box's carry\n * `PROXIED_HEADER`, so the edge can tell the box's own 404 or 401 from the host's and show its page\n * for the latter. The edge strips every `x-kvbox-*` header before a visitor sees the answer.\n */\nexport const PROXY_ERROR_HEADER = \"x-kvbox-proxy-error\";\n/**\n * `hibernated`, `standby` and `stopped` say why a box is not running (#80): the edge may ask for the\n * first two to be woken, never the last. `waking`: a wake asked for is still under way. `wake-failed`:\n * it did not work. `not-running` is what a host from before #80 says for all three.\n */\nexport type ProxyError = \"not-found\" | \"hibernated\" | \"standby\" | \"stopped\" | \"not-running\" | \"waking\" | \"wake-failed\" | \"unreachable\" | \"timeout\";\n/** Set by the host on every answer that came from the box: anything without it is the host's own (a refusal, a host too old for #31). */\nexport const PROXIED_HEADER = \"x-kvbox-proxied\";\n/**\n * The visitor's path and query. It never goes into the URL the edge calls on the host: a URL resolves\n * `..`, and `/machines/<box>/http/<port>/../../..` would reach any route on the host with the host\n * secret. The host URL is always exactly `/machines/<box>/http/<port>`.\n */\nexport const VISITOR_PATH_HEADER = \"x-kvbox-path\";\n/**\n * Sent by the edge when the box may be woken for this request (#80): its slug is not suspended and\n * the edge has not had it woken in the last minute. A host then wakes a hibernated box (resumes one in\n * standby) before forwarding, and stamps its answer with WOKE_HEADER when it did.\n */\nexport const WAKE_HEADER = \"x-kvbox-wake\";\n/**\n * The longest a host holds a request on a wake before answering `waking` (the wake itself goes on).\n * The edge adds it to its own wait for the host's answer when it sends WAKE_HEADER.\n */\nexport const WAKE_WAIT_MS = 30_000;\n/**\n * On a host's answer: this request woke the box, so the edge counts it against the box's wake limit.\n * Also on the host's own `unreachable` or `timeout` after a wake: the box was woken all the same.\n */\nexport const WOKE_HEADER = \"x-kvbox-woke\";\n/** The visitor's own `Authorization`, carried past the host secret that takes its place between edge and host. */\nexport const VISITOR_AUTH_HEADER = \"x-kvbox-authorization\";\n\n/**\n * Request headers neither hop passes on although they are not hop-by-hop: undici refuses to send\n * `expect` at all, so `Expect: 100-continue` (curl on a large upload) would fail every forward.\n * Node's server already answers the `100 Continue` itself.\n */\nexport const NOT_FORWARDED: ReadonlySet<string> = new Set([\"expect\"]);\n\n/** Headers that describe one connection, never passed along by a proxy (RFC 9110 §7.6.1). */\nexport const HOP_BY_HOP: ReadonlySet<string> = new Set([\"connection\", \"keep-alive\", \"proxy-authenticate\", \"proxy-authorization\", \"proxy-connection\", \"te\", \"trailer\", \"transfer-encoding\", \"upgrade\"]);\n\n/** The one host path the edge calls: a box's port, `/machines/<box>/http/<port>`. */\nexport const BOX_HTTP_PATH_RE = /^\\/machines\\/([^/]+)\\/http\\/(\\d{1,5})\\/?$/;\n\n/**\n * The edge's bearer for a host, derived from the host secret so neither side stores anything new.\n * A host takes it on `BOX_HTTP_PATH_RE` alone, so the internet-facing edge never holds a key to the\n * rest of a host's API; the control plane keeps it in `hosts.edge_secret` for the edge to read.\n */\nexport function edgeCredential(hostSecret: string): string {\n return createHmac(\"sha256\", hostSecret).update(\"kvbox-edge-v1\").digest(\"base64url\");\n}\n","import { KvboxError } from \"@kvbox/shared/errors\";\nimport type { Machine, PortForward, Subdomain } from \"@kvbox/shared/api\";\nimport { boxesFor, me, type ServerClient } from \"../../../client.js\";\nimport { pickRef } from \"../../../output.js\";\nimport { displayName } from \"../new.js\";\n\n/** One published port as `--json` prints it (#30). `address` is the host's public address, known only through a control plane. */\nexport type ForwardRow = PortForward & { box: string };\n\n/** One HTTPS name as `--json` prints it (#31): the box's subdomain (no `name`) or a named port under it. */\nexport interface HttpsRow {\n box: string;\n guestPort: number;\n proto: \"https\";\n url: string;\n name?: string;\n}\n\n/** The box as `ls` shows it: bare when it is the caller's, `slug/name` otherwise. */\nconst boxOf = (sub: Subdomain, user: string | undefined) => (user !== undefined && sub.owner !== user ? `${sub.owner}/${sub.box}` : sub.box);\n\n/** A subdomain as `claim --json` and `set-port --json` print it. */\nexport function subdomainJson(sub: Subdomain, user: string | undefined) {\n return { box: boxOf(sub, user), subdomain: sub.subdomain, port: sub.port, url: sub.url, routes: sub.routes };\n}\n\nexport function httpsRowsOf(sub: Subdomain, user: string | undefined): HttpsRow[] {\n const box = boxOf(sub, user);\n return [{ box, guestPort: sub.port, proto: \"https\", url: sub.url }, ...sub.routes.map((r) => ({ box, guestPort: r.port, proto: \"https\" as const, url: r.url, name: r.name }))];\n}\n\n/** HTTPS names are the control plane's (#31): a host's own socket has none. */\nexport function requireCloud(client: ServerClient): void {\n if (client.target.kind !== \"cloud\") throw new KvboxError(\"HTTPS names need the kvbox cloud: kvbox login (this host's own socket has none)\");\n}\n\nexport function rowsOf(box: Machine, user: string | undefined, only?: (f: PortForward) => boolean): ForwardRow[] {\n return (box.ports ?? []).filter(only ?? (() => true)).map((f) => ({ box: displayName(box, user), ...f }));\n}\n\n/** Where the port is reached from outside: in words, or `short` for a table cell. */\nexport function reaches(row: ForwardRow, short = false): string {\n if (row.address !== undefined) return `${row.address}:${row.hostPort}`;\n return short ? `:${row.hostPort}` : `port ${row.hostPort} of this host's public address`;\n}\n\n/** Box ports as the user typed them: whole numbers 1-65535. */\nexport function parsePorts(texts: readonly string[]): number[] {\n return texts.map((t) => {\n const n = Number(t);\n if (!/^\\d+$/.test(t) || n < 1 || n > 65535) throw new KvboxError(`\"${t}\" is not a port (1-65535)`);\n return n;\n });\n}\n\n/** The box `text` names, among the caller's boxes and their orgs'. */\nexport async function findBox(client: ServerClient, text: string): Promise<Machine> {\n const found = pickRef(await boxesFor(client, text), text, me(client));\n if (!found) throw new KvboxError(`box ${text}: not found (kvbox ls)`);\n return found;\n}\n","import { Command } from \"commander\";\nimport { addCommand } from \"./add.js\";\nimport { claimCommand } from \"./claim.js\";\nimport { lsCommand } from \"./ls.js\";\nimport { releaseCommand } from \"./release.js\";\nimport { rmCommand } from \"./rm.js\";\nimport { setPortCommand } from \"./set-port.js\";\n\n/**\n * kvbox vm proxy add|ls|rm (#30): box ports on the host's public address. claim|set-port|release\n * and `add --name` (#31): the box's HTTPS address `https://<subdomain>.kvbox.app` and names under it.\n */\nexport const proxyCommand = new Command(\"proxy\")\n .description(\"publish box ports on the internet\")\n .addCommand(addCommand)\n .addCommand(lsCommand)\n .addCommand(rmCommand)\n .addCommand(claimCommand)\n .addCommand(setPortCommand)\n .addCommand(releaseCommand);\n\nfor (const cmd of proxyCommand.commands) cmd.option(\"--org <slug>\", \"act in this org (- for your personal boxes)\");\n","import { Command } from \"commander\";\nimport { assertRouteName } from \"@kvbox/shared/names\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { clientFor, me } from \"../../../client.js\";\nimport { color, info, json, spin } from \"../../../output.js\";\nimport { displayName } from \"../new.js\";\nimport { findBox, parsePorts, reaches, requireCloud, rowsOf } from \"./shared.js\";\n\n/**\n * kvbox vm proxy add <box> <port...> [--udp] [--json]\n * --json output: the forwards this call added, [{box, guestPort, hostPort, proto, address?}]\n * (`address`: the host's public address, through a control plane only). The host port is drawn at random.\n *\n * kvbox vm proxy add <box> <port> --name <name> [--json] (#31)\n * --json output: {box, guestPort, proto: \"https\", url, name}: `https://<name>.<subdomain>.kvbox.app`\n * under the box's claimed subdomain (kvbox vm proxy claim).\n */\nexport const addCommand = new Command(\"add\")\n .description(\"publish box ports on the internet; each gets a random public port, or an HTTPS name with --name\")\n .argument(\"<box>\", \"box name\")\n .argument(\"<port...>\", \"ports inside the box, e.g. 3000 8080\")\n .option(\"--udp\", \"UDP instead of TCP\")\n .option(\"--name <name>\", \"serve the port at https://<name>.<subdomain>.kvbox.app (one port; needs kvbox vm proxy claim first)\")\n .option(\"--json\", \"print the new forwards as JSON\")\n .action(async (name: string, portTexts: string[], opts: { udp?: boolean; name?: string; json?: boolean }, cmd: Command) => {\n const guestPorts = parsePorts(portTexts);\n if (opts.name !== undefined) {\n assertRouteName(opts.name);\n if (guestPorts.length !== 1) throw new KvboxError(\"--name publishes one port: kvbox vm proxy add <box> <port> --name <name>\");\n if (opts.udp) throw new KvboxError(\"--name serves HTTPS, which is TCP: drop --udp\");\n }\n const proto = opts.udp ? \"udp\" : \"tcp\";\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const user = me(client);\n if (opts.name !== undefined) requireCloud(client);\n const found = await findBox(client, name);\n const box = displayName(found, user);\n if (opts.name !== undefined) {\n const route = opts.name;\n const sub = await spin(`publishing ${guestPorts[0]} on ${name} as ${route}…`, client.addSubdomainRoute(box, { name: route, port: guestPorts[0]! }));\n const url = sub.routes.find((r) => r.name === route)!.url;\n if (opts.json) {\n json({ box, guestPort: guestPorts[0], proto: \"https\", url, name: route });\n return;\n }\n info(`${color.green(\"✓\")} ${color.bold(url)} → box ${color.bold(box)} port ${guestPorts[0]}`);\n info(\" the first name under a subdomain waits for its certificate, about a minute\");\n if (found.status !== \"running\") info(` box ${box} is ${found.status}: the address answers once it runs`);\n return;\n }\n const updated = await spin(`publishing ${guestPorts.join(\", \")} on ${name}…`, client.addPorts(box, { ports: guestPorts.map((guestPort) => ({ guestPort, proto })) }));\n const rows = rowsOf(updated, user, (f) => f.proto === proto && guestPorts.includes(f.guestPort));\n if (opts.json) {\n json(rows);\n return;\n }\n for (const row of rows) info(`${color.green(\"✓\")} box ${color.bold(row.box)} port ${row.guestPort} is reachable at ${reaches(row)} (${row.proto})`);\n if (updated.status !== \"running\") info(` box ${name} is ${updated.status}: the ports open when it runs`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport type { Subdomain } from \"@kvbox/shared/api\";\nimport { clientFor, me, type ServerClient } from \"../../../client.js\";\nimport { info, json, table, warn } from \"../../../output.js\";\nimport { displayName } from \"../new.js\";\nimport { findBox, httpsRowsOf, reaches, rowsOf, type ForwardRow, type HttpsRow } from \"./shared.js\";\n\n/**\n * kvbox vm proxy ls [box] [--json]\n * --json output: every published port, raw forwards [{box, guestPort, hostPort, proto, address?}]\n * (`address`: the host's public address, through a control plane only) and HTTPS names (#31)\n * [{box, guestPort, proto: \"https\", url, name?}] (`name` absent for the box's subdomain itself) in one\n * array. SSH ports are not listed.\n */\n/** The HTTPS names, or none with a warning: a control plane older than #31 must not cost the raw ports. */\nasync function subdomainsOf(client: ServerClient): Promise<Subdomain[]> {\n try {\n return await client.listSubdomains();\n } catch (err) {\n warn(`HTTPS names not listed: ${(err as Error).message}`);\n return [];\n }\n}\n\nexport const lsCommand = new Command(\"ls\")\n .description(\"list the box ports published on the internet\")\n .argument(\"[box]\", \"only this box\")\n .option(\"--json\", \"print as JSON\")\n .action(async (name: string | undefined, opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const user = me(client);\n // both from the control plane at once: the subdomains are its own (Postgres), the boxes ask every host\n const [boxes, subs] = await Promise.all([\n name === undefined ? client.listMachines() : findBox(client, name).then((b) => [b]),\n client.target.kind === \"cloud\" ? subdomainsOf(client) : [],\n ]);\n const shown = new Set(boxes.map((b) => displayName(b, user)));\n const https: HttpsRow[] = subs.flatMap((s) => httpsRowsOf(s, user)).filter((r) => shown.has(r.box));\n const rows: (ForwardRow | HttpsRow)[] = [...boxes.flatMap((b) => rowsOf(b, user)), ...https].sort((a, b) => a.box.localeCompare(b.box) || a.guestPort - b.guestPort);\n if (opts.json) {\n json(rows);\n return;\n }\n if (rows.length === 0) {\n info(name === undefined ? \"no published ports (kvbox vm proxy add <box> <port>)\" : `box ${name} publishes no ports (kvbox vm proxy add ${name} <port>)`);\n return;\n }\n table(rows.map((r) => ({ box: r.box, port: r.guestPort, reaches: r.proto === \"https\" ? r.url : reaches(r, true), proto: r.proto })));\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { clientFor, me } from \"../../../client.js\";\nimport { color, confirm, info, spin } from \"../../../output.js\";\nimport { displayName } from \"../new.js\";\nimport { findBox, requireCloud } from \"./shared.js\";\n\n/** kvbox vm proxy release <box> [-y] — destructive: asks y/N on a TTY, needs -y otherwise (#31) */\nexport const releaseCommand = new Command(\"release\")\n .description(\"give up a box's HTTPS address and every name under it\")\n .argument(\"<box>\", \"box name\")\n .option(\"-y, --yes\", \"do not ask for confirmation\")\n .action(async (name: string, opts: { yes?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n requireCloud(client);\n const box = displayName(await findBox(client, name), me(client));\n if (!(await confirm(`Give up box ${box}'s HTTPS address and every name under it? Anyone may claim it after.`, opts.yes ?? false))) {\n info(\"cancelled\");\n process.exitCode = 1;\n return;\n }\n const sub = await spin(`releasing ${name}'s address…`, client.releaseSubdomain(box));\n const names = sub.routes.length === 0 ? \"\" : ` and ${sub.routes.length} name${sub.routes.length > 1 ? \"s\" : \"\"} under it`;\n info(`${color.green(\"✓\")} ${sub.url.replace(/^https:\\/\\//, \"\")}${names} no longer reach box ${color.bold(box)}`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { assertRouteName } from \"@kvbox/shared/names\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { clientFor, me } from \"../../../client.js\";\nimport { color, confirm, info, spin } from \"../../../output.js\";\nimport { displayName } from \"../new.js\";\nimport { findBox, parsePorts, requireCloud } from \"./shared.js\";\n\n/**\n * kvbox vm proxy rm <box> <port...> [--udp] [-y]\n * kvbox vm proxy rm <box> --name <name> [-y] (#31: frees https://<name>.<subdomain>.kvbox.app)\n * Destructive: asks y/N on a TTY, needs -y otherwise.\n */\nexport const rmCommand = new Command(\"rm\")\n .description(\"stop publishing box ports, or an HTTPS name with --name\")\n .argument(\"<box>\", \"box name\")\n .argument(\"[port...]\", \"ports inside the box, as given to add\")\n .option(\"--udp\", \"the UDP forwards of those ports\")\n .option(\"--name <name>\", \"the HTTPS name to free (kvbox vm proxy release frees the whole subdomain)\")\n .option(\"-y, --yes\", \"do not ask for confirmation\")\n .action(async (name: string, portTexts: string[], opts: { udp?: boolean; name?: string; yes?: boolean }, cmd: Command) => {\n if (opts.name !== undefined) {\n assertRouteName(opts.name);\n if (portTexts.length > 0) throw new KvboxError(\"--name frees a name, not ports: kvbox vm proxy rm <box> --name <name>\");\n } else if (portTexts.length === 0) {\n throw new KvboxError(\"which ports? kvbox vm proxy rm <box> <port...>, or --name <name> for an HTTPS name\");\n }\n const guestPorts = parsePorts(portTexts);\n const proto = opts.udp ? \"udp\" : \"tcp\";\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n if (opts.name !== undefined) requireCloud(client);\n const box = displayName(await findBox(client, name), me(client));\n const question = opts.name !== undefined ? `Stop serving ${opts.name} under box ${box}'s subdomain?` : `Stop publishing port${guestPorts.length > 1 ? \"s\" : \"\"} ${guestPorts.join(\", \")} of box ${box}?`;\n if (!(await confirm(question, opts.yes ?? false))) {\n info(\"cancelled\");\n process.exitCode = 1;\n return;\n }\n if (opts.name !== undefined) {\n const sub = await spin(`freeing ${opts.name} on ${name}…`, client.removeSubdomainRoute(box, opts.name));\n info(`${color.green(\"✓\")} ${opts.name}.${sub.url.replace(/^https:\\/\\//, \"\")} no longer reaches box ${color.bold(box)}`);\n return;\n }\n await spin(`closing ${guestPorts.join(\", \")} on ${name}…`, client.removePorts(box, { ports: guestPorts.map((guestPort) => ({ guestPort, proto })) }));\n info(`${color.green(\"✓\")} box ${color.bold(name)} no longer publishes ${guestPorts.join(\", \")} (${proto})`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { clientFor, me } from \"../../../client.js\";\nimport { color, info, json, spin } from \"../../../output.js\";\nimport { displayName } from \"../new.js\";\nimport { findBox, parsePorts, requireCloud, subdomainJson } from \"./shared.js\";\n\n/** kvbox vm proxy set-port <box> <port> [--json] — --json output: the subdomain, as `claim --json` prints it (#31) */\nexport const setPortCommand = new Command(\"set-port\")\n .description(\"point a box's HTTPS address at another of its ports\")\n .argument(\"<box>\", \"box name\")\n .argument(\"<port>\", \"the box port https://<subdomain>.kvbox.app serves from now on\")\n .option(\"--json\", \"print the subdomain as JSON\")\n .action(async (name: string, portText: string, opts: { json?: boolean }, cmd: Command) => {\n const [port] = parsePorts([portText]);\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n requireCloud(client);\n const box = displayName(await findBox(client, name), me(client));\n const sub = await spin(`pointing ${name} at port ${port}…`, client.setSubdomainPort(box, { port: port! }));\n if (opts.json) {\n json(subdomainJson(sub, me(client)));\n return;\n }\n info(`${color.green(\"✓\")} ${color.bold(sub.url)} → box ${color.bold(box)} port ${sub.port}`);\n } finally {\n await client.close();\n }\n });\n","import { Command, Option } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { SIZE_NAMES, parseMib } from \"@kvbox/shared/sizes\";\nimport { boxesFor, clientFor, me } from \"../../client.js\";\nimport { color, info, json, pickRef, spin } from \"../../output.js\";\nimport { describe, displayName } from \"./new.js\";\n\n/**\n * kvbox vm rescale <name> [--size xs|s|m|l] [--vcpu N] [--mem 16GB] [--disk 32GB] [--json]\n * --json output: the Machine object. Explicit values override the preset; the disk can only grow.\n * Takes effect at boot: a running box is restarted (files intact, processes gone).\n */\nexport const rescaleCommand = new Command(\"rescale\")\n .description(\"change a box's vCPUs, memory or disk (e.g. --vcpu 4 --mem 16GB); a running box restarts\")\n .argument(\"<name>\", \"box name\")\n .addOption(new Option(\"-s, --size <size>\", \"a preset to start from\").choices(SIZE_NAMES))\n .option(\"--vcpu <n>\", \"number of vCPUs\")\n .option(\"--mem <size>\", \"memory, e.g. 16GB or 4096MB\")\n .option(\"--disk <size>\", \"disk size, e.g. 32GB (grow only)\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string, opts: { size?: string; vcpu?: string; mem?: string; disk?: string; json?: boolean }, cmd: Command) => {\n const req = {\n ...(opts.size !== undefined ? { size: opts.size } : {}),\n ...(opts.vcpu !== undefined ? { vcpu: parseCount(opts.vcpu) } : {}),\n ...(opts.mem !== undefined ? { memMib: parseSize(\"--mem\", opts.mem) } : {}),\n ...(opts.disk !== undefined ? { diskGib: parseGib(\"--disk\", opts.disk) } : {}),\n };\n if (Object.keys(req).length === 0) throw new KvboxError(\"nothing to change: give --size, --vcpu, --mem or --disk\");\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const before = pickRef(await boxesFor(client, name), name, me(client));\n if (!before) throw new KvboxError(`box ${name}: not found (kvbox ls)`);\n const box = await spin(`rescaling ${name}…`, client.rescaleMachine(displayName(before, me(client)), req));\n if (opts.json) {\n json(box);\n return;\n }\n const same = box.vcpu === before.vcpu && box.memMib === before.memMib && box.diskBytes === before.diskBytes;\n if (same) {\n info(`box ${name} already has that shape; nothing changed`);\n return;\n }\n info(`${color.green(\"✓\")} ${describe(box)}`);\n if (before.status === \"running\") info(\" it was restarted: processes that were running are gone, files are intact\");\n } finally {\n await client.close();\n }\n });\n\nfunction parseCount(text: string): number {\n const n = Number(text);\n if (!Number.isInteger(n) || n < 1) throw new KvboxError(`--vcpu ${text}: give a whole number of vCPUs`);\n return n;\n}\n\nfunction parseSize(flag: string, text: string): number {\n const mib = parseMib(text);\n if (mib === undefined) throw new KvboxError(`${flag} ${text}: give a size like 16GB or 4096MB`);\n return mib;\n}\n\nfunction parseGib(flag: string, text: string): number {\n const mib = parseSize(flag, text);\n if (mib % 1024 !== 0) throw new KvboxError(`${flag} ${text}: disk sizes are whole GB`);\n return mib / 1024;\n}\n","import { Command } from \"commander\";\nimport { clientFor } from \"../../client.js\";\nimport { color, info, json, spin } from \"../../output.js\";\n\n/** kvbox vm resume <name> [--json] — --json output: the Machine object */\nexport const resumeCommand = new Command(\"resume\")\n .description(\"continue a box that is in standby (kvbox pause)\")\n .argument(\"<name>\", \"box name\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string, opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const box = await spin(`resuming ${name}…`, client.resumeMachine(name));\n if (opts.json) json(box);\n else info(`${color.green(\"✓\")} box ${name} resumed`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { boxesFor, clientFor, me } from \"../../client.js\";\nimport { color, confirm, info, pickRef, spin } from \"../../output.js\";\nimport { displayName } from \"./new.js\";\n\n/**\n * kvbox vm rm <name> [-y] — destructive: asks y/N on a TTY, needs -y otherwise. A bare name is\n * resolved like everywhere else (yours, else the one org box of that name, #68); the question names\n * the box that resolved, `acme/lab1`, so what goes is what you see.\n */\nexport const rmCommand = new Command(\"rm\")\n .description(\"destroy a box (its disk is deleted; snapshots are kept)\")\n .argument(\"<name>\", \"box name\")\n .option(\"-y, --yes\", \"do not ask for confirmation\")\n .action(async (name: string, opts: { yes?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const box = pickRef(await boxesFor(client, name), name, me(client));\n if (!box) throw new KvboxError(`box ${name}: not found (kvbox ls)`);\n // Also what is sent: the control plane must not resolve a second time.\n const ref = displayName(box, me(client));\n if (!(await confirm(`Destroy box ${ref} and its disk?`, opts.yes ?? false))) {\n info(\"cancelled\");\n process.exitCode = 1;\n return;\n }\n await spin(`destroying ${ref}…`, client.deleteMachine(ref));\n info(`${color.green(\"✓\")} box ${ref} destroyed`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { boxesFor, clientFor, me } from \"../../client.js\";\nimport { color, info, json, pickRef, spin } from \"../../output.js\";\nimport { autoHibernateText, displayName, parseIdleTimeout } from \"./new.js\";\n\n/**\n * kvbox vm set <name> [--auto-hibernate <duration>|off] [--json]\n * --json output: the Machine object (`autoHibernateSec` absent when off). Applies at once, in any state.\n */\nexport const setCommand = new Command(\"set\")\n .description(\"change a box's settings, e.g. --auto-hibernate 30m (off: never)\")\n .argument(\"<name>\", \"box name\")\n .option(\"--auto-hibernate <duration>\", \"hibernate the box after this long without network traffic (30m, 4h, 1d; off: never)\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string, opts: { autoHibernate?: string; json?: boolean }, cmd: Command) => {\n if (opts.autoHibernate === undefined) throw new KvboxError(\"nothing to change: give --auto-hibernate\");\n const autoHibernateSec = parseIdleTimeout(opts.autoHibernate);\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const found = pickRef(await boxesFor(client, name), name, me(client));\n if (!found) throw new KvboxError(`box ${name}: not found (kvbox ls)`);\n const box = await spin(`updating ${name}…`, client.setMachine(displayName(found, me(client)), { autoHibernateSec }));\n if (opts.json) {\n json(box);\n return;\n }\n info(`${color.green(\"✓\")} box ${color.bold(name)}: ${autoHibernateText(box.autoHibernateSec)}`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { clientFor } from \"../../client.js\";\nimport { color, info, json, spin } from \"../../output.js\";\nimport { describe } from \"./new.js\";\n\n/** kvbox vm start <name> [--json] — boot a stopped box from its own disk; --json output: the Machine object */\nexport const startCommand = new Command(\"start\")\n .description(\"boot a stopped box again (same name, IP and disk)\")\n .argument(\"<name>\", \"box name\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string, opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const box = await spin(`booting ${name}…`, client.startMachine(name));\n if (opts.json) json(box);\n else info(`${color.green(\"✓\")} ${describe(box)}`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { clientFor } from \"../../client.js\";\nimport { color, info, json, spin } from \"../../output.js\";\n\n/** kvbox vm stop <name> [--json] — clean shutdown, disk kept; --json output: the Machine object */\nexport const stopCommand = new Command(\"stop\")\n .description(\"shut a box down (its disk is kept; start it again with kvbox start)\")\n .argument(\"<name>\", \"box name\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string, opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const box = await spin(`shutting ${name} down…`, client.stopMachine(name));\n if (opts.json) json(box);\n else info(`${color.green(\"✓\")} box ${name} stopped (disk kept; kvbox start ${name} boots it again)`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport type { GuestStats, Machine } from \"@kvbox/shared/api\";\nimport { clientFor } from \"../../client.js\";\nimport { boxName, color, duration, gbShort, info, json, slugOf, table } from \"../../output.js\";\nimport { ownerCell } from \"./ls.js\";\n\n/** One running box and what its guest said: `stats` null for an image too old to say, `error` when it did not answer. */\nexport interface TopEntry {\n name: string;\n owner: string;\n ownerKind?: \"user\" | \"org\" | undefined;\n stats: GuestStats | null;\n error?: string;\n}\n\n/**\n * kvbox vm top [--all] [--json] — load, memory, disk and uptime of each running box of yours and your orgs' (`--all`: the platform's, admins only), as each guest sees\n * itself (#67). --json output: TopEntry[], i.e. [{ name, owner, ownerKind?, stats: { load: [1m, 5m, 15m],\n * cpus, memTotalMib, memUsedMib, diskTotalBytes, diskUsedBytes, uptimeSec } | null, error? }];\n * `ownerKind` (\"user\" | \"org\") only through a control plane, `stats` is null for a box whose image\n * predates base v0.7.0, `error` says why a box did not answer. Exits 1 when no box answered.\n */\nexport const topCommand = new Command(\"top\")\n .description(\"load, memory and disk of each running box, as the box itself sees them\")\n .option(\"-a, --all\", \"every running box on the platform (platform admins only)\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { all?: boolean; json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const running = (await client.listMachines({ all: opts.all })).filter((b) => b.status === \"running\");\n const entries = await mapLimit(running, ASK_AT_ONCE, async (b: Machine): Promise<TopEntry> => {\n const who = { name: b.name, owner: b.owner, ...(b.ownerKind === undefined ? {} : { ownerKind: b.ownerKind }) };\n try {\n return { ...who, stats: (await client.machineStats(`${slugOf(b.owner)}/${b.name}`)).stats };\n } catch (err) {\n return { ...who, stats: null, error: (err as Error).message };\n }\n });\n if (entries.length > 0 && entries.every((e) => e.error !== undefined)) process.exitCode = 1;\n if (opts.json) {\n json(entries);\n return;\n }\n if (entries.length === 0) {\n info(\"no running boxes\");\n return;\n }\n table(topRows(entries, client.target.kind === \"cloud\" ? { me: client.target.user } : undefined));\n for (const e of entries) if (e.error !== undefined) info(color.dim(`${e.name}: ${e.error}`));\n if (entries.some((e) => e.stats === null && e.error === undefined)) {\n info(color.dim(\"-: the box's image is older than base v0.7.0; kvbox vm update <box> moves it onto the current one\"));\n }\n } finally {\n await client.close();\n }\n });\n\n/** Each answer is a vsock round trip on some host (a forwarded HTTPS call too, through a control plane): a few at a time. */\nconst ASK_AT_ONCE = 8;\n\n/** `fn` over `items`, at most `limit` running at once; results in input order. */\nasync function mapLimit<T, R>(items: readonly T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {\n const out = new Array<R>(items.length);\n let next = 0;\n const worker = async () => {\n while (next < items.length) {\n const i = next++;\n out[i] = await fn(items[i]!);\n }\n };\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\n return out;\n}\n\nconst pct = (used: number, total: number) => (total > 0 ? color.dim(` ${Math.round((used / total) * 100)}%`) : \"\");\n\n/** LOAD is the 1 and 5 minute averages over the box's CPU count; an OWNER column first through a control plane, as in `ls`. */\nexport function topRows(entries: TopEntry[], cloud?: { me?: string | undefined }): Record<string, string>[] {\n return entries.map((e) => {\n const s = e.stats;\n return {\n ...(cloud ? { owner: ownerCell(e, cloud.me) } : {}),\n name: boxName(e.name),\n load: s ? `${s.load[0].toFixed(2)} ${s.load[1].toFixed(2)} ${color.dim(`/${s.cpus}`)}` : \"-\",\n mem: s ? `${gbShort(s.memUsedMib * 1024 ** 2)}/${gbShort(s.memTotalMib * 1024 ** 2)}${pct(s.memUsedMib, s.memTotalMib)}` : \"-\",\n disk: s ? `${gbShort(s.diskUsedBytes)}/${gbShort(s.diskTotalBytes)}${pct(s.diskUsedBytes, s.diskTotalBytes)}` : \"-\",\n // duration() writes \"-\" for 0, which here would read as \"no numbers\".\n uptime: s ? (s.uptimeSec >= 1 ? duration(s.uptimeSec) : \"0s\") : \"-\",\n };\n });\n}\n","import { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { boxesFor, clientFor, me } from \"../../client.js\";\nimport { color, info, json, pickRef, spin } from \"../../output.js\";\nimport { displayName } from \"./new.js\";\n\n/**\n * kvbox vm update <name> [--json] — move a box onto the current base image; --json output: the Machine object.\n * The box's own files stay (they live in its overlay); a running box is restarted, so its processes do not.\n * Snapshots are not updated: they are fixed captures. Make a box from one, update it, snapshot again.\n */\nexport const updateCommand = new Command(\"update\")\n .description(\"move a box onto the current base image (its files stay; a running box restarts)\")\n .argument(\"<name>\", \"box name\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string, opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const before = pickRef(await boxesFor(client, name), name, me(client));\n if (!before) throw new KvboxError(`box ${name}: not found (kvbox ls)`);\n const box = await spin(`updating ${name}…`, client.updateMachine(displayName(before, me(client))));\n if (opts.json) {\n json(box);\n return;\n }\n if (box.base === before.base) {\n info(`box ${name} is already on base image ${box.base}`);\n } else {\n const restarted = before.status === \"running\" ? \" (restarted: processes that were running are gone, files are intact)\" : \"\";\n info(`${color.green(\"✓\")} box ${color.bold(name)} now runs on base image ${box.base} (was ${before.base})${restarted}`);\n }\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport type { MachineUsage } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { clientFor } from \"../../client.js\";\nimport { boxName, color, duration, hours, json, status } from \"../../output.js\";\n\n/**\n * kvbox vm usage <name> [--since <date>] [--json] — --json output: the MachineUsage object.\n * Modeled on boxd's `machine usage`: a right-aligned key/value block.\n */\nexport const usageCommand = new Command(\"usage\")\n .description(\"how long a box ran, slept and sat stopped, as vCPU-hours, RAM and disk GiB-hours (and cost, when the host prices them)\")\n .argument(\"<name>\", \"box name\")\n .option(\"--since <date>\", \"count from this date instead of the box's creation, e.g. 2026-10-01\")\n .option(\"--json\", \"print as JSON\")\n .action(async (name: string, opts: { since?: string; json?: boolean }, cmd: Command) => {\n let since: string | undefined;\n if (opts.since !== undefined) {\n const t = Date.parse(opts.since);\n if (Number.isNaN(t)) throw new KvboxError(`--since ${opts.since}: not a date; write it like 2026-10-19 or 2026-10-19T08:00:00Z`);\n since = new Date(t).toISOString();\n }\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const u = await client.machineUsage(name, since);\n if (opts.json) json(u);\n else process.stdout.write(block(u));\n } finally {\n await client.close();\n }\n });\n\nconst day = (iso: string) => iso.slice(0, 10);\n\nconst SYMBOLS: Record<string, string> = { EUR: \"€\", USD: \"$\", GBP: \"£\" };\nexport function money(amount: number, currency: string): string {\n const sign = amount < 0 ? \"-\" : \"\";\n const n = Math.abs(amount).toFixed(2);\n const sym = SYMBOLS[currency.toUpperCase()];\n return sym === undefined ? `${sign}${n} ${currency}` : `${sign}${sym}${n}`;\n}\n\n/** The human output, one `key: value` per line with the keys right-aligned. */\nexport function block(u: MachineUsage): string {\n const estimated = u.estimatedStops === 0 ? \"\" : color.dim(` (${u.estimatedStops} stop time${u.estimatedStops === 1 ? \"\" : \"s\"} estimated)`);\n const rows: [string, string][] = [\n [\"name\", boxName(u.name)],\n [\"status\", status(u.status)],\n [\"window\", `${day(u.window.from)} to ${day(u.window.to)}`],\n [\"running\", duration(u.seconds.running) + estimated],\n [\"standby\", duration(u.seconds.standby)],\n [\"hibernated\", duration(u.seconds.hibernated)],\n [\"stopped\", duration(u.seconds.stopped)],\n [\"vcpu-h\", hours(u.vcpuHours)],\n [\"ram GiB-h\", hours(u.ramGibHours)],\n [\"disk GiB-h\", hours(u.diskGibHours)],\n ];\n if (u.cost !== undefined) rows.push([\"cost\", `${money(u.cost.amount, u.cost.currency)} ${color.dim(\"(estimated)\")}`]);\n if (u.historyFrom !== null && u.historyFrom > u.window.from) {\n rows.push([\"history\", color.dim(`from ${u.historyFrom.slice(0, 16).replace(\"T\", \" \")} UTC; the box is older, but its time before that was not recorded`)]);\n }\n const w = Math.max(...rows.map(([k]) => k.length));\n return rows.map(([k, v]) => `${\" \".repeat(w - k.length)}${k}: ${v}`).join(\"\\n\") + \"\\n\";\n}\n","import { Command } from \"commander\";\nimport { clientFor } from \"../../client.js\";\nimport { color, info, json, spin } from \"../../output.js\";\n\n/** kvbox vm wake <name> [--json] — --json output: the Machine object */\nexport const wakeCommand = new Command(\"wake\")\n .description(\"continue a hibernated box where it left off (same name, IP and disk)\")\n .argument(\"<name>\", \"box name\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string, opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const box = await spin(`waking ${name} (loading its memory from disk)…`, client.wakeMachine(name));\n if (opts.json) json(box);\n else info(`${color.green(\"✓\")} box ${name} is awake, running where it left off`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { joinCommand } from \"./join.js\";\nimport { leaveCommand } from \"./leave.js\";\nimport { relayCommand } from \"./relay.js\";\nimport { startCommand } from \"./start.js\";\nimport { statusCommand } from \"./status.js\";\nimport { stopCommand } from \"./stop.js\";\nimport { trustCaCommand } from \"./trust-ca.js\";\n\nexport const serverCommand = new Command(\"server\")\n .description(\"run or manage the kvbox server\")\n .addCommand(startCommand)\n .addCommand(statusCommand)\n .addCommand(stopCommand)\n .addCommand(joinCommand)\n .addCommand(leaveCommand)\n .addCommand(relayCommand)\n .addCommand(trustCaCommand);\n","import { Command } from \"commander\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { info, spin } from \"../../output.js\";\nimport { restartLocalServer, runKvboxServer } from \"./daemon.js\";\n\n/** kvbox server join <url> --token <t> — `kvbox-server join`, then restart the daemon so it answers the control plane now. */\nexport const joinCommand = new Command(\"join\")\n .description(\"put this machine behind a control plane (needs a one-time token minted there) and restart its server\")\n .argument(\"<control-plane-url>\", \"the control plane, e.g. https://api.kvbox.sh\")\n .requiredOption(\"--token <token>\", \"one-time join token from the control plane\")\n .option(\"--advertise <host-or-ip>\", \"address the control plane reaches this machine at (default: its default-route address)\")\n .option(\"--name <name>\", \"how the control plane lists this machine (default: hostname)\")\n .action(async (url: string, opts: { token: string; advertise?: string; name?: string }) => {\n const args = [\"join\", url, \"--token\", opts.token];\n if (opts.advertise !== undefined) args.push(\"--advertise\", opts.advertise);\n if (opts.name !== undefined) args.push(\"--name\", opts.name);\n for (const line of (await runKvboxServer(args)).split(\"\\n\")) info(line);\n const pid = await spin(\"restarting kvbox-server…\", restartLocalServer(paths()));\n info(`kvbox-server restarted (pid ${pid}); it answers the control plane now`);\n });\n","/**\n * This machine's kvbox-server as a process: stop it, wait for it to be gone, start it again, and run\n * its one-off subcommands (`kvbox-server join|leave`) from PATH. The CLI never imports server code.\n */\nimport { spawn } from \"node:child_process\";\nimport { readFile } from \"node:fs/promises\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { NOT_A_HOST_HINT, startLocalServer } from \"../../client.js\";\n\n/** The pid in server.pid when that process exists, else null. */\nexport async function runningPid(p: Paths = paths()): Promise<number | null> {\n let pid: number;\n try {\n pid = Number.parseInt(await readFile(p.serverPid, \"utf8\"), 10);\n } catch {\n return null;\n }\n return alive(pid) ? pid : null;\n}\n\nfunction alive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/** SIGTERM the daemon and resolve once the process is gone (boxes keep running). */\nexport async function stopLocalServer(pid: number, timeoutMs = 10_000): Promise<void> {\n process.kill(pid, \"SIGTERM\");\n const deadline = Date.now() + timeoutMs;\n while (alive(pid)) {\n if (Date.now() > deadline) throw new KvboxError(`kvbox-server (pid ${pid}) did not stop within ${timeoutMs / 1000}s`);\n await sleep(100);\n }\n}\n\n/** Stop the daemon when it runs, then start it: the way it picks up a join or a leave. Returns the new pid. */\nexport async function restartLocalServer(p: Paths = paths()): Promise<number> {\n const pid = await runningPid(p);\n if (pid !== null) await stopLocalServer(pid);\n return (await startLocalServer(p)).pid;\n}\n\n/**\n * Run `kvbox-server <args>` to completion and return what it printed. Its `error: …` line becomes\n * the thrown message; no binary on PATH is the not-a-host hint, like auto-start.\n */\nexport function runKvboxServer(args: string[]): Promise<string> {\n return new Promise((resolve, reject) => {\n const child = spawn(\"kvbox-server\", args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n let out = \"\";\n let err = \"\";\n child.stdout.on(\"data\", (chunk: Buffer) => (out += chunk.toString()));\n child.stderr.on(\"data\", (chunk: Buffer) => (err += chunk.toString()));\n child.once(\"error\", (e: NodeJS.ErrnoException) => {\n reject(new KvboxError(e.code === \"ENOENT\" ? NOT_A_HOST_HINT : `could not run kvbox-server: ${e.message}`));\n });\n child.once(\"close\", (code) => { // close, not exit: stderr is fully read by then\n if (code === 0) resolve(out.trimEnd());\n else reject(new KvboxError(err.trim().replace(/^error: /, \"\") || `kvbox-server ${args[0] ?? \"\"} exited with code ${String(code)}`, code === 2 ? 2 : 1));\n });\n });\n}\n","import { Command } from \"commander\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { info, spin } from \"../../output.js\";\nimport { restartLocalServer, runKvboxServer, runningPid } from \"./daemon.js\";\n\n/** kvbox server leave — `kvbox-server leave`, then restart a running daemon so the HTTPS port closes now. */\nexport const leaveCommand = new Command(\"leave\")\n .description(\"take this machine out from behind its control plane and restart its server\")\n .action(async () => {\n const p = paths();\n for (const line of (await runKvboxServer([\"leave\"])).split(\"\\n\")) info(line);\n if ((await runningPid(p)) === null) return;\n const pid = await spin(\"restarting kvbox-server…\", restartLocalServer(p));\n info(`kvbox-server restarted (pid ${pid}); only this machine talks to it now`);\n });\n","import { Command } from \"commander\";\nimport { info } from \"../../output.js\";\nimport { runKvboxServer } from \"./daemon.js\";\n\n/**\n * kvbox server relay <join-string> | off — `kvbox-server relay`: dial the tunnel to a relay that lends\n * this machine a public IP (what `kvbox-relay add` printed there), or take it down. No daemon restart:\n * the HTTPS listener already answers on every address.\n */\nexport const relayCommand = new Command(\"relay\")\n .description(\"reach the internet through a relay (paste what `kvbox-relay add` printed on the relay VM); `off` takes the tunnel down\")\n .argument(\"<join-string>\", \"the line `kvbox-relay add` printed, or `off`\")\n .action(async (joinString: string) => {\n for (const line of (await runKvboxServer([\"relay\", joinString])).split(\"\\n\")) info(line);\n });\n","/**\n * kvbox server start\n * Starts the local `kvbox-server` (a separate package) detached, logging to\n * ~/.kvbox/server.log, and waits for its socket. The CLI never imports server code.\n */\nimport { Command } from \"commander\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { clientFor, startLocalServer } from \"../../client.js\";\nimport { info } from \"../../output.js\";\n\nexport const startCommand = new Command(\"start\")\n .description(\"start the local kvbox-server in the background\")\n .action(async (_opts: Record<string, never>, cmd: Command) => {\n const client = await clientFor({ ...cmd.optsWithGlobals(), local: true }, { autoStart: false }); // this machine, whatever kvbox login says\n try {\n const health = await client.health();\n info(`kvbox-server ${health.version} is already running (pid ${health.pid})`);\n return;\n } catch {\n // not running: start it\n } finally {\n await client.close();\n }\n const { pid, socketPath, viaGroup } = await startLocalServer(paths());\n info(`kvbox-server started (pid ${pid}), listening on ${socketPath}`);\n if (viaGroup !== undefined) info(`started through the ${viaGroup} group, which this shell does not have yet (log out and back in to get it)`);\n });\n","import { Command } from \"commander\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { clientFor } from \"../../client.js\";\nimport { info, json } from \"../../output.js\";\nimport { startsAtBoot } from \"../../systemd.js\";\n\n/**\n * kvbox server status [--json] — --json output: Health (version, pid, base image new boxes get, control plane,\n * `relay` with `restarts`/`lastRestartAt` (tunnel redials since the server started),\n * `recovery`: boxes brought back at the server's last start) plus `startsAtBoot` (the systemd unit is enabled, #29)\n */\nexport const statusCommand = new Command(\"status\")\n .description(\"show whether this machine's server is running, its control plane and which base image new boxes get\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor({ ...cmd.optsWithGlobals(), local: true }); // this machine, whatever kvbox login says\n try {\n const health = await client.health();\n const atBoot = startsAtBoot(paths());\n if (opts.json) json({ ...health, startsAtBoot: atBoot });\n else {\n info(`kvbox-server ${health.version} running, pid ${health.pid}`);\n info(atBoot ? \"starts at boot: yes, and brings back the boxes that were running\" : \"starts at boot: no (install-server.sh sets that up)\");\n const r = health.recovery;\n if (r) {\n if (r.booted.length > 0) info(`after the last restart it booted again: ${r.booted.join(\", \")}`);\n if (r.leftStopped.length > 0) info(`left stopped (were in standby, their memory was lost): ${r.leftStopped.join(\", \")}`);\n for (const f of r.failed) info(`did not come back: ${f.box} (${f.error})`);\n }\n if (health.controlPlane) info(`control plane: ${health.controlPlane.name} at ${health.controlPlane.url}, this host answers it on ${health.controlPlane.hostUrl}`);\n else info(\"control plane: none (kvbox server join <url> --token <token> puts this machine behind one)\");\n if (health.relay) {\n info(`relay: ${health.relay.name} lends this machine ${health.relay.publicIp} (tunnel to ${health.relay.endpoint})`);\n if (health.relay.restarts && health.relay.lastRestartAt) {\n info(`the tunnel stopped carrying traffic and was redialed ${health.relay.restarts} time(s) since the server started, last at ${health.relay.lastRestartAt}`);\n }\n }\n if (health.base === null) info(\"base image: none usable yet (run install-server.sh)\");\n else info(`base image: ${health.base} (what kvbox new uses; kvbox vm update <box> moves an older box onto it)`);\n }\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { info } from \"../../output.js\";\nimport { runningPid, stopLocalServer } from \"./daemon.js\";\n\n/** kvbox server stop — SIGTERM the pid in server.pid and wait for it to go. Boxes keep running. */\nexport const stopCommand = new Command(\"stop\")\n .description(\"stop the local server (running boxes are not affected)\")\n .action(async () => {\n const pid = await runningPid(paths());\n if (pid === null) throw new KvboxError(\"kvbox-server is not running\");\n await stopLocalServer(pid);\n info(`kvbox-server stopped (pid ${pid})`);\n });\n","import { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport type { SshKeysApplied, TrustCaReport } from \"@kvbox/shared/api\";\nimport { clientFor } from \"../../client.js\";\nimport { confirm, info, json, warn } from \"../../output.js\";\n\n/**\n * kvbox server trust-ca [public-key] [--from-cloud] [-y] [--json] — every cloud box on this machine\n * trusts a new SSH CA (#55), the step after `ca rotate` on the control plane. Works over this\n * machine's socket only: the control plane cannot ask a host to trust a CA.\n * --json output: TrustCaReport {publicKey, fingerprint, updated: [\"owner/name\"], pending: [{box, when, why?}], failed: [{box, error}], local}\n */\nexport const trustCaCommand = new Command(\"trust-ca\")\n .description(\"make every cloud box on this machine trust a new SSH CA (after `ca rotate` on the control plane)\")\n .argument(\"[public-key]\", \"the CA public key (or its cert-authority line); or --from-cloud\")\n .option(\"--from-cloud\", \"ask the control plane this host joined for its current CA, show the fingerprint, then ask\")\n .option(\"-y, --yes\", \"do not ask for confirmation\")\n .option(\"--json\", \"print the report as JSON\")\n .action(async (publicKey: string | undefined, opts: { fromCloud?: boolean; yes?: boolean; json?: boolean }, cmd: Command) => {\n if (publicKey === undefined && !opts.fromCloud) throw new KvboxError(\"give the CA public key, or --from-cloud to fetch it from the control plane this host joined\");\n if (publicKey !== undefined && opts.fromCloud) throw new KvboxError(\"either a public key or --from-cloud, not both\");\n const client = await clientFor({ ...cmd.optsWithGlobals(), local: true }); // this machine, whatever kvbox login says\n try {\n let key = publicKey;\n if (key === undefined) {\n const ca = await client.cloudCa();\n info(`${ca.controlPlane} says its SSH CA is ${ca.fingerprint}`);\n if (!(await confirm(`make every cloud box on this machine trust it (in place of the CA it trusts now)?`, opts.yes ?? false))) {\n throw new KvboxError(\"cancelled\", 130);\n }\n key = ca.publicKey;\n }\n const report = await client.trustCa({ publicKey: key });\n if (opts.json) json(report);\n else describeReport(report);\n } finally {\n await client.close();\n }\n });\n\nconst WHEN: Record<Exclude<SshKeysApplied, \"now\">, string> = {\n start: \"is stopped: it trusts the CA from its next start\",\n wake: \"is hibernated: it trusts the CA from its next wake\",\n resume: \"is in standby: it trusts the CA from its next resume\",\n later: \"is running but could not take it now; it trusts the CA from its next stop and start\",\n};\n\nexport function describeReport(report: TrustCaReport): void {\n info(`CA ${report.fingerprint}`);\n for (const box of report.updated) info(`box ${box} now trusts the CA`);\n for (const p of report.pending) info(`box ${p.box} ${WHEN[p.when as Exclude<SshKeysApplied, \"now\">]}${p.why ? ` (${p.why})` : \"\"}`);\n for (const f of report.failed) warn(`box ${f.box}: ${f.error}`);\n const parts = [`${report.updated.length} box(es) updated now`, `${report.pending.length} pending`, `${report.failed.length} failed`];\n if (report.local > 0) parts.push(`${report.local} local box(es) untouched (they trust this host's key only)`);\n info(parts.join(\", \"));\n}\n","import { spawnSync } from \"node:child_process\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { hostname as osHostname } from \"node:os\";\nimport { createInterface } from \"node:readline/promises\";\nimport { Writable, type Readable } from \"node:stream\";\nimport { Command } from \"commander\";\nimport { DEFAULT_CLOUD_URL } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { writeCert } from \"../cert.js\";\nimport { ServerClient } from \"../client.js\";\nimport { info } from \"../output.js\";\nimport { askLine } from \"../prompt.js\";\nimport { hostOf, normalizeUrl, writeSession, type Session } from \"../session.js\";\n\n/**\n * kvbox login [url] [--email <email>] [--password-stdin]\n * Exchanges email + password for a bearer token at the control plane (default api.kvbox.sh),\n * uploads this machine's SSH public key (generated under ~/.kvbox/ssh if missing), stores the\n * certificate the control plane signs it with next to the key (#51) and the session in ~/.kvbox/cli.json. From then on every command targets the\n * control plane; `--local` or `kvbox logout` goes back to this machine's socket.\n */\nexport const loginCommand = new Command(\"login\")\n .description(\"log in to the kvbox cloud (or your own control plane) and target it from now on\")\n .argument(\"[url]\", `control plane URL (default: ${DEFAULT_CLOUD_URL})`)\n .option(\"-e, --email <email>\", \"account email (prompted otherwise)\")\n .option(\"--password-stdin\", \"read the password from the first line of stdin (for scripts)\")\n .action(async (urlArg: string | undefined, opts: { email?: string; passwordStdin?: boolean }) => {\n const url = normalizeUrl(urlArg ?? DEFAULT_CLOUD_URL);\n const creds = await readCredentials(opts);\n const session = await runLogin(url, creds, paths());\n info(`logged in to ${hostOf(url)} as ${session.user}`);\n });\n\nexport interface Credentials {\n email: string;\n password: string;\n}\n\ninterface Stdio {\n stdin: Readable;\n /** Whether stdin is a terminal we may prompt on. */\n isTTY: boolean;\n}\n\n/** Email and password from flags, the first line of stdin (`--password-stdin`) or a prompt. */\nexport async function readCredentials(\n opts: { email?: string; passwordStdin?: boolean },\n io: Stdio = { stdin: process.stdin, isTTY: process.stdin.isTTY === true },\n): Promise<Credentials> {\n const noTerminal = () => new KvboxError(\"stdin is not a terminal: pass --email and --password-stdin\");\n let email = opts.email;\n if (email === undefined) {\n if (!io.isTTY) throw noTerminal();\n email = await prompt(\"email: \", { input: process.stdin, output: process.stderr });\n }\n let password: string;\n if (opts.passwordStdin) password = await firstLine(io.stdin);\n else if (io.isTTY) password = await promptSecret(\"password: \", { input: process.stdin, output: process.stderr });\n else throw noTerminal();\n if (email === \"\") throw new KvboxError(\"email is empty\");\n if (password === \"\") throw new KvboxError(\"password is empty\");\n return { email, password };\n}\n\n/** The login itself, minus the prompting: key, request, session file. Returns what was stored. */\nexport async function runLogin(url: string, creds: Credentials, p: Paths = paths(), hostname: string = osHostname()): Promise<Session> {\n const publicKey = await ensureSshKey(p, hostname);\n const client = new ServerClient({ kind: \"cloud\", url, token: \"\" }, { autoStart: false });\n let res;\n try {\n res = await client.login({ email: creds.email, password: creds.password, publicKey });\n } finally {\n await client.close();\n }\n const session: Session = { url, token: res.token, user: res.user.username };\n if (res.sshCert !== undefined && res.sshCertExpires !== undefined) {\n await writeCert(res.sshCert, p);\n session.sshCertExpires = res.sshCertExpires;\n if (res.sshCertPrincipals !== undefined) session.sshCertPrincipals = res.sshCertPrincipals;\n }\n await writeSession(session, p);\n return session;\n}\n\n/**\n * This machine's kvbox SSH key, generated on first use (`ssh-keygen -t ed25519`, no passphrase,\n * comment `kvbox@<hostname>` so it is recognisable in a box's authorized_keys). Returns the public key line.\n */\nexport async function ensureSshKey(p: Paths = paths(), hostname: string = osHostname()): Promise<string> {\n const pubPath = `${p.sshKey}.pub`;\n const pub = await readFile(pubPath, \"utf8\").catch(() => null);\n if (pub !== null) return pub.trim();\n await mkdir(p.ssh, { recursive: true, mode: 0o700 });\n const havePrivate = await readFile(p.sshKey).then(() => true, () => false);\n const args = havePrivate\n ? [\"-y\", \"-f\", p.sshKey] // private key without its .pub: derive it instead of overwriting the key\n : [\"-q\", \"-t\", \"ed25519\", \"-N\", \"\", \"-C\", `kvbox@${hostname}`, \"-f\", p.sshKey];\n const res = spawnSync(\"ssh-keygen\", args, { stdio: [\"ignore\", \"pipe\", \"pipe\"], encoding: \"utf8\" });\n if (res.error) {\n if ((res.error as NodeJS.ErrnoException).code === \"ENOENT\") throw new KvboxError(\"ssh-keygen not found; install OpenSSH\");\n throw new KvboxError(`could not run ssh-keygen: ${res.error.message}`);\n }\n if (res.status !== 0) throw new KvboxError(`ssh-keygen failed: ${res.stderr.trim()}`);\n if (havePrivate) await writeFile(pubPath, res.stdout.trim() + \"\\n\");\n return (await readFile(pubPath, \"utf8\")).trim();\n}\n\ninterface PromptIo {\n input: Readable;\n output: Writable;\n}\n\nexport async function prompt(question: string, io: PromptIo): Promise<string> {\n const rl = createInterface({ input: io.input, output: io.output });\n return (await askLine(rl, question)).trim();\n}\n\n/** A prompt that does not echo: readline in terminal mode writing to a sink; the question goes to `output` by hand. */\nexport async function promptSecret(question: string, io: PromptIo): Promise<string> {\n const sink = new Writable({ write: (_chunk, _enc, cb) => cb() });\n const rl = createInterface({ input: io.input, output: sink, terminal: true });\n io.output.write(question);\n try {\n return await askLine(rl, question);\n } finally {\n io.output.write(\"\\n\");\n }\n}\n\nasync function firstLine(stream: Readable): Promise<string> {\n const rl = createInterface({ input: stream });\n try {\n for await (const line of rl) return line.trim();\n return \"\";\n } finally {\n rl.close();\n }\n}\n","/**\n * Interactive questions for commands that set something up (`kvbox deploy`): a list to pick from\n * with the arrow keys and a line of text with a default. Node built-ins only (raw mode on stdin,\n * a few ANSI sequences on stderr), so the CLI keeps its five runtime libraries.\n *\n * Every question is a terminal thing: a command asks only on a TTY and takes defaults or flags\n * otherwise (`-y`). Answered, a question collapses to one line, `✓ Name myapp`, so the terminal\n * reads like a summary afterwards. Ctrl-C (or Ctrl-D) throws `KvboxError(\"cancelled\", 130)`, so the\n * command's cleanup runs and the exit code is an interrupted command's.\n */\nimport { createInterface, type Interface } from \"node:readline/promises\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { color } from \"./output.js\";\n\nexport interface Choice<T extends string> {\n value: T;\n label: string;\n /** A few dim words after the label: what picking it means. */\n hint?: string;\n}\n\n/** Whether questions can be asked at all: both ends must be a terminal. */\nexport function interactive(): boolean {\n return process.stdin.isTTY === true && process.stderr.isTTY === true;\n}\n\nconst ESC = \"\\x1b\";\nconst ENTER = \"\\r\";\nconst CTRL_C = \"\\x03\";\nconst CTRL_D = \"\\x04\";\n\n/** The cancel every question ends in. */\nexport const cancelled = (): KvboxError => new KvboxError(\"cancelled\", 130);\n\n/**\n * The keys in one chunk from a raw-mode stdin: an escape sequence (`ESC [ A`, or `ESC O A` from a\n * terminal in application-cursor mode) is one key, anything else one character each. A paste or\n * two fast keys arrive as one chunk; every key in it counts.\n */\nexport function keysIn(chunk: string): string[] {\n const keys: string[] = [];\n for (let i = 0; i < chunk.length; ) {\n if (chunk[i] === ESC && (chunk[i + 1] === \"[\" || chunk[i + 1] === \"O\") && i + 2 < chunk.length) {\n keys.push(chunk.slice(i, i + 3));\n i += 3;\n } else {\n keys.push(chunk[i]!);\n i += 1;\n }\n }\n return keys;\n}\n\nconst isUp = (k: string) => k === `${ESC}[A` || k === `${ESC}OA` || k === \"k\";\nconst isDown = (k: string) => k === `${ESC}[B` || k === `${ESC}OB` || k === \"j\";\n\n// eslint-disable-next-line no-control-regex\nconst ANSI = /\\x1b\\[[0-9;]*[A-Za-z]/g;\n/** Terminal rows a line takes once wrapped at the terminal's width (a narrow pane wraps a long hint). */\nexport function rows(line: string, columns = process.stderr.columns ?? 80): number {\n const width = line.replace(ANSI, \"\").length;\n return Math.max(1, Math.ceil(width / Math.max(1, columns)));\n}\n\n/** The line a settled question leaves behind. */\nfunction settled(message: string, answer: string): string {\n return `${color.green(\"✓\")} ${color.bold(message)} ${color.cyan(answer)}`;\n}\n\n/** Pick one of `choices` with ↑/↓ (or j/k), Enter to confirm. `initial` is the index highlighted first. */\nexport async function select<T extends string>(message: string, choices: readonly Choice<T>[], initial = 0): Promise<T> {\n const out = process.stderr;\n const inp = process.stdin;\n let index = Math.min(Math.max(initial, 0), choices.length - 1);\n let drawn = 0;\n\n const render = (): void => {\n if (drawn > 0) out.write(`${ESC}[${drawn}A`);\n const lines = [\n `${color.green(\"?\")} ${color.bold(message)} ${color.dim(\"↑↓ to move, enter to pick\")}`,\n ...choices.map((c, i) => {\n const hint = c.hint ? color.dim(` ${c.hint}`) : \"\";\n return i === index ? `${color.cyan(`❯ ${c.label}`)}${hint}` : ` ${c.label}${hint}`;\n }),\n ];\n out.write(`\\r${ESC}[J${lines.join(\"\\n\")}\\n`);\n drawn = lines.reduce((n, l) => n + rows(l), 0);\n };\n\n inp.setRawMode(true);\n inp.resume();\n inp.setEncoding(\"utf8\");\n render();\n let done = false;\n try {\n return await new Promise<T>((resolve, reject) => {\n const onData = (chunk: string): void => {\n for (const key of keysIn(chunk)) {\n if (isUp(key)) index = (index - 1 + choices.length) % choices.length;\n else if (isDown(key)) index = (index + 1) % choices.length;\n else if (key === ENTER || key === \"\\n\") {\n inp.off(\"data\", onData);\n done = true;\n resolve(choices[index]!.value);\n return;\n } else if (key === CTRL_C || key === CTRL_D) {\n inp.off(\"data\", onData);\n reject(cancelled());\n return;\n } else continue;\n render();\n }\n };\n inp.on(\"data\", onData);\n });\n } finally {\n inp.setRawMode(false);\n inp.pause();\n out.write(`${ESC}[${drawn}A\\r${ESC}[J${done ? `${settled(message, choices[index]!.label)}\\n` : \"\"}`);\n }\n}\n\nexport interface TextOptions {\n /** Taken when the user just presses Enter; shown dim in the prompt. */\n default?: string;\n /** Why an answer is not acceptable, or undefined when it is; the question is asked again. */\n validate?: (answer: string) => string | undefined;\n}\n\n/** One line of text. Empty takes the default; an answer `validate` rejects is explained and asked again. */\nexport async function text(message: string, opts: TextOptions = {}): Promise<string> {\n const out = process.stderr;\n for (;;) {\n const hint = opts.default !== undefined ? ` ${color.dim(`(${opts.default})`)}` : \"\";\n const question = `${color.green(\"?\")} ${color.bold(message)}${hint} ${color.dim(\"›\")} `;\n const rl = createInterface({ input: process.stdin, output: out });\n const raw = (await askLine(rl, question)).trim();\n const answer = raw === \"\" && opts.default !== undefined ? opts.default : raw;\n const problem = opts.validate?.(answer);\n // readline moved to the next line: rewrite the question (as many rows as it wrapped to) as its settled form.\n out.write(`${ESC}[${rows(question + raw)}A\\r${ESC}[J`);\n if (problem === undefined) {\n out.write(`${settled(message, answer)}\\n`);\n return answer;\n }\n out.write(`${color.yellow(\"!\")} ${problem}\\n`);\n }\n}\n\n/**\n * One question on a readline interface, closing it afterwards. Ctrl-C in terminal mode rejects the\n * question (ABORT_ERR); Ctrl-D or EOF only closes the interface and would leave the question pending\n * forever, so a close before the answer is treated the same way: the user cancelled (exit 130).\n */\nexport async function askLine(rl: Interface, question: string): Promise<string> {\n let onClose = () => {};\n const closed = new Promise<never>((_, reject) => {\n onClose = () => reject(cancelled());\n rl.once(\"close\", onClose);\n });\n try {\n return await Promise.race([rl.question(question).catch(abortIsCancel), closed]);\n } finally {\n rl.off(\"close\", onClose);\n rl.close();\n }\n}\n\nfunction abortIsCancel(err: unknown): never {\n if ((err as NodeJS.ErrnoException).code === \"ABORT_ERR\") throw cancelled();\n throw err;\n}\n","import { Command } from \"commander\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { removeCert } from \"../cert.js\";\nimport { ServerClient } from \"../client.js\";\nimport { info } from \"../output.js\";\nimport { clearSession, hostOf, readSession } from \"../session.js\";\n\n/** kvbox logout — revoke the token at the control plane (best effort) and forget the session: back to local mode. */\nexport const logoutCommand = new Command(\"logout\")\n .description(\"log out of the control plane; commands target this machine's kvbox-server again\")\n .action(async () => {\n const p = paths();\n const session = await readSession(p).catch(() => null);\n switch (await runLogout(p)) {\n case \"none\":\n info(\"not logged in\");\n break;\n case \"unreadable\":\n info(`logged out (${p.cli} was unreadable and is gone)`);\n break;\n case \"cleared\":\n info(`logged out of ${hostOf(session?.url ?? \"\")}`);\n }\n });\n\n/**\n * The logout itself. An unreadable cli.json is cleared too: logout is the way out that\n * readSession's error points at, so it must never refuse.\n */\nexport async function runLogout(p: Paths = paths()): Promise<\"none\" | \"cleared\" | \"unreadable\"> {\n let session;\n try {\n session = await readSession(p);\n } catch {\n await clearSession(p);\n await removeCert(p);\n return \"unreadable\";\n }\n if (!session) return \"none\";\n const client = new ServerClient({ kind: \"cloud\", url: session.url, token: session.token }, { autoStart: false });\n try {\n await client.logout();\n } catch {\n // unreachable or already revoked: the local file is what matters\n } finally {\n await client.close();\n }\n await clearSession(p);\n await removeCert(p); // the certificate belonged to this login; the key stays for the next one\n return \"cleared\";\n}\n","import { Command } from \"commander\";\nimport { json } from \"../output.js\";\nimport { hostOf, readSession, type Session } from \"../session.js\";\n\n/** kvbox whoami [--json] — the stored login, without a network call. --json: { user, url, sshCertExpires } or null. */\nexport const whoamiCommand = new Command(\"whoami\")\n .description(\"show which account and control plane commands target (or local mode)\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { json?: boolean }) => {\n const session = await readSession();\n if (opts.json) {\n json(session ? { user: session.user, url: session.url, sshCertExpires: session.sshCertExpires ?? null } : null);\n return;\n }\n process.stdout.write(describeSession(session) + \"\\n\");\n });\n\n/** \"ghalex on api.kvbox.sh\" plus the certificate's expiry day. */\nexport function describeSession(session: Session | null): string {\n if (!session) return \"not logged in (local mode)\";\n const lines = [`${session.user} on ${hostOf(session.url)}`];\n if (session.sshCertExpires) lines.push(`certificate valid until ${session.sshCertExpires.slice(0, 10)}`);\n return lines.join(\"\\n\");\n}\n","import { Command } from \"commander\";\nimport { lsCommand } from \"./ls.js\";\nimport { newCommand } from \"./new.js\";\nimport { rmCommand } from \"./rm.js\";\n\nexport const snapshotsCommand = new Command(\"snapshots\")\n .aliases([\"snapshot\", \"snap\"])\n .description(\"freeze running boxes into snapshots and manage them\")\n .addCommand(newCommand)\n .addCommand(lsCommand)\n .addCommand(rmCommand);\n\nfor (const cmd of snapshotsCommand.commands) cmd.option(\"--org <slug>\", \"act in this org (- for your personal boxes)\");\n","import { Command } from \"commander\";\nimport { clientFor } from \"../../client.js\";\nimport { age, boxName, gbShort, info, json, shape, shortRef, slugOf, table } from \"../../output.js\";\n\n/** kvbox snapshots ls [--all] [--json] — the user's and their orgs' snapshots (`--org <slug>` for one org, `--all` the whole platform for a platform admin). --json output: Snapshot[] */\nexport const lsCommand = new Command(\"ls\")\n .description(\"list snapshots (yours and your orgs'; --org <slug> for one org)\")\n .option(\"-a, --all\", \"every snapshot on the platform (platform admins only)\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { all?: boolean; json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const cloud = client.target.kind === \"cloud\";\n const snaps = await client.listSnapshots({ all: opts.all });\n if (opts.json) {\n json(snaps);\n return;\n }\n if (snaps.length === 0) {\n info(\"no snapshots yet; freeze a running box with: kvbox snapshots new <box> <name>\");\n return;\n }\n const org = client.target.kind === \"cloud\" ? client.target.org : undefined;\n if (org !== undefined) info(`snapshots of ${org}`);\n // Base image version stays in --json; a restore checks it, a reader rarely needs it.\n table(\n snaps.map((s) => ({\n ...(cloud ? { owner: slugOf(s.owner) === client.target.user ? \"private\" : slugOf(s.owner) } : {}),\n name: boxName(s.name),\n \"from box\": shortRef(s.source, s.owner),\n shape: shape(s.vcpu, s.memMib),\n \"on disk\": gbShort(s.sizeBytes),\n created: age(s.createdAt),\n })),\n );\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { clientFor } from \"../../client.js\";\nimport { color, gb, info, json, spin } from \"../../output.js\";\n\n/** kvbox snapshots new <box> <name> [--json] — --json output: Snapshot */\nexport const newCommand = new Command(\"new\")\n .description(\"freeze a running box (memory + disk) into a snapshot; the box keeps running\")\n .argument(\"<box>\", \"box name\")\n .argument(\"<name>\", \"snapshot name\")\n .option(\"--json\", \"print the snapshot as JSON\")\n .action(async (box: string, name: string, opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const snap = await spin(`saving snapshot ${name} from box ${box} (memory + disk)…`, client.createSnapshot({ box, name }));\n if (opts.json) json(snap);\n else info(`${color.green(\"✓\")} snapshot ${name} saved from box ${box} (${gb(snap.sizeBytes)} on disk); start a warm clone with: kvbox new --from ${name}`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { clientFor } from \"../../client.js\";\nimport { color, confirm, info, spin } from \"../../output.js\";\n\n/** kvbox snapshots rm <name> [-y] — destructive: asks y/N on a TTY, needs -y otherwise */\nexport const rmCommand = new Command(\"rm\")\n .description(\"delete a snapshot (boxes made from it are not affected)\")\n .argument(\"<name>\", \"snapshot name\")\n .option(\"-y, --yes\", \"do not ask for confirmation\")\n .action(async (name: string, opts: { yes?: boolean }, cmd: Command) => {\n if (!(await confirm(`Delete snapshot ${name}?`, opts.yes ?? false))) {\n info(\"cancelled\");\n process.exitCode = 1;\n return;\n }\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n await spin(`deleting snapshot ${name}…`, client.deleteSnapshot(name));\n info(`${color.green(\"✓\")} snapshot ${name} deleted`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { lsCommand } from \"./ls.js\";\nimport { membersCommand } from \"./members.js\";\nimport { newCommand } from \"./new.js\";\nimport { rmCommand } from \"./rm.js\";\nimport { roleCommand } from \"./role.js\";\n\n/** kvbox org … — orgs own boxes like a user does; members work in them by role (control plane only). */\nexport const orgCommand = new Command(\"org\")\n .description(\"orgs: shared slugs that own boxes, with owners, admins and members\")\n .addCommand(lsCommand)\n .addCommand(newCommand)\n .addCommand(membersCommand)\n .addCommand(roleCommand)\n .addCommand(rmCommand);\n","import { Command } from \"commander\";\nimport type { OrgMembership } from \"@kvbox/shared/api\";\nimport { age, boxName, info, json, table } from \"../../output.js\";\nimport { cloudClientFor } from \"./context.js\";\n\n/** kvbox org ls [--json] — the user's orgs with their role in each. --json: OrgMembership[] */\nexport const lsCommand = new Command(\"ls\")\n .description(\"list the orgs you belong to and your role in each\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { json?: boolean }, cmd: Command) => {\n const client = await cloudClientFor(cmd.optsWithGlobals());\n try {\n const orgs = await client.listOrgs();\n if (opts.json) {\n json(orgs);\n return;\n }\n if (orgs.length === 0) {\n info(\"you are in no org yet; make one with: kvbox org new <slug>\");\n return;\n }\n table(orgRows(orgs));\n } finally {\n await client.close();\n }\n });\n\nexport function orgRows(orgs: OrgMembership[]): Record<string, string>[] {\n return orgs.map((o) => ({ org: boxName(o.slug), name: o.name, role: o.role, since: age(o.createdAt) }));\n}\n","import { KvboxError } from \"@kvbox/shared/errors\";\nimport { clientFor, type GlobalOptions, type ServerClient, type Target } from \"../../client.js\";\n\nconst NOT_LOGGED_IN = \"orgs live on the control plane: kvbox login first\";\n\n/** A client for an org command: the control plane or nothing (never the local daemon, which has no orgs). */\nexport async function cloudClientFor(opts: GlobalOptions): Promise<ServerClient> {\n const client = await clientFor(opts, { autoStart: false });\n if (client.target.kind === \"local\") {\n await client.close();\n throw new KvboxError(NOT_LOGGED_IN);\n }\n return client;\n}\n\n/** The org a members or role command acts on: `--org` on the command or before it, else a plain error. */\nexport function orgFor(opts: { org?: string | undefined }, target: Target): string {\n if (target.kind === \"local\") throw new KvboxError(NOT_LOGGED_IN);\n const slug = opts.org ?? target.org;\n if (slug === undefined) throw new KvboxError(\"no org: pass --org <slug>\");\n return slug;\n}\n","import { Command, Option } from \"commander\";\nimport { ORG_ROLES, type OrgRole } from \"@kvbox/shared/api\";\nimport { age, boxName, color, confirm, info, json, table } from \"../../output.js\";\nimport { cloudClientFor, orgFor } from \"./context.js\";\n\ntype Opts = { org?: string; json?: boolean };\n\n/** kvbox org members ls [--org <slug>] [--json] — --json: OrgMember[] */\nconst lsCommand = new Command(\"ls\")\n .description(\"list an org's members and their roles\")\n .option(\"-o, --org <slug>\", \"the org (or --org before the command)\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: Opts, cmd: Command) => {\n const client = await cloudClientFor(cmd.optsWithGlobals());\n try {\n const org = await client.getOrg(orgFor(opts, client.target));\n if (opts.json) {\n json(org.members);\n return;\n }\n info(`${org.slug} (${org.name})`);\n table(org.members.map((m) => ({ user: boxName(m.username), name: m.name, role: m.role, since: age(m.addedAt) })));\n } finally {\n await client.close();\n }\n });\n\n/** kvbox org members add <user> [--role <role>] [--org <slug>] */\nconst addCommand = new Command(\"add\")\n .description(\"add a user to an org (admins and owners; only an owner can add an owner)\")\n .argument(\"<user>\", \"their username\")\n .addOption(new Option(\"-r, --role <role>\", \"their role\").choices(ORG_ROLES).default(\"member\"))\n .option(\"-o, --org <slug>\", \"the org (or --org before the command)\")\n .action(async (user: string, opts: Opts & { role: OrgRole }, cmd: Command) => {\n const client = await cloudClientFor(cmd.optsWithGlobals());\n try {\n const slug = orgFor(opts, client.target);\n await client.addMember(slug, { username: user, role: opts.role });\n info(`${color.green(\"✓\")} ${user} is now a ${opts.role} of ${slug}`);\n } finally {\n await client.close();\n }\n });\n\n/** kvbox org members rm <user> [--org <slug>] [-y] — y/N on a TTY, -y otherwise; removing yourself is leaving */\nconst rmCommand = new Command(\"rm\")\n .description(\"remove a member (or leave: remove yourself)\")\n .argument(\"<user>\", \"their username\")\n .option(\"-o, --org <slug>\", \"the org (or --org before the command)\")\n .option(\"-y, --yes\", \"do not ask for confirmation\")\n .action(async (user: string, opts: Opts & { yes?: boolean }, cmd: Command) => {\n const client = await cloudClientFor(cmd.optsWithGlobals());\n try {\n const slug = orgFor(opts, client.target);\n if (!(await confirm(`Remove ${user} from ${slug}?`, opts.yes ?? false))) {\n info(\"cancelled\");\n process.exitCode = 1;\n return;\n }\n const self = client.target.kind === \"cloud\" && client.target.user === user;\n await client.removeMember(slug, user);\n info(`${color.green(\"✓\")} ${self ? `you left ${slug}` : `${user} removed from ${slug}`}`);\n } finally {\n await client.close();\n }\n });\n\nexport const membersCommand = new Command(\"members\")\n .description(\"who is in an org and what they may do\")\n .addCommand(lsCommand)\n .addCommand(addCommand)\n .addCommand(rmCommand);\n","import { Command } from \"commander\";\nimport { color, info, json } from \"../../output.js\";\nimport { cloudClientFor } from \"./context.js\";\n\n/** kvbox org new <slug> [--name <name>] [--json] — the caller becomes the org's owner. --json: CloudOrg */\nexport const newCommand = new Command(\"new\")\n .description(\"create an org; you become its owner (the slug is permanent, the name is not)\")\n .argument(\"<slug>\", \"the org's slug: lowercase, like a username (acme)\")\n .option(\"-n, --name <name>\", \"display name (default: the slug)\")\n .option(\"--json\", \"print the org as JSON\")\n .action(async (slug: string, opts: { name?: string; json?: boolean }, cmd: Command) => {\n const client = await cloudClientFor(cmd.optsWithGlobals());\n try {\n const org = await client.createOrg({ slug, name: opts.name ?? slug });\n if (opts.json) {\n json(org);\n return;\n }\n info(`${color.green(\"✓\")} org ${color.bold(org.slug)} created (${org.name}); you are its owner`);\n info(` work in it with: kvbox org use ${org.slug} (then bare box names are ${org.slug}'s)`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { color, confirm, info } from \"../../output.js\";\nimport { cloudClientFor } from \"./context.js\";\n\n/** kvbox org rm <slug> [-y] — owners only; refused while the org still has boxes or snapshots */\nexport const rmCommand = new Command(\"rm\")\n .description(\"delete an org (owners only; remove its boxes and snapshots first)\")\n .argument(\"<slug>\", \"the org\")\n .option(\"-y, --yes\", \"do not ask for confirmation\")\n .action(async (slug: string, opts: { yes?: boolean }, cmd: Command) => {\n if (!(await confirm(`Delete org ${slug}? Its members lose access; its slug stays taken.`, opts.yes ?? false))) {\n info(\"cancelled\");\n process.exitCode = 1;\n return;\n }\n const client = await cloudClientFor(cmd.optsWithGlobals());\n try {\n await client.deleteOrg(slug);\n info(`${color.green(\"✓\")} org ${slug} deleted`);\n } finally {\n await client.close();\n }\n });\n","import { Argument, Command } from \"commander\";\nimport { ORG_ROLES, type OrgRole } from \"@kvbox/shared/api\";\nimport { color, info } from \"../../output.js\";\nimport { cloudClientFor, orgFor } from \"./context.js\";\n\n/** kvbox org role <user> <role> [--org <slug>] — owners only; the last owner cannot step down */\nexport const roleCommand = new Command(\"role\")\n .description(\"change a member's role (owners only)\")\n .argument(\"<user>\", \"their username\")\n .addArgument(new Argument(\"<role>\", \"owner, admin or member\").choices(ORG_ROLES))\n .option(\"-o, --org <slug>\", \"the org (default: the current context)\")\n .action(async (user: string, role: OrgRole, opts: { org?: string }, cmd: Command) => {\n const client = await cloudClientFor(cmd.optsWithGlobals());\n try {\n const slug = orgFor(opts, client.target);\n await client.setRole(slug, user, role);\n info(`${color.green(\"✓\")} ${user} is now a ${role} of ${slug}`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport type { Balance, BoxUsage, UsageReport } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { round, sumUsage } from \"@kvbox/shared/usage\";\nimport { clientFor } from \"../client.js\";\nimport { boxName, color, duration, hours, info, json, slugOf, status, table } from \"../output.js\";\nimport { money } from \"./vm/usage.js\";\n\n/**\n * kvbox usage [--since <date>] [--until <date>] [--all] [--by-user] [--json] — every box of yours over the window\n * (this calendar month by default), removed ones included, with totals. Through a control plane it\n * covers you and your orgs (`--org <slug>` for one org, `--all` every slug for a platform admin) and is priced with its price list; on\n * this machine it is the host's ledger (priced only when config.json has `pricing`).\n * `--by-user` (control plane only, #60) sums the same boxes per user who made them, typically with `--org`.\n * --json output: the UsageReport object { window, boxes: BoxUsage[], totals };\n * with --by-user { window, users: UserUsage[], totals }, a UserUsage being { user: string | null,\n * boxes: number, seconds, vcpuHours, ramGibHours, diskGibHours, cost? }. `user` is null for boxes\n * whose maker is unknown: removed ones (the ledger does not record who made a box) and ones made\n * outside the control plane.\n */\nexport const usageCommand = new Command(\"usage\")\n .description(\"what your boxes used this month (or --since/--until): running time, vCPU-h, RAM and disk GiB-h, cost\")\n .option(\"--since <date>\", \"count from this date, e.g. 2026-10-01 (default: the 1st of this month)\")\n .option(\"--until <date>\", \"count up to this date (default: now)\")\n .option(\"--org <slug>\", \"one org's boxes only\")\n .option(\"-a, --all\", \"every box on the platform (platform admins only)\")\n .option(\"--by-user\", \"one line per user who made the boxes (e.g. who spent what in --org)\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { since?: string; until?: string; org?: string; all?: boolean; byUser?: boolean; json?: boolean }, cmd: Command) => {\n for (const [name, value] of [\n [\"since\", opts.since],\n [\"until\", opts.until],\n ] as const) {\n if (value !== undefined && Number.isNaN(Date.parse(value))) throw new KvboxError(`--${name} ${value}: not a date; write it like 2026-10-19 or 2026-10-19T08:00:00Z`);\n }\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n // On this machine there are no orgs: a silently ignored --org would print the whole host as if it were one.\n if (client.target.kind === \"local\" && cmd.optsWithGlobals<{ org?: string }>().org) throw new KvboxError(\"--org needs a control plane: kvbox login, or drop --org\");\n if (client.target.kind === \"local\" && opts.byUser) throw new KvboxError(\"--by-user needs a control plane: kvbox login, or drop --by-user\");\n const report = await client.usageReport(opts.since, opts.until, opts.all);\n const perUser = opts.byUser ? byUser(report) : undefined;\n if (opts.json) {\n json(perUser ?? report);\n return;\n }\n const cloud = client.target.kind === \"cloud\" ? { me: client.target.user } : undefined;\n info(`${day(report.window.from)} to ${day(report.window.to)}`);\n if (report.boxes.length === 0) info(\"no usage in this window\");\n else table(perUser ? userRows(perUser) : usageRows(report, cloud));\n if (cloud) {\n const line = await creditLine(client, cloud.me);\n if (line !== undefined) info(line);\n }\n } finally {\n await client.close();\n }\n });\n\nconst day = (iso: string) => iso.slice(0, 10);\n\n/**\n * The prepaid balance under the table (#76): the caller's own with no `--org`, the org's with it.\n * A control plane without the route (older than #76) answers an error: then there is no line.\n */\nasync function creditLine(client: { balance(): Promise<Balance> }, me: string | undefined): Promise<string | undefined> {\n let b: Balance;\n try {\n b = await client.balance();\n } catch (err) {\n if (err instanceof KvboxError) return undefined;\n throw err;\n }\n const whose = b.slug === me ? \"private\" : b.slug;\n const left = money(b.balance, b.currency);\n const line = `credit: ${b.balance > 0 ? left : color.red(left)} left ${color.dim(`(${whose})`)}`;\n // Suspended (#76): the control plane hibernated the boxes at zero; a top-up brings them back.\n return b.suspendedAt ? `${line} ${color.red(\"out of credit: boxes hibernated until you top up\")}` : line;\n}\n\n/** The OWNER cell, like `kvbox ls`: `private` for the user's own, else the slug and its kind. */\nfunction ownerCell(b: BoxUsage, me: string | undefined): string {\n const slug = slugOf(b.owner);\n if (slug === me) return \"private\";\n return b.ownerKind === undefined ? slug : `${slug} ${color.dim(b.ownerKind)}`;\n}\n\n/**\n * One row per box plus a totals row; an OWNER column first through a control plane. A removed box\n * is marked, its figures are its final ones. The COST column is there when the report is priced.\n */\nexport function usageRows(report: UsageReport, cloud?: { me?: string | undefined }): Record<string, string>[] {\n const priced = report.totals.cost !== undefined;\n const rows = report.boxes.map((b) => ({\n ...(cloud ? { owner: ownerCell(b, cloud.me) } : {}),\n name: boxName(b.name),\n status: b.status === \"removed\" ? color.dim(\"removed\") : status(b.status),\n running: duration(b.seconds.running),\n \"vcpu-h\": hours(b.vcpuHours),\n \"ram GiB-h\": hours(b.ramGibHours),\n \"disk GiB-h\": hours(b.diskGibHours),\n ...(priced ? { cost: money(b.cost?.amount ?? 0, report.totals.cost!.currency) } : {}),\n }));\n const t = report.totals;\n rows.push({\n ...(cloud ? { owner: \"\" } : {}),\n name: color.bold(\"total\"),\n status: \"\",\n running: duration(t.seconds.running),\n \"vcpu-h\": hours(t.vcpuHours),\n \"ram GiB-h\": hours(t.ramGibHours),\n \"disk GiB-h\": hours(t.diskGibHours),\n ...(priced ? { cost: `${money(t.cost!.amount, t.cost!.currency)} ${color.dim(\"(estimated)\")}` } : {}),\n });\n return rows;\n}\n\nexport interface UserUsage {\n /** The username that made the boxes; null when unknown (removed boxes, boxes made outside the control plane). */\n user: string | null;\n boxes: number;\n seconds: BoxUsage[\"seconds\"];\n vcpuHours: number;\n ramGibHours: number;\n diskGibHours: number;\n cost?: { amount: number; currency: string };\n}\n\n/** The report's boxes summed per maker (#60), by name with the unknown last; the totals are the report's. */\nexport function byUser(report: UsageReport): { window: UsageReport[\"window\"]; users: UserUsage[]; totals: UsageReport[\"totals\"] } {\n const groups = new Map<string | null, BoxUsage[]>();\n for (const b of report.boxes) {\n const user = b.createdBy ?? null;\n const list = groups.get(user);\n if (list === undefined) groups.set(user, [b]);\n else list.push(b);\n }\n const currency = report.totals.cost?.currency;\n const users = [...groups].map(([user, boxes]): UserUsage => {\n const { cost: _none, ...sum } = sumUsage(boxes);\n const u: UserUsage = { user, boxes: boxes.length, ...sum };\n if (currency !== undefined) u.cost = { amount: round(boxes.reduce((n, b) => n + (b.cost?.amount ?? 0), 0), 4), currency };\n return u;\n });\n users.sort((a, b) => (a.user === null ? 1 : b.user === null ? -1 : a.user.localeCompare(b.user)));\n return { window: report.window, users, totals: report.totals };\n}\n\n/** One row per maker plus the totals row; removed boxes and ones the control plane did not make go under `unknown`. */\nexport function userRows(r: ReturnType<typeof byUser>): Record<string, string>[] {\n const priced = r.totals.cost !== undefined;\n const cells = (t: Pick<UserUsage, \"seconds\" | \"vcpuHours\" | \"ramGibHours\" | \"diskGibHours\">) => ({\n running: duration(t.seconds.running),\n \"vcpu-h\": hours(t.vcpuHours),\n \"ram GiB-h\": hours(t.ramGibHours),\n \"disk GiB-h\": hours(t.diskGibHours),\n });\n const rows = r.users.map((u) => ({\n user: u.user ?? color.dim(\"unknown\"),\n boxes: String(u.boxes),\n ...cells(u),\n ...(priced ? { cost: money(u.cost?.amount ?? 0, r.totals.cost!.currency) } : {}),\n }));\n rows.push({\n user: color.bold(\"total\"),\n boxes: String(r.users.reduce((n, u) => n + u.boxes, 0)),\n ...cells(r.totals),\n ...(priced ? { cost: `${money(r.totals.cost!.amount, r.totals.cost!.currency)} ${color.dim(\"(estimated)\")}` } : {}),\n });\n return rows;\n}\n","/**\n * Summing a box's usage ledger: one pure function over its state-change rows, used by the host\n * (`kvbox vm usage`, `GET /usage`) and by the control plane over the rows it pulled (#42). A row\n * opens an interval that lasts until the next row; the sizes ride on every row so a rescale\n * changes the rate from that moment on. Pricing is per resource-hour (decision \"Usage is priced\n * per resource-hour\").\n */\nimport { z } from \"zod\";\nimport type { BoxStatus, BoxUsage } from \"./api.js\";\n\nexport type UsageState = \"running\" | \"standby\" | \"hibernated\" | \"stopped\";\n\n/** One state change of a box. */\nexport interface UsageEvent {\n at: string;\n state: UsageState;\n vcpu: number;\n memMib: number;\n diskGib: number;\n /** What made it: new, start, stop, pause, resume, hibernate, wake, rescale, update, rm, server (a stop the server did not see). */\n by: string;\n}\n\n/** What an hour of each resource costs. */\nexport const PricingSchema = z.object({\n currency: z.string().min(1),\n vcpuHour: z.number().nonnegative(),\n ramGibHour: z.number().nonnegative(),\n diskGibHour: z.number().nonnegative(),\n});\nexport type Pricing = z.infer<typeof PricingSchema>;\n\nexport interface UsageWindow {\n from: string;\n to: string;\n pricing?: Pricing | undefined;\n}\n\nexport interface UsageTotals {\n seconds: Record<UsageState, number>;\n vcpuHours: number;\n ramGibHours: number;\n diskGibHours: number;\n cost?: { amount: number; currency: string };\n /** Stops the server did not witness (Firecracker died, host rebooted) and dated to when it noticed. */\n estimatedStops: number;\n /** The first recorded moment, null when nothing is recorded. */\n historyFrom: string | null;\n}\n\nconst HOUR_MS = 3_600_000;\n\nexport const round = (n: number, places: number) => Math.round(n * 10 ** places) / 10 ** places;\n\n/**\n * Each event opens an interval that lasts until the next one (or `to`); intervals are clipped to the\n * window, so the event before `from` supplies the state the window starts in. Time before the first\n * event belongs to no state: it was never recorded. Running hours earn vCPU and RAM; standby hours\n * earn RAM (the memory is still held) but no vCPU; every hour the box exists earns disk (its overlay\n * is there while it is hibernated or stopped too). A repeated state continues it.\n */\nexport function computeUsage(events: readonly UsageEvent[], w: UsageWindow): UsageTotals {\n const sorted = [...events].sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));\n const from = Date.parse(w.from);\n const to = Date.parse(w.to);\n const ms: Record<UsageState, number> = { running: 0, standby: 0, hibernated: 0, stopped: 0 };\n let vcpuHours = 0;\n let ramGibHours = 0;\n let diskGibHours = 0;\n sorted.forEach((e, i) => {\n const start = Math.max(Date.parse(e.at), from);\n const next = sorted[i + 1];\n const end = Math.min(next === undefined ? to : Date.parse(next.at), to);\n if (end <= start) return;\n const h = (end - start) / HOUR_MS;\n ms[e.state] += end - start;\n if (e.state === \"running\") vcpuHours += h * e.vcpu;\n if (e.state === \"running\" || e.state === \"standby\") ramGibHours += (h * e.memMib) / 1024;\n diskGibHours += h * e.diskGib;\n });\n const totals: UsageTotals = {\n seconds: {\n running: Math.round(ms.running / 1000),\n standby: Math.round(ms.standby / 1000),\n hibernated: Math.round(ms.hibernated / 1000),\n stopped: Math.round(ms.stopped / 1000),\n },\n vcpuHours: round(vcpuHours, 3),\n ramGibHours: round(ramGibHours, 3),\n diskGibHours: round(diskGibHours, 3),\n estimatedStops: sorted.filter((e) => e.state === \"stopped\" && e.by === \"server\" && e.at >= w.from).length,\n historyFrom: sorted[0]?.at ?? null,\n };\n if (w.pricing !== undefined) totals.cost = { amount: round(costOf(totals, w.pricing), 4), currency: w.pricing.currency };\n return totals;\n}\n\n/** The price of a set of resource-hours; totals over several boxes are summed the same way. */\nexport function costOf(t: Pick<UsageTotals, \"vcpuHours\" | \"ramGibHours\" | \"diskGibHours\">, pricing: Pricing): number {\n return t.vcpuHours * pricing.vcpuHour + t.ramGibHours * pricing.ramGibHour + t.diskGibHours * pricing.diskGibHour;\n}\n\n/** Add up several boxes' totals (hours and seconds; the cost is recomputed from the hours when priced). */\nexport function sumUsage(items: readonly Pick<UsageTotals, \"seconds\" | \"vcpuHours\" | \"ramGibHours\" | \"diskGibHours\">[], pricing?: Pricing): Omit<UsageTotals, \"estimatedStops\" | \"historyFrom\"> {\n const sum: Omit<UsageTotals, \"estimatedStops\" | \"historyFrom\"> = {\n seconds: { running: 0, standby: 0, hibernated: 0, stopped: 0 },\n vcpuHours: 0,\n ramGibHours: 0,\n diskGibHours: 0,\n };\n for (const t of items) {\n for (const s of Object.keys(sum.seconds) as UsageState[]) sum.seconds[s] += t.seconds[s];\n sum.vcpuHours += t.vcpuHours;\n sum.ramGibHours += t.ramGibHours;\n sum.diskGibHours += t.diskGibHours;\n }\n sum.vcpuHours = round(sum.vcpuHours, 3);\n sum.ramGibHours = round(sum.ramGibHours, 3);\n sum.diskGibHours = round(sum.diskGibHours, 3);\n if (pricing !== undefined) sum.cost = { amount: round(costOf(sum, pricing), 4), currency: pricing.currency };\n return sum;\n}\n\n/**\n * The window a `GET /usage` call asks for: `since` and `until` as the user wrote them (any Date.parse\n * form), defaulting to the start of the current calendar month (UTC, what a bill covers) and now.\n */\nexport function usageWindow(since: string | undefined, until: string | undefined, now = new Date()): { from: string; to: string } {\n const parse = (name: string, value: string): string => {\n const t = Date.parse(value);\n if (Number.isNaN(t)) throw new Error(`${name}: \"${value}\" is not a date; write it like 2026-10-19 or 2026-10-19T08:00:00Z`);\n return new Date(t).toISOString();\n };\n const from = since === undefined ? new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString() : parse(\"since\", since);\n const to = until === undefined ? now.toISOString() : parse(\"until\", until);\n return { from, to };\n}\n\n/** A ledger row as the host stores it: the event plus whose box it is. */\nexport interface LedgerRow extends UsageEvent {\n /** The host ledger the row came from, when rows of several hosts are mixed: box ids are only unique within one. */\n ledger?: string;\n boxId: string;\n owner: string;\n name: string;\n}\n\n/**\n * Rows of many boxes → one `BoxUsage` per box id, in owner/name order: the report both the host\n * (`GET /usage`) and the control plane build. A box's `rm` row ends its time: nothing accrues after\n * it, and a box gone before the window opened (or made after it closed) is left out. `live` says what\n * a box that still exists is doing now; one not in it reads its state off its last row, `removed`\n * when that row is the `rm`. A name removed and made again is two boxes (two ids); rows carrying a\n * `ledger` are grouped by ledger and box id, so two hosts' boxes never merge.\n */\nexport function groupUsage(\n rows: readonly LedgerRow[],\n window: { from: string; to: string },\n pricing: Pricing | undefined,\n live: ReadonlyMap<string, BoxStatus> = new Map(),\n): BoxUsage[] {\n const byBox = new Map<string, LedgerRow[]>();\n for (const r of rows) {\n const key = r.ledger === undefined ? r.boxId : `${r.ledger}:${r.boxId}`;\n const list = byBox.get(key);\n if (list === undefined) byBox.set(key, [r]);\n else list.push(r);\n }\n const out: BoxUsage[] = [];\n for (const events of byBox.values()) {\n events.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));\n const first = events[0]!;\n const last = events[events.length - 1]!;\n const id = last.boxId;\n const removed = last.by === \"rm\" && !live.has(id);\n const to = removed && last.at < window.to ? last.at : window.to;\n if (first.at >= to || (removed && last.at <= window.from)) continue;\n const totals = computeUsage(events, { from: window.from, to, pricing });\n const status: BoxUsage[\"status\"] = live.get(id) ?? (removed ? \"removed\" : last.state);\n out.push({ id, name: last.name, owner: last.owner, status, ...totals });\n }\n return out.sort(usageOrder);\n}\n\n/** The order `groupUsage` returns boxes in: owner, name, then the older of a name made twice first. */\nexport const usageOrder = (a: BoxUsage, b: BoxUsage): number => a.owner.localeCompare(b.owner) || a.name.localeCompare(b.name) || (a.historyFrom ?? \"\").localeCompare(b.historyFrom ?? \"\");\n","import { Command } from \"commander\";\nimport type { Balance } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { clientFor } from \"../client.js\";\nimport { boxName, color, json, table } from \"../output.js\";\nimport { money } from \"./vm/usage.js\";\n\n/**\n * kvbox credit [--org <slug>] [--json] — the prepaid credit left (#76): yours and every org's you\n * are in, or one org's with `--org`. A control plane only; topping up is the admin's or the app's.\n * --json output: Balance[] { slug, balance, currency, topUps, spent, since, suspendedAt }.\n */\nexport const creditCommand = new Command(\"credit\")\n .description(\"the prepaid credit left on your account and on each of your orgs\")\n .option(\"--org <slug>\", \"one org only\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });\n try {\n if (client.target.kind === \"local\") throw new KvboxError(\"credit lives on the control plane: kvbox login first\");\n const me = client.target.user;\n const balances =\n client.target.org !== undefined\n ? [await client.balance()]\n : await Promise.all([undefined, ...(await client.listOrgs()).map((o) => o.slug)].map((org) => client.balance(org)));\n if (opts.json) {\n json(balances);\n return;\n }\n table(balances.map((b) => creditRow(b, me)));\n } finally {\n await client.close();\n }\n });\n\nfunction creditRow(b: Balance, me: string | undefined): Record<string, string> {\n const left = money(b.balance, b.currency);\n return {\n owner: b.slug === me ? \"private\" : boxName(b.slug),\n credit: b.balance > 0 ? left : color.red(left),\n \"topped up\": money(b.topUps, b.currency),\n spent: money(b.spent, b.currency),\n // Suspended (#76): the sweep hibernated the boxes at zero; a top-up brings them back.\n state: b.suspendedAt ? color.red(\"suspended\") : b.since === null ? color.dim(\"never topped up\") : \"ok\",\n };\n}\n","import { readFile } from \"node:fs/promises\";\nimport { basename, resolve } from \"node:path\";\nimport { Command, Option } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { assertSubdomain, subdomainProblem } from \"@kvbox/shared/names\";\nimport { SIZE_NAMES, SIZES } from \"@kvbox/shared/sizes\";\nimport { ensureCert, renewAfterRefusal } from \"../../cert.js\";\nimport { clientFor, me, orgOption, sshEndpoint, wakeUp, type GlobalOptions, type ServerClient } from \"../../client.js\";\nimport { color, gb, info, json, slugOf, spin } from \"../../output.js\";\nimport { interactive, select, text } from \"../../prompt.js\";\nimport { displayName } from \"../vm/new.js\";\nimport { BOX_NAME_RE, CONFIG_FILE, nameFromDir, readConfig, subdomainFor, writeConfig, type DeployConfig } from \"./config.js\";\nimport { DEPLOY_AUTO_HIBERNATE_SEC } from \"./config.js\";\nimport { IMAGE_TOO_OLD, shipping, SSH_FAILED } from \"./ship.js\";\nimport { detectTemplate, TEMPLATE_IDS, TEMPLATES, templateById, type PackageJson, type Template } from \"./templates/index.js\";\n\n/**\n * kvbox deploy [dir] [-t react|nextjs] [-n name] [--sub name] [-s xs|s|m|l] [--org slug] [-y] [--json]\n *\n * The first time, a few questions (template, box name, HTTPS name, size), each with a default,\n * saved to kvbox.json in the app's directory; after that, no questions: the file is the answer and a\n * flag overrides one field and is saved too. Then: build (React: here; Next.js: in the box), make\n * the box if it is not there (the template's size, hibernating after an hour idle; wake it if it\n * sleeps), ship into it and give it its address. Off a terminal the first run needs `-y` (defaults)\n * or the flags: agents deploy with `kvbox deploy -y --json`.\n *\n * The box is the caller's own, or the `--org` org's (saved as `org` in kvbox.json); an org's box\n * of the same name is never taken by a bare name here, since `deploy` creates what it does not find.\n *\n * --json output: {box, created, template, url, dist?, files, bytes}; `box` is bare for the caller's\n * own box, `slug/name` otherwise; `dist` only when a build output directory was shipped. On this\n * machine's own host there is no HTTPS name: `url` is http://<ip>.\n */\nexport const deployCommand = new Command(\"deploy\")\n .description(\"put the app in this directory (React or Next.js) on a box with its own HTTPS address; redeploy by running it again\")\n .argument(\"[dir]\", \"the app's directory (default: the current one)\")\n .addOption(new Option(\"-t, --template <template>\", \"what kind of app it is (detected from package.json when not given)\").choices(TEMPLATE_IDS))\n .option(\"-n, --name <name>\", \"the box's name (default: the directory's name)\")\n .option(\"--sub <subdomain>\", \"its HTTPS name, https://<subdomain>.kvbox.app (default: the box's name)\")\n .addOption(new Option(\"-s, --size <size>\", \"size of the box when it has to be made\").choices(SIZE_NAMES))\n .option(\"-y, --yes\", \"ask nothing: take the defaults for whatever the flags and kvbox.json leave open\")\n .option(\"--json\", \"print the result as JSON\")\n .option(\"--org <slug>\", \"deploy into this org's boxes (saved to kvbox.json)\")\n .action(async (dirArg: string | undefined, opts: DeployOptions, cmd: Command) => {\n const dir = resolve(dirArg ?? \".\");\n const pkg = await readPackageJson(dir);\n const saved = await readConfig(dir);\n // The org comes from the flag (before or after `deploy`), else from the file: the client has to\n // know it before anything is listed, so it is the one place the org is read.\n const globals = cmd.optsWithGlobals<GlobalOptions>();\n const orgFlag = orgOption(globals);\n const org = orgFlag ?? saved?.org;\n const client = await clientFor({ ...(globals.local ? { local: true } : {}), ...(org !== undefined ? { org } : {}) });\n try {\n const cloud = client.target.kind === \"cloud\";\n // On this machine there are no orgs: a silently ignored --org would deploy to the host owner's box as if it were one.\n if (!cloud && org !== undefined) throw new KvboxError(\"--org needs a control plane: kvbox login, or drop --org\");\n const { config, template, fresh } = await settle(dir, pkg, saved, opts, orgFlag, cloud);\n // A box that already answers under another name keeps it: said now, before anything is built or saved.\n if (cloud && config.subdomain !== undefined) await refuseOtherAddress(client, config);\n await writeConfig(dir, config);\n if (fresh) info(` ${color.dim(`saved to ${CONFIG_FILE}; next time kvbox deploy asks nothing`)}\\n`);\n\n info(`${color.bold(\"Building\")} ${color.cyan(config.name)} ${color.dim(`(${template.label})`)}`);\n const built = await template.build({ dir, pkg, dist: config.dist });\n if (built.dist !== undefined && built.dist !== config.dist) await writeConfig(dir, { ...config, dist: built.dist });\n const size = await shipping.measure(built.outDir, built.exclude);\n info(\"\");\n\n const { box: found, ref, created } = await findOrCreate(client, config);\n // The box trusts the CA for its owner: settle the certificate before waking (and billing) a box.\n const cert = await ensureCert(client, undefined, undefined, { owner: found.owner });\n const wasRunning = !created && found.status === \"running\";\n const box = created || wasRunning ? found : await wakeUp(client, found, ref);\n const ep = sshEndpoint(box, client.target);\n if (!wasRunning) await spin(`waiting for ${ref} to accept SSH…`, shipping.waitForSsh(ep));\n\n const shipIt = () => shipping.ship(ep, built.outDir, template.remote(built), built.exclude);\n const doing = built.dist === undefined ? `shipping ${built.what} (${size.files} files, ${gb(size.bytes)}) to ${ref} and building there, a minute or two…` : `shipping ${built.what} (${size.files} files, ${gb(size.bytes)}) to ${ref}…`;\n let result = await spin(doing, shipIt);\n if (result.status === SSH_FAILED && (await renewAfterRefusal(client, cert, box.owner))) {\n info(\"renewed your SSH certificate, trying again…\");\n result = await spin(doing, shipIt);\n }\n if (result.status === SSH_FAILED) throw new KvboxError(`box ${ref}: could not reach it over SSH (still booting?)${result.output ? `\\n${result.output.trim()}` : \"\"}`, SSH_FAILED);\n if (result.status === IMAGE_TOO_OLD) {\n throw new KvboxError(\n `box ${ref} runs an image too old for the ${template.label} template (base v0.8.0 or newer). ` +\n `Update the box (kvbox vm update ${ref}) once its host has the new image, or deploy under another name (--name) to get a fresh box`,\n );\n }\n if (result.status !== 0) throw new KvboxError(`deploying to ${ref} failed (exit ${result.status}):\\n${result.output.trim()}`);\n\n let url = `http://${box.ip}`;\n if (cloud) {\n const got = await address(client, box, ref, config, template);\n url = got.url;\n // The address the box really has is the one to remember.\n if (got.subdomain !== config.subdomain) await writeConfig(dir, { ...config, subdomain: got.subdomain, ...(built.dist !== undefined && built.dist !== config.dist ? { dist: built.dist } : {}) });\n }\n\n if (opts.json) {\n json({ box: ref, created, template: template.id, url, ...(built.dist !== undefined ? { dist: built.dist } : {}), files: size.files, bytes: size.bytes });\n return;\n }\n process.stdout.write(`${url}\\n`);\n info(`${color.green(\"✓\")} ${color.bold(config.name)} is live at ${color.bold(url)}`);\n info(` box ${ref}${created ? \" (new)\" : \"\"} · ${template.label} · ${size.files} files, ${gb(size.bytes)}`);\n info(` redeploy: kvbox deploy${dirArg !== undefined ? ` ${dirArg}` : \"\"}`);\n } finally {\n await client.close();\n }\n });\n\ninterface DeployOptions {\n template?: string;\n name?: string;\n sub?: string;\n size?: string;\n yes?: boolean;\n json?: boolean;\n}\n\nasync function readPackageJson(dir: string): Promise<PackageJson | undefined> {\n try {\n return JSON.parse(await readFile(resolve(dir, \"package.json\"), \"utf8\")) as PackageJson;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw new KvboxError(`${resolve(dir, \"package.json\")}: ${(err as Error).message}`);\n }\n}\n\n/**\n * The settings for this deploy: kvbox.json, overridden by flags; whatever is still open is asked\n * (first run on a terminal), or defaulted (`-y`), or refused with the flags named. A saved\n * subdomain belongs to the saved box: a `--name` or `--org` that changes the box leaves it behind.\n */\nasync function settle(dir: string, pkg: PackageJson | undefined, saved: DeployConfig | undefined, opts: DeployOptions, orgFlag: string | undefined, cloud: boolean): Promise<{ config: DeployConfig; template: Template; fresh: boolean }> {\n const detected = detectTemplate(pkg);\n if (opts.name !== undefined && !BOX_NAME_RE.test(opts.name)) throw new KvboxError(`--name ${opts.name}: ${NAME_RULE}`);\n if (opts.sub !== undefined) assertSubdomain(opts.sub);\n const renamed = saved !== undefined && ((opts.name !== undefined && opts.name !== saved.name) || (orgFlag !== undefined && orgFlag !== saved.org));\n const savedSub = renamed ? undefined : saved?.subdomain;\n const defaults = {\n template: opts.template ?? saved?.template ?? detected?.id,\n name: opts.name ?? saved?.name ?? nameFromDir(basename(dir)),\n subdomain: opts.sub ?? savedSub,\n size: opts.size ?? saved?.size,\n };\n /** The size when nothing says one: the template's. */\n const sizeFor = (t: Template | undefined) => defaults.size ?? t?.size ?? \"xs\";\n // A saved file answers everything it holds; only a first run (or a renamed box's address) has open questions.\n const open = {\n template: opts.template === undefined && saved?.template === undefined,\n name: opts.name === undefined && saved?.name === undefined,\n subdomain: cloud && opts.sub === undefined && savedSub === undefined,\n size: opts.size === undefined && saved === undefined,\n };\n const anyOpen = open.template || open.name || open.subdomain || open.size;\n const fresh = saved === undefined;\n\n if (anyOpen && !opts.yes && !interactive()) {\n const sub = defaults.subdomain ?? subdomainFor(defaults.name);\n throw new KvboxError(\n `kvbox deploy asks a few questions the first time, and this is not a terminal. ` +\n `Pass -y to take the defaults (${defaults.template ?? \"template?\"}, box ${defaults.name}${cloud ? `, https://${sub}.kvbox.app` : \"\"}, size ${sizeFor(defaults.template !== undefined ? templateById(defaults.template) : undefined)}), ` +\n `or answer with --template, --name${cloud ? \", --sub\" : \"\"} and --size`,\n );\n }\n const ask = anyOpen && !opts.yes;\n if (ask && fresh) info(`${color.bold(\"kvbox deploy\")} ${color.dim(dir)}\\n`);\n\n let templateId = defaults.template;\n if (open.template && ask) {\n const initial = detected ? TEMPLATES.indexOf(detected) : 0;\n templateId = await select(\"Template\", TEMPLATES.map((t) => ({ value: t.id, label: t.label, hint: t === detected ? `${t.hint} · detected` : t.hint })), initial);\n }\n if (templateId === undefined) throw new KvboxError(`could not tell what kind of app ${dir} is (no package.json of a Vite, Create React App or Next.js project): say it with --template ${TEMPLATE_IDS.join(\"|\")}`);\n const template = templateById(templateId);\n\n let name = defaults.name;\n if (open.name && ask) name = await text(\"Box name\", { default: defaults.name, validate: (a) => (BOX_NAME_RE.test(a) ? undefined : NAME_RULE) });\n\n let subdomain = defaults.subdomain ?? (cloud ? subdomainFor(name) : undefined);\n if (open.subdomain && ask) {\n subdomain = await text(\"Address\", {\n default: subdomainFor(name),\n validate: (a) => {\n const problem = subdomainProblem(a);\n return problem ? `that name ${problem}` : undefined;\n },\n });\n info(` ${color.dim(`https://${subdomain}.kvbox.app`)}`);\n }\n\n let size = sizeFor(template);\n if (open.size && ask) {\n size = await select(\"Box size\", SIZE_NAMES.map((s) => ({ value: s, label: s, hint: `${SIZES[s].vcpu} vCPU, ${SIZES[s].memMib / 1024} GB RAM, ${SIZES[s].diskGib} GB disk` })), SIZE_NAMES.indexOf(template.size));\n }\n\n const org = orgFlag ?? saved?.org;\n const config: DeployConfig = {\n template: template.id,\n name,\n ...(org !== undefined ? { org } : {}),\n ...(subdomain !== undefined ? { subdomain } : {}),\n size,\n ...(saved?.dist !== undefined ? { dist: saved.dist } : {}),\n };\n return { config, template, fresh };\n}\n\nconst NAME_RULE = \"1-12 chars, lowercase letters, digits and '-', starting with a letter or digit\";\n\n/**\n * The box named in kvbox.json, made when it does not exist. The listing is the client's (the\n * `--org` org's boxes, else everything readable), but only the right slug's box counts: the\n * caller's own, or the org's. Nothing else of that name is touched.\n */\nasync function findOrCreate(client: ServerClient, config: DeployConfig) {\n const user = me(client);\n const slug = config.org ?? user;\n const named = (await client.listMachines()).filter((b) => b.name === config.name);\n let box = slug === undefined ? named[0] : named.find((b) => slugOf(b.owner) === slug);\n let created = false;\n if (!box) {\n box = await spin(`booting a new box ${config.name}…`, client.createMachine({ name: config.name, ...(config.size !== undefined ? { size: config.size } : {}), autoHibernateSec: DEPLOY_AUTO_HIBERNATE_SEC }));\n created = true;\n info(`${color.green(\"✓\")} box ${color.bold(config.name)} is up: ${box.vcpu} vCPU, ${gb(box.memMib * 1024 ** 2)} RAM, ${gb(box.diskBytes)} disk`);\n }\n return { box, ref: displayName(box, user), created };\n}\n\n/** The HTTPS address the box of that name (the caller's own, or the org's) already has, if any. */\nasync function existingAddress(client: ServerClient, config: DeployConfig) {\n const slug = config.org ?? me(client);\n return (await client.listSubdomains()).find((s) => s.box === config.name && s.owner === slug);\n}\n\n/**\n * A box that already answers under another name keeps it: moving it is the user's call\n * (`kvbox vm proxy release`), not something to do behind a warning, and not worth a build first.\n */\nasync function refuseOtherAddress(client: ServerClient, config: DeployConfig): Promise<void> {\n const have = await existingAddress(client, config);\n if (!have || have.subdomain === config.subdomain) return;\n const ref = config.org !== undefined ? `${config.org}/${config.name}` : config.name;\n throw new KvboxError(\n `box ${ref} already answers at ${have.url}, not ${config.subdomain}. ` +\n `To keep the address: kvbox deploy --sub ${have.subdomain}. To move it: kvbox vm proxy release ${ref}, then deploy again`,\n );\n}\n\n/**\n * The box's HTTPS address: the one it has, moved to the template's port if needed, else the one\n * kvbox.json names, claimed now.\n */\nasync function address(client: ServerClient, box: { name: string; owner: string }, ref: string, config: DeployConfig, template: Template): Promise<{ url: string; subdomain: string }> {\n const have = (await client.listSubdomains()).find((s) => s.box === box.name && s.owner === slugOf(box.owner));\n if (have) {\n if (have.port !== template.port) await client.setSubdomainPort(ref, { port: template.port });\n return { url: have.url, subdomain: have.subdomain };\n }\n const wanted = config.subdomain ?? subdomainFor(config.name);\n try {\n const sub = await spin(`claiming https://${wanted}.kvbox.app…`, client.claimSubdomain(ref, { name: wanted, port: template.port }));\n return { url: sub.url, subdomain: sub.subdomain };\n } catch (err) {\n if (!(err instanceof KvboxError)) throw err;\n throw new KvboxError(`${err.message}\\nthe app is on box ${ref} but has no address yet: pick another with kvbox deploy --sub <name> (saved to ${CONFIG_FILE})`);\n }\n}\n","/**\n * `kvbox.json`, the deploy settings kept next to the app: written by the first `kvbox deploy`\n * from its questions, read by every later one so a redeploy asks nothing. Hand-editable; a bad\n * file is refused with the field named.\n *\n * { \"template\": \"react\", \"name\": \"myapp\", \"subdomain\": \"myapp\", \"size\": \"s\", \"dist\": \"dist\" }\n * plus \"org\": \"acme\" when the box is an org's.\n */\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { z } from \"zod\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { subdomainProblem } from \"@kvbox/shared/names\";\nimport { SIZE_NAMES } from \"@kvbox/shared/sizes\";\nimport { ORG_SLUG_RE } from \"../../client.js\";\nimport { TEMPLATE_IDS } from \"./templates/index.js\";\n\n/** A deployed site sleeps after an hour without traffic; a visit wakes it (#80). */\nexport const DEPLOY_AUTO_HIBERNATE_SEC = 3600;\nexport const CONFIG_FILE = \"kvbox.json\";\n\n/** The server's rule for a box name (core/machines.ts), checked here so a typo fails before the build. */\nexport const BOX_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;\n\nexport const DeployConfigSchema = z.object({\n template: z.enum(TEMPLATE_IDS),\n name: z.string().regex(BOX_NAME_RE, \"1-12 chars, lowercase letters, digits and '-', starting with a letter or digit\"),\n /** The org whose box it is; absent for the user's own. */\n org: z.string().regex(ORG_SLUG_RE, \"not an org slug\").optional(),\n /** The HTTPS name (`<subdomain>.kvbox.app`); absent when deploying to this machine's own host. */\n subdomain: z.string().check((ctx) => {\n const problem = subdomainProblem(ctx.value);\n if (problem) ctx.issues.push({ code: \"custom\", message: problem, input: ctx.value });\n }).optional(),\n size: z.enum(SIZE_NAMES as [string, ...string[]]).optional(),\n /** The build output directory, relative to the app; the template's default when absent. */\n dist: z.string().optional(),\n});\nexport type DeployConfig = z.infer<typeof DeployConfigSchema>;\n\n/** The config in `dir`, or undefined when there is none. */\nexport async function readConfig(dir: string): Promise<DeployConfig | undefined> {\n const path = join(dir, CONFIG_FILE);\n let raw: string;\n try {\n raw = await readFile(path, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw err;\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n throw new KvboxError(`${path}: not valid JSON`);\n }\n const parsed = DeployConfigSchema.safeParse(json);\n if (!parsed.success) {\n const issue = parsed.error.issues[0]!;\n throw new KvboxError(`${path}: ${issue.path.join(\".\") || \"file\"}: ${issue.message}`);\n }\n return parsed.data;\n}\n\nexport async function writeConfig(dir: string, config: DeployConfig): Promise<void> {\n await writeFile(join(dir, CONFIG_FILE), JSON.stringify(config, null, 2) + \"\\n\");\n}\n\n/** A box name made from a directory name: lowercased, anything else becomes '-', cut to the limit. */\nexport function nameFromDir(dirName: string): string {\n const slug = dirName.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 12).replace(/-+$/, \"\");\n return slug === \"\" ? \"app\" : slug;\n}\n\n/** The HTTPS name a box name suggests: itself when the subdomain rules allow it, else `<name>-site`. */\nexport function subdomainFor(name: string): string {\n return subdomainProblem(name) === null ? name : `${name}-site`;\n}\n","/** The package manager a Node project uses, told by its lockfile; shared by the templates. */\nimport { access } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nexport type PackageManager = \"pnpm\" | \"yarn\" | \"bun\" | \"npm\";\n\nexport async function packageManager(dir: string): Promise<PackageManager> {\n const has = (f: string) => access(join(dir, f)).then(() => true, () => false);\n if (await has(\"pnpm-lock.yaml\")) return \"pnpm\";\n if (await has(\"yarn.lock\")) return \"yarn\";\n if ((await has(\"bun.lockb\")) || (await has(\"bun.lock\"))) return \"bun\";\n return \"npm\";\n}\n\n/** `<pm> run <script>` as that manager says it. */\nexport function runScript(pm: PackageManager, script: string): string[] {\n return pm === \"yarn\" ? [script] : [\"run\", script];\n}\n","/**\n * Next.js template: an app with its own server. Nothing is built here: the source is shipped\n * (without node_modules, .next and .git) and the box installs, builds and runs it with the\n * project's own package manager, as a systemd service `kvbox-app` on port 3000. The box has\n * Node.js 22 and npm; pnpm and yarn come through corepack. Building in the box keeps the result\n * independent of this machine and leaves the whole project there for `kvbox connect`.\n */\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { packageManager, type PackageManager } from \"./pm.js\";\nimport type { BuildContext, BuildResult, PackageJson, Template } from \"./types.js\";\n\n/** Where the app lives in the box; a deploy stages beside it and swaps. */\nexport const APP_DIR = \"/srv/app/current\";\nexport const SERVICE = \"kvbox-app\";\nconst PORT = 3000;\n\n/** The box's commands for each manager; bun is not in the image, so its project installs with npm. */\nfunction commands(pm: PackageManager): { setup: string[]; install: string; build: string; start: string } {\n switch (pm) {\n case \"pnpm\":\n return { setup: [\"sudo -n corepack enable pnpm\"], install: \"pnpm install --frozen-lockfile\", build: \"pnpm run build\", start: \"pnpm run start\" };\n case \"yarn\":\n return { setup: [\"sudo -n corepack enable yarn\"], install: \"yarn install --frozen-lockfile\", build: \"yarn build\", start: \"yarn start\" };\n case \"bun\":\n return { setup: [], install: \"npm install\", build: \"npm run build\", start: \"npm run start\" };\n case \"npm\":\n return { setup: [], install: \"if [ -f package-lock.json ]; then npm ci; else npm install; fi\", build: \"npm run build\", start: \"npm run start\" };\n }\n}\n\nexport const nextjsTemplate: Template = {\n id: \"nextjs\",\n label: \"Next.js\",\n hint: \"source shipped; installed, built and run in the box on port 3000\",\n size: \"s\",\n port: PORT,\n\n detect(pkg: PackageJson | undefined): boolean {\n if (!pkg) return false;\n return \"next\" in { ...pkg.dependencies, ...pkg.devDependencies };\n },\n\n /** No local build: the box does it. Only the scripts it will need are checked here. */\n async build(ctx: BuildContext): Promise<BuildResult> {\n for (const script of [\"build\", \"start\"]) {\n if (typeof ctx.pkg?.scripts?.[script] !== \"string\") throw new KvboxError(`${ctx.dir}: package.json has no \"${script}\" script; Next.js needs \"build\": \"next build\" and \"start\": \"next start\"`);\n }\n const pm = await packageManager(ctx.dir);\n return { outDir: ctx.dir, exclude: [\"node_modules\", \".next\", \".git\"], pm, what: \"the source\" };\n },\n\n /**\n * The source lands in a staging directory and is installed and built there while the old app\n * keeps serving; only then is it swapped into place and the service restarted, so a failed\n * install or build leaves the running app alone. The unit is rewritten every time, so a changed\n * package manager or start script takes effect. /srv/app is the kvbox user's (image v0.8.0+).\n */\n remote(built: BuildResult): string {\n const c = commands(built.pm);\n const unit = [\n \"[Unit]\",\n \"Description=kvbox deploy: the app in \" + APP_DIR,\n \"After=network.target\",\n \"\",\n \"[Service]\",\n \"User=kvbox\",\n `WorkingDirectory=${APP_DIR}`,\n `ExecStart=/usr/bin/env ${c.start}`,\n `Environment=NODE_ENV=production PORT=${PORT}`,\n \"Restart=always\",\n \"RestartSec=2\",\n \"\",\n \"[Install]\",\n \"WantedBy=multi-user.target\",\n ];\n return [\n \"set -e\",\n \"test -d /srv/app -a -w /srv/app || exit 3\",\n \"rm -rf /srv/app/.incoming /srv/app/.old\",\n \"mkdir -p /srv/app/.incoming\",\n \"tar -xf - -C /srv/app/.incoming\",\n \"cd /srv/app/.incoming\",\n \"export CI=1 NEXT_TELEMETRY_DISABLED=1 NODE_ENV=production\",\n ...c.setup,\n c.install,\n c.build,\n \"cd /\",\n `sudo -n tee /etc/systemd/system/${SERVICE}.service >/dev/null <<'UNIT'`,\n ...unit,\n \"UNIT\",\n `if [ -e ${APP_DIR} ]; then mv ${APP_DIR} /srv/app/.old; fi`,\n `mv /srv/app/.incoming ${APP_DIR}`,\n \"sudo -n systemctl daemon-reload\",\n `sudo -n systemctl enable --quiet ${SERVICE}`,\n `sudo -n systemctl restart ${SERVICE}`,\n \"rm -rf /srv/app/.old\",\n ].join(\"\\n\");\n },\n};\n","/**\n * React template: a static single-page app. Built on this machine with the project's own `build`\n * script (Vite, CRA or anything that leaves a directory of files), the output directory is shipped\n * to `/srv/app/dist` in the box and nginx serves it on port 80. nginx comes with the base image\n * (v0.8.0 and later), wired to that directory and off until the first deploy turns it on.\n */\nimport { spawn } from \"node:child_process\";\nimport { access } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { color, info } from \"../../../output.js\";\nimport { packageManager, runScript, type PackageManager } from \"./pm.js\";\nimport type { BuildContext, BuildResult, PackageJson, Template } from \"./types.js\";\n\n/** Where a React build lands, by tool: Vite's `dist`, Create React App's `build`. */\nconst OUT_DIRS = [\"dist\", \"build\"];\n\n/**\n * Run the project's `build` script where the user can watch it: both of its streams go to stderr,\n * because stdout is the command's result (the URL, or `--json`). A non-zero exit is the error.\n */\nexport async function runBuild(dir: string, pm: PackageManager): Promise<void> {\n const args = runScript(pm, \"build\");\n info(`${color.dim(\"$\")} ${pm} ${args.join(\" \")}`);\n const status = await new Promise<number>((resolve, reject) => {\n const child = spawn(pm, args, { cwd: dir, stdio: [\"ignore\", process.stderr, process.stderr], shell: process.platform === \"win32\" });\n child.once(\"error\", (err) => reject(new KvboxError(`could not run ${pm}: ${err.message}`)));\n child.once(\"close\", (code) => resolve(code ?? 1));\n });\n if (status !== 0) throw new KvboxError(`the build failed (${pm} exited ${status}); nothing was deployed`);\n}\n\nexport const reactTemplate: Template = {\n id: \"react\",\n label: \"React\",\n hint: \"static site: built here, served by nginx in the box\",\n size: \"xs\",\n port: 80,\n\n /** A Vite or Create React App project. A framework with its own server (Next.js, Remix, Expo) is not a static site. */\n detect(pkg: PackageJson | undefined): boolean {\n if (!pkg) return false;\n const deps = { ...pkg.dependencies, ...pkg.devDependencies };\n if (!(\"react\" in deps) || \"next\" in deps || \"@remix-run/react\" in deps || \"expo\" in deps) return false;\n return \"vite\" in deps || \"react-scripts\" in deps;\n },\n\n async build(ctx: BuildContext): Promise<BuildResult> {\n if (typeof ctx.pkg?.scripts?.[\"build\"] !== \"string\") throw new KvboxError(`${ctx.dir}: package.json has no \"build\" script`);\n const pm = await packageManager(ctx.dir);\n await runBuild(ctx.dir, pm);\n const candidates = ctx.dist !== undefined ? [ctx.dist] : OUT_DIRS;\n for (const dist of candidates) {\n const outDir = join(ctx.dir, dist);\n if (await access(join(outDir, \"index.html\")).then(() => true, () => false)) return { outDir, dist, exclude: [], pm, what: `${dist}/` };\n }\n throw new KvboxError(\n `the build left no ${candidates.join(\" or \")}/index.html. The React template ships a directory of static files; ` +\n `set \"dist\" in kvbox.json to the build output directory, or pick the right template with --template`,\n );\n },\n\n /**\n * The archive lands in a staging directory, which then becomes /srv/app/dist in one move; the\n * old site is kept beside it until the new one is in place, so a failed step never leaves nginx\n * without a root and a visitor never sees a half-copied site. Files get read permission for\n * nginx's user, whatever umask the build ran under. /srv/app is the kvbox user's (image v0.8.0+);\n * the missing site file means an older image.\n */\n remote(): string {\n return [\n \"set -e\",\n \"test -e /etc/nginx/sites-enabled/kvbox-app || exit 3\",\n \"rm -rf /srv/app/.incoming /srv/app/.old\",\n \"mkdir -p /srv/app/.incoming\",\n \"tar -xf - -C /srv/app/.incoming\",\n \"chmod -R a+rX /srv/app/.incoming\",\n \"if [ -e /srv/app/dist ]; then mv /srv/app/dist /srv/app/.old; fi\",\n \"mv /srv/app/.incoming /srv/app/dist\",\n \"rm -rf /srv/app/.old\",\n \"sudo -n systemctl enable --now --quiet nginx\",\n \"sudo -n systemctl reload nginx\",\n ].join(\"\\n\");\n },\n};\n","/** The deploy templates, one file each; a new kind of app is a new file and a line here. */\nimport { nextjsTemplate } from \"./nextjs.js\";\nimport { reactTemplate } from \"./react.js\";\nimport type { PackageJson, Template } from \"./types.js\";\n\nexport const TEMPLATES: readonly Template[] = [reactTemplate, nextjsTemplate];\n\nexport const TEMPLATE_IDS = TEMPLATES.map((t) => t.id) as [string, ...string[]];\n\nexport function templateById(id: string): Template {\n const t = TEMPLATES.find((x) => x.id === id);\n if (!t) throw new Error(`no template ${id}`);\n return t;\n}\n\n/** The first template that recognizes the app, or undefined. */\nexport function detectTemplate(pkg: PackageJson | undefined): Template | undefined {\n return TEMPLATES.find((t) => t.detect(pkg));\n}\n\nexport type { BuildContext, BuildResult, PackageJson, Template } from \"./types.js\";\nexport type { PackageManager } from \"./pm.js\";\n","/**\n * Shipping a directory into a box: `tar` on this machine, piped into `ssh` running the template's\n * script in the box. No library and nothing new in the image: tar and ssh are on every machine\n * the CLI runs on (Windows 10+ has both), and the box side is the same `ssh` every command uses.\n */\nimport { spawn } from \"node:child_process\";\nimport { readdir, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { sshArgs, waitForSsh, type SshEndpoint } from \"../../client.js\";\n\n/** Exit status the template's script uses for \"this box's image is too old\". */\nexport const IMAGE_TOO_OLD = 3;\n/** ssh's own status when it could not connect or the session broke. */\nexport const SSH_FAILED = 255;\n\nexport interface Shipped {\n files: number;\n bytes: number;\n}\n\n/** How many files and bytes a directory holds, for the summary line; excluded names are not entered. */\nexport async function measure(dir: string, exclude: string[] = []): Promise<Shipped> {\n const total = { files: 0, bytes: 0 };\n const walk = async (d: string): Promise<void> => {\n for (const entry of await readdir(d, { withFileTypes: true })) {\n if (exclude.includes(entry.name)) continue;\n const path = join(d, entry.name);\n if (entry.isDirectory()) await walk(path);\n else if (entry.isFile()) {\n total.files += 1;\n total.bytes += (await stat(path)).size;\n }\n }\n };\n await walk(dir);\n return total;\n}\n\n/**\n * `tar -cf - -C <dir> . | ssh <box> '<remote>'`: the archive holds the directory's contents, so\n * the remote script extracts straight into its staging directory whatever the directory is called\n * here. An excluded name is left out at any depth (every `node_modules`, not only the top one). Resolves with the remote script's exit status; ssh's output is kept and returned so a\n * failure can show it. ssh exiting before it has read the archive (the script refused the image,\n * the connection was refused) is a normal outcome: the status is the answer, so the broken pipe\n * tar then hits is expected and tar is let go.\n */\nexport async function ship(ep: SshEndpoint, dir: string, remote: string, exclude: string[] = []): Promise<{ status: number; output: string }> {\n const tar = spawn(\"tar\", [\"-cf\", \"-\", ...exclude.map((e) => `--exclude=${e}`), \"-C\", dir, \".\"], { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n const ssh = spawn(\"ssh\", [...sshArgs(ep), remote], { stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n tar.stdout.pipe(ssh.stdin);\n const chunks: Buffer[] = [];\n ssh.stdout.on(\"data\", (c: Buffer) => chunks.push(c));\n ssh.stderr.on(\"data\", (c: Buffer) => chunks.push(c));\n tar.stderr.on(\"data\", (c: Buffer) => chunks.push(c));\n // EPIPE when ssh is gone: expected, see above. Without a listener it is an uncaught exception.\n ssh.stdin.on(\"error\", () => {});\n tar.stdout.on(\"error\", () => {});\n // tar failing (a vanished file) must surface as a broken pipe on the ssh side, not a hang.\n tar.once(\"error\", () => ssh.stdin.end());\n tar.once(\"close\", (code) => { if (code !== 0) ssh.stdin.end(); });\n\n const tarDone = new Promise<void>((resolve) => tar.once(\"close\", () => resolve()));\n const status = await new Promise<number>((resolve, reject) => {\n ssh.once(\"error\", (err) => reject(new KvboxError(`could not run ssh: ${err.message}`)));\n ssh.once(\"close\", (code, signal) => {\n // Whatever tar still has to say goes nowhere now; let it finish instead of blocking on a full pipe.\n tar.stdout.unpipe(ssh.stdin);\n tar.stdout.resume();\n tar.kill();\n resolve(code ?? (signal === \"SIGINT\" ? 130 : 1));\n });\n });\n await tarDone;\n return { status, output: Buffer.concat(chunks).toString(\"utf8\") };\n}\n\n/** The pieces the command shells out through; tests replace them. */\nexport const shipping = { ship, measure, waitForSsh };\n","/** Entry point: parse argv, map KvboxError to an exit code. */\nimport { color } from \"./output.js\";\nimport { buildProgram } from \"./program.js\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\n\ntry {\n await buildProgram().parseAsync(process.argv);\n} catch (err) {\n if (err instanceof KvboxError) {\n process.stderr.write(color.red(`error: ${err.message}`) + \"\\n\");\n process.exit(err.exitCode);\n }\n throw err;\n}\n"],"mappings":";;;AACO,IAAM,aAAN,cAAyB,MAAM;AAAA,EACpC,YACE,SACgB,WAAmB,GACnC;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AAAA,EAJkB;AAKpB;AA0BO,IAAM,oBAAN,cAAgC,WAAW;AAAA;AAAA,EAEhD,YAAY,MAAc,MAAc,OAA0B,UAAU,MAAM;AAChF,UAAM,MAAM,UAAU,SAAS,MAAM,CAAC,CAAC,OAAO,MAAM,CAAC,CAAC,IAAI,IAAI,KAAK,GAAG,MAAM,CAAC,CAAC,IAAI,IAAI;AACtF,UAAM,GAAG,IAAI,IAAI,IAAI,cAAc,MAAM,MAAM,GAAG,EAAE,EAAE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,OAAO,UAAW,SAAQ,WAAW,GAAG;AAEnD,SAAO;AACT;;;AwEhCA,IAAI;AACF,QAAM,aAAa,EAAE,WAAW,QAAQ,IAAI;AAC9C,SAAS,KAAK;AACZ,MAAI,eAAe,YAAY;AAC7B,YAAQ,OAAO,MAAM,MAAM,IAAI,UAAU,IAAI,OAAO,EAAE,IAAI,IAAI;AAC9D,YAAQ,KAAK,IAAI,QAAQ;AAAA,EAC3B;AACA,QAAM;AACR;","names":["rows","createInterface","day","text","me","Command","require","Command","spawnSync","Command","readFile","rm","writeFile","text","writeFile","rm","readFile","mkdir","readFile","z","z","text","z","text","readFileSync","text","text","json","z","resolve","readFile","mkdir","text","Command","spawnSync","spawn","Command","SSH_FAILED","spawn","status","resolve","Command","Command","Option","Command","Option","Command","Command","Command","me","Command","Command","Command","Command","text","text","Command","Command","Command","Command","rows","Command","lsCommand","Command","rows","Command","Command","Command","Command","Command","Command","Command","lsCommand","Command","Option","Command","Option","text","Command","Command","Command","rmCommand","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","rows","Command","Command","Command","rmCommand","Command","Command","spawn","readFile","sleep","readFile","sleep","resolve","spawn","Command","Command","Command","Command","Command","Command","startCommand","Command","Command","Command","Command","stopCommand","Command","Command","Command","Command","startCommand","stopCommand","spawnSync","mkdir","readFile","writeFile","createInterface","Command","ANSI","width","resolve","Command","readFile","mkdir","spawnSync","writeFile","createInterface","Command","Command","Command","Command","Command","Command","lsCommand","Command","Command","newCommand","Command","Command","rmCommand","Command","Command","newCommand","lsCommand","rmCommand","Command","Command","lsCommand","Command","Command","Option","lsCommand","Command","addCommand","Option","rmCommand","Command","newCommand","Command","Command","rmCommand","Command","Command","Command","Command","lsCommand","newCommand","rmCommand","Command","z","usageCommand","Command","day","me","ownerCell","rows","Command","Command","me","readFile","resolve","Command","Option","readFile","writeFile","join","z","join","spawn","access","join","status","resolve","spawn","join","access","z","join","readFile","json","writeFile","spawn","stat","join","SSH_FAILED","join","stat","spawn","resolve","status","Command","Option","resolve","SSH_FAILED","readFile","Command","usageCommand"]}
1
+ {"version":3,"sources":["../../shared/src/errors.ts","../src/output.ts","../src/program.ts","../../shared/src/version.ts","../src/version.ts","../src/commands/vm/index.ts","../src/commands/vm/connect.ts","../src/cert.ts","../../shared/src/paths.ts","../src/session.ts","../src/client.ts","../../shared/src/api.ts","../../shared/src/sizes.ts","../src/kvm.ts","../src/systemd.ts","../src/commands/vm/new.ts","../src/commands/vm/exec.ts","../src/commands/vm/fork.ts","../src/commands/vm/get.ts","../src/commands/vm/ls.ts","../src/commands/vm/proxy/shared.ts","../src/commands/vm/hibernate.ts","../src/commands/vm/pause.ts","../src/commands/vm/proxy/claim.ts","../../shared/src/names.ts","../src/commands/vm/proxy/index.ts","../src/commands/vm/proxy/add.ts","../src/commands/vm/proxy/ls.ts","../src/commands/vm/proxy/release.ts","../src/commands/vm/proxy/rm.ts","../src/commands/vm/proxy/set-port.ts","../src/commands/vm/rescale.ts","../src/commands/vm/resume.ts","../src/commands/vm/rm.ts","../src/commands/vm/set.ts","../src/commands/vm/start.ts","../src/commands/vm/stop.ts","../src/commands/vm/top.ts","../src/commands/vm/update.ts","../src/commands/vm/usage.ts","../src/commands/vm/wake.ts","../src/commands/server/index.ts","../src/commands/server/join.ts","../src/commands/server/daemon.ts","../src/commands/server/leave.ts","../src/commands/server/relay.ts","../src/commands/server/start.ts","../src/commands/server/status.ts","../src/commands/server/stop.ts","../src/commands/server/trust-ca.ts","../src/commands/login.ts","../src/prompt.ts","../src/commands/logout.ts","../src/commands/whoami.ts","../src/commands/snapshots/index.ts","../src/commands/snapshots/ls.ts","../src/commands/snapshots/new.ts","../src/commands/snapshots/rm.ts","../src/commands/org/index.ts","../src/commands/org/ls.ts","../src/commands/org/context.ts","../src/commands/org/members.ts","../src/commands/org/new.ts","../src/commands/org/rm.ts","../src/commands/org/role.ts","../src/commands/usage.ts","../../shared/src/usage.ts","../src/commands/credit.ts","../src/commands/deploy/index.ts","../src/commands/deploy/config.ts","../src/commands/deploy/templates/pm.ts","../src/commands/deploy/templates/nextjs.ts","../src/commands/deploy/templates/react.ts","../src/commands/deploy/templates/index.ts","../src/commands/deploy/ship.ts","../src/commands/volume/index.ts","../src/commands/volume/attach.ts","../src/commands/volume/create.ts","../src/commands/volume/detach.ts","../src/commands/volume/ls.ts","../src/commands/volume/rm.ts","../src/index.ts"],"sourcesContent":["/** Errors with an exit code; the entry point prints `message` and exits with `exitCode`. */\nexport class KvboxError extends Error {\n constructor(\n message: string,\n public readonly exitCode: number = 1,\n ) {\n super(message);\n this.name = \"KvboxError\";\n }\n}\n\nexport class NotImplementedError extends KvboxError {\n constructor(what: string) {\n super(`${what}: not implemented yet`, 2);\n this.name = \"NotImplementedError\";\n }\n}\n\n/** The named box/snapshot/host does not exist: HTTP 404, exit 1. */\nexport class NotFoundError extends KvboxError {\n constructor(what: string) {\n super(`${what}: not found`, 1);\n this.name = \"NotFoundError\";\n }\n}\n\n/** The caller is known but the rule says no (an org member outside their role): HTTP 403, exit 1. */\nexport class ForbiddenError extends KvboxError {\n constructor(message: string) {\n super(message, 1);\n this.name = \"ForbiddenError\";\n }\n}\n\n/** A bare name that is in more than one of the caller's orgs (#68); the CLI and the control plane say it the same way. */\nexport class AmbiguousRefError extends KvboxError {\n /** `orgFlag` false: `--org` names something else on this command (a fork's target), so only `slug/name` is offered. */\n constructor(kind: string, name: string, slugs: readonly string[], orgFlag = true) {\n const way = orgFlag ? `--org ${slugs[0]} or ${slugs[0]}/${name}` : `${slugs[0]}/${name}`;\n super(`${kind} ${name} exists in ${slugs.slice(0, -1).join(\", \")} and ${slugs.at(-1)}; say which with ${way}`, 1);\n this.name = \"AmbiguousRefError\";\n }\n}\n","/** Printing: tables for humans, `--json` for agents, colors only on a TTY. */\nimport { AmbiguousRefError } from \"@kvbox/shared/errors\";\nimport pc from \"picocolors\";\n\nexport const color = pc.createColors(process.stdout.isTTY === true && !process.env[\"NO_COLOR\"]);\n\nexport function json(value: unknown): void {\n process.stdout.write(JSON.stringify(value, null, 2) + \"\\n\");\n}\n\n// eslint-disable-next-line no-control-regex\nconst ANSI = /\\x1b\\[[0-9;]*m/g;\n/** Printed width of a cell: color codes take no columns. */\nconst width = (s: string) => s.replace(ANSI, \"\").length;\n\n/** Cells may carry color codes; alignment uses the visible text. */\nexport function table(rows: Record<string, string | number | null | undefined>[], columns?: string[]): void {\n if (rows.length === 0) return;\n const cols = columns ?? Object.keys(rows[0]!);\n const cells = rows.map((r) => cols.map((c) => String(r[c] ?? \"\")));\n const widths = cols.map((c, i) => Math.max(c.length, ...cells.map((r) => width(r[i]!))));\n const line = (parts: string[]) =>\n parts.map((p, i) => p + \" \".repeat(Math.max(0, widths[i]! - width(p)))).join(\" \").trimEnd();\n process.stdout.write(color.dim(line(cols.map((c) => c.toUpperCase()))) + \"\\n\");\n for (const row of cells) process.stdout.write(line(row) + \"\\n\");\n}\n\nexport function info(msg: string): void {\n process.stderr.write(msg + \"\\n\");\n}\n\nexport function warn(msg: string): void {\n process.stderr.write(color.yellow(msg) + \"\\n\");\n}\n\nexport function notImplemented(command: string): never {\n process.stderr.write(color.yellow(`kvbox ${command}: not implemented yet\\n`));\n process.exit(2);\n}\n\n/** y/N prompt on a TTY; requires `-y` otherwise (boxd's rule for destructive commands). */\nexport async function confirm(question: string, yes: boolean): Promise<boolean> {\n if (yes) return true;\n if (!process.stdin.isTTY) {\n warn(\"refusing without -y when stdin is not a terminal\");\n return false;\n }\n const { createInterface } = await import(\"node:readline/promises\");\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n try {\n const answer = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();\n return answer === \"y\" || answer === \"yes\";\n } finally {\n rl.close();\n }\n}\n\n/** Bytes for humans: 4 GiB -> \"4 GB\", 3.4 GiB -> \"3.4 GB\", under 1 GiB -> \"640 MB\". */\nexport function gb(bytes: number): string {\n const g = bytes / 1024 ** 3;\n if (g >= 1) return `${Number.isInteger(g) ? g : g.toFixed(1)} GB`;\n return `${Math.round(bytes / 1024 ** 2)} MB`;\n}\n\n/** Compact byte count for a table cell: \"4GB\", \"3.4GB\", \"640MB\". */\nexport function gbShort(bytes: number): string {\n return gb(bytes).replace(\" \", \"\");\n}\n\n/** \"2×4GB · 8GB disk\": the shape of a box in one cell. */\nexport function shape(vcpu: number, memMib: number, diskBytes?: number): string {\n const cpuRam = `${vcpu}×${gbShort(memMib * 1024 ** 2)}`;\n return diskBytes === undefined ? cpuRam : `${cpuRam} · ${gbShort(diskBytes)} disk`;\n}\n\n/** Box name as it appears in every table: one color, so the eye finds it first. */\nexport function boxName(name: string): string {\n return color.cyan(name);\n}\n\n/** Status word, colored: running green, asleep (standby, hibernated) yellow, anything else dim. */\nexport function status(s: string): string {\n if (s === \"running\") return color.green(s);\n if (s === \"standby\" || s === \"hibernated\") return color.yellow(s);\n return color.dim(s);\n}\n\n/** How long ago an ISO timestamp was, in docker's style: \"just now\", \"5m ago\", \"2h ago\", \"3d ago\". */\nexport function age(iso: string, now = Date.now()): string {\n const sec = Math.max(0, Math.floor((now - Date.parse(iso)) / 1000));\n if (sec < 60) return \"just now\";\n const min = Math.floor(sec / 60);\n if (min < 60) return `${min}m ago`;\n const hr = Math.floor(min / 60);\n if (hr < 24) return `${hr}h ago`;\n const day = Math.floor(hr / 24);\n if (day < 30) return `${day}d ago`;\n const month = Math.floor(day / 30);\n if (month < 12) return `${month}mo ago`;\n return `${Math.floor(day / 365)}y ago`;\n}\n\n/** Seconds for humans, the two biggest units: \"1d 6h\", \"20h 14m\", \"5m 3s\", \"52s\"; \"-\" for none. */\nexport function duration(seconds: number): string {\n const s = Math.max(0, Math.round(seconds));\n if (s === 0) return \"-\";\n const d = Math.floor(s / 86400);\n const h = Math.floor((s % 86400) / 3600);\n const m = Math.floor((s % 3600) / 60);\n const sec = s % 60;\n if (d > 0) return `${d}d ${h}h`;\n if (h > 0) return `${h}h ${m}m`;\n if (m > 0) return `${m}m ${sec}s`;\n return `${sec}s`;\n}\n\n/** Resource-hours for humans: one decimal under 100 (\"40.5\"), whole above (\"118\"). */\nexport function hours(h: number): string {\n return h < 100 ? String(Math.round(h * 10) / 10) : String(Math.round(h));\n}\n\n/** The bare slug of an owner: `acme@kvbox.sh` → `acme`; a local owner is already bare. */\nexport function slugOf(owner: string): string {\n const at = owner.indexOf(\"@\");\n return at === -1 ? owner : owner.slice(0, at);\n}\n\n/**\n * The item the user named in a listing (#68): `acme/lab1` (the owner's slug) or the full\n * `acme@kvbox.sh/lab1` is explicit; a bare `lab1` is the user's own (`me`) when they have one, else\n * the single org item of that name, else an error naming the candidates. Another user's private\n * box (an admin lists those) is never a bare name's. Undefined when nothing matches.\n */\nexport function pickRef<T extends { name: string; owner: string; ownerKind?: \"user\" | \"org\" | undefined }>(items: T[], text: string, me: string | undefined, kind = \"box\"): T | undefined {\n if (text.includes(\"/\")) return items.find((i) => text === `${slugOf(i.owner)}/${i.name}` || text === `${i.owner}/${i.name}`);\n const named = items.filter((i) => i.name === text);\n const own = named.find((i) => slugOf(i.owner) === me);\n if (own) return own;\n const orgs = me === undefined ? named : named.filter((i) => i.ownerKind !== \"user\"); // no user: this machine's socket, one owner\n if (orgs.length <= 1) return orgs[0];\n throw new AmbiguousRefError(kind, text, orgs.map((i) => slugOf(i.owner)));\n}\n\n/** `owner/name` with the owner dropped when it is the same person as `owner`: what a reader needs to see. */\nexport function shortRef(ref: string, owner: string): string {\n return ref.startsWith(`${owner}/`) ? ref.slice(owner.length + 1) : ref;\n}\n\nconst SPINNER_FRAMES = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\n/** Nothing is drawn before this: a 0.2 s pause/resume never shows a spinner, a 15 s hibernate does. */\nconst SPINNER_DELAY_MS = 150;\nconst SPINNER_FRAME_MS = 80;\n\nexport interface SpinOptions {\n /** Where the spinner is drawn and whether it is a terminal; defaults to stderr. */\n stream?: NodeJS.WriteStream;\n /** Milliseconds before the first frame (default 150). */\n delayMs?: number;\n}\n\n/**\n * Run `work` with a spinner on stderr: \"⠋ hibernating lab1…\" redrawn in place until the promise settles,\n * then the line is cleared so the command's own ✓ line takes its place. Off a terminal (pipes, agents,\n * `--json` captured by a script) nothing is written at all; the result and errors pass through untouched.\n */\nexport async function spin<T>(message: string, work: Promise<T> | (() => Promise<T>), opts: SpinOptions = {}): Promise<T> {\n const stream = opts.stream ?? process.stderr;\n const promise = typeof work === \"function\" ? work() : work;\n if (stream.isTTY !== true) return promise;\n\n let frame = 0;\n let drawn = false;\n const draw = () => {\n stream.write(`\\r\\x1b[K${color.cyan(SPINNER_FRAMES[frame % SPINNER_FRAMES.length]!)} ${message}`);\n frame += 1;\n drawn = true;\n };\n let interval: NodeJS.Timeout | undefined;\n const delay = setTimeout(() => {\n draw();\n interval = setInterval(draw, SPINNER_FRAME_MS);\n }, opts.delayMs ?? SPINNER_DELAY_MS);\n try {\n return await promise;\n } finally {\n clearTimeout(delay);\n if (interval !== undefined) clearInterval(interval);\n if (drawn) stream.write(\"\\r\\x1b[K\");\n }\n}\n","/** Builds the commander tree. Importable without side effects (tests); src/index.ts runs it. */\nimport { Command } from \"commander\";\nimport { VERSION } from \"./version.js\";\nimport { vmAliases, vmCommand } from \"./commands/vm/index.js\";\nimport { serverCommand } from \"./commands/server/index.js\";\nimport { loginCommand } from \"./commands/login.js\";\nimport { logoutCommand } from \"./commands/logout.js\";\nimport { whoamiCommand } from \"./commands/whoami.js\";\nimport { snapshotsCommand } from \"./commands/snapshots/index.js\";\nimport { orgCommand } from \"./commands/org/index.js\";\nimport { usageCommand } from \"./commands/usage.js\";\nimport { creditCommand } from \"./commands/credit.js\";\nimport { deployCommand } from \"./commands/deploy/index.js\";\nimport { volumeCommand } from \"./commands/volume/index.js\";\n\nexport function buildProgram(): Command {\n const program = new Command(\"kvbox\")\n .description(\"self-hosted Firecracker microVMs with Docker-like ergonomics\")\n .version(VERSION, \"-v, --version\")\n .option(\"--local\", \"use this machine's kvbox-server over its socket, ignoring kvbox login\")\n .option(\"--org <slug>\", \"the org: where kvbox new creates, and which box a name means when it is not one of yours; before the command here, or after it\")\n .showHelpAfterError()\n .enablePositionalOptions();\n\n program.addCommand(vmCommand);\n program.addCommand(snapshotsCommand);\n program.addCommand(volumeCommand);\n program.addCommand(serverCommand);\n program.addCommand(loginCommand);\n program.addCommand(logoutCommand);\n program.addCommand(whoamiCommand);\n program.addCommand(orgCommand);\n program.addCommand(usageCommand);\n program.addCommand(creditCommand);\n program.addCommand(deployCommand);\n // Top-level shortcuts: the same Command objects as under `vm`.\n for (const cmd of vmAliases) program.addCommand(cmd);\n\n return program;\n}\n","/**\n * Each binary's version comes from its own package.json: tsup injects\n * `__KVBOX_VERSION__` at build time; the dev path (tsx) reads the file.\n * Usage in a package: `versionOf(import.meta.url)` from its `src/version.ts`.\n */\nimport { createRequire } from \"node:module\";\n\nexport function versionOf(srcFileUrl: string, injected?: string): string {\n if (typeof injected === \"string\") return injected;\n try {\n const require = createRequire(srcFileUrl);\n return (require(\"../package.json\") as { version: string }).version;\n } catch {\n return \"0.0.0-dev\";\n }\n}\n","import { versionOf } from \"@kvbox/shared/version\";\n\ndeclare const __KVBOX_VERSION__: string | undefined;\n\nexport const VERSION: string = versionOf(import.meta.url, typeof __KVBOX_VERSION__ === \"string\" ? __KVBOX_VERSION__ : undefined);\n","import { Command } from \"commander\";\nimport { connectCommand } from \"./connect.js\";\nimport { execCommand } from \"./exec.js\";\nimport { forkCommand } from \"./fork.js\";\nimport { getCommand } from \"./get.js\";\nimport { hibernateCommand } from \"./hibernate.js\";\nimport { lsCommand } from \"./ls.js\";\nimport { newCommand } from \"./new.js\";\nimport { pauseCommand } from \"./pause.js\";\nimport { claimCommand } from \"./proxy/claim.js\";\nimport { proxyCommand } from \"./proxy/index.js\";\nimport { rescaleCommand } from \"./rescale.js\";\nimport { resumeCommand } from \"./resume.js\";\nimport { rmCommand } from \"./rm.js\";\nimport { setCommand } from \"./set.js\";\nimport { startCommand } from \"./start.js\";\nimport { stopCommand } from \"./stop.js\";\nimport { topCommand } from \"./top.js\";\nimport { updateCommand } from \"./update.js\";\nimport { usageCommand } from \"./usage.js\";\nimport { wakeCommand } from \"./wake.js\";\n\nexport const vmCommand = new Command(\"vm\")\n .enablePositionalOptions()\n .description(\"manage boxes (each one is a Firecracker microVM)\")\n .addCommand(newCommand)\n .addCommand(forkCommand)\n .addCommand(lsCommand)\n .addCommand(getCommand)\n .addCommand(connectCommand)\n .addCommand(execCommand)\n .addCommand(stopCommand)\n .addCommand(startCommand)\n .addCommand(pauseCommand)\n .addCommand(resumeCommand)\n .addCommand(hibernateCommand)\n .addCommand(wakeCommand)\n .addCommand(updateCommand)\n .addCommand(rescaleCommand)\n .addCommand(setCommand)\n .addCommand(usageCommand)\n .addCommand(topCommand)\n .addCommand(proxyCommand)\n .addCommand(rmCommand);\n\n/** `--org` goes after the command like every other flag (the root's `--org` must come before it); the leaf's value wins. */\nfor (const cmd of vmCommand.commands) if (cmd !== proxyCommand) cmd.option(\"--org <slug>\", \"act in this org (- for your personal boxes)\");\n\n/**\n * The same Command objects, added again at the top level so they cannot drift. Only the daily\n * ones: a new vm command gets a shortcut when people type it every day, not by default\n * (fork, update, rescale, set, usage, top and proxy stay under `kvbox vm`, so the top level does not fill up).\n * `claim` is the one proxy command with a shortcut: giving a box its HTTPS address is the daily step.\n */\nexport const vmAliases = [newCommand, lsCommand, getCommand, connectCommand, execCommand, stopCommand, startCommand, pauseCommand, resumeCommand, hibernateCommand, wakeCommand, rmCommand, claimCommand];\n","import { spawnSync } from \"node:child_process\";\nimport { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { ensureCert, renewAfterRefusal } from \"../../cert.js\";\nimport { boxesFor, clientFor, me, sshArgs, sshEndpoint, waitForSsh, wakeUp, type SshEndpoint } from \"../../client.js\";\nimport { info, pickRef, spin } from \"../../output.js\";\nimport { displayName } from \"./new.js\";\n\n/** ssh's own status when it could not connect or was refused. */\nconst SSH_FAILED = 255;\n\n/**\n * kvbox vm connect <name> [-- cmd...] — ssh into the box with the kvbox key; a shell, or run a command.\n * On this machine that is the box's ip; through the control plane its host's public address and port (#21).\n * A stopped box is started first, a sleeping one resumed or woken: \"connect\" means \"get me in\", not\n * \"fail because I forgot start\".\n */\nexport const connectCommand = new Command(\"connect\")\n .alias(\"cn\")\n .description(\"open a shell in a box over SSH (or run a command: kvbox connect <name> -- <cmd>)\")\n .argument(\"<name>\", \"box name\")\n .argument(\"[cmd...]\", \"command to run instead of a shell\")\n .passThroughOptions()\n .action(async (name: string, cmdArgs: string[], _opts: unknown, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n let ep: SshEndpoint;\n let cert: \"local\" | \"kept\" | \"renewed\";\n let owner: string;\n try {\n let box = pickRef(await boxesFor(client, name), name, me(client));\n if (!box) throw new KvboxError(`box ${name}: not found (kvbox ls)`);\n // The box trusts the CA for its owner (#51, orgs phase 4): settle the certificate first, so a\n // refusal does not leave a box it woke or booted (and bills) behind.\n cert = await ensureCert(client, undefined, undefined, { owner: box.owner });\n owner = box.owner;\n const wasRunning = box.status === \"running\";\n if (!wasRunning) box = await wakeUp(client, box, displayName(box, me(client)));\n ep = sshEndpoint(box, client.target);\n if (!wasRunning) await spin(`waiting for ${name} to accept SSH…`, waitForSsh(ep));\n } finally {\n await client.close();\n }\n let res = spawnSync(\"ssh\", [...sshArgs(ep), ...cmdArgs], { stdio: \"inherit\" });\n if (res.error) throw new KvboxError(`could not run ssh: ${res.error.message}`);\n if (res.status === SSH_FAILED) {\n // Refused with a certificate that was fine yesterday: the box may trust a new CA (#55). Renew once, try again.\n const again = await clientFor(cmd.optsWithGlobals());\n const retry = await renewAfterRefusal(again, cert, owner).finally(() => again.close());\n if (retry) {\n info(\"renewed your SSH certificate, trying again…\");\n res = spawnSync(\"ssh\", [...sshArgs(ep), ...cmdArgs], { stdio: \"inherit\" });\n if (res.error) throw new KvboxError(`could not run ssh: ${res.error.message}`);\n }\n }\n process.exit(res.status ?? 1);\n });\n","/**\n * The SSH certificate for this machine's key (#51). `kvbox login` gets one from the control\n * plane and writes it next to the key (`id_ed25519-cert.pub`), where ssh loads it by itself.\n * It lives one day and names the slugs it opens (the user's and their orgs', orgs phase 4);\n * before connecting to a cloud box the CLI renews it when it is missing, about to expire, or\n * does not name the box's owner yet (the user just joined that org), so the user never sees\n * a box refuse a stale certificate.\n */\nimport { readFile, rm, writeFile } from \"node:fs/promises\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport type { ServerClient } from \"./client.js\";\nimport { readSession, writeSession } from \"./session.js\";\n\n/** Renew when less than this is left: one hour, longer than any ssh session takes to start. */\nexport const RENEW_BEFORE_MS = 60 * 60 * 1000;\n\nexport async function writeCert(cert: string, p: Paths = paths()): Promise<void> {\n await writeFile(p.sshCert, cert.trim() + \"\\n\", { mode: 0o644 });\n}\n\n/**\n * ssh exited 255 against a cloud box: the box may have stopped trusting the CA that signed the\n * certificate on disk (`kvbox server trust-ca` after a rotation, #55). When the certificate was\n * simply kept, renew it once and say so, and the caller tries again; a certificate renewed this\n * very run is as good as it gets, so false.\n */\nexport async function renewAfterRefusal(client: ServerClient, kept: \"local\" | \"kept\" | \"renewed\", owner: string, p: Paths = paths()): Promise<boolean> {\n if (kept !== \"kept\") return false;\n await ensureCert(client, p, Date.now(), { owner, force: true });\n return true;\n}\n\nexport async function removeCert(p: Paths = paths()): Promise<void> {\n await rm(p.sshCert, { force: true });\n}\n\nexport interface EnsureCertOptions {\n /** The box's `owner` (`<slug>@<realm>`): renew unless the certificate is known to name it. */\n owner?: string;\n /** Renew whatever the state (`kvbox org use`: the new org must be on the certificate). */\n force?: boolean;\n}\n\n/**\n * Make sure a usable certificate is on disk before ssh runs against a cloud box. A local target\n * needs none (the box trusts the host's key directly). Renews through `POST /ssh/cert`; a failure\n * there is reported, never swallowed: without the certificate the box would refuse the key.\n */\nexport async function ensureCert(client: ServerClient, p: Paths = paths(), now: number = Date.now(), opts: EnsureCertOptions = {}): Promise<\"local\" | \"kept\" | \"renewed\"> {\n if (client.target.kind !== \"cloud\") return \"local\";\n const session = await readSession(p);\n if (!session) return \"local\";\n const expires = session.sshCertExpires ? new Date(session.sshCertExpires).getTime() : 0;\n const onDisk = await readFile(p.sshCert, \"utf8\").then(() => true, () => false);\n // Whether the certificate is known to open the box: the owner must be among the stored principals.\n const names = opts.owner === undefined || (session.sshCertPrincipals ?? []).includes(opts.owner);\n if (onDisk && expires - now > RENEW_BEFORE_MS && names && !opts.force) return \"kept\";\n const publicKey = await readFile(`${p.sshKey}.pub`, \"utf8\").catch(() => null);\n if (publicKey === null) throw new KvboxError(`could not renew your SSH certificate: no key at ${p.sshKey}.pub; run: kvbox login`);\n let signed;\n try {\n signed = await client.sshCert({ publicKey: publicKey.trim() });\n } catch (err) {\n throw new KvboxError(`could not renew your SSH certificate: ${(err as Error).message}`);\n }\n await writeCert(signed.cert, p);\n await writeSession({ ...session, sshCertExpires: signed.expires, sshCertPrincipals: signed.principals }, p);\n // Renewed and still not named: the user is not in that org (a membership the session remembered is gone, or\n // a platform admin reaching over the API). Say so here; ssh would only say \"Permission denied\".\n if (opts.owner !== undefined && !signed.principals.includes(opts.owner)) {\n const slug = opts.owner.split(\"@\")[0]!;\n const sameSlugElsewhere = signed.principals.find((pr) => pr.split(\"@\")[0] === slug && pr !== opts.owner);\n const why = sameSlugElsewhere\n ? `the control plane signs for ${sameSlugElsewhere} but the box's host qualifies its owner as ${opts.owner}: the control plane's name (KVBOX_CLOUD_NAME) changed after the host joined`\n : `you are not a member of ${slug} (a platform admin reaches org boxes over the API, not over SSH)`;\n throw new KvboxError(`your SSH certificate does not name ${opts.owner}: ${why}`);\n }\n return \"renewed\";\n}\n","/**\n * Host state layout. The filesystem is the database and `~/.kvbox` is its root.\n * This module is dependency-free so both the CLI (socket path, cli.json)\n * and core (everything else) can use it without crossing the layer boundary.\n *\n * `KVBOX_HOME` overrides the root, mainly for tests.\n */\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport function kvboxHome(): string {\n return process.env[\"KVBOX_HOME\"] ?? join(homedir(), \".kvbox\");\n}\n\nexport function paths(home: string = kvboxHome()) {\n return {\n home,\n config: join(home, \"config.json\"),\n /** The host's ledgers (SQLite via node:sqlite): usage events today. Boxes and snapshots stay files; see server core/db.ts. */\n db: join(home, \"kvbox.db\"),\n serverSock: join(home, \"server.sock\"),\n serverPid: join(home, \"server.pid\"),\n serverLog: join(home, \"server.log\"),\n /** The CLI's login to the control plane (`kvbox login`): url, bearer token, user. Mode 600. */\n cli: join(home, \"cli.json\"),\n ssh: join(home, \"ssh\"),\n sshKey: join(home, \"ssh\", \"id_ed25519\"),\n /** The device key signed by the control plane's CA (#51); ssh loads it by itself next to `-i id_ed25519`. */\n sshCert: join(home, \"ssh\", \"id_ed25519-cert.pub\"),\n /** Host keys of the cloud boxes this laptop connected to, one entry per box (`connect`, #21). */\n sshKnownHosts: join(home, \"ssh\", \"known_hosts\"),\n /** The host's self-signed TLS identity for the control plane (`kvbox-server join`): pinned there by fingerprint. */\n tls: join(home, \"tls\"),\n tlsKey: join(home, \"tls\", \"key.pem\"),\n tlsCert: join(home, \"tls\", \"cert.pem\"),\n /** The host's WireGuard tunnel to its relay (`kvbox server relay`, #50): the conf net-setup.sh installs for wg-quick. Mode 600. */\n relay: join(home, \"relay\"),\n relayConf: join(home, \"relay\", \"kvbox.conf\"),\n bin: join(home, \"bin\"),\n firecracker: join(home, \"bin\", \"firecracker\"),\n /** Firecracker's snapshot-editor, from the same release: merges a diff snapshot onto a full memory image. */\n snapshotEditor: join(home, \"bin\", \"snapshot-editor\"),\n assets: join(home, \"assets\"),\n kernel: join(home, \"assets\", \"vmlinux\"),\n /** Symlink to the current base image, assets/rootfs-<version>.ext4; boxes keep using the version they were made from. */\n rootfs: join(home, \"assets\", \"rootfs.ext4\"),\n baseImage: (version: string) => join(home, \"assets\", `rootfs-${version}.ext4`),\n machines: join(home, \"machines\"),\n snapshots: join(home, \"snapshots\"),\n /** Boxes and snapshots are filed by owner: machines/<owner>/<name>. The owner is part of a box's identity. */\n ownerMachines: (owner: string) => join(home, \"machines\", owner),\n ownerSnapshots: (owner: string) => join(home, \"snapshots\", owner),\n machine: (owner: string, name: string) => {\n const dir = join(home, \"machines\", owner, name);\n return {\n dir,\n meta: join(dir, \"meta.json\"),\n /** The box's writable layer, stacked on the read-only base image inside the guest. */\n overlay: join(dir, \"overlay.ext4\"),\n /**\n * The box's memory as of its last snapshot (a hard link to that snapshot's `mem`, never modified).\n * The next snapshot is a diff of the pages dirtied since, merged onto this. Absent after a boot.\n */\n memBase: join(dir, \"mem.base\"),\n /** `kvbox vm fork` (#79): the source's VM state, captured here and gone once the box runs. Its memory is `memBase`. */\n forkVmstate: join(dir, \"fork.vmstate\"),\n /** `kvbox hibernate`: the box's memory image and VM state while it is hibernated; gone again after `wake` or `stop`. */\n hibernateDir: join(dir, \"hibernate\"),\n hibernateVmstate: join(dir, \"hibernate\", \"vmstate\"),\n hibernateMem: join(dir, \"hibernate\", \"mem\"),\n sock: join(dir, \"fc.sock\"),\n /** Firecracker's vsock endpoint: the host connects here to reach kvbox-agent inside the box (core/agent.ts). */\n vsock: join(dir, \"vsock.sock\"),\n log: join(dir, \"fc.log\"),\n /**\n * An attached volume's drive as Firecracker sees it (#52): a symlink in the box dir to the volume's\n * disk, given to Firecracker by its relative name (`volumeDriveRel`), so a snapshot's vmstate names\n * it relative to whichever box dir it is restored into. There it is a same-size empty placeholder.\n */\n volumeDrive: (volume: string) => join(dir, volumeDriveRel(volume)),\n };\n },\n /** Volumes are filed like boxes, by owner: volumes/<owner>/<name> (#52). */\n volumes: join(home, \"volumes\"),\n ownerVolumes: (owner: string) => join(home, \"volumes\", owner),\n volume: (owner: string, name: string) => {\n const dir = join(home, \"volumes\", owner, name);\n return {\n dir,\n meta: join(dir, \"meta.json\"),\n /** The volume itself: a sparse ext4 the guest sees as a whole disk. */\n disk: join(dir, \"disk.ext4\"),\n };\n },\n snapshot: (owner: string, name: string) => {\n const dir = join(home, \"snapshots\", owner, name);\n return {\n dir,\n meta: join(dir, \"meta.json\"),\n vmstate: join(dir, \"vmstate\"),\n mem: join(dir, \"mem\"),\n /** Copy of the box's overlay at the moment of the snapshot; the base image is referenced by version in meta.json. */\n overlay: join(dir, \"overlay.ext4\"),\n };\n },\n } as const;\n}\n\nexport type Paths = ReturnType<typeof paths>;\n\n/** The file name of a volume's drive inside a box dir (relative: how Firecracker is given it). */\nexport function volumeDriveRel(volume: string): string {\n return `volume-${volume}.ext4`;\n}\n\n/** Where a volume is mounted inside the box (the image's kvbox-volumes.service, by label). */\nexport function volumeMountPath(volume: string): string {\n return `/mnt/${volume}`;\n}\n","/**\n * The CLI's login: `~/.kvbox/cli.json` holds the control plane URL, the bearer token `kvbox login`\n * got, the user name and the SSH certificate's expiry, mode 600 (it is a credential). Present →\n * every command targets the control plane; absent → the local Unix socket. `kvbox logout` removes it.\n */\nimport { chmod, mkdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\n\nexport const SessionSchema = z.object({\n url: z.string(),\n token: z.string(),\n user: z.string(),\n /** When the SSH certificate at paths().sshCert stops being accepted (ISO); absent before the first login with a key. */\n sshCertExpires: z.string().optional(),\n /** Whose boxes that certificate opens (`<slug>@<realm>`, the user and their orgs); absent with `sshCertExpires`. */\n sshCertPrincipals: z.array(z.string()).optional(),\n});\nexport type Session = z.infer<typeof SessionSchema>;\n\nexport async function readSession(p: Paths = paths()): Promise<Session | null> {\n let text: string;\n try {\n text = await readFile(p.cli, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw err;\n }\n try {\n return SessionSchema.parse(JSON.parse(text));\n } catch {\n throw new KvboxError(`${p.cli} is unreadable; run: kvbox logout (then log in again)`);\n }\n}\n\nexport async function writeSession(session: Session, p: Paths = paths()): Promise<void> {\n await mkdir(p.home, { recursive: true });\n await writeFile(p.cli, JSON.stringify(session, null, 2) + \"\\n\", { mode: 0o600 });\n await chmod(p.cli, 0o600); // the mode above only applies when the file is created\n}\n\nexport async function clearSession(p: Paths = paths()): Promise<void> {\n await rm(p.cli, { force: true });\n}\n\n/** \"https://api.kvbox.sh/\" → \"api.kvbox.sh\"; \"http://localhost:18080\" → \"localhost:18080\". For messages. */\nexport function hostOf(url: string): string {\n try {\n return new URL(url).host;\n } catch {\n return url;\n }\n}\n\nfunction isLoopback(hostname: string): boolean {\n return hostname === \"localhost\" || hostname.startsWith(\"127.\") || hostname === \"[::1]\";\n}\n\n/** What the user typed as a control plane URL: \"api.kvbox.sh/\" → \"https://api.kvbox.sh\". */\nexport function normalizeUrl(input: string): string {\n const withScheme = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(input) ? input : `https://${input}`;\n let url: URL;\n try {\n url = new URL(withScheme);\n } catch {\n throw new KvboxError(`not a URL: ${input}`);\n }\n if (!/^https?:$/.test(url.protocol) || url.hostname === \"\" || /\\s/.test(input)) throw new KvboxError(`not a URL: ${input}`);\n // The password and then the token travel on this URL: plain http only to this machine (a dev control plane).\n if (url.protocol === \"http:\" && !isLoopback(url.hostname)) {\n throw new KvboxError(`${input}: use https (plain http is only allowed for localhost)`);\n }\n return url.origin + url.pathname.replace(/\\/+$/, \"\");\n}\n","/**\n * ServerClient: one method per route of the kvbox API, over undici.\n * Target resolution: `--local` -> the local Unix socket; else a `kvbox login` session (cli.json) ->\n * the control plane with its bearer token; else the local socket, auto-starting kvbox-server when\n * nothing listens (`startLocalServer`).\n */\nimport { spawn } from \"node:child_process\";\nimport { openSync } from \"node:fs\";\nimport { mkdir, readFile, stat } from \"node:fs/promises\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { Agent, request, type Dispatcher } from \"undici\";\nimport { z } from \"zod\";\nimport {\n type AddMemberRequest,\n ApiErrorSchema,\n type AttachVolumeRequest,\n type CreateVolumeRequest,\n VolumeSchema,\n BalanceSchema,\n BOX_SSH_USER,\n CapacitySchema,\n type ClaimSubdomainRequest,\n CloudCaSchema,\n CloudOrgSchema,\n type CreateMachineRequest,\n type ForkMachineRequest,\n type CreateOrgRequest,\n type CreateSnapshotRequest,\n HealthSchema,\n type LoginRequest,\n LoginResponseSchema,\n type Machine,\n MachineSchema,\n MachineStatsSchema,\n MachineUsageSchema,\n MeResponseSchema,\n OrgDetailSchema,\n OrgMembershipSchema,\n type OrgRole,\n type PortsRequest,\n type RescaleMachineRequest,\n type SetMachineRequest,\n SnapshotSchema,\n SshCaResponseSchema,\n type SshCertRequest,\n SshCertResponseSchema,\n type SubdomainPortRequest,\n type SubdomainRouteRequest,\n SubdomainSchema,\n TrustCaReportSchema,\n type TrustCaRequest,\n UsageReportSchema,\n} from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { info, spin } from \"./output.js\";\nimport { serverLauncher } from \"./kvm.js\";\nimport { hasUnitFor, startUnitProcess, unitActive, UNIT } from \"./systemd.js\";\nimport { hostOf, readSession } from \"./session.js\";\n\n/**\n * `cloud` with an empty token is the unauthenticated client `kvbox login` itself uses. `org` is the\n * slug bare box names belong to (sent as `X-Kvbox-Org`); absent: the user's own. `user` is the\n * logged-in username, for messages that say whose a box is.\n */\nexport type Target = { kind: \"local\"; socketPath: string } | { kind: \"cloud\"; url: string; token: string; org?: string; user?: string };\n\n/** The root command's global options. */\nexport interface GlobalOptions {\n local?: boolean;\n /** `--org <slug>`: where `kvbox new` creates, and which org a bare name means when the user's own slug has no such box (#68). Nothing is stored. */\n org?: string;\n}\n\nexport const ORG_SLUG_RE = /^[a-z0-9][a-z0-9._-]{0,31}$/;\n\n/** `--org` for this command, checked; undefined when not given (an empty value is not given). */\nexport function orgOption(opts: GlobalOptions): string | undefined {\n if (opts.org === undefined || opts.org === \"\") return undefined;\n if (!ORG_SLUG_RE.test(opts.org)) throw new KvboxError(`${opts.org}: not an org slug (lowercase letters, digits, '.', '_' or '-')`);\n return opts.org;\n}\n\nexport async function resolveTarget(opts: GlobalOptions, p: Paths = paths()): Promise<Target> {\n if (!opts.local) {\n const session = await readSession(p);\n if (session) {\n const org = orgOption(opts);\n return { kind: \"cloud\", url: session.url, token: session.token, user: session.user, ...(org === undefined ? {} : { org }) };\n }\n }\n return { kind: \"local\", socketPath: p.serverSock };\n}\n\nexport interface ClientOptions {\n /** Spawn `kvbox-server` when the local socket does not answer (default true; the start probe turns it off). */\n autoStart?: boolean;\n}\n\n/** A listing's scope: `org` names one slug (default: `--org`'s), `all` asks for the whole platform. */\nexport interface ListOptions {\n org?: string | undefined;\n all?: boolean | undefined;\n}\n\nconst allQuery = (opts: ListOptions): string => (opts.all ? \"?all=1\" : \"\");\n\nexport class ServerClient {\n private readonly dispatcher: Dispatcher;\n private readonly base: string;\n private readonly autoStart: boolean;\n private startedOnce = false;\n\n constructor(\n readonly target: Target,\n opts: ClientOptions = {},\n ) {\n this.autoStart = opts.autoStart ?? true;\n if (target.kind === \"local\") {\n this.dispatcher = new Agent({ connect: { socketPath: target.socketPath } });\n this.base = \"http://kvbox\";\n } else {\n this.dispatcher = new Agent();\n this.base = target.url;\n }\n }\n\n private async call<T>(\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n path: string,\n schema: z.ZodType<T>,\n body?: unknown,\n org: string | undefined = this.target.kind === \"cloud\" ? this.target.org : undefined,\n ): Promise<T> {\n const headers: Record<string, string> = {};\n if (body !== undefined) headers[\"content-type\"] = \"application/json\";\n if (this.target.kind === \"cloud\" && this.target.token !== \"\") headers[\"authorization\"] = `Bearer ${this.target.token}`;\n if (this.target.kind === \"cloud\" && org !== undefined) headers[\"x-kvbox-org\"] = org;\n let res;\n try {\n res = await request(this.base + path, {\n dispatcher: this.dispatcher,\n method,\n headers,\n body: body === undefined ? null : JSON.stringify(body),\n });\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code ?? (err as Error).cause;\n if (this.target.kind === \"local\") {\n // Nothing listens locally: start the daemon once and retry (architecture: \"auto-start\").\n if (this.autoStart && !this.startedOnce) {\n this.startedOnce = true;\n await spin(\"starting kvbox-server…\", startLocalServer(paths(), 5000));\n return this.call(method, path, schema, body);\n }\n throw new KvboxError(`kvbox-server is not running (${String(code)}); start it with: kvbox server start`);\n }\n throw new KvboxError(cloudDown(this.target.url, String(code)));\n }\n const text = await res.body.text();\n const where = this.target.kind === \"cloud\" ? hostOf(this.target.url) : \"kvbox-server\";\n if (res.statusCode >= 300) {\n const parsed = ApiErrorSchema.safeParse(safeJson(text) ?? {});\n // Not our JSON: a reverse proxy's page while the cloud is down, or anything else in the way.\n if (!parsed.success) throw new KvboxError(`${where} answered ${res.statusCode}`);\n if (this.target.kind === \"cloud\" && this.target.token !== \"\") {\n // A logged-in call: the token was revoked or expired.\n if (res.statusCode === 401) throw new KvboxError(\"session expired: kvbox login\");\n // The --org org does not know the user (removed, left, or the org is gone).\n if (res.statusCode === 404 && this.target.org !== undefined && parsed.data.error === `org ${this.target.org}: not found`) {\n throw new KvboxError(`${parsed.data.error} (you are not in it, or it is gone)`);\n }\n }\n throw new KvboxError(parsed.data.error, res.statusCode === 501 ? 2 : 1);\n }\n if (text === \"\") return schema.parse(undefined);\n const json = safeJson(text);\n if (json === undefined) throw new KvboxError(`${where} answered ${res.statusCode} with something that is not JSON`);\n return schema.parse(json);\n }\n\n health() {\n return this.call(\"GET\", \"/health\", HealthSchema);\n }\n\n capacity() {\n return this.call(\"GET\", \"/capacity\", CapacitySchema);\n }\n\n /**\n * Through a control plane: the user's boxes and their orgs', the `--org` org's, or `org`'s;\n * `all`: every box on the platform (platform admins only, #78).\n */\n listMachines(opts: ListOptions = {}) {\n return this.call(\"GET\", `/machines${allQuery(opts)}`, z.array(MachineSchema), undefined, opts.org);\n }\n\n createMachine(req: CreateMachineRequest) {\n return this.call(\"POST\", \"/machines\", MachineSchema, req);\n }\n\n /** `kvbox vm fork` (#79): `name` is the source; the copy goes to the `--org` slug, else the caller's own. */\n forkMachine(name: string, req: ForkMachineRequest) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/fork`, MachineSchema, req);\n }\n\n stopMachine(name: string) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/stop`, MachineSchema);\n }\n\n startMachine(name: string) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/start`, MachineSchema);\n }\n\n pauseMachine(name: string) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/pause`, MachineSchema);\n }\n\n resumeMachine(name: string) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/resume`, MachineSchema);\n }\n\n hibernateMachine(name: string) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/hibernate`, MachineSchema);\n }\n\n wakeMachine(name: string) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/wake`, MachineSchema);\n }\n\n updateMachine(name: string) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/update`, MachineSchema);\n }\n\n rescaleMachine(name: string, req: RescaleMachineRequest) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/rescale`, MachineSchema, req);\n }\n\n setMachine(name: string, req: SetMachineRequest) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/set`, MachineSchema, req);\n }\n\n /** Publish box ports on the host (#30); the answer is the box with every port it publishes. */\n addPorts(name: string, req: PortsRequest) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/ports`, MachineSchema, req);\n }\n\n /** Stop publishing them (#30). */\n removePorts(name: string, req: PortsRequest) {\n return this.call(\"DELETE\", `/machines/${encodeURIComponent(name)}/ports`, MachineSchema, req);\n }\n\n /** HTTPS names (#31), the control plane's only: the box's subdomain, claimed for its default port. */\n claimSubdomain(name: string, req: ClaimSubdomainRequest) {\n return this.call(\"PUT\", `/machines/${encodeURIComponent(name)}/subdomain`, SubdomainSchema, req);\n }\n\n setSubdomainPort(name: string, req: SubdomainPortRequest) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/subdomain/port`, SubdomainSchema, req);\n }\n\n releaseSubdomain(name: string) {\n return this.call(\"DELETE\", `/machines/${encodeURIComponent(name)}/subdomain`, SubdomainSchema);\n }\n\n /** `<route>.<sub>`: a named port under the box's subdomain. */\n addSubdomainRoute(name: string, req: SubdomainRouteRequest) {\n return this.call(\"POST\", `/machines/${encodeURIComponent(name)}/subdomain/routes`, SubdomainSchema, req);\n }\n\n removeSubdomainRoute(name: string, route: string) {\n return this.call(\"DELETE\", `/machines/${encodeURIComponent(name)}/subdomain/routes/${encodeURIComponent(route)}`, SubdomainSchema);\n }\n\n /** Every readable box's subdomain. */\n listSubdomains() {\n return this.call(\"GET\", \"/subdomains\", z.array(SubdomainSchema));\n }\n\n /** A running box's own load, memory and disk, asked of its guest (#67). */\n machineStats(name: string) {\n return this.call(\"GET\", `/machines/${encodeURIComponent(name)}/stats`, MachineStatsSchema);\n }\n\n /** `since`: an ISO date, already validated; the server counts from the box's creation without it. */\n machineUsage(name: string, since?: string) {\n const query = since === undefined ? \"\" : `?since=${encodeURIComponent(since)}`;\n return this.call(\"GET\", `/machines/${encodeURIComponent(name)}/usage${query}`, MachineUsageSchema);\n }\n\n /** Every box of the caller over the window (#41 on a host, #42 through a control plane); dates as the user wrote them. */\n usageReport(since?: string, until?: string, all = false) {\n const q = new URLSearchParams();\n if (all) q.set(\"all\", \"1\");\n if (since !== undefined) q.set(\"since\", since);\n if (until !== undefined) q.set(\"until\", until);\n const query = q.size === 0 ? \"\" : `?${q.toString()}`;\n return this.call(\"GET\", `/usage${query}`, UsageReportSchema);\n }\n\n /** The prepaid balance of the caller's slug, or of `org` (default: `--org`'s) (#76); a control plane only. */\n balance(org?: string) {\n return this.call(\"GET\", \"/billing/balance\", BalanceSchema, undefined, org);\n }\n\n deleteMachine(name: string) {\n return this.call(\"DELETE\", `/machines/${encodeURIComponent(name)}`, z.undefined());\n }\n\n /** Like `listMachines`, for snapshots. */\n listSnapshots(opts: ListOptions = {}) {\n return this.call(\"GET\", `/snapshots${allQuery(opts)}`, z.array(SnapshotSchema), undefined, opts.org);\n }\n\n createSnapshot(req: CreateSnapshotRequest) {\n return this.call(\"POST\", \"/snapshots\", SnapshotSchema, req);\n }\n\n deleteSnapshot(name: string) {\n return this.call(\"DELETE\", `/snapshots/${encodeURIComponent(name)}`, z.undefined());\n }\n\n // ---- volumes (#52) ----\n listVolumes(opts: ListOptions = {}) {\n return this.call(\"GET\", `/volumes${allQuery(opts)}`, z.array(VolumeSchema), undefined, opts.org);\n }\n\n createVolume(req: CreateVolumeRequest) {\n return this.call(\"POST\", \"/volumes\", VolumeSchema, req);\n }\n\n deleteVolume(name: string) {\n return this.call(\"DELETE\", `/volumes/${encodeURIComponent(name)}`, z.undefined());\n }\n\n /** Both answer with the box as it is afterwards (restarted when it was running). */\n attachVolume(name: string, req: AttachVolumeRequest) {\n return this.call(\"POST\", `/volumes/${encodeURIComponent(name)}/attach`, MachineSchema, req);\n }\n\n detachVolume(name: string, req: AttachVolumeRequest) {\n return this.call(\"POST\", `/volumes/${encodeURIComponent(name)}/detach`, MachineSchema, req);\n }\n\n // ---- control plane only (`kvbox login`, `logout`, `whoami`) ----\n\n login(req: LoginRequest) {\n return this.call(\"POST\", \"/login\", LoginResponseSchema, req);\n }\n\n logout() {\n return this.call(\"POST\", \"/logout\", z.unknown()).then(() => undefined);\n }\n\n me() {\n return this.call(\"GET\", \"/me\", MeResponseSchema);\n }\n\n // ---- orgs (`kvbox org …`) ----\n\n listOrgs() {\n return this.call(\"GET\", \"/orgs\", z.array(OrgMembershipSchema));\n }\n\n createOrg(req: CreateOrgRequest) {\n return this.call(\"POST\", \"/orgs\", CloudOrgSchema, req);\n }\n\n getOrg(slug: string) {\n return this.call(\"GET\", `/orgs/${encodeURIComponent(slug)}`, OrgDetailSchema);\n }\n\n deleteOrg(slug: string) {\n return this.call(\"DELETE\", `/orgs/${encodeURIComponent(slug)}`, z.undefined());\n }\n\n addMember(slug: string, req: AddMemberRequest) {\n return this.call(\"POST\", `/orgs/${encodeURIComponent(slug)}/members`, z.undefined(), req);\n }\n\n setRole(slug: string, username: string, role: OrgRole) {\n return this.call(\"PATCH\", `/orgs/${encodeURIComponent(slug)}/members/${encodeURIComponent(username)}`, z.unknown(), { role }).then(() => undefined);\n }\n\n removeMember(slug: string, username: string) {\n return this.call(\"DELETE\", `/orgs/${encodeURIComponent(slug)}/members/${encodeURIComponent(username)}`, z.undefined());\n }\n\n /** Sign this machine's key again (#51); the key must be one the user logged in with. */\n sshCert(req: SshCertRequest) {\n return this.call(\"POST\", \"/ssh/cert\", SshCertResponseSchema, req);\n }\n\n sshCa() {\n return this.call(\"GET\", \"/ssh/ca\", SshCaResponseSchema);\n }\n\n /** This host's socket only (#55): the CA its control plane says boxes should trust. */\n cloudCa() {\n return this.call(\"GET\", \"/ssh/cloud-ca\", CloudCaSchema);\n }\n\n /** This host's socket only (#55): make every cloud box on it trust this CA. */\n trustCa(req: TrustCaRequest) {\n return this.call(\"POST\", \"/ssh/trust-ca\", TrustCaReportSchema, req);\n }\n\n async close() {\n await this.dispatcher.close();\n }\n}\n\n/**\n * The control plane did not answer. kvbox.sh has a status page; a dev control plane does not, so that\n * message points at the way back to this machine instead.\n */\nexport function cloudDown(url: string, code: string): string {\n const host = hostOf(url);\n const hint = host.endsWith(\"kvbox.sh\") ? \"check status.kvbox.sh\" : \"use --local for this machine, or kvbox logout\";\n return `${host} is not available or is down (${code}). You are logged in there, so kvbox talks to it instead of this machine; ${hint}`;\n}\n\nfunction safeJson(text: string): unknown {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Bring a box that is not running to running the way its state asks for: start a stopped one, resume\n * one in standby, wake a hibernated one. Says what it is doing. Returns the box as the server sees it now.\n */\nexport async function wakeUp(client: ServerClient, box: Machine, name: string): Promise<Machine> {\n switch (box.status) {\n case \"standby\":\n info(`box ${name} is in standby; resuming it`);\n return spin(`resuming ${name}…`, client.resumeMachine(name));\n case \"hibernated\":\n info(`box ${name} is hibernated; waking it`);\n return spin(`waking ${name} (loading its memory from disk)…`, client.wakeMachine(name));\n case \"stopped\":\n info(`box ${name} is stopped; starting it`);\n return spin(`booting ${name}…`, client.startMachine(name));\n default:\n return box;\n }\n}\n\n/**\n * The listing a box is picked from (`pickRef`): `slug/name` through a control plane lists that slug\n * alone, so a box outside the default listing (a platform admin's reach, #78) is still found.\n */\nexport function boxesFor(client: ServerClient, text: string): Promise<Machine[]> {\n const slash = text.indexOf(\"/\");\n if (slash === -1 || client.target.kind !== \"cloud\") return client.listMachines();\n return client.listMachines({ org: text.slice(0, slash).split(\"@\")[0] });\n}\n\n/** The logged-in user's slug, for telling their own boxes from an org's in a listing; undefined on this machine. */\nexport const me = (client: ServerClient): string | undefined => (client.target.kind === \"cloud\" ? client.target.user : undefined);\n\n/** Build a client from the root command's global options (`--local`). */\nexport async function clientFor(opts: { local?: boolean }, client: ClientOptions = {}): Promise<ServerClient> {\n return new ServerClient(await resolveTarget(opts), client);\n}\n\n/** Where `ssh` reaches a box, and under what name its host key is remembered. */\nexport interface SshEndpoint {\n host: string;\n port: number;\n user: string;\n /**\n * known_hosts name for a cloud box: the box's id on its host. Public ports get reused by later\n * boxes, so keying the host key by `[host]:port` would make the next box look like an impostor;\n * keyed by box, a new box is simply a new entry. Absent for a local box (no known_hosts at all).\n */\n alias?: string;\n}\n\n/**\n * How to reach a box over ssh from here (#21). On this machine: its private ip on the host's\n * bridge. Through the control plane: the host's public address and the port the host opened for\n * the box, which the control plane adds to every box it answers with.\n */\nexport function sshEndpoint(box: Machine, target: Target): SshEndpoint {\n if (target.kind === \"local\") return { host: box.ip, port: 22, user: BOX_SSH_USER };\n if (box.ssh === undefined) throw new KvboxError(`box ${box.name} has no public SSH port`);\n return { ...box.ssh, alias: `${box.id}.${box.ssh.host}` };\n}\n\n/**\n * `ssh` argv for a box. A local box's host key is not checked: keys are per box and ips get\n * reused. A cloud box's is remembered on first use under its alias (see SshEndpoint) in kvbox's\n * own known_hosts, so a changed key is refused like ssh always does. SetEnv pins the locale\n * because the image only ships C.UTF-8 (#24).\n */\nexport function sshArgs(ep: SshEndpoint, p: Paths = paths()): string[] {\n const hostKey =\n ep.alias === undefined\n ? [\"-o\", \"StrictHostKeyChecking=no\", \"-o\", \"UserKnownHostsFile=/dev/null\"]\n : [\"-o\", \"StrictHostKeyChecking=accept-new\", \"-o\", `UserKnownHostsFile=${p.sshKnownHosts}`, \"-o\", `HostKeyAlias=${ep.alias}`];\n return [\n \"-i\", p.sshKey,\n \"-p\", String(ep.port),\n ...hostKey,\n \"-o\", \"LogLevel=ERROR\",\n // A quiet open session still moves a few bytes a minute, so the host's auto-hibernate (#47) sees it.\n \"-o\", \"ServerAliveInterval=60\",\n \"-o\", \"SetEnv=LC_ALL=C.UTF-8\",\n `${ep.user}@${ep.host}`,\n ];\n}\n\n/**\n * Resolve once something accepts a TCP connection on the endpoint, or reject after `timeoutMs`.\n * A freshly started box takes a second or two before sshd listens; ssh itself would just fail.\n */\nexport async function waitForSsh(ep: Pick<SshEndpoint, \"host\" | \"port\">, timeoutMs = 30_000): Promise<void> {\n const { connect } = await import(\"node:net\");\n const deadline = Date.now() + timeoutMs;\n const attempt = () =>\n new Promise<boolean>((resolve) => {\n const sock = connect({ host: ep.host, port: ep.port, timeout: 1000 });\n sock.once(\"connect\", () => { sock.destroy(); resolve(true); });\n sock.once(\"timeout\", () => { sock.destroy(); resolve(false); });\n sock.once(\"error\", () => resolve(false));\n });\n while (Date.now() < deadline) {\n if (await attempt()) return;\n await new Promise((r) => setTimeout(r, 250));\n }\n throw new KvboxError(`box at ${ep.host}:${ep.port} did not answer within ${Math.round(timeoutMs / 1000)}s`);\n}\n\nexport const NOT_A_HOST_HINT =\n \"kvbox-server is not installed, so this machine is not a kvbox host. \" +\n \"Set it up with install-server.sh, or log in to the cloud with: kvbox login\";\n\n/**\n * The last `error: …` line of server.log, which is why a daemon that just died did not come up.\n * `from`: only what was written past that byte offset (this start's lines, not an earlier run's).\n */\nasync function lastErrorLine(logPath: string, from = 0): Promise<string | undefined> {\n const { readFile } = await import(\"node:fs/promises\");\n const text = (await readFile(logPath).catch(() => Buffer.alloc(0))).subarray(from).toString(\"utf8\");\n const lines = text.trimEnd().split(\"\\n\").slice(-20).reverse();\n return lines.find((l) => l.startsWith(\"error: \"))?.slice(\"error: \".length);\n}\n\n/**\n * Spawn `kvbox-server start` from PATH, detached, stdio to ~/.kvbox/server.log,\n * and resolve once its socket accepts a /health call (or reject after `timeoutMs`).\n * Where install-server.sh set up the systemd unit for this home (#29), systemd does the spawning\n * instead, so the server running is the one it keeps and brings back at boot.\n * When this process cannot open /dev/kvm but the user is in its group, the daemon is started\n * through `sg <group>` so it can (#61, `serverLauncher`); the pid is then read from server.pid,\n * which the daemon writes itself, since the child here would be sg.\n */\nexport async function startLocalServer(p: Paths = paths(), timeoutMs = 5000): Promise<{ pid: number; socketPath: string; viaGroup: string | undefined }> {\n await mkdir(p.home, { recursive: true });\n if (hasUnitFor(p)) return startUnit(p, timeoutMs);\n const log = openSync(p.serverLog, \"a\");\n const launcher = serverLauncher();\n const child = spawn(launcher.cmd, launcher.args, { detached: true, stdio: [\"ignore\", log, log] });\n\n const failed = new Promise<never>((_, reject) => {\n child.once(\"error\", (err: NodeJS.ErrnoException) => {\n reject(new KvboxError(err.code === \"ENOENT\" && launcher.viaGroup === undefined ? NOT_A_HOST_HINT : `could not start kvbox-server: ${err.message}`));\n });\n child.once(\"exit\", (code) => {\n void lastErrorLine(p.serverLog).then((why) => {\n reject(new KvboxError(why === undefined ? `kvbox-server exited with code ${String(code)} before listening; see ${p.serverLog}` : `kvbox-server could not start: ${why}`));\n });\n });\n });\n\n await Promise.race([serving(p, timeoutMs), failed]);\n child.removeAllListeners(\"exit\");\n child.unref();\n const pid = Number.parseInt(await readFile(p.serverPid, \"utf8\").catch(() => \"\"), 10);\n return { pid: Number.isNaN(pid) ? (child.pid ?? -1) : pid, socketPath: p.serverSock, viaGroup: launcher.viaGroup };\n}\n\n/** `systemctl start kvbox-server`, then the same wait for the socket, giving up early if the server exits. */\nasync function startUnit(p: Paths, timeoutMs: number): Promise<{ pid: number; socketPath: string; viaGroup: undefined }> {\n const logFrom = await stat(p.serverLog).then((s) => s.size, () => 0);\n const res = startUnitProcess();\n if (!res.ok) {\n const why = res.out || (await lastErrorLine(p.serverLog, logFrom)) || \"systemctl start failed\";\n throw new KvboxError(`kvbox-server could not start: ${why} (journalctl -u ${UNIT}; rerun install-server.sh if sudo asked for a password)`);\n }\n await serving(p, timeoutMs, async () => {\n if (unitActive()) return;\n const why = (await lastErrorLine(p.serverLog, logFrom)) ?? \"it exited right after starting\";\n throw new KvboxError(`kvbox-server could not start: ${why} (journalctl -u ${UNIT})`);\n });\n const pid = Number.parseInt(await readFile(p.serverPid, \"utf8\").catch(() => \"\"), 10);\n return { pid: Number.isNaN(pid) ? -1 : pid, socketPath: p.serverSock, viaGroup: undefined };\n}\n\n/** Resolve once the socket answers /health; reject after `timeoutMs`, or when `check` throws (polled while waiting). */\nasync function serving(p: Paths, timeoutMs: number, check?: () => Promise<void>): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n await check?.();\n if (await stat(p.serverSock).then(() => true, () => false)) {\n const probe = new ServerClient({ kind: \"local\", socketPath: p.serverSock }, { autoStart: false });\n try {\n await probe.health();\n return;\n } catch {\n // socket exists but not serving yet\n } finally {\n await probe.close();\n }\n }\n await sleep(100);\n }\n throw new KvboxError(`kvbox-server did not start within ${timeoutMs / 1000}s; see ${p.serverLog}`);\n}\n","/**\n * Wire shapes of the kvbox HTTP API, shared by the client (src/cli) and the\n * server (src/server). Validated with zod on both sides because the client\n * may be talking to an older or newer server.\n */\nimport { z } from \"zod\";\nimport { SIZE_NAMES } from \"./sizes.js\";\n\nexport const SizeSchema = z.enum(SIZE_NAMES as [string, ...string[]]);\n\n/** The guest account every box has; `ssh` logs in as it. */\nexport const BOX_SSH_USER = \"kvbox\";\n\n/**\n * A box's state. `running`: Firecracker up, guest executing. `standby`: Firecracker up but frozen (kvbox\n * pause): memory and processes kept, no CPU. `hibernated`: no process; memory dumped to the box's dir\n * (kvbox hibernate), wake continues where it left off. `stopped`: no process, memory gone, next start boots.\n * `unknown`: only from the control plane, for a box whose host did not answer in time (#20).\n */\nexport const BoxStatusSchema = z.enum([\"running\", \"standby\", \"hibernated\", \"stopped\", \"unknown\"]);\nexport type BoxStatus = z.infer<typeof BoxStatusSchema>;\n\n/** A published box port's protocol (#30). */\nexport const PortProtoSchema = z.enum([\"tcp\", \"udp\"]);\nexport type PortProto = z.infer<typeof PortProtoSchema>;\n\n/** At most this many published ports per box (#30): room for a lab of services, not for draining the host's range. */\nexport const MAX_BOX_PORTS = 16;\n\n/**\n * A box port published on the host's public address (#30, `kvbox vm proxy`): `hostPort` on the\n * host reaches `guestPort` in the box. The host port is drawn at random and stays the box's.\n */\nexport const PortForwardSchema = z.object({\n guestPort: z.number().int().min(1).max(65535),\n hostPort: z.number().int(),\n proto: PortProtoSchema,\n /** The host's public address; only the control plane fills it in, as for `ssh`. */\n address: z.string().optional(),\n});\nexport type PortForward = z.infer<typeof PortForwardSchema>;\n\n/** `POST /machines/:name/ports` adds these, `DELETE` removes them; the answer is the box. */\nexport const PortsRequest = z.object({\n ports: z.array(z.object({ guestPort: z.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS),\n});\nexport type PortsRequest = z.infer<typeof PortsRequest>;\n\nconst BoxPortSchema = z.number().int().min(1).max(65535);\n\n/** `PUT /machines/:name/subdomain` (#31): claim `<name>.kvbox.app` for the box, serving `port`. */\nexport const ClaimSubdomainRequest = z.object({ name: z.string(), port: BoxPortSchema });\nexport type ClaimSubdomainRequest = z.infer<typeof ClaimSubdomainRequest>;\n\n/** `POST /machines/:name/subdomain/port`: the default port changes. */\nexport const SubdomainPortRequest = z.object({ port: BoxPortSchema });\nexport type SubdomainPortRequest = z.infer<typeof SubdomainPortRequest>;\n\n/** `POST /machines/:name/subdomain/routes`: `<name>.<sub>.kvbox.app` serves `port`. */\nexport const SubdomainRouteRequest = z.object({ name: z.string(), port: BoxPortSchema });\nexport type SubdomainRouteRequest = z.infer<typeof SubdomainRouteRequest>;\n\n/**\n * A box's HTTPS subdomain (#31): `url` serves the box's `port`, each route's `url` its own port.\n * `owner` is the box's slug (a user's or an org's), `box` its name.\n */\nexport const SubdomainSchema = z.object({\n owner: z.string(),\n box: z.string(),\n subdomain: z.string(),\n port: BoxPortSchema,\n url: z.string(),\n routes: z.array(z.object({ name: z.string(), port: BoxPortSchema, url: z.string() })),\n});\nexport type Subdomain = z.infer<typeof SubdomainSchema>;\n\nexport const MachineSchema = z.object({\n /** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */\n id: z.string(),\n name: z.string(),\n /** Who the box belongs to; names are unique per owner. A bare name is local to the host, `user@control-plane` later. */\n owner: z.string(),\n ip: z.string(),\n mac: z.string(),\n pid: z.number().int().nullable(),\n vcpu: z.number().int(),\n memMib: z.number().int(),\n diskBytes: z.number().int(), // the box's own writable disk, as the guest sees it\n diskUsedBytes: z.number().int(), // what that sparse file really occupies on the host\n base: z.string(), // base image version the box's overlay stacks on\n createdAt: z.string(),\n source: z.string(), // \"base\", \"snapshot:<owner/name>\" or \"fork:<owner/name>\" (#79)\n status: BoxStatusSchema,\n /**\n * Public TCP port on the host that reaches the box's SSH while it runs (#49). Only boxes made\n * through a control plane have one; the control plane adds the host's address for `connect` (#21).\n */\n sshPort: z.number().int().optional(),\n /**\n * Where `ssh` reaches the box from outside: the host's public address and that port (#21). Only\n * the control plane fills it in (a host does not know its own public address); absent for a box\n * whose host reported no port or did not answer.\n */\n ssh: z.object({ host: z.string(), port: z.number().int(), user: z.string() }).optional(),\n /** Box ports published on the host (#30). Absent: none. */\n ports: z.array(PortForwardSchema).optional(),\n /** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /machines`. */\n ownerKind: z.enum([\"user\", \"org\"]).optional(),\n /** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */\n autoHibernateSec: z.number().int().positive().optional(),\n /** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */\n volumes: z.array(z.object({ name: z.string(), sizeGib: z.number().int(), mountPath: z.string() })).optional(),\n});\nexport type Machine = z.infer<typeof MachineSchema>;\n\n/**\n * A volume (#52): a disk of its own, created apart from any box, attached to one box at a time and\n * kept when that box goes. `attachedTo` is the box's name (same owner), null when detached.\n */\nexport const VolumeSchema = z.object({\n /** The host's 6-hex volume id (#91): the ledger's key, so a name removed and made again is two volumes. */\n id: z.string(),\n name: z.string(),\n owner: z.string(),\n sizeGib: z.number().int(),\n /** What the sparse file really occupies on the host. */\n usedBytes: z.number().int(),\n attachedTo: z.string().nullable(),\n createdAt: z.string(),\n /** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /volumes`. */\n ownerKind: z.enum([\"user\", \"org\"]).optional(),\n});\nexport type Volume = z.infer<typeof VolumeSchema>;\n\n/** Volume sizes: whole GiB, at least 1, at most 4 TiB. */\nexport const MAX_VOLUME_GIB = 4096;\n\nexport const CreateVolumeRequest = z.object({\n name: z.string(),\n sizeGib: z.number().int().min(1).max(MAX_VOLUME_GIB),\n /**\n * Through a control plane (#91): the box this volume is for, so it is made on that box's host. A\n * volume attaches only to a box on its own host. Absent: the host with the most room for volumes.\n * A host ignores it.\n */\n box: z.string().optional(),\n});\nexport type CreateVolumeRequest = z.infer<typeof CreateVolumeRequest>;\n\n/** `POST /volumes/:name/attach`: the box, as the caller names it (a bare name is the caller's own). */\nexport const AttachVolumeRequest = z.object({\n box: z.string(),\n});\nexport type AttachVolumeRequest = z.infer<typeof AttachVolumeRequest>;\n\nexport const CreateMachineRequest = z.object({\n name: z.string().optional(),\n /** Ignored over the local socket (the caller is the host owner); the control plane sets it over HTTPS. */\n owner: z.string().optional(),\n size: SizeSchema.optional(),\n from: z.string().optional(),\n force: z.boolean().optional(),\n /**\n * Extra authorized_keys lines for the box, on top of the host's own key: the control plane sends\n * its SSH CA as one `cert-authority …` line (#51). Written into the box's authorized_keys at every\n * boot (#49); a host older than that ignores them.\n */\n sshKeys: z.array(z.string()).optional(),\n /** Seconds without network traffic before the box is hibernated (#47); 0: never. Absent: the host's default. */\n autoHibernateSec: z.number().int().min(0).optional(),\n});\nexport type CreateMachineRequest = z.infer<typeof CreateMachineRequest>;\n\n/**\n * `POST /machines/:name/fork` (#79): a new box from `:name` as it is right now. A running or paused\n * source is copied warm (memory and disk, processes keep running); a stopped one cold (its disk, then a\n * fresh boot). Absent fields come from the source: its size and its auto-hibernate.\n */\nexport const ForkMachineRequest = z.object({\n name: z.string().optional(),\n /**\n * The new box's slug, bare (`acme`): the control plane sends the target of `--org` here; the host\n * qualifies it with the caller's realm. Absent: the source's owner. A CLI leaves it out.\n */\n owner: z.string().optional(),\n /** A cold fork only: a warm one keeps the source's vCPU and memory. */\n size: SizeSchema.optional(),\n force: z.boolean().optional(),\n /** As in CreateMachineRequest: the control plane's CA line for the new box's owner. */\n sshKeys: z.array(z.string()).optional(),\n autoHibernateSec: z.number().int().min(0).optional(),\n});\nexport type ForkMachineRequest = z.infer<typeof ForkMachineRequest>;\n\n/**\n * `POST /machines/:name/ssh-keys` on a host (orgs phase 4): replace the authorized_keys lines the box\n * gets on top of the host's own key. Takes effect at the box's next boot (kvbox-init rewrites the\n * file from the kernel command line); a running or hibernated box keeps its current file until then.\n */\nexport const SetSshKeysRequest = z.object({\n sshKeys: z.array(z.string()),\n});\nexport type SetSshKeysRequest = z.infer<typeof SetSshKeysRequest>;\n\n/** `kvbox vm rescale`: a preset and/or explicit values; explicit ones win. Anything omitted stays as it is. */\nexport const RescaleMachineRequest = z.object({\n size: SizeSchema.optional(),\n vcpu: z.number().int().min(1).max(64).optional(),\n memMib: z.number().int().min(256).optional(),\n diskGib: z.number().int().min(1).optional(),\n});\nexport type RescaleMachineRequest = z.infer<typeof RescaleMachineRequest>;\n\n/** `kvbox vm set`: settings that change nothing in the running VM. Anything omitted stays as it is. */\nexport const SetMachineRequest = z.object({\n /** Seconds without network traffic before the box is hibernated (#47); 0: never. */\n autoHibernateSec: z.number().int().min(0).optional(),\n});\nexport type SetMachineRequest = z.infer<typeof SetMachineRequest>;\n\nexport const SnapshotSchema = z.object({\n name: z.string(),\n owner: z.string(),\n source: z.string(), // the box it was taken from, as owner/name\n base: z.string(), // base image version the overlay stacks on; a restore needs the same one\n vcpu: z.number().int(),\n memMib: z.number().int(),\n sizeBytes: z.number().int(), // what vmstate + mem + overlay really occupy on the host\n createdAt: z.string(),\n});\nexport type Snapshot = z.infer<typeof SnapshotSchema>;\n\nexport const CreateSnapshotRequest = z.object({\n box: z.string(),\n name: z.string(),\n});\nexport type CreateSnapshotRequest = z.infer<typeof CreateSnapshotRequest>;\n\n/**\n * The host's disk as volumes see it (#91). Volumes are sparse, so what they promise (`volumesGib`,\n * the sum of their sizes) and what they hold (`volumesUsedGib`) differ; a host may promise at most\n * the disk its boxes, snapshots and base images do not use, less `headroomGib` (@kvbox/shared/capacity `sellableGib`).\n */\nexport const DiskCapacitySchema = z.object({\n totalGib: z.number().int(),\n freeGib: z.number().int(),\n volumesGib: z.number().int(),\n volumesUsedGib: z.number().int(),\n headroomGib: z.number().int(),\n});\nexport type DiskCapacity = z.infer<typeof DiskCapacitySchema>;\n\nexport const CapacitySchema = z.object({\n hostMemMib: z.number().int(),\n hostCores: z.number().int(),\n reservedMemMib: z.number().int(),\n reservedVcpu: z.number().int(),\n running: z.number().int(),\n /** Absent on a host from before volumes (#91): it cannot take one. */\n disk: DiskCapacitySchema.optional(),\n});\nexport type Capacity = z.infer<typeof CapacitySchema>;\n\n/**\n * What the server did at its last start about boxes whose Firecracker had died (host reboot or crash,\n * #29). Boxes are `owner/name`. `leftStopped`: they were in standby, their memory went with the process.\n */\nexport const RecoveryReportSchema = z.object({\n at: z.string(),\n booted: z.array(z.string()),\n leftStopped: z.array(z.string()),\n failed: z.array(z.object({ box: z.string(), error: z.string() })),\n});\nexport type RecoveryReport = z.infer<typeof RecoveryReportSchema>;\n\nexport const HealthSchema = z.object({\n ok: z.literal(true),\n version: z.string(),\n pid: z.number().int(),\n /** Base image version new boxes get (null when the host has no usable base image yet). */\n base: z.string().nullable(),\n /** Owner that boxes made over the local socket get (the Unix user running the server). */\n owner: z.string(),\n /** The control plane this host joined (null when none). */\n controlPlane: z\n .object({\n /** Realm name, e.g. kvbox.sh. */\n name: z.string(),\n url: z.string(),\n /** Where this host answers the control plane. */\n hostUrl: z.string(),\n })\n .nullable(),\n /** The relay this host reaches the internet through (#50); null when it has its own public address. Older servers omit it. */\n relay: z\n .object({\n name: z.string(),\n /** The public IP the relay owns for this host. */\n publicIp: z.string(),\n /** The relay's WireGuard endpoint the tunnel dials. */\n endpoint: z.string(),\n /** Times the server redialed the tunnel since it started, because the relay stopped answering. Older servers omit them. */\n restarts: z.number().int().optional(),\n lastRestartAt: z.string().nullable().optional(),\n })\n .nullable()\n .optional(),\n /** Boxes brought back at the server's last start; null when there were none or it is still at it. Older servers omit it. */\n recovery: RecoveryReportSchema.nullable().optional(),\n});\nexport type Health = z.infer<typeof HealthSchema>;\n\n/**\n * `kvbox vm usage <box>`: how long the box spent in each state over a window and what that adds up\n * to. Hours are fractional; the CLI rounds. `cost` is present only when the host prices usage.\n * `historyFrom` is the first recorded moment, null when nothing is recorded yet.\n */\nexport const MachineUsageSchema = z.object({\n name: z.string(),\n owner: z.string(),\n status: BoxStatusSchema,\n window: z.object({ from: z.string(), to: z.string() }),\n seconds: z.object({\n running: z.number().int(),\n standby: z.number().int(),\n hibernated: z.number().int(),\n stopped: z.number().int(),\n }),\n vcpuHours: z.number(),\n ramGibHours: z.number(),\n diskGibHours: z.number(),\n cost: z.object({ amount: z.number(), currency: z.string() }).optional(),\n /** Stops the server did not witness (Firecracker died, host rebooted) and dated to when it noticed. */\n estimatedStops: z.number().int(),\n historyFrom: z.string().nullable(),\n});\nexport type MachineUsage = z.infer<typeof MachineUsageSchema>;\n\n/** What a running box says about itself through kvbox-agent's `stats` (base v0.7.0 and later). */\nexport const GuestStatsSchema = z.object({\n /** Load average over 1, 5 and 15 minutes. */\n load: z.tuple([z.number(), z.number(), z.number()]),\n cpus: z.number().int(),\n memTotalMib: z.number().int(),\n /** Total minus available: page cache counts as free. */\n memUsedMib: z.number().int(),\n /** The box's root, which is its overlay disk: the box's own writes, not the shared base. */\n diskTotalBytes: z.number().int(),\n diskUsedBytes: z.number().int(),\n uptimeSec: z.number().int(),\n});\nexport type GuestStats = z.infer<typeof GuestStatsSchema>;\n\n/** `GET /machines/:name/stats` (#67): `stats` is null when the box's image predates the request. */\nexport const MachineStatsSchema = z.object({\n name: z.string(),\n owner: z.string(),\n stats: GuestStatsSchema.nullable(),\n});\nexport type MachineStats = z.infer<typeof MachineStatsSchema>;\n\n/** A box's state as the usage ledger tells it: a box status, or `removed` when its last row is the `rm`. */\nexport const UsageStatusSchema = z.enum([...BoxStatusSchema.options, \"removed\"]);\nexport type UsageStatus = z.infer<typeof UsageStatusSchema>;\n\n/** One box's share of a `GET /usage` report (#41, #42): the same figures as `MachineUsage`, over the report's window. */\nexport const BoxUsageSchema = MachineUsageSchema.omit({ window: true, status: true }).extend({\n /** The host's box id; a name removed and recreated appears twice, with two ids. */\n id: z.string(),\n status: UsageStatusSchema,\n /** Through a control plane: whether the owner slug is a user's or an org's (what `kvbox ls` shows). */\n ownerKind: z.enum([\"user\", \"org\"]).optional(),\n /**\n * Through a control plane: the username that made the box (#60), absent when the box is gone from\n * the index (removed), was found by reconcile, or its maker was deleted. The ledger does not record it.\n */\n createdBy: z.string().optional(),\n});\nexport type BoxUsage = z.infer<typeof BoxUsageSchema>;\n\n/**\n * `GET /usage?since=&until=`: every box of the caller over the window (removed ones included) and\n * the totals. On a host over its socket: the host owner's boxes; through a control plane: every slug\n * the user can read (`X-Kvbox-Org` narrows to one). `cost` is present when the answering side prices usage.\n */\n/**\n * One volume's share of a `GET /usage` report (#91): the hours it existed over the window and its\n * GiB-hours (its size, not what it holds: a volume is a reservation). `removed` when its last row is\n * the `rm`. The price is per volume-hour plus per GiB-hour (decision \"Cloud pricing v1\").\n */\nexport const VolumeUsageSchema = z.object({\n /** The host's volume id; a name removed and made again appears twice, with two ids. */\n id: z.string(),\n name: z.string(),\n owner: z.string(),\n ownerKind: z.enum([\"user\", \"org\"]).optional(),\n /** The size at the end of the window (or when removed). */\n sizeGib: z.number().int(),\n status: z.enum([\"present\", \"removed\"]),\n volumeHours: z.number(),\n volumeGibHours: z.number(),\n cost: z.object({ amount: z.number(), currency: z.string() }).optional(),\n historyFrom: z.string().nullable(),\n});\nexport type VolumeUsage = z.infer<typeof VolumeUsageSchema>;\n\nexport const UsageReportSchema = z.object({\n window: z.object({ from: z.string(), to: z.string() }),\n boxes: z.array(BoxUsageSchema),\n /** Absent from a side older than #91. */\n volumes: z.array(VolumeUsageSchema).optional(),\n totals: z.object({\n seconds: MachineUsageSchema.shape.seconds,\n vcpuHours: z.number(),\n ramGibHours: z.number(),\n diskGibHours: z.number(),\n volumeHours: z.number().optional(),\n volumeGibHours: z.number().optional(),\n /** Boxes and volumes together. */\n cost: z.object({ amount: z.number(), currency: z.string() }).optional(),\n }),\n});\nexport type UsageReport = z.infer<typeof UsageReportSchema>;\n\n/**\n * `GET /usage/events?after=<id>&limit=<n>` on a host (#42): the ledger rows after `after`, oldest\n * first, as the control plane pulls them. `next` is the last row's id (the cursor to store), equal\n * to `after` when there was nothing new. Over HTTPS only rows of the caller's realm come back.\n * `ledger` names the host's ledger: row ids are unique only within it, and a new one restarts at 1.\n */\nexport const UsageEventRowSchema = z.object({\n id: z.number().int(),\n boxId: z.string(),\n owner: z.string(),\n name: z.string(),\n at: z.string(),\n state: z.enum([\"running\", \"standby\", \"hibernated\", \"stopped\"]),\n vcpu: z.number().int(),\n memMib: z.number().int(),\n diskGib: z.number().int(),\n by: z.string(),\n});\nexport type UsageEventRow = z.infer<typeof UsageEventRowSchema>;\n\nexport const UsageEventsResponseSchema = z.object({\n ledger: z.string().min(1),\n events: z.array(UsageEventRowSchema),\n next: z.number().int(),\n});\nexport type UsageEventsResponse = z.infer<typeof UsageEventsResponseSchema>;\n\n/**\n * `GET /usage/volume-events?after=<id>&limit=<n>` on a host (#91): the volume ledger, pulled like the\n * box ledger and in the same host ledger (one `ledger` id, its own row ids). A row per create, resize\n * and rm, carrying the size from that moment on.\n */\nexport const VolumeEventRowSchema = z.object({\n id: z.number().int(),\n volumeId: z.string(),\n owner: z.string(),\n name: z.string(),\n at: z.string(),\n sizeGib: z.number().int(),\n by: z.enum([\"create\", \"resize\", \"rm\"]),\n});\nexport type VolumeEventRow = z.infer<typeof VolumeEventRowSchema>;\n\nexport const VolumeEventsResponseSchema = z.object({\n ledger: z.string().min(1),\n events: z.array(VolumeEventRowSchema),\n next: z.number().int(),\n});\nexport type VolumeEventsResponse = z.infer<typeof VolumeEventsResponseSchema>;\n\nexport const ApiErrorSchema = z.object({\n error: z.string(),\n});\n\n// ---- control plane (kvbox-cloud) ----\n\n/** Where `kvbox login` goes without a URL, and the control plane's own public URL by default. */\nexport const DEFAULT_CLOUD_URL = \"https://api.kvbox.sh\";\n\n/**\n * Who turned a slug (a user or an org) on: a card on file (`card`, #75) or an admin by hand\n * (`admin`, #74). Until one of them does, the account only logs in and looks: every other route\n * answers 402 (decision \"Signup is email + password… inactive until a card is on file\").\n */\nexport const ACTIVATED_BY = [\"card\", \"admin\"] as const;\nexport const ActivatedBySchema = z.enum(ACTIVATED_BY);\nexport type ActivatedBy = z.infer<typeof ActivatedBySchema>;\n\n/** A user account on the control plane; returned by `GET /me`, `GET /users` (#48). */\nexport const CloudUserSchema = z.object({\n /** The handle: what hosts file boxes under (`<username>@<control plane>`). Lowercase, no `@` or `/`. */\n username: z.string(),\n /** Display name, free text (\"Alexandru Ghiura\"). */\n name: z.string(),\n /** Login identity, unique. */\n email: z.string(),\n role: z.enum([\"admin\", \"user\"]),\n createdAt: z.string(),\n /**\n * False until a card is on file or an admin activates the account (#74): then only `/me` and\n * `/logout` answer. Admins are never gated. A control plane older than #74 does not send these and\n * gates nobody, hence the defaults: a newer CLI must still parse its answers.\n */\n active: z.boolean().default(true),\n activatedBy: ActivatedBySchema.nullable().default(null),\n});\nexport type CloudUser = z.infer<typeof CloudUserSchema>;\n\n// ---- orgs (plan \"Orgs, slugs and roles\") ----\n\nexport const ORG_ROLES = [\"owner\", \"admin\", \"member\"] as const;\nexport const OrgRoleSchema = z.enum(ORG_ROLES);\nexport type OrgRole = z.infer<typeof OrgRoleSchema>;\n\n/** An org as the API shows it; its slug owns boxes the way a username does. */\nexport const CloudOrgSchema = z.object({\n slug: z.string(),\n /** Display name; the slug never changes, this may. */\n name: z.string(),\n createdAt: z.string(),\n /** 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. */\n active: z.boolean().default(true),\n activatedBy: ActivatedBySchema.nullable().default(null),\n});\nexport type CloudOrg = z.infer<typeof CloudOrgSchema>;\n\n/** One of the caller's orgs with their role in it (`GET /orgs`, `GET /me`). */\nexport const OrgMembershipSchema = CloudOrgSchema.extend({ role: OrgRoleSchema });\nexport type OrgMembership = z.infer<typeof OrgMembershipSchema>;\n\nexport const OrgMemberSchema = z.object({\n username: z.string(),\n name: z.string(),\n role: OrgRoleSchema,\n addedAt: z.string(),\n});\nexport type OrgMember = z.infer<typeof OrgMemberSchema>;\n\n/** `GET /orgs/:slug`: the org and its members (members and up see it). */\nexport const OrgDetailSchema = CloudOrgSchema.extend({ members: z.array(OrgMemberSchema) });\nexport type OrgDetail = z.infer<typeof OrgDetailSchema>;\n\n/** `POST /orgs`: the caller becomes the org's owner. */\nexport const CreateOrgRequestSchema = z.object({\n slug: z.string().min(1),\n name: z.string().min(1),\n});\nexport type CreateOrgRequest = z.infer<typeof CreateOrgRequestSchema>;\n\n/** `PATCH /orgs/:slug` (owner): the display name. */\nexport const RenameOrgRequestSchema = z.object({ name: z.string().min(1) });\n\n/** `POST /orgs/:slug/members` (admin, owner): an existing user joins, as a member unless said otherwise. */\nexport const AddMemberRequestSchema = z.object({\n username: z.string().min(1),\n role: OrgRoleSchema.default(\"member\"),\n});\nexport type AddMemberRequest = z.infer<typeof AddMemberRequestSchema>;\n\n/** `PATCH /orgs/:slug/members/:username` (owner). */\nexport const SetRoleRequestSchema = z.object({ role: OrgRoleSchema });\n\n/** `GET /me`: the account plus the orgs it belongs to. */\nexport const MeResponseSchema = CloudUserSchema.extend({ orgs: z.array(OrgMembershipSchema) });\nexport type MeResponse = z.infer<typeof MeResponseSchema>;\n\n// ---- prepaid credit (#76) ----\n\n/**\n * `GET /billing/balance`: what a slug (the caller's own, or `X-Kvbox-Org`'s) has left. `balance` is\n * every top-up minus what the usage ledger says its boxes cost since `since`, the slug's first top-up\n * (null: it never had any); at or below zero the slug cannot start or create anything (402).\n * `topUps` and `spent` are the two sides of it.\n */\nexport const BalanceSchema = z.object({\n slug: z.string(),\n balance: z.number(),\n currency: z.string(),\n topUps: z.number(),\n spent: z.number(),\n /** The first moment usage counts from: the slug's first top-up; null when it has none. */\n since: z.string().nullable(),\n /** 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. */\n suspendedAt: z.string().nullable().default(null),\n});\nexport type Balance = z.infer<typeof BalanceSchema>;\n\n/** `POST /admin/billing/top-ups` (platform admin): give a slug money by hand. */\nexport const TopUpRequestSchema = z.object({\n slug: z.string().min(1),\n /** In the control plane's currency; negative corrects a mistake. */\n amount: z.number().finite(),\n note: z.string().max(200).optional(),\n});\nexport type TopUpRequest = z.infer<typeof TopUpRequestSchema>;\n\n/** One top-up as recorded, answered by `POST /admin/billing/top-ups`. */\nexport const TopUpSchema = z.object({\n id: z.string(),\n slug: z.string(),\n amount: z.number(),\n currency: z.string(),\n source: z.enum([\"admin\", \"card\", \"trial\"]),\n note: z.string().nullable(),\n at: z.string(),\n});\nexport type TopUp = z.infer<typeof TopUpSchema>;\n\n/** `POST /login` body from `kvbox login` (#48); `publicKey` is the user's SSH key to inject into new boxes. */\nexport const LoginRequestSchema = z.object({\n email: z.string().min(1),\n password: z.string().min(1),\n publicKey: z.string().optional(),\n});\nexport type LoginRequest = z.infer<typeof LoginRequestSchema>;\n\n/** `POST /signup` body from the website: a new account with the `user` role; answers like `/login` (logged in at once). */\nexport const SignupRequestSchema = z.object({\n username: z.string().min(1),\n name: z.string().min(1),\n email: z.string().min(1),\n password: z.string().min(1),\n});\nexport type SignupRequest = z.infer<typeof SignupRequestSchema>;\n\n/**\n * `POST /login` answer: the bearer token the CLI stores (#48). With a `publicKey` in the request,\n * also that key signed by the control plane's SSH CA (#51): the `-cert.pub` text and when it expires (ISO).\n */\nexport const LoginResponseSchema = z.object({\n token: z.string(),\n user: CloudUserSchema,\n sshCert: z.string().optional(),\n sshCertExpires: z.string().optional(),\n /** Whose boxes the certificate opens: `<slug>@<realm>` for the user and each org they are in (orgs phase 4). */\n sshCertPrincipals: z.array(z.string()).optional(),\n});\nexport type LoginResponse = z.infer<typeof LoginResponseSchema>;\n\n/** `POST /ssh/cert` body: one of the caller's uploaded keys to sign again (#51). */\nexport const SshCertRequestSchema = z.object({\n publicKey: z.string().min(1),\n});\nexport type SshCertRequest = z.infer<typeof SshCertRequestSchema>;\n\n/** `POST /ssh/cert` answer: the certificate text, its expiry (ISO) and its principals. */\nexport const SshCertResponseSchema = z.object({\n cert: z.string(),\n expires: z.string(),\n principals: z.array(z.string()),\n});\nexport type SshCertResponse = z.infer<typeof SshCertResponseSchema>;\n\n/** `GET /ssh/ca` answer: the CA's public key, the line boxes trust after `cert-authority `. */\nexport const SshCaResponseSchema = z.object({\n publicKey: z.string(),\n /** 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. */\n retired: z.array(z.object({ publicKey: z.string(), retiredAt: z.string() })).optional(),\n});\nexport type SshCaResponse = z.infer<typeof SshCaResponseSchema>;\n\n/** `GET /hosts/self/ssh-ca` on the control plane, by the host secret: the CA every box should trust (`kvbox server trust-ca --from-cloud`, #55). */\nexport const HostSshCaResponseSchema = z.object({\n publicKey: z.string(),\n});\n\n/** `GET /ssh/cloud-ca` on a host's socket: what its control plane says the CA is, with the fingerprint to confirm. */\nexport const CloudCaSchema = z.object({\n controlPlane: z.string(),\n publicKey: z.string(),\n fingerprint: z.string(),\n});\nexport type CloudCa = z.infer<typeof CloudCaSchema>;\n\n/** `POST /ssh/trust-ca` on a host's socket (#55): the CA public key (a pasted `cert-authority …` line is accepted too). */\nexport const TrustCaRequestSchema = z.object({\n publicKey: z.string().min(1),\n});\nexport type TrustCaRequest = z.infer<typeof TrustCaRequestSchema>;\n\n/**\n * When a box's new authorized_keys reach the guest: `now` (pushed through kvbox-agent), or at its\n * next `start` (stopped: kvbox-init writes the file at boot), `wake` (hibernated), `resume`\n * (standby), or `later` (running, but its agent could not take them: the next stop and start).\n */\nexport const SshKeysAppliedSchema = z.enum([\"now\", \"start\", \"wake\", \"resume\", \"later\"]);\nexport type SshKeysApplied = z.infer<typeof SshKeysAppliedSchema>;\n\n/** `POST /ssh/trust-ca` answer: every cloud box on the host, by what happened to it. Boxes are `owner/name`. */\nexport const TrustCaReportSchema = z.object({\n publicKey: z.string(),\n fingerprint: z.string(),\n /** The guest trusts the CA now. */\n updated: z.array(z.string()),\n /** meta.json has the line; the guest gets it at `when`. */\n pending: z.array(z.object({ box: z.string(), when: SshKeysAppliedSchema, why: z.string().optional() })),\n failed: z.array(z.object({ box: z.string(), error: z.string() })),\n /** Local boxes, untouched: they trust the host's key only. */\n local: z.number().int(),\n});\nexport type TrustCaReport = z.infer<typeof TrustCaReportSchema>;\n\n/** `POST /hosts/join` body from `kvbox-server join` (#18); `fingerprint` is the host's TLS cert sha256, colon-separated. */\nexport const HostJoinRequestSchema = z.object({\n token: z.string().min(1),\n name: z.string().min(1),\n url: z.string().url(),\n fingerprint: z.string().regex(/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/),\n publicAddress: z.string().min(1),\n});\nexport type HostJoinRequest = z.infer<typeof HostJoinRequestSchema>;\n\n/** `POST /hosts/join` answer: the secret the control plane will present to the host from now on (#18). */\nexport const HostJoinResponseSchema = z.object({\n hostSecret: z.string(),\n controlPlane: z.object({ name: z.string() }),\n});\nexport type HostJoinResponse = z.infer<typeof HostJoinResponseSchema>;\n\n/** A host as the control plane knows it; returned by `GET /hosts` (admin). */\nexport const CloudHostSchema = z.object({\n name: z.string(),\n url: z.string(),\n publicAddress: z.string(),\n joinedAt: z.string(),\n lastSeenAt: z.string().nullable(),\n capacity: CapacitySchema.nullable(),\n});\nexport type CloudHost = z.infer<typeof CloudHostSchema>;\n","/**\n * Fixed box sizes. Firecracker backs guest memory lazily and the disk is a sparse overlay on the\n * shared base image, so a box only costs what the guest actually touches.\n */\nexport const SIZES = {\n xs: { vcpu: 1, memMib: 2048, diskGib: 8 },\n s: { vcpu: 2, memMib: 4096, diskGib: 8 },\n m: { vcpu: 4, memMib: 8192, diskGib: 16 },\n l: { vcpu: 8, memMib: 16384, diskGib: 32 },\n} as const;\n\nexport type SizeName = keyof typeof SIZES;\nexport const SIZE_NAMES = Object.keys(SIZES) as SizeName[];\nexport const DEFAULT_SIZE: SizeName = \"s\";\n\nexport function isSizeName(value: string): value is SizeName {\n return value in SIZES;\n}\n\n/**\n * \"16GB\", \"16G\", \"16\", \"4096MB\", \"4096M\", \"0.5GB\" -> MiB. A bare number is GB: that is how\n * people say it (\"16gb\", \"4 vcpu 16gb\"). Returns undefined when it is not a size.\n */\nexport function parseMib(text: string): number | undefined {\n const m = /^\\s*(\\d+(?:\\.\\d+)?)\\s*([gm]i?b?)?\\s*$/i.exec(text);\n if (!m) return undefined;\n const n = Number(m[1]);\n const unit = (m[2] ?? \"g\").toLowerCase();\n const mib = unit.startsWith(\"m\") ? n : n * 1024;\n return Number.isInteger(mib) && mib > 0 ? mib : undefined;\n}\n","/**\n * How to launch `kvbox-server` so it can open /dev/kvm (#61). A shell that logged in (or a tmux\n * server that started) before the user was added to the kvm group hands that stale group list to\n * every process it spawns, the daemon included; firecracker then fails with \"Permission denied\".\n * When this process cannot open the device but /etc/group says the user belongs to its group,\n * the daemon is started through `sg <group>`, which grants a group the user already holds without\n * a password. Everything else (device missing, user not in the group) is left to kvbox-server's own\n * check, which explains the situation in plain words.\n */\nimport { accessSync, constants, readFileSync, statSync } from \"node:fs\";\nimport { userInfo } from \"node:os\";\n\nexport const KVM_DEVICE = \"/dev/kvm\";\n\nexport interface Launcher {\n cmd: string;\n args: string[];\n /** The group `sg` switches to, undefined for a plain spawn. */\n viaGroup?: string;\n}\n\nexport interface LauncherOptions {\n device?: string;\n groupFile?: string;\n user?: string;\n}\n\n/** The argv that runs `kvbox-server start`: plain, or through `sg <group>` when that is what makes /dev/kvm openable. */\nexport function serverLauncher(opts: LauncherOptions = {}): Launcher {\n const device = opts.device ?? KVM_DEVICE;\n const plain: Launcher = { cmd: \"kvbox-server\", args: [\"start\"] };\n try {\n accessSync(device, constants.R_OK | constants.W_OK);\n return plain;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== \"EACCES\" && code !== \"EPERM\") return plain;\n }\n let gid: number;\n try {\n gid = statSync(device).gid;\n } catch {\n return plain;\n }\n const group = groupWithMember(gid, opts.user ?? userInfo().username, opts.groupFile ?? \"/etc/group\");\n if (group === undefined) return plain;\n // sg runs a shell string; the command is a fixed literal, no user input reaches it.\n return { cmd: \"sg\", args: [group, \"-c\", \"kvbox-server start\"], viaGroup: group };\n}\n\n/** The name of the group with this gid when the group file lists `user` among its members, else undefined. */\nexport function groupWithMember(gid: number, user: string, groupFile: string): string | undefined {\n let text: string;\n try {\n text = readFileSync(groupFile, \"utf8\");\n } catch {\n return undefined;\n }\n for (const line of text.split(\"\\n\")) {\n const [name, , id, members = \"\"] = line.split(\":\");\n if (name === undefined || id === undefined || Number.parseInt(id, 10) !== gid) continue;\n return members.split(\",\").includes(user) ? name : undefined;\n }\n return undefined;\n}\n","/**\n * The systemd unit install-server.sh writes so kvbox-server starts at boot (#29): a system unit that\n * runs the server as the installing user. When it serves this KVBOX_HOME, the CLI starts the daemon\n * through it (`sudo -n`, the sudoers rule allows exactly that) instead of spawning one beside it.\n */\nimport { spawnSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport type { Paths } from \"@kvbox/shared/paths\";\n\nexport const UNIT = \"kvbox-server\";\nexport const UNIT_FILE = `/etc/systemd/system/${UNIT}.service`;\n\n/** True when the unit exists and runs the server on `p.home` (a dev or test KVBOX_HOME has none). */\nexport function hasUnitFor(p: Paths, file = UNIT_FILE): boolean {\n let text: string;\n try {\n text = readFileSync(file, \"utf8\");\n } catch {\n return false;\n }\n const home = /^Environment=\"?KVBOX_HOME=([^\"\\n]+)\"?$/m.exec(text)?.[1];\n return home !== undefined && resolve(home) === resolve(p.home);\n}\n\n/** `sudo -n systemctl start kvbox-server`; what it said when it failed. */\nexport function startUnitProcess(): { ok: boolean; out: string } {\n const res = spawnSync(\"sudo\", [\"-n\", \"systemctl\", \"start\", UNIT], { encoding: \"utf8\" });\n return { ok: res.status === 0, out: `${res.stdout ?? \"\"}${res.stderr ?? \"\"}`.trim() };\n}\n\n/**\n * False once the unit's server has exited: systemd then shows it waiting to restart (\"activating\")\n * or given up (\"failed\"). `systemctl start` returns as soon as a Type=simple unit forks, so this is\n * how a server that dies right away is told apart from one still coming up.\n */\nexport function unitActive(): boolean {\n const res = spawnSync(\"systemctl\", [\"is-active\", UNIT], { encoding: \"utf8\" });\n return (res.stdout ?? \"\").trim() === \"active\";\n}\n\n/** Whether the server comes back by itself after a reboot: the unit serves this home and is enabled. */\nexport function startsAtBoot(p: Paths): boolean {\n return hasUnitFor(p) && spawnSync(\"systemctl\", [\"is-enabled\", \"--quiet\", UNIT]).status === 0;\n}\n","import { Command, Option } from \"commander\";\nimport type { Machine } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { SIZE_NAMES } from \"@kvbox/shared/sizes\";\nimport { clientFor } from \"../../client.js\";\nimport { color, duration, gb, info, json, shortRef, slugOf, spin, warn } from \"../../output.js\";\n\n/**\n * kvbox vm new [name] [--size xs|s|m|l] [--from <snapshot>] [--auto-hibernate <duration>|off] [--force] [--json]\n * --json output: the Machine object (see packages/shared/src/api.ts).\n */\nexport const newCommand = new Command(\"new\")\n .description(\"boot a new box from the base image or a snapshot\")\n .argument(\"[name]\", \"box name (box1, box2, … when omitted)\")\n .addOption(new Option(\"-s, --size <size>\", \"box size (default: server config, s)\").choices(SIZE_NAMES))\n .option(\"-f, --from <snapshot>\", \"start from a snapshot instead of the base image\")\n .option(\"--auto-hibernate <duration>\", \"hibernate the box after this long without network traffic (30m, 4h, 1d; off: never; default: server config, off)\")\n .option(\"--force\", \"skip the capacity guard\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string | undefined, opts: { size?: string; from?: string; autoHibernate?: string; force?: boolean; json?: boolean }, cmd: Command) => {\n const autoHibernateSec = opts.autoHibernate === undefined ? undefined : parseIdleTimeout(opts.autoHibernate);\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const what = opts.from !== undefined ? `restoring ${name ?? \"a new box\"} from snapshot ${opts.from}…` : `booting ${name ?? \"a new box\"}…`;\n const box = await spin(what, client.createMachine({\n ...(name !== undefined ? { name } : {}),\n ...(opts.size !== undefined ? { size: opts.size } : {}),\n ...(opts.from !== undefined ? { from: opts.from } : {}),\n ...(autoHibernateSec !== undefined ? { autoHibernateSec } : {}),\n ...(opts.force ? { force: true } : {}),\n }));\n // A host from before #47 drops the field without a word.\n if (autoHibernateSec && !box.autoHibernateSec) warn(`box ${name ?? box.name}: its host runs a kvbox-server too old for auto-hibernate; it will not hibernate on its own`);\n if (opts.json) {\n json(box);\n return;\n }\n const user = client.target.kind === \"cloud\" ? client.target.user : undefined;\n process.stdout.write(`${box.name}\\n`);\n info(`${color.green(\"✓\")} ${describe(box, user)}`);\n if (opts.from !== undefined) info(` connect with: kvbox connect ${displayName(box, user)} (already up: everything that ran in the snapshot is running)`);\n else info(` connect with: kvbox connect ${displayName(box, user)} (SSH is up a couple of seconds after boot)`);\n if (box.autoHibernateSec) info(` it ${autoHibernateText(box.autoHibernateSec)}`);\n } finally {\n await client.close();\n }\n });\n\n/** `user`: the caller's own slug; a box of any other slug is named `slug/name` so nobody misses where it went, and that name works in every context. */\nexport function displayName(box: Machine, user: string | undefined): string {\n return user !== undefined && slugOf(box.owner) !== user ? `${slugOf(box.owner)}/${box.name}` : box.name;\n}\n\nexport function describe(box: Machine, user?: string): string {\n const from = box.source.startsWith(\"snapshot:\")\n ? ` from snapshot ${shortRef(box.source.slice(\"snapshot:\".length), box.owner)}`\n : box.source.startsWith(\"fork:\")\n ? `, a fork of ${shortRef(box.source.slice(\"fork:\".length), box.owner)}`\n : \"\";\n return `box ${color.bold(displayName(box, user))} is ${box.status} at ${box.ip}${from}: ${box.vcpu} vCPU, ${gb(box.memMib * 1024 ** 2)} RAM, ${gb(box.diskBytes)} disk`;\n}\n\n/** What a box does when its network goes quiet, in words. */\nexport function autoHibernateText(sec: number | undefined): string {\n return sec ? `hibernates after ${duration(sec)} without network traffic (kvbox connect wakes it)` : \"never hibernates on its own\";\n}\n\nconst UNIT_SEC: Record<string, number> = { m: 60, h: 3600, d: 86400 };\n\n/** \"30m\", \"4h\", \"1d\", \"1h30m\" -> seconds; \"off\", \"never\" or \"0\" -> 0. The server checks once a minute, so minutes are the unit. */\nexport function parseIdleTimeout(text: string): number {\n const t = text.trim().toLowerCase();\n if (t === \"off\" || t === \"never\" || t === \"0\") return 0;\n if (!/^(\\d+[mhd])+$/.test(t)) throw new KvboxError(`--auto-hibernate ${text}: give a duration like 30m, 4h or 1d, or off`);\n let sec = 0;\n for (const [, n, unit] of t.matchAll(/(\\d+)([mhd])/g)) sec += Number(n) * UNIT_SEC[unit!]!;\n return sec;\n}\n","import { spawn } from \"node:child_process\";\nimport { Command, InvalidArgumentError } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { pickRef, spin } from \"../../output.js\";\nimport { ensureCert, renewAfterRefusal } from \"../../cert.js\";\nimport { boxesFor, clientFor, me, sshArgs, sshEndpoint, waitForSsh, wakeUp, type SshEndpoint } from \"../../client.js\";\nimport { displayName } from \"./new.js\";\n\n/** POSIX single-quote a string for the guest's shell. */\nexport function shellQuote(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/**\n * The one string handed to the guest's login shell: the words after `--` joined with spaces\n * (so `'cd /app && npm test'` and `cd /app '&&' npm test` both work), preceded by `export`s\n * for `--env` so the shell itself expands `$VAR` in the command. SSH SetEnv is not an option:\n * the image's sshd does not AcceptEnv (#24).\n */\nexport function remoteCommand(cmdArgs: string[], env: string[]): string {\n const cmd = cmdArgs.join(\" \");\n if (env.length === 0) return cmd;\n const assignments = env.map((entry) => {\n const eq = entry.indexOf(\"=\");\n const key = eq > 0 ? entry.slice(0, eq) : \"\";\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) throw new KvboxError(`--env ${entry}: expected KEY=VALUE`);\n return `${key}=${shellQuote(entry.slice(eq + 1))}`;\n });\n return `export ${assignments.join(\" \")}; ${cmd}`;\n}\n\n/** `timeout(1)`'s exit status when the command was killed. */\nconst TIMEOUT_EXIT = 124;\n/** ssh's own status when it could not connect or the session broke. */\nconst SSH_FAILED = 255;\n\nfunction collect(value: string, previous: string[] | undefined): string[] {\n return [...(previous ?? []), value];\n}\n\nfunction positiveSeconds(value: string): number {\n const n = Number(value);\n if (!Number.isFinite(n) || n <= 0) throw new InvalidArgumentError(\"expected a number of seconds > 0\");\n return n;\n}\n\ninterface ExecOptions {\n env?: string[];\n timeout?: number;\n tty?: boolean;\n json?: boolean;\n}\n\n/** One ssh run: its exit status, what it printed (captured only with --json), whether --timeout cut it short. */\nasync function runSsh(ssh: string[], opts: ExecOptions): Promise<{ status: number; chunks: Buffer[]; timedOut: boolean }> {\n const child = spawn(\"ssh\", ssh, { stdio: [\"inherit\", opts.json ? \"pipe\" : \"inherit\", opts.json ? \"pipe\" : \"inherit\"] });\n const chunks: Buffer[] = [];\n child.stdout?.on(\"data\", (c: Buffer) => chunks.push(c));\n child.stderr?.on(\"data\", (c: Buffer) => chunks.push(c));\n\n let timedOut = false;\n const timer =\n opts.timeout === undefined\n ? undefined\n : setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGTERM\");\n }, opts.timeout * 1000);\n\n const status = await new Promise<number>((resolve, reject) => {\n child.once(\"error\", (err) => reject(new KvboxError(`could not run ssh: ${err.message}`)));\n child.once(\"close\", (code, signal) => {\n if (timedOut) resolve(TIMEOUT_EXIT);\n else if (code !== null) resolve(code);\n else resolve(signal === \"SIGINT\" ? 130 : 1);\n });\n }).finally(() => clearTimeout(timer));\n return { status, chunks, timedOut };\n}\n\n/** kvbox vm exec <name> [-e K=V]... [--timeout N] [--tty] [--json] -- <cmd...> */\nexport const execCommand = new Command(\"exec\")\n .description(\"run a command in a box and exit with its status (kvbox exec <name> -- <cmd>)\")\n .argument(\"<name>\", \"box name\")\n .argument(\"<cmd...>\", \"command, passed to the box's shell as one string (pipes, &&, cd work)\")\n .option(\"-e, --env <KEY=VALUE>\", \"set an environment variable for the command (repeatable)\", collect)\n .option(\"--timeout <seconds>\", \"kill the command after N seconds and exit 124\", positiveSeconds)\n .option(\"--tty\", \"allocate a pseudo-terminal (for interactive tools like htop)\")\n .option(\"--json\", 'capture output and print {\"output\": \"...\", \"exit_code\": N}')\n // No passThroughOptions: flags come after the box name, `--` ends them, the rest is the command.\n .action(async (name: string, cmdArgs: string[], opts: ExecOptions, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n let ep: SshEndpoint;\n let cert: \"local\" | \"kept\" | \"renewed\";\n let owner: string;\n try {\n let box = pickRef(await boxesFor(client, name), name, me(client));\n if (!box) throw new KvboxError(`box ${name}: not found (kvbox ls)`);\n if (box.status === \"stopped\") throw new KvboxError(`box ${name} is stopped (kvbox start ${name})`);\n // The box trusts the CA for its owner (#51, orgs phase 4): settle the certificate before waking anything.\n cert = await ensureCert(client, undefined, undefined, { owner: box.owner });\n owner = box.owner;\n const wasRunning = box.status === \"running\";\n // Asleep, not off: the processes are still there, so the command can run as if nothing happened.\n if (!wasRunning) box = await wakeUp(client, box, displayName(box, me(client)));\n ep = sshEndpoint(box, client.target);\n if (!wasRunning) await spin(`waiting for ${name} to accept SSH…`, waitForSsh(ep));\n } finally {\n await client.close();\n }\n\n const remote = remoteCommand(cmdArgs, opts.env ?? []);\n const stdinIsTty = process.stdin.isTTY === true;\n const ssh = [\n ...(opts.tty ? [\"-t\"] : []),\n // With a terminal on stdin nothing is sent (the command would otherwise wait on it);\n // from a pipe or file, stdin is forwarded and its EOF reaches the command.\n ...(stdinIsTty && !opts.tty ? [\"-n\"] : []),\n ...sshArgs(ep),\n // ssh joins everything after the host into the remote command line.\n remote,\n ];\n\n let { status, chunks, timedOut } = await runSsh(ssh, opts);\n if (status === SSH_FAILED && !timedOut) {\n // Refused with a certificate that was fine yesterday: the box may trust a new CA (#55). Renew once, try again.\n const again = await clientFor(cmd.optsWithGlobals());\n if (await renewAfterRefusal(again, cert, owner).finally(() => again.close())) {\n if (opts.json) process.stderr.write(Buffer.concat(chunks));\n process.stderr.write(\"renewed your SSH certificate, trying again…\\n\");\n ({ status, chunks, timedOut } = await runSsh(ssh, opts));\n }\n }\n if (status === SSH_FAILED && !timedOut) {\n if (opts.json) process.stderr.write(Buffer.concat(chunks));\n throw new KvboxError(`box ${name}: could not run the command over SSH (box still booting?)`, SSH_FAILED);\n }\n if (opts.json) {\n process.stdout.write(JSON.stringify({ output: Buffer.concat(chunks).toString(\"utf8\"), exit_code: status }) + \"\\n\");\n }\n process.exit(status);\n });\n","import { Command, Option } from \"commander\";\nimport { SIZE_NAMES } from \"@kvbox/shared/sizes\";\nimport { clientFor, me } from \"../../client.js\";\nimport { color, info, json, spin } from \"../../output.js\";\nimport { autoHibernateText, describe, displayName, parseIdleTimeout } from \"./new.js\";\n\n/**\n * kvbox vm fork <box> [name] [--org <slug>] [--size xs|s|m|l] [--auto-hibernate <duration>|off] [--force] [--json]\n * --json output: the new box, a Machine object (see packages/shared/src/api.ts); its `source` is `fork:<owner>/<box>`.\n * A running or paused box is copied warm (its memory too: what ran in it runs in the copy), a stopped one\n * cold (its disk, then a fresh boot); a hibernated one is refused. `--org` names the slug the copy goes\n * to; the source is named as anywhere else (`acme/web` for an org's). No snapshot is left behind.\n */\nexport const forkCommand = new Command(\"fork\")\n .description(\"copy a box, running or stopped, into a new one on the same host (--org: into an org)\")\n .argument(\"<box>\", \"the box to copy\")\n .argument(\"[name]\", \"the copy's name (box1, box2, … when omitted)\")\n .addOption(new Option(\"-s, --size <size>\", \"the copy's size, for a stopped box only (default: the box's)\").choices(SIZE_NAMES))\n .option(\"--auto-hibernate <duration>\", \"hibernate the copy after this long without network traffic (30m, 4h, 1d; off: never; default: the box's)\")\n .option(\"--force\", \"skip the capacity guard\")\n .option(\"--json\", \"print the new box as JSON\")\n .action(async (source: string, name: string | undefined, opts: { size?: string; autoHibernate?: string; force?: boolean; json?: boolean }, cmd: Command) => {\n const autoHibernateSec = opts.autoHibernate === undefined ? undefined : parseIdleTimeout(opts.autoHibernate);\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const box = await spin(`forking ${source}…`, client.forkMachine(source, {\n ...(name !== undefined ? { name } : {}),\n ...(opts.size !== undefined ? { size: opts.size } : {}),\n ...(autoHibernateSec !== undefined ? { autoHibernateSec } : {}),\n ...(opts.force ? { force: true } : {}),\n }));\n if (opts.json) {\n json(box);\n return;\n }\n const user = me(client);\n process.stdout.write(`${box.name}\\n`);\n info(`${color.green(\"✓\")} ${describe(box, user)}`);\n info(` connect with: kvbox connect ${displayName(box, user)}`);\n info(` it ${autoHibernateText(box.autoHibernateSec)}; published ports and HTTPS names stay with ${source}`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport type { Machine, Subdomain } from \"@kvbox/shared/api\";\nimport { clientFor, me, type ServerClient } from \"../../client.js\";\nimport { age, color, duration, gb, info, json, shape, slugOf, status, warn } from \"../../output.js\";\nimport { ownerCell } from \"./ls.js\";\nimport { displayName } from \"./new.js\";\nimport { findBox, reaches, rowsOf, subdomainJson } from \"./proxy/shared.js\";\n\n/**\n * kvbox vm get <name> [--json] — everything about one box on one screen: status, size, address,\n * ssh, HTTPS name, published ports, volumes, source, auto-hibernate. --json output: the Machine object plus\n * `subdomain?: {box, subdomain, port, url, routes}` (#31; absent without a control plane or a claim).\n */\nexport const getCommand = new Command(\"get\")\n .description(\"show one box in full: status, size, address, HTTPS name, ports, auto-hibernate\")\n .argument(\"<name>\", \"box name\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string, opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const user = me(client);\n const box = await findBox(client, name);\n const sub = client.target.kind === \"cloud\" ? await subdomainOf(client, box) : undefined;\n if (opts.json) {\n json({ ...box, ...(sub ? { subdomain: subdomainJson(sub, user) } : {}) });\n return;\n }\n const rows = getRows(box, sub, user);\n const width = Math.max(...rows.map(([k]) => k.length));\n for (const [k, v] of rows) info(`${color.dim(k.padStart(width))} ${v}`);\n } finally {\n await client.close();\n }\n });\n\n/** The box's HTTPS name, or none with a warning: a control plane older than #31 must not cost the rest. */\nasync function subdomainOf(client: ServerClient, box: Machine): Promise<Subdomain | undefined> {\n try {\n const slug = slugOf(box.owner);\n return (await client.listSubdomains()).find((s) => s.box === box.name && s.owner === slug);\n } catch (err) {\n warn(`HTTPS name not shown: ${(err as Error).message}`);\n return undefined;\n }\n}\n\n/** The lines `get` prints, in order: [label, value]. `user` is the caller's slug through a control plane. */\nexport function getRows(box: Machine, sub: Subdomain | undefined, user: string | undefined): [string, string][] {\n const rows: [string, string][] = [\n [\"name\", color.bold(displayName(box, user))],\n [\"status\", status(box.status)],\n ];\n if (user !== undefined) rows.push([\"owner\", ownerCell(box, user)]);\n if (box.status !== \"unknown\") {\n rows.push([\"size\", `${shape(box.vcpu, box.memMib, box.diskBytes)} ${color.dim(`(${gb(box.diskUsedBytes)} used)`)}`]);\n rows.push([\"address\", box.ssh?.host ?? (box.ip === \"\" ? \"-\" : box.ip)]);\n rows.push([\"ssh\", box.ssh ? `ssh -p ${box.ssh.port} ${box.ssh.user}@${box.ssh.host}` : `kvbox connect ${displayName(box, user)}`]);\n }\n rows.push([\"url\", sub ? [`${sub.url} ${color.dim(`(port ${sub.port})`)}`, ...sub.routes.map((r) => `${r.url} ${color.dim(`(port ${r.port})`)}`)].join(\", \") : \"-\"]);\n const ports = rowsOf(box, user).map((r) => `${r.guestPort}/${r.proto} → ${reaches(r, true)}`);\n rows.push([\"ports\", ports.length === 0 ? \"-\" : ports.join(\", \")]);\n rows.push([\"volumes\", box.volumes?.length ? box.volumes.map((v) => `${v.name} ${color.dim(`(${v.sizeGib} GB at ${v.mountPath})`)}`).join(\", \") : \"-\"]);\n rows.push([\"auto-hibernate\", box.autoHibernateSec ? `after ${duration(box.autoHibernateSec)} without network traffic` : \"off\"]);\n rows.push([\"source\", box.source]);\n rows.push([\"base\", box.base]);\n rows.push([\"created\", `${age(box.createdAt)} ${color.dim(`(${box.createdAt})`)}`]);\n return rows;\n}\n","import { Command } from \"commander\";\nimport type { Machine } from \"@kvbox/shared/api\";\nimport { clientFor } from \"../../client.js\";\nimport { age, boxName, color, gbShort, info, json, shape, slugOf, spin, status, table } from \"../../output.js\";\n\n/**\n * The OWNER cell: `private` for the user's own box, else the slug tagged with what it is (`acme org`,\n * or `bob user` for what a platform admin sees with --all); a control plane that does not say the\n * kind leaves the bare slug.\n */\nexport function ownerCell(b: Pick<Machine, \"owner\" | \"ownerKind\">, me: string | undefined): string {\n const slug = slugOf(b.owner);\n if (slug === me) return \"private\";\n return b.ownerKind === undefined ? slug : `${slug} ${color.dim(b.ownerKind)}`;\n}\n\n/**\n * The box's address: its host's public one through the control plane (#21; no port, a box can publish\n * several and the ssh one is `connect`'s business), its ip on this machine, `-` when unknown.\n */\nexport function addressOf(b: Machine): string {\n if (b.ssh !== undefined) return b.ssh.host;\n return b.ip === \"\" ? \"-\" : b.ip;\n}\n\n/**\n * kvbox vm ls [--all] [--json] — the user's boxes (and each of their orgs' through a control plane;\n * `--org <slug>` narrows to that org, `--all` lists the whole platform for a platform admin, #78). --json output: Machine[] (each item carries its `owner`, and\n * through a control plane `ownerKind`: \"user\" or \"org\")\n */\nexport const lsCommand = new Command(\"ls\")\n .description(\"list boxes with status and address (yours and your orgs'; --org <slug> for one org)\")\n .option(\"-a, --all\", \"every box on the platform (platform admins only)\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { all?: boolean; json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n // a control plane still asks a host live for a box it has not described lately: a slow host shows as a spinner, not a hang\n const boxes = await spin(\"listing boxes…\", client.listMachines({ all: opts.all }));\n if (opts.json) {\n json(boxes);\n return;\n }\n const org = client.target.kind === \"cloud\" ? client.target.org : undefined;\n if (boxes.length === 0) {\n info(org === undefined ? \"no boxes yet; create one with: kvbox new\" : `no boxes in ${org} yet; create one with: kvbox new --org ${org}`);\n return;\n }\n if (org !== undefined) info(`boxes of ${org}`);\n table(lsRows(boxes, client.target.kind === \"cloud\" ? { me: client.target.user } : undefined));\n } finally {\n await client.close();\n }\n });\n\n/**\n * Six columns, an OWNER one first through a control plane (`cloud` set, with the logged-in user as\n * `me`), the base image version last; cpu/ram/disk/source details stay in --json. A box whose host\n * did not answer the control plane comes back as `unknown` with no ip, size or base (#20).\n */\nexport function lsRows(boxes: Machine[], cloud?: { me?: string | undefined }): Record<string, string>[] {\n return boxes.map((b) => ({\n ...(cloud ? { owner: ownerCell(b, cloud.me) } : {}),\n name: boxName(b.name),\n status: status(b.status),\n address: addressOf(b),\n size: b.status === \"unknown\" ? \"-\" : `${shape(b.vcpu, b.memMib, b.diskBytes)} ${color.dim(`(${gbShort(b.diskUsedBytes)} used)`)}`,\n created: age(b.createdAt),\n base: b.status === \"unknown\" || b.base === \"\" ? \"-\" : b.base,\n }));\n}\n","import { KvboxError } from \"@kvbox/shared/errors\";\nimport type { Machine, PortForward, Subdomain } from \"@kvbox/shared/api\";\nimport { boxesFor, me, type ServerClient } from \"../../../client.js\";\nimport { pickRef } from \"../../../output.js\";\nimport { displayName } from \"../new.js\";\n\n/** One published port as `--json` prints it (#30). `address` is the host's public address, known only through a control plane. */\nexport type ForwardRow = PortForward & { box: string };\n\n/** One HTTPS name as `--json` prints it (#31): the box's subdomain (no `name`) or a named port under it. */\nexport interface HttpsRow {\n box: string;\n guestPort: number;\n proto: \"https\";\n url: string;\n name?: string;\n}\n\n/** The box as `ls` shows it: bare when it is the caller's, `slug/name` otherwise. */\nconst boxOf = (sub: Subdomain, user: string | undefined) => (user !== undefined && sub.owner !== user ? `${sub.owner}/${sub.box}` : sub.box);\n\n/** A subdomain as `claim --json` and `set-port --json` print it. */\nexport function subdomainJson(sub: Subdomain, user: string | undefined) {\n return { box: boxOf(sub, user), subdomain: sub.subdomain, port: sub.port, url: sub.url, routes: sub.routes };\n}\n\nexport function httpsRowsOf(sub: Subdomain, user: string | undefined): HttpsRow[] {\n const box = boxOf(sub, user);\n return [{ box, guestPort: sub.port, proto: \"https\", url: sub.url }, ...sub.routes.map((r) => ({ box, guestPort: r.port, proto: \"https\" as const, url: r.url, name: r.name }))];\n}\n\n/** HTTPS names are the control plane's (#31): a host's own socket has none. */\nexport function requireCloud(client: ServerClient): void {\n if (client.target.kind !== \"cloud\") throw new KvboxError(\"HTTPS names need the kvbox cloud: kvbox login (this host's own socket has none)\");\n}\n\nexport function rowsOf(box: Machine, user: string | undefined, only?: (f: PortForward) => boolean): ForwardRow[] {\n return (box.ports ?? []).filter(only ?? (() => true)).map((f) => ({ box: displayName(box, user), ...f }));\n}\n\n/** Where the port is reached from outside: in words, or `short` for a table cell. */\nexport function reaches(row: ForwardRow, short = false): string {\n if (row.address !== undefined) return `${row.address}:${row.hostPort}`;\n return short ? `:${row.hostPort}` : `port ${row.hostPort} of this host's public address`;\n}\n\n/** Box ports as the user typed them: whole numbers 1-65535. */\nexport function parsePorts(texts: readonly string[]): number[] {\n return texts.map((t) => {\n const n = Number(t);\n if (!/^\\d+$/.test(t) || n < 1 || n > 65535) throw new KvboxError(`\"${t}\" is not a port (1-65535)`);\n return n;\n });\n}\n\n/** The box `text` names, among the caller's boxes and their orgs'. */\nexport async function findBox(client: ServerClient, text: string): Promise<Machine> {\n const found = pickRef(await boxesFor(client, text), text, me(client));\n if (!found) throw new KvboxError(`box ${text}: not found (kvbox ls)`);\n return found;\n}\n","import { Command } from \"commander\";\nimport { clientFor } from \"../../client.js\";\nimport { color, info, json, spin } from \"../../output.js\";\n\n/** kvbox vm hibernate <name> [--json] — --json output: the Machine object */\nexport const hibernateCommand = new Command(\"hibernate\")\n .description(\"save a box's memory to disk and free its RAM (kvbox wake continues it where it left off)\")\n .argument(\"<name>\", \"box name\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string, opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const box = await spin(`hibernating ${name} (saving its memory to disk)…`, client.hibernateMachine(name));\n if (opts.json) json(box);\n else info(`${color.green(\"✓\")} box ${name} hibernated (memory saved to disk, RAM freed; kvbox wake ${name} continues it where it left off)`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { clientFor } from \"../../client.js\";\nimport { color, info, json, spin } from \"../../output.js\";\n\n/** kvbox vm pause <name> [--json] — --json output: the Machine object */\nexport const pauseCommand = new Command(\"pause\")\n .description(\"freeze a box in place (memory and processes kept, no CPU used; kvbox resume continues it instantly)\")\n .argument(\"<name>\", \"box name\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string, opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const box = await spin(`pausing ${name}…`, client.pauseMachine(name));\n if (opts.json) json(box);\n else info(`${color.green(\"✓\")} box ${name} is in standby (frozen in place; kvbox resume ${name} continues it)`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { assertSubdomain } from \"@kvbox/shared/names\";\nimport { clientFor, me } from \"../../../client.js\";\nimport { color, info, json, spin } from \"../../../output.js\";\nimport { displayName } from \"../new.js\";\nimport { findBox, parsePorts, requireCloud, subdomainJson } from \"./shared.js\";\n\n/**\n * kvbox vm proxy claim <box> <subdomain> --port <port> [--json]\n * --json output: {box, subdomain, port, url, routes: [{name, port, url}]} (#31), `box` bare for the\n * caller's own box, `slug/name` otherwise.\n */\nexport const claimCommand = new Command(\"claim\")\n .description(\"give a box its HTTPS address, https://<subdomain>.kvbox.app, serving one of its ports\")\n .argument(\"<box>\", \"box name\")\n .argument(\"<subdomain>\", \"3-63 lowercase letters, digits and '-'; must be free\")\n .requiredOption(\"--port <port>\", \"the box port the address serves\")\n .option(\"--json\", \"print the subdomain as JSON\")\n .action(async (name: string, subdomain: string, opts: { port: string; json?: boolean }, cmd: Command) => {\n assertSubdomain(subdomain);\n const [port] = parsePorts([opts.port]);\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n requireCloud(client);\n const user = me(client);\n const found = await findBox(client, name);\n const box = displayName(found, user);\n const sub = await spin(`claiming ${subdomain}…`, client.claimSubdomain(box, { name: subdomain, port: port! }));\n if (opts.json) {\n json(subdomainJson(sub, me(client)));\n return;\n }\n info(`${color.green(\"✓\")} ${color.bold(sub.url)} → box ${color.bold(box)} port ${sub.port}`);\n info(` more ports under it: kvbox vm proxy add ${box} <port> --name <name> → https://<name>.${sub.url.replace(/^https:\\/\\//, \"\")}`);\n if (found.status !== \"running\") info(` box ${box} is ${found.status}: the address answers once it runs`);\n } finally {\n await client.close();\n }\n });\n","/**\n * HTTPS names for boxes (#31, decision \"A box claims one subdomain\"): a box claims one subdomain\n * `<sub>.kvbox.app` with a default port, and named ports nest under it as `<name>.<sub>.kvbox.app`.\n * Both are single DNS labels. The CLI checks them before calling; the control plane checks again.\n */\nimport { createHmac } from \"node:crypto\";\nimport { KvboxError } from \"./errors.js\";\n\n/** Where box URLs live (decision d2cb4d88's domain); the control plane and the edge can be told otherwise. */\nexport const DEFAULT_PROXY_DOMAIN = \"kvbox.app\";\n\n/** A domain box names may live under (`kvbox.app`): the control plane's and the edge's must match. */\nexport function assertProxyDomain(text: string, key: string): string {\n if (!/^[a-z0-9-]+(\\.[a-z0-9-]+)+$/.test(text)) throw new KvboxError(`${key} must be a domain like ${DEFAULT_PROXY_DOMAIN}: ${text}`);\n return text;\n}\n\n/** One DNS label: lowercase letters, digits and `-`, never at either end. */\nconst LABEL_RE = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;\n\n/** Subdomains nobody may claim: the platform's own names, and ones that would read as ours. */\nexport const RESERVED_SUBDOMAINS: ReadonlySet<string> = new Set([\n \"admin\",\n \"api\",\n \"app\",\n \"assets\",\n \"auth\",\n \"billing\",\n \"blog\",\n \"cdn\",\n \"dashboard\",\n \"dev\",\n \"docs\",\n \"edge\",\n \"help\",\n \"install\",\n \"kvbox\",\n \"login\",\n \"mail\",\n \"relay\",\n \"root\",\n \"smtp\",\n \"static\",\n \"status\",\n \"support\",\n \"www\",\n]);\n\n/** Why `text` cannot be a claimed subdomain, or null when it can. */\nexport function subdomainProblem(text: string): string | null {\n if (text.length < 3 || text.length > 63) return `\"${text}\" must be 3 to 63 characters`;\n if (!LABEL_RE.test(text)) return `\"${text}\" may hold only lowercase letters, digits and '-', not at either end`;\n if (RESERVED_SUBDOMAINS.has(text)) return `\"${text}\" is reserved; pick another name`;\n return null;\n}\n\n/** Why `text` cannot be a name under a subdomain (`<name>.<sub>`), or null when it can. */\nexport function routeNameProblem(text: string): string | null {\n if (text.length < 1 || text.length > 63) return `\"${text}\" must be 1 to 63 characters`;\n if (!LABEL_RE.test(text)) return `\"${text}\" may hold only lowercase letters, digits and '-', not at either end`;\n return null;\n}\n\nexport function assertSubdomain(text: string): string {\n const problem = subdomainProblem(text);\n if (problem) throw new KvboxError(`subdomain ${problem}`);\n return text;\n}\n\nexport function assertRouteName(text: string): string {\n const problem = routeNameProblem(text);\n if (problem) throw new KvboxError(`name ${problem}`);\n return text;\n}\n\n/** `https://<sub>.<domain>`, or `https://<name>.<sub>.<domain>` for a named port. */\nexport function subdomainUrl(domain: string, sub: string, name?: string): string {\n return `https://${name === undefined ? \"\" : `${name}.`}${sub}.${domain}`;\n}\n\n/**\n * What a request's `Host` names under `domain`: the subdomain and, for `<name>.<sub>`, the name.\n * Null for anything else (the bare domain, deeper names, another domain).\n */\nexport function parseProxyHost(host: string, domain: string): { sub: string; name?: string } | null {\n const bare = host.toLowerCase().replace(/:\\d+$/, \"\").replace(/\\.$/, \"\");\n const suffix = `.${domain}`;\n if (!bare.endsWith(suffix)) return null;\n const labels = bare.slice(0, -suffix.length).split(\".\");\n if (labels.some((l) => !LABEL_RE.test(l))) return null;\n if (labels.length === 1) return { sub: labels[0]! };\n if (labels.length === 2) return { sub: labels[1]!, name: labels[0]! };\n return null;\n}\n\n/**\n * How the edge and a host carry a visitor's request to a box (#31). The host's answers of its own\n * (no such box, box not running, nothing listening) carry `PROXY_ERROR_HEADER`, and the box's carry\n * `PROXIED_HEADER`, so the edge can tell the box's own 404 or 401 from the host's and show its page\n * for the latter. The edge strips every `x-kvbox-*` header before a visitor sees the answer.\n */\nexport const PROXY_ERROR_HEADER = \"x-kvbox-proxy-error\";\n/**\n * `hibernated`, `standby` and `stopped` say why a box is not running (#80): the edge may ask for the\n * first two to be woken, never the last. `waking`: a wake asked for is still under way. `wake-failed`:\n * it did not work. `not-running` is what a host from before #80 says for all three.\n */\nexport type ProxyError = \"not-found\" | \"hibernated\" | \"standby\" | \"stopped\" | \"not-running\" | \"waking\" | \"wake-failed\" | \"unreachable\" | \"timeout\";\n/** Set by the host on every answer that came from the box: anything without it is the host's own (a refusal, a host too old for #31). */\nexport const PROXIED_HEADER = \"x-kvbox-proxied\";\n/**\n * The visitor's path and query. It never goes into the URL the edge calls on the host: a URL resolves\n * `..`, and `/machines/<box>/http/<port>/../../..` would reach any route on the host with the host\n * secret. The host URL is always exactly `/machines/<box>/http/<port>`.\n */\nexport const VISITOR_PATH_HEADER = \"x-kvbox-path\";\n/**\n * Sent by the edge when the box may be woken for this request (#80): its slug is not suspended and\n * the edge has not had it woken in the last minute. A host then wakes a hibernated box (resumes one in\n * standby) before forwarding, and stamps its answer with WOKE_HEADER when it did.\n */\nexport const WAKE_HEADER = \"x-kvbox-wake\";\n/**\n * The longest a host holds a request on a wake before answering `waking` (the wake itself goes on).\n * The edge adds it to its own wait for the host's answer when it sends WAKE_HEADER.\n */\nexport const WAKE_WAIT_MS = 30_000;\n/**\n * On a host's answer: this request woke the box, so the edge counts it against the box's wake limit.\n * Also on the host's own `unreachable` or `timeout` after a wake: the box was woken all the same.\n */\nexport const WOKE_HEADER = \"x-kvbox-woke\";\n/** The visitor's own `Authorization`, carried past the host secret that takes its place between edge and host. */\nexport const VISITOR_AUTH_HEADER = \"x-kvbox-authorization\";\n\n/**\n * Request headers neither hop passes on although they are not hop-by-hop: undici refuses to send\n * `expect` at all, so `Expect: 100-continue` (curl on a large upload) would fail every forward.\n * Node's server already answers the `100 Continue` itself.\n */\nexport const NOT_FORWARDED: ReadonlySet<string> = new Set([\"expect\"]);\n\n/** Headers that describe one connection, never passed along by a proxy (RFC 9110 §7.6.1). */\nexport const HOP_BY_HOP: ReadonlySet<string> = new Set([\"connection\", \"keep-alive\", \"proxy-authenticate\", \"proxy-authorization\", \"proxy-connection\", \"te\", \"trailer\", \"transfer-encoding\", \"upgrade\"]);\n\n/** The one host path the edge calls: a box's port, `/machines/<box>/http/<port>`. */\nexport const BOX_HTTP_PATH_RE = /^\\/machines\\/([^/]+)\\/http\\/(\\d{1,5})\\/?$/;\n\n/**\n * The edge's bearer for a host, derived from the host secret so neither side stores anything new.\n * A host takes it on `BOX_HTTP_PATH_RE` alone, so the internet-facing edge never holds a key to the\n * rest of a host's API; the control plane keeps it in `hosts.edge_secret` for the edge to read.\n */\nexport function edgeCredential(hostSecret: string): string {\n return createHmac(\"sha256\", hostSecret).update(\"kvbox-edge-v1\").digest(\"base64url\");\n}\n","import { Command } from \"commander\";\nimport { addCommand } from \"./add.js\";\nimport { claimCommand } from \"./claim.js\";\nimport { lsCommand } from \"./ls.js\";\nimport { releaseCommand } from \"./release.js\";\nimport { rmCommand } from \"./rm.js\";\nimport { setPortCommand } from \"./set-port.js\";\n\n/**\n * kvbox vm proxy add|ls|rm (#30): box ports on the host's public address. claim|set-port|release\n * and `add --name` (#31): the box's HTTPS address `https://<subdomain>.kvbox.app` and names under it.\n */\nexport const proxyCommand = new Command(\"proxy\")\n .description(\"publish box ports on the internet\")\n .addCommand(addCommand)\n .addCommand(lsCommand)\n .addCommand(rmCommand)\n .addCommand(claimCommand)\n .addCommand(setPortCommand)\n .addCommand(releaseCommand);\n\nfor (const cmd of proxyCommand.commands) cmd.option(\"--org <slug>\", \"act in this org (- for your personal boxes)\");\n","import { Command } from \"commander\";\nimport { assertRouteName } from \"@kvbox/shared/names\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { clientFor, me } from \"../../../client.js\";\nimport { color, info, json, spin } from \"../../../output.js\";\nimport { displayName } from \"../new.js\";\nimport { findBox, parsePorts, reaches, requireCloud, rowsOf } from \"./shared.js\";\n\n/**\n * kvbox vm proxy add <box> <port...> [--udp] [--json]\n * --json output: the forwards this call added, [{box, guestPort, hostPort, proto, address?}]\n * (`address`: the host's public address, through a control plane only). The host port is drawn at random.\n *\n * kvbox vm proxy add <box> <port> --name <name> [--json] (#31)\n * --json output: {box, guestPort, proto: \"https\", url, name}: `https://<name>.<subdomain>.kvbox.app`\n * under the box's claimed subdomain (kvbox vm proxy claim).\n */\nexport const addCommand = new Command(\"add\")\n .description(\"publish box ports on the internet; each gets a random public port, or an HTTPS name with --name\")\n .argument(\"<box>\", \"box name\")\n .argument(\"<port...>\", \"ports inside the box, e.g. 3000 8080\")\n .option(\"--udp\", \"UDP instead of TCP\")\n .option(\"--name <name>\", \"serve the port at https://<name>.<subdomain>.kvbox.app (one port; needs kvbox vm proxy claim first)\")\n .option(\"--json\", \"print the new forwards as JSON\")\n .action(async (name: string, portTexts: string[], opts: { udp?: boolean; name?: string; json?: boolean }, cmd: Command) => {\n const guestPorts = parsePorts(portTexts);\n if (opts.name !== undefined) {\n assertRouteName(opts.name);\n if (guestPorts.length !== 1) throw new KvboxError(\"--name publishes one port: kvbox vm proxy add <box> <port> --name <name>\");\n if (opts.udp) throw new KvboxError(\"--name serves HTTPS, which is TCP: drop --udp\");\n }\n const proto = opts.udp ? \"udp\" : \"tcp\";\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const user = me(client);\n if (opts.name !== undefined) requireCloud(client);\n const found = await findBox(client, name);\n const box = displayName(found, user);\n if (opts.name !== undefined) {\n const route = opts.name;\n const sub = await spin(`publishing ${guestPorts[0]} on ${name} as ${route}…`, client.addSubdomainRoute(box, { name: route, port: guestPorts[0]! }));\n const url = sub.routes.find((r) => r.name === route)!.url;\n if (opts.json) {\n json({ box, guestPort: guestPorts[0], proto: \"https\", url, name: route });\n return;\n }\n info(`${color.green(\"✓\")} ${color.bold(url)} → box ${color.bold(box)} port ${guestPorts[0]}`);\n info(\" the first name under a subdomain waits for its certificate, about a minute\");\n if (found.status !== \"running\") info(` box ${box} is ${found.status}: the address answers once it runs`);\n return;\n }\n const updated = await spin(`publishing ${guestPorts.join(\", \")} on ${name}…`, client.addPorts(box, { ports: guestPorts.map((guestPort) => ({ guestPort, proto })) }));\n const rows = rowsOf(updated, user, (f) => f.proto === proto && guestPorts.includes(f.guestPort));\n if (opts.json) {\n json(rows);\n return;\n }\n for (const row of rows) info(`${color.green(\"✓\")} box ${color.bold(row.box)} port ${row.guestPort} is reachable at ${reaches(row)} (${row.proto})`);\n if (updated.status !== \"running\") info(` box ${name} is ${updated.status}: the ports open when it runs`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport type { Subdomain } from \"@kvbox/shared/api\";\nimport { clientFor, me, type ServerClient } from \"../../../client.js\";\nimport { info, json, table, warn } from \"../../../output.js\";\nimport { displayName } from \"../new.js\";\nimport { findBox, httpsRowsOf, reaches, rowsOf, type ForwardRow, type HttpsRow } from \"./shared.js\";\n\n/**\n * kvbox vm proxy ls [box] [--json]\n * --json output: every published port, raw forwards [{box, guestPort, hostPort, proto, address?}]\n * (`address`: the host's public address, through a control plane only) and HTTPS names (#31)\n * [{box, guestPort, proto: \"https\", url, name?}] (`name` absent for the box's subdomain itself) in one\n * array. SSH ports are not listed.\n */\n/** The HTTPS names, or none with a warning: a control plane older than #31 must not cost the raw ports. */\nasync function subdomainsOf(client: ServerClient): Promise<Subdomain[]> {\n try {\n return await client.listSubdomains();\n } catch (err) {\n warn(`HTTPS names not listed: ${(err as Error).message}`);\n return [];\n }\n}\n\nexport const lsCommand = new Command(\"ls\")\n .description(\"list the box ports published on the internet\")\n .argument(\"[box]\", \"only this box\")\n .option(\"--json\", \"print as JSON\")\n .action(async (name: string | undefined, opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const user = me(client);\n // both from the control plane at once: the subdomains are its own (Postgres), the boxes ask every host\n const [boxes, subs] = await Promise.all([\n name === undefined ? client.listMachines() : findBox(client, name).then((b) => [b]),\n client.target.kind === \"cloud\" ? subdomainsOf(client) : [],\n ]);\n const shown = new Set(boxes.map((b) => displayName(b, user)));\n const https: HttpsRow[] = subs.flatMap((s) => httpsRowsOf(s, user)).filter((r) => shown.has(r.box));\n const rows: (ForwardRow | HttpsRow)[] = [...boxes.flatMap((b) => rowsOf(b, user)), ...https].sort((a, b) => a.box.localeCompare(b.box) || a.guestPort - b.guestPort);\n if (opts.json) {\n json(rows);\n return;\n }\n if (rows.length === 0) {\n info(name === undefined ? \"no published ports (kvbox vm proxy add <box> <port>)\" : `box ${name} publishes no ports (kvbox vm proxy add ${name} <port>)`);\n return;\n }\n table(rows.map((r) => ({ box: r.box, port: r.guestPort, reaches: r.proto === \"https\" ? r.url : reaches(r, true), proto: r.proto })));\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { clientFor, me } from \"../../../client.js\";\nimport { color, confirm, info, spin } from \"../../../output.js\";\nimport { displayName } from \"../new.js\";\nimport { findBox, requireCloud } from \"./shared.js\";\n\n/** kvbox vm proxy release <box> [-y] — destructive: asks y/N on a TTY, needs -y otherwise (#31) */\nexport const releaseCommand = new Command(\"release\")\n .description(\"give up a box's HTTPS address and every name under it\")\n .argument(\"<box>\", \"box name\")\n .option(\"-y, --yes\", \"do not ask for confirmation\")\n .action(async (name: string, opts: { yes?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n requireCloud(client);\n const box = displayName(await findBox(client, name), me(client));\n if (!(await confirm(`Give up box ${box}'s HTTPS address and every name under it? Anyone may claim it after.`, opts.yes ?? false))) {\n info(\"cancelled\");\n process.exitCode = 1;\n return;\n }\n const sub = await spin(`releasing ${name}'s address…`, client.releaseSubdomain(box));\n const names = sub.routes.length === 0 ? \"\" : ` and ${sub.routes.length} name${sub.routes.length > 1 ? \"s\" : \"\"} under it`;\n info(`${color.green(\"✓\")} ${sub.url.replace(/^https:\\/\\//, \"\")}${names} no longer reach box ${color.bold(box)}`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { assertRouteName } from \"@kvbox/shared/names\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { clientFor, me } from \"../../../client.js\";\nimport { color, confirm, info, spin } from \"../../../output.js\";\nimport { displayName } from \"../new.js\";\nimport { findBox, parsePorts, requireCloud } from \"./shared.js\";\n\n/**\n * kvbox vm proxy rm <box> <port...> [--udp] [-y]\n * kvbox vm proxy rm <box> --name <name> [-y] (#31: frees https://<name>.<subdomain>.kvbox.app)\n * Destructive: asks y/N on a TTY, needs -y otherwise.\n */\nexport const rmCommand = new Command(\"rm\")\n .description(\"stop publishing box ports, or an HTTPS name with --name\")\n .argument(\"<box>\", \"box name\")\n .argument(\"[port...]\", \"ports inside the box, as given to add\")\n .option(\"--udp\", \"the UDP forwards of those ports\")\n .option(\"--name <name>\", \"the HTTPS name to free (kvbox vm proxy release frees the whole subdomain)\")\n .option(\"-y, --yes\", \"do not ask for confirmation\")\n .action(async (name: string, portTexts: string[], opts: { udp?: boolean; name?: string; yes?: boolean }, cmd: Command) => {\n if (opts.name !== undefined) {\n assertRouteName(opts.name);\n if (portTexts.length > 0) throw new KvboxError(\"--name frees a name, not ports: kvbox vm proxy rm <box> --name <name>\");\n } else if (portTexts.length === 0) {\n throw new KvboxError(\"which ports? kvbox vm proxy rm <box> <port...>, or --name <name> for an HTTPS name\");\n }\n const guestPorts = parsePorts(portTexts);\n const proto = opts.udp ? \"udp\" : \"tcp\";\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n if (opts.name !== undefined) requireCloud(client);\n const box = displayName(await findBox(client, name), me(client));\n const question = opts.name !== undefined ? `Stop serving ${opts.name} under box ${box}'s subdomain?` : `Stop publishing port${guestPorts.length > 1 ? \"s\" : \"\"} ${guestPorts.join(\", \")} of box ${box}?`;\n if (!(await confirm(question, opts.yes ?? false))) {\n info(\"cancelled\");\n process.exitCode = 1;\n return;\n }\n if (opts.name !== undefined) {\n const sub = await spin(`freeing ${opts.name} on ${name}…`, client.removeSubdomainRoute(box, opts.name));\n info(`${color.green(\"✓\")} ${opts.name}.${sub.url.replace(/^https:\\/\\//, \"\")} no longer reaches box ${color.bold(box)}`);\n return;\n }\n await spin(`closing ${guestPorts.join(\", \")} on ${name}…`, client.removePorts(box, { ports: guestPorts.map((guestPort) => ({ guestPort, proto })) }));\n info(`${color.green(\"✓\")} box ${color.bold(name)} no longer publishes ${guestPorts.join(\", \")} (${proto})`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { clientFor, me } from \"../../../client.js\";\nimport { color, info, json, spin } from \"../../../output.js\";\nimport { displayName } from \"../new.js\";\nimport { findBox, parsePorts, requireCloud, subdomainJson } from \"./shared.js\";\n\n/** kvbox vm proxy set-port <box> <port> [--json] — --json output: the subdomain, as `claim --json` prints it (#31) */\nexport const setPortCommand = new Command(\"set-port\")\n .description(\"point a box's HTTPS address at another of its ports\")\n .argument(\"<box>\", \"box name\")\n .argument(\"<port>\", \"the box port https://<subdomain>.kvbox.app serves from now on\")\n .option(\"--json\", \"print the subdomain as JSON\")\n .action(async (name: string, portText: string, opts: { json?: boolean }, cmd: Command) => {\n const [port] = parsePorts([portText]);\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n requireCloud(client);\n const box = displayName(await findBox(client, name), me(client));\n const sub = await spin(`pointing ${name} at port ${port}…`, client.setSubdomainPort(box, { port: port! }));\n if (opts.json) {\n json(subdomainJson(sub, me(client)));\n return;\n }\n info(`${color.green(\"✓\")} ${color.bold(sub.url)} → box ${color.bold(box)} port ${sub.port}`);\n } finally {\n await client.close();\n }\n });\n","import { Command, Option } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { SIZE_NAMES, parseMib } from \"@kvbox/shared/sizes\";\nimport { boxesFor, clientFor, me } from \"../../client.js\";\nimport { color, info, json, pickRef, spin } from \"../../output.js\";\nimport { describe, displayName } from \"./new.js\";\n\n/**\n * kvbox vm rescale <name> [--size xs|s|m|l] [--vcpu N] [--mem 16GB] [--disk 32GB] [--json]\n * --json output: the Machine object. Explicit values override the preset; the disk can only grow.\n * Takes effect at boot: a running box is restarted (files intact, processes gone).\n */\nexport const rescaleCommand = new Command(\"rescale\")\n .description(\"change a box's vCPUs, memory or disk (e.g. --vcpu 4 --mem 16GB); a running box restarts\")\n .argument(\"<name>\", \"box name\")\n .addOption(new Option(\"-s, --size <size>\", \"a preset to start from\").choices(SIZE_NAMES))\n .option(\"--vcpu <n>\", \"number of vCPUs\")\n .option(\"--mem <size>\", \"memory, e.g. 16GB or 4096MB\")\n .option(\"--disk <size>\", \"disk size, e.g. 32GB (grow only)\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string, opts: { size?: string; vcpu?: string; mem?: string; disk?: string; json?: boolean }, cmd: Command) => {\n const req = {\n ...(opts.size !== undefined ? { size: opts.size } : {}),\n ...(opts.vcpu !== undefined ? { vcpu: parseCount(opts.vcpu) } : {}),\n ...(opts.mem !== undefined ? { memMib: parseSize(\"--mem\", opts.mem) } : {}),\n ...(opts.disk !== undefined ? { diskGib: parseGib(\"--disk\", opts.disk) } : {}),\n };\n if (Object.keys(req).length === 0) throw new KvboxError(\"nothing to change: give --size, --vcpu, --mem or --disk\");\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const before = pickRef(await boxesFor(client, name), name, me(client));\n if (!before) throw new KvboxError(`box ${name}: not found (kvbox ls)`);\n const box = await spin(`rescaling ${name}…`, client.rescaleMachine(displayName(before, me(client)), req));\n if (opts.json) {\n json(box);\n return;\n }\n const same = box.vcpu === before.vcpu && box.memMib === before.memMib && box.diskBytes === before.diskBytes;\n if (same) {\n info(`box ${name} already has that shape; nothing changed`);\n return;\n }\n info(`${color.green(\"✓\")} ${describe(box)}`);\n if (before.status === \"running\") info(\" it was restarted: processes that were running are gone, files are intact\");\n } finally {\n await client.close();\n }\n });\n\nfunction parseCount(text: string): number {\n const n = Number(text);\n if (!Number.isInteger(n) || n < 1) throw new KvboxError(`--vcpu ${text}: give a whole number of vCPUs`);\n return n;\n}\n\nfunction parseSize(flag: string, text: string): number {\n const mib = parseMib(text);\n if (mib === undefined) throw new KvboxError(`${flag} ${text}: give a size like 16GB or 4096MB`);\n return mib;\n}\n\nfunction parseGib(flag: string, text: string): number {\n const mib = parseSize(flag, text);\n if (mib % 1024 !== 0) throw new KvboxError(`${flag} ${text}: disk sizes are whole GB`);\n return mib / 1024;\n}\n","import { Command } from \"commander\";\nimport { clientFor } from \"../../client.js\";\nimport { color, info, json, spin } from \"../../output.js\";\n\n/** kvbox vm resume <name> [--json] — --json output: the Machine object */\nexport const resumeCommand = new Command(\"resume\")\n .description(\"continue a box that is in standby (kvbox pause)\")\n .argument(\"<name>\", \"box name\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string, opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const box = await spin(`resuming ${name}…`, client.resumeMachine(name));\n if (opts.json) json(box);\n else info(`${color.green(\"✓\")} box ${name} resumed`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { boxesFor, clientFor, me } from \"../../client.js\";\nimport { color, confirm, info, pickRef, spin } from \"../../output.js\";\nimport { displayName } from \"./new.js\";\n\n/**\n * kvbox vm rm <name> [-y] — destructive: asks y/N on a TTY, needs -y otherwise. A bare name is\n * resolved like everywhere else (yours, else the one org box of that name, #68); the question names\n * the box that resolved, `acme/lab1`, so what goes is what you see.\n */\nexport const rmCommand = new Command(\"rm\")\n .description(\"destroy a box (its disk is deleted; snapshots are kept)\")\n .argument(\"<name>\", \"box name\")\n .option(\"-y, --yes\", \"do not ask for confirmation\")\n .action(async (name: string, opts: { yes?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const box = pickRef(await boxesFor(client, name), name, me(client));\n if (!box) throw new KvboxError(`box ${name}: not found (kvbox ls)`);\n // Also what is sent: the control plane must not resolve a second time.\n const ref = displayName(box, me(client));\n if (!(await confirm(`Destroy box ${ref} and its disk?`, opts.yes ?? false))) {\n info(\"cancelled\");\n process.exitCode = 1;\n return;\n }\n await spin(`destroying ${ref}…`, client.deleteMachine(ref));\n const volumes = box.volumes?.map((v) => v.name) ?? [];\n info(`${color.green(\"✓\")} box ${ref} destroyed${volumes.length > 0 ? `; its volume${volumes.length > 1 ? \"s\" : \"\"} ${volumes.join(\", \")} ${volumes.length > 1 ? \"are\" : \"is\"} kept, detached` : \"\"}`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { boxesFor, clientFor, me } from \"../../client.js\";\nimport { color, info, json, pickRef, spin } from \"../../output.js\";\nimport { autoHibernateText, displayName, parseIdleTimeout } from \"./new.js\";\n\n/**\n * kvbox vm set <name> [--auto-hibernate <duration>|off] [--json]\n * --json output: the Machine object (`autoHibernateSec` absent when off). Applies at once, in any state.\n */\nexport const setCommand = new Command(\"set\")\n .description(\"change a box's settings, e.g. --auto-hibernate 30m (off: never)\")\n .argument(\"<name>\", \"box name\")\n .option(\"--auto-hibernate <duration>\", \"hibernate the box after this long without network traffic (30m, 4h, 1d; off: never)\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string, opts: { autoHibernate?: string; json?: boolean }, cmd: Command) => {\n if (opts.autoHibernate === undefined) throw new KvboxError(\"nothing to change: give --auto-hibernate\");\n const autoHibernateSec = parseIdleTimeout(opts.autoHibernate);\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const found = pickRef(await boxesFor(client, name), name, me(client));\n if (!found) throw new KvboxError(`box ${name}: not found (kvbox ls)`);\n const box = await spin(`updating ${name}…`, client.setMachine(displayName(found, me(client)), { autoHibernateSec }));\n if (opts.json) {\n json(box);\n return;\n }\n info(`${color.green(\"✓\")} box ${color.bold(name)}: ${autoHibernateText(box.autoHibernateSec)}`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { clientFor } from \"../../client.js\";\nimport { color, info, json, spin } from \"../../output.js\";\nimport { describe } from \"./new.js\";\n\n/** kvbox vm start <name> [--json] — boot a stopped box from its own disk; --json output: the Machine object */\nexport const startCommand = new Command(\"start\")\n .description(\"boot a stopped box again (same name, IP and disk)\")\n .argument(\"<name>\", \"box name\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string, opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const box = await spin(`booting ${name}…`, client.startMachine(name));\n if (opts.json) json(box);\n else info(`${color.green(\"✓\")} ${describe(box)}`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { clientFor } from \"../../client.js\";\nimport { color, info, json, spin } from \"../../output.js\";\n\n/** kvbox vm stop <name> [--json] — clean shutdown, disk kept; --json output: the Machine object */\nexport const stopCommand = new Command(\"stop\")\n .description(\"shut a box down (its disk is kept; start it again with kvbox start)\")\n .argument(\"<name>\", \"box name\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string, opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const box = await spin(`shutting ${name} down…`, client.stopMachine(name));\n if (opts.json) json(box);\n else info(`${color.green(\"✓\")} box ${name} stopped (disk kept; kvbox start ${name} boots it again)`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport type { GuestStats, Machine } from \"@kvbox/shared/api\";\nimport { clientFor } from \"../../client.js\";\nimport { boxName, color, duration, gbShort, info, json, slugOf, table } from \"../../output.js\";\nimport { ownerCell } from \"./ls.js\";\n\n/** One running box and what its guest said: `stats` null for an image too old to say, `error` when it did not answer. */\nexport interface TopEntry {\n name: string;\n owner: string;\n ownerKind?: \"user\" | \"org\" | undefined;\n stats: GuestStats | null;\n error?: string;\n}\n\n/**\n * kvbox vm top [--all] [--json] — load, memory, disk and uptime of each running box of yours and your orgs' (`--all`: the platform's, admins only), as each guest sees\n * itself (#67). --json output: TopEntry[], i.e. [{ name, owner, ownerKind?, stats: { load: [1m, 5m, 15m],\n * cpus, memTotalMib, memUsedMib, diskTotalBytes, diskUsedBytes, uptimeSec } | null, error? }];\n * `ownerKind` (\"user\" | \"org\") only through a control plane, `stats` is null for a box whose image\n * predates base v0.7.0, `error` says why a box did not answer. Exits 1 when no box answered.\n */\nexport const topCommand = new Command(\"top\")\n .description(\"load, memory and disk of each running box, as the box itself sees them\")\n .option(\"-a, --all\", \"every running box on the platform (platform admins only)\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { all?: boolean; json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const running = (await client.listMachines({ all: opts.all })).filter((b) => b.status === \"running\");\n const entries = await mapLimit(running, ASK_AT_ONCE, async (b: Machine): Promise<TopEntry> => {\n const who = { name: b.name, owner: b.owner, ...(b.ownerKind === undefined ? {} : { ownerKind: b.ownerKind }) };\n try {\n return { ...who, stats: (await client.machineStats(`${slugOf(b.owner)}/${b.name}`)).stats };\n } catch (err) {\n return { ...who, stats: null, error: (err as Error).message };\n }\n });\n if (entries.length > 0 && entries.every((e) => e.error !== undefined)) process.exitCode = 1;\n if (opts.json) {\n json(entries);\n return;\n }\n if (entries.length === 0) {\n info(\"no running boxes\");\n return;\n }\n table(topRows(entries, client.target.kind === \"cloud\" ? { me: client.target.user } : undefined));\n for (const e of entries) if (e.error !== undefined) info(color.dim(`${e.name}: ${e.error}`));\n if (entries.some((e) => e.stats === null && e.error === undefined)) {\n info(color.dim(\"-: the box's image is older than base v0.7.0; kvbox vm update <box> moves it onto the current one\"));\n }\n } finally {\n await client.close();\n }\n });\n\n/** Each answer is a vsock round trip on some host (a forwarded HTTPS call too, through a control plane): a few at a time. */\nconst ASK_AT_ONCE = 8;\n\n/** `fn` over `items`, at most `limit` running at once; results in input order. */\nasync function mapLimit<T, R>(items: readonly T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {\n const out = new Array<R>(items.length);\n let next = 0;\n const worker = async () => {\n while (next < items.length) {\n const i = next++;\n out[i] = await fn(items[i]!);\n }\n };\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\n return out;\n}\n\nconst pct = (used: number, total: number) => (total > 0 ? color.dim(` ${Math.round((used / total) * 100)}%`) : \"\");\n\n/** LOAD is the 1 and 5 minute averages over the box's CPU count; an OWNER column first through a control plane, as in `ls`. */\nexport function topRows(entries: TopEntry[], cloud?: { me?: string | undefined }): Record<string, string>[] {\n return entries.map((e) => {\n const s = e.stats;\n return {\n ...(cloud ? { owner: ownerCell(e, cloud.me) } : {}),\n name: boxName(e.name),\n load: s ? `${s.load[0].toFixed(2)} ${s.load[1].toFixed(2)} ${color.dim(`/${s.cpus}`)}` : \"-\",\n mem: s ? `${gbShort(s.memUsedMib * 1024 ** 2)}/${gbShort(s.memTotalMib * 1024 ** 2)}${pct(s.memUsedMib, s.memTotalMib)}` : \"-\",\n disk: s ? `${gbShort(s.diskUsedBytes)}/${gbShort(s.diskTotalBytes)}${pct(s.diskUsedBytes, s.diskTotalBytes)}` : \"-\",\n // duration() writes \"-\" for 0, which here would read as \"no numbers\".\n uptime: s ? (s.uptimeSec >= 1 ? duration(s.uptimeSec) : \"0s\") : \"-\",\n };\n });\n}\n","import { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { boxesFor, clientFor, me } from \"../../client.js\";\nimport { color, info, json, pickRef, spin } from \"../../output.js\";\nimport { displayName } from \"./new.js\";\n\n/**\n * kvbox vm update <name> [--json] — move a box onto the current base image; --json output: the Machine object.\n * The box's own files stay (they live in its overlay); a running box is restarted, so its processes do not.\n * Snapshots are not updated: they are fixed captures. Make a box from one, update it, snapshot again.\n */\nexport const updateCommand = new Command(\"update\")\n .description(\"move a box onto the current base image (its files stay; a running box restarts)\")\n .argument(\"<name>\", \"box name\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string, opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const before = pickRef(await boxesFor(client, name), name, me(client));\n if (!before) throw new KvboxError(`box ${name}: not found (kvbox ls)`);\n const box = await spin(`updating ${name}…`, client.updateMachine(displayName(before, me(client))));\n if (opts.json) {\n json(box);\n return;\n }\n if (box.base === before.base) {\n info(`box ${name} is already on base image ${box.base}`);\n } else {\n const restarted = before.status === \"running\" ? \" (restarted: processes that were running are gone, files are intact)\" : \"\";\n info(`${color.green(\"✓\")} box ${color.bold(name)} now runs on base image ${box.base} (was ${before.base})${restarted}`);\n }\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport type { MachineUsage } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { clientFor } from \"../../client.js\";\nimport { boxName, color, duration, hours, json, status } from \"../../output.js\";\n\n/**\n * kvbox vm usage <name> [--since <date>] [--json] — --json output: the MachineUsage object.\n * Modeled on boxd's `machine usage`: a right-aligned key/value block.\n */\nexport const usageCommand = new Command(\"usage\")\n .description(\"how long a box ran, slept and sat stopped, as vCPU-hours, RAM and disk GiB-hours (and cost, when the host prices them)\")\n .argument(\"<name>\", \"box name\")\n .option(\"--since <date>\", \"count from this date instead of the box's creation, e.g. 2026-10-01\")\n .option(\"--json\", \"print as JSON\")\n .action(async (name: string, opts: { since?: string; json?: boolean }, cmd: Command) => {\n let since: string | undefined;\n if (opts.since !== undefined) {\n const t = Date.parse(opts.since);\n if (Number.isNaN(t)) throw new KvboxError(`--since ${opts.since}: not a date; write it like 2026-10-19 or 2026-10-19T08:00:00Z`);\n since = new Date(t).toISOString();\n }\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const u = await client.machineUsage(name, since);\n if (opts.json) json(u);\n else process.stdout.write(block(u));\n } finally {\n await client.close();\n }\n });\n\nconst day = (iso: string) => iso.slice(0, 10);\n\nconst SYMBOLS: Record<string, string> = { EUR: \"€\", USD: \"$\", GBP: \"£\" };\nexport function money(amount: number, currency: string): string {\n const sign = amount < 0 ? \"-\" : \"\";\n const n = Math.abs(amount).toFixed(2);\n const sym = SYMBOLS[currency.toUpperCase()];\n return sym === undefined ? `${sign}${n} ${currency}` : `${sign}${sym}${n}`;\n}\n\n/** The human output, one `key: value` per line with the keys right-aligned. */\nexport function block(u: MachineUsage): string {\n const estimated = u.estimatedStops === 0 ? \"\" : color.dim(` (${u.estimatedStops} stop time${u.estimatedStops === 1 ? \"\" : \"s\"} estimated)`);\n const rows: [string, string][] = [\n [\"name\", boxName(u.name)],\n [\"status\", status(u.status)],\n [\"window\", `${day(u.window.from)} to ${day(u.window.to)}`],\n [\"running\", duration(u.seconds.running) + estimated],\n [\"standby\", duration(u.seconds.standby)],\n [\"hibernated\", duration(u.seconds.hibernated)],\n [\"stopped\", duration(u.seconds.stopped)],\n [\"vcpu-h\", hours(u.vcpuHours)],\n [\"ram GiB-h\", hours(u.ramGibHours)],\n [\"disk GiB-h\", hours(u.diskGibHours)],\n ];\n if (u.cost !== undefined) rows.push([\"cost\", `${money(u.cost.amount, u.cost.currency)} ${color.dim(\"(estimated)\")}`]);\n if (u.historyFrom !== null && u.historyFrom > u.window.from) {\n rows.push([\"history\", color.dim(`from ${u.historyFrom.slice(0, 16).replace(\"T\", \" \")} UTC; the box is older, but its time before that was not recorded`)]);\n }\n const w = Math.max(...rows.map(([k]) => k.length));\n return rows.map(([k, v]) => `${\" \".repeat(w - k.length)}${k}: ${v}`).join(\"\\n\") + \"\\n\";\n}\n","import { Command } from \"commander\";\nimport { clientFor } from \"../../client.js\";\nimport { color, info, json, spin } from \"../../output.js\";\n\n/** kvbox vm wake <name> [--json] — --json output: the Machine object */\nexport const wakeCommand = new Command(\"wake\")\n .description(\"continue a hibernated box where it left off (same name, IP and disk)\")\n .argument(\"<name>\", \"box name\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string, opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const box = await spin(`waking ${name} (loading its memory from disk)…`, client.wakeMachine(name));\n if (opts.json) json(box);\n else info(`${color.green(\"✓\")} box ${name} is awake, running where it left off`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { joinCommand } from \"./join.js\";\nimport { leaveCommand } from \"./leave.js\";\nimport { relayCommand } from \"./relay.js\";\nimport { startCommand } from \"./start.js\";\nimport { statusCommand } from \"./status.js\";\nimport { stopCommand } from \"./stop.js\";\nimport { trustCaCommand } from \"./trust-ca.js\";\n\nexport const serverCommand = new Command(\"server\")\n .description(\"run or manage the kvbox server\")\n .addCommand(startCommand)\n .addCommand(statusCommand)\n .addCommand(stopCommand)\n .addCommand(joinCommand)\n .addCommand(leaveCommand)\n .addCommand(relayCommand)\n .addCommand(trustCaCommand);\n","import { Command } from \"commander\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { info, spin } from \"../../output.js\";\nimport { restartLocalServer, runKvboxServer } from \"./daemon.js\";\n\n/** kvbox server join <url> --token <t> — `kvbox-server join`, then restart the daemon so it answers the control plane now. */\nexport const joinCommand = new Command(\"join\")\n .description(\"put this machine behind a control plane (needs a one-time token minted there) and restart its server\")\n .argument(\"<control-plane-url>\", \"the control plane, e.g. https://api.kvbox.sh\")\n .requiredOption(\"--token <token>\", \"one-time join token from the control plane\")\n .option(\"--advertise <host-or-ip>\", \"address the control plane reaches this machine at (default: its default-route address)\")\n .option(\"--name <name>\", \"how the control plane lists this machine (default: hostname)\")\n .action(async (url: string, opts: { token: string; advertise?: string; name?: string }) => {\n const args = [\"join\", url, \"--token\", opts.token];\n if (opts.advertise !== undefined) args.push(\"--advertise\", opts.advertise);\n if (opts.name !== undefined) args.push(\"--name\", opts.name);\n for (const line of (await runKvboxServer(args)).split(\"\\n\")) info(line);\n const pid = await spin(\"restarting kvbox-server…\", restartLocalServer(paths()));\n info(`kvbox-server restarted (pid ${pid}); it answers the control plane now`);\n });\n","/**\n * This machine's kvbox-server as a process: stop it, wait for it to be gone, start it again, and run\n * its one-off subcommands (`kvbox-server join|leave`) from PATH. The CLI never imports server code.\n */\nimport { spawn } from \"node:child_process\";\nimport { readFile } from \"node:fs/promises\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { NOT_A_HOST_HINT, startLocalServer } from \"../../client.js\";\n\n/** The pid in server.pid when that process exists, else null. */\nexport async function runningPid(p: Paths = paths()): Promise<number | null> {\n let pid: number;\n try {\n pid = Number.parseInt(await readFile(p.serverPid, \"utf8\"), 10);\n } catch {\n return null;\n }\n return alive(pid) ? pid : null;\n}\n\nfunction alive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/** SIGTERM the daemon and resolve once the process is gone (boxes keep running). */\nexport async function stopLocalServer(pid: number, timeoutMs = 10_000): Promise<void> {\n process.kill(pid, \"SIGTERM\");\n const deadline = Date.now() + timeoutMs;\n while (alive(pid)) {\n if (Date.now() > deadline) throw new KvboxError(`kvbox-server (pid ${pid}) did not stop within ${timeoutMs / 1000}s`);\n await sleep(100);\n }\n}\n\n/** Stop the daemon when it runs, then start it: the way it picks up a join or a leave. Returns the new pid. */\nexport async function restartLocalServer(p: Paths = paths()): Promise<number> {\n const pid = await runningPid(p);\n if (pid !== null) await stopLocalServer(pid);\n return (await startLocalServer(p)).pid;\n}\n\n/**\n * Run `kvbox-server <args>` to completion and return what it printed. Its `error: …` line becomes\n * the thrown message; no binary on PATH is the not-a-host hint, like auto-start.\n */\nexport function runKvboxServer(args: string[]): Promise<string> {\n return new Promise((resolve, reject) => {\n const child = spawn(\"kvbox-server\", args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n let out = \"\";\n let err = \"\";\n child.stdout.on(\"data\", (chunk: Buffer) => (out += chunk.toString()));\n child.stderr.on(\"data\", (chunk: Buffer) => (err += chunk.toString()));\n child.once(\"error\", (e: NodeJS.ErrnoException) => {\n reject(new KvboxError(e.code === \"ENOENT\" ? NOT_A_HOST_HINT : `could not run kvbox-server: ${e.message}`));\n });\n child.once(\"close\", (code) => { // close, not exit: stderr is fully read by then\n if (code === 0) resolve(out.trimEnd());\n else reject(new KvboxError(err.trim().replace(/^error: /, \"\") || `kvbox-server ${args[0] ?? \"\"} exited with code ${String(code)}`, code === 2 ? 2 : 1));\n });\n });\n}\n","import { Command } from \"commander\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { info, spin } from \"../../output.js\";\nimport { restartLocalServer, runKvboxServer, runningPid } from \"./daemon.js\";\n\n/** kvbox server leave — `kvbox-server leave`, then restart a running daemon so the HTTPS port closes now. */\nexport const leaveCommand = new Command(\"leave\")\n .description(\"take this machine out from behind its control plane and restart its server\")\n .action(async () => {\n const p = paths();\n for (const line of (await runKvboxServer([\"leave\"])).split(\"\\n\")) info(line);\n if ((await runningPid(p)) === null) return;\n const pid = await spin(\"restarting kvbox-server…\", restartLocalServer(p));\n info(`kvbox-server restarted (pid ${pid}); only this machine talks to it now`);\n });\n","import { Command } from \"commander\";\nimport { info } from \"../../output.js\";\nimport { runKvboxServer } from \"./daemon.js\";\n\n/**\n * kvbox server relay <join-string> | off — `kvbox-server relay`: dial the tunnel to a relay that lends\n * this machine a public IP (what `kvbox-relay add` printed there), or take it down. No daemon restart:\n * the HTTPS listener already answers on every address.\n */\nexport const relayCommand = new Command(\"relay\")\n .description(\"reach the internet through a relay (paste what `kvbox-relay add` printed on the relay VM); `off` takes the tunnel down\")\n .argument(\"<join-string>\", \"the line `kvbox-relay add` printed, or `off`\")\n .action(async (joinString: string) => {\n for (const line of (await runKvboxServer([\"relay\", joinString])).split(\"\\n\")) info(line);\n });\n","/**\n * kvbox server start\n * Starts the local `kvbox-server` (a separate package) detached, logging to\n * ~/.kvbox/server.log, and waits for its socket. The CLI never imports server code.\n */\nimport { Command } from \"commander\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { clientFor, startLocalServer } from \"../../client.js\";\nimport { info } from \"../../output.js\";\n\nexport const startCommand = new Command(\"start\")\n .description(\"start the local kvbox-server in the background\")\n .action(async (_opts: Record<string, never>, cmd: Command) => {\n const client = await clientFor({ ...cmd.optsWithGlobals(), local: true }, { autoStart: false }); // this machine, whatever kvbox login says\n try {\n const health = await client.health();\n info(`kvbox-server ${health.version} is already running (pid ${health.pid})`);\n return;\n } catch {\n // not running: start it\n } finally {\n await client.close();\n }\n const { pid, socketPath, viaGroup } = await startLocalServer(paths());\n info(`kvbox-server started (pid ${pid}), listening on ${socketPath}`);\n if (viaGroup !== undefined) info(`started through the ${viaGroup} group, which this shell does not have yet (log out and back in to get it)`);\n });\n","import { Command } from \"commander\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { clientFor } from \"../../client.js\";\nimport { info, json } from \"../../output.js\";\nimport { startsAtBoot } from \"../../systemd.js\";\n\n/**\n * kvbox server status [--json] — --json output: Health (version, pid, base image new boxes get, control plane,\n * `relay` with `restarts`/`lastRestartAt` (tunnel redials since the server started),\n * `recovery`: boxes brought back at the server's last start) plus `startsAtBoot` (the systemd unit is enabled, #29)\n */\nexport const statusCommand = new Command(\"status\")\n .description(\"show whether this machine's server is running, its control plane and which base image new boxes get\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor({ ...cmd.optsWithGlobals(), local: true }); // this machine, whatever kvbox login says\n try {\n const health = await client.health();\n const atBoot = startsAtBoot(paths());\n if (opts.json) json({ ...health, startsAtBoot: atBoot });\n else {\n info(`kvbox-server ${health.version} running, pid ${health.pid}`);\n info(atBoot ? \"starts at boot: yes, and brings back the boxes that were running\" : \"starts at boot: no (install-server.sh sets that up)\");\n const r = health.recovery;\n if (r) {\n if (r.booted.length > 0) info(`after the last restart it booted again: ${r.booted.join(\", \")}`);\n if (r.leftStopped.length > 0) info(`left stopped (were in standby, their memory was lost): ${r.leftStopped.join(\", \")}`);\n for (const f of r.failed) info(`did not come back: ${f.box} (${f.error})`);\n }\n if (health.controlPlane) info(`control plane: ${health.controlPlane.name} at ${health.controlPlane.url}, this host answers it on ${health.controlPlane.hostUrl}`);\n else info(\"control plane: none (kvbox server join <url> --token <token> puts this machine behind one)\");\n if (health.relay) {\n info(`relay: ${health.relay.name} lends this machine ${health.relay.publicIp} (tunnel to ${health.relay.endpoint})`);\n if (health.relay.restarts && health.relay.lastRestartAt) {\n info(`the tunnel stopped carrying traffic and was redialed ${health.relay.restarts} time(s) since the server started, last at ${health.relay.lastRestartAt}`);\n }\n }\n if (health.base === null) info(\"base image: none usable yet (run install-server.sh)\");\n else info(`base image: ${health.base} (what kvbox new uses; kvbox vm update <box> moves an older box onto it)`);\n }\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths } from \"@kvbox/shared/paths\";\nimport { info } from \"../../output.js\";\nimport { runningPid, stopLocalServer } from \"./daemon.js\";\n\n/** kvbox server stop — SIGTERM the pid in server.pid and wait for it to go. Boxes keep running. */\nexport const stopCommand = new Command(\"stop\")\n .description(\"stop the local server (running boxes are not affected)\")\n .action(async () => {\n const pid = await runningPid(paths());\n if (pid === null) throw new KvboxError(\"kvbox-server is not running\");\n await stopLocalServer(pid);\n info(`kvbox-server stopped (pid ${pid})`);\n });\n","import { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport type { SshKeysApplied, TrustCaReport } from \"@kvbox/shared/api\";\nimport { clientFor } from \"../../client.js\";\nimport { confirm, info, json, warn } from \"../../output.js\";\n\n/**\n * kvbox server trust-ca [public-key] [--from-cloud] [-y] [--json] — every cloud box on this machine\n * trusts a new SSH CA (#55), the step after `ca rotate` on the control plane. Works over this\n * machine's socket only: the control plane cannot ask a host to trust a CA.\n * --json output: TrustCaReport {publicKey, fingerprint, updated: [\"owner/name\"], pending: [{box, when, why?}], failed: [{box, error}], local}\n */\nexport const trustCaCommand = new Command(\"trust-ca\")\n .description(\"make every cloud box on this machine trust a new SSH CA (after `ca rotate` on the control plane)\")\n .argument(\"[public-key]\", \"the CA public key (or its cert-authority line); or --from-cloud\")\n .option(\"--from-cloud\", \"ask the control plane this host joined for its current CA, show the fingerprint, then ask\")\n .option(\"-y, --yes\", \"do not ask for confirmation\")\n .option(\"--json\", \"print the report as JSON\")\n .action(async (publicKey: string | undefined, opts: { fromCloud?: boolean; yes?: boolean; json?: boolean }, cmd: Command) => {\n if (publicKey === undefined && !opts.fromCloud) throw new KvboxError(\"give the CA public key, or --from-cloud to fetch it from the control plane this host joined\");\n if (publicKey !== undefined && opts.fromCloud) throw new KvboxError(\"either a public key or --from-cloud, not both\");\n const client = await clientFor({ ...cmd.optsWithGlobals(), local: true }); // this machine, whatever kvbox login says\n try {\n let key = publicKey;\n if (key === undefined) {\n const ca = await client.cloudCa();\n info(`${ca.controlPlane} says its SSH CA is ${ca.fingerprint}`);\n if (!(await confirm(`make every cloud box on this machine trust it (in place of the CA it trusts now)?`, opts.yes ?? false))) {\n throw new KvboxError(\"cancelled\", 130);\n }\n key = ca.publicKey;\n }\n const report = await client.trustCa({ publicKey: key });\n if (opts.json) json(report);\n else describeReport(report);\n } finally {\n await client.close();\n }\n });\n\nconst WHEN: Record<Exclude<SshKeysApplied, \"now\">, string> = {\n start: \"is stopped: it trusts the CA from its next start\",\n wake: \"is hibernated: it trusts the CA from its next wake\",\n resume: \"is in standby: it trusts the CA from its next resume\",\n later: \"is running but could not take it now; it trusts the CA from its next stop and start\",\n};\n\nexport function describeReport(report: TrustCaReport): void {\n info(`CA ${report.fingerprint}`);\n for (const box of report.updated) info(`box ${box} now trusts the CA`);\n for (const p of report.pending) info(`box ${p.box} ${WHEN[p.when as Exclude<SshKeysApplied, \"now\">]}${p.why ? ` (${p.why})` : \"\"}`);\n for (const f of report.failed) warn(`box ${f.box}: ${f.error}`);\n const parts = [`${report.updated.length} box(es) updated now`, `${report.pending.length} pending`, `${report.failed.length} failed`];\n if (report.local > 0) parts.push(`${report.local} local box(es) untouched (they trust this host's key only)`);\n info(parts.join(\", \"));\n}\n","import { spawnSync } from \"node:child_process\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { hostname as osHostname } from \"node:os\";\nimport { createInterface } from \"node:readline/promises\";\nimport { Writable, type Readable } from \"node:stream\";\nimport { Command } from \"commander\";\nimport { DEFAULT_CLOUD_URL } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { writeCert } from \"../cert.js\";\nimport { ServerClient } from \"../client.js\";\nimport { info } from \"../output.js\";\nimport { askLine } from \"../prompt.js\";\nimport { hostOf, normalizeUrl, writeSession, type Session } from \"../session.js\";\n\n/**\n * kvbox login [url] [--email <email>] [--password-stdin]\n * Exchanges email + password for a bearer token at the control plane (default api.kvbox.sh),\n * uploads this machine's SSH public key (generated under ~/.kvbox/ssh if missing), stores the\n * certificate the control plane signs it with next to the key (#51) and the session in ~/.kvbox/cli.json. From then on every command targets the\n * control plane; `--local` or `kvbox logout` goes back to this machine's socket.\n */\nexport const loginCommand = new Command(\"login\")\n .description(\"log in to the kvbox cloud (or your own control plane) and target it from now on\")\n .argument(\"[url]\", `control plane URL (default: ${DEFAULT_CLOUD_URL})`)\n .option(\"-e, --email <email>\", \"account email (prompted otherwise)\")\n .option(\"--password-stdin\", \"read the password from the first line of stdin (for scripts)\")\n .action(async (urlArg: string | undefined, opts: { email?: string; passwordStdin?: boolean }) => {\n const url = normalizeUrl(urlArg ?? DEFAULT_CLOUD_URL);\n const creds = await readCredentials(opts);\n const session = await runLogin(url, creds, paths());\n info(`logged in to ${hostOf(url)} as ${session.user}`);\n });\n\nexport interface Credentials {\n email: string;\n password: string;\n}\n\ninterface Stdio {\n stdin: Readable;\n /** Whether stdin is a terminal we may prompt on. */\n isTTY: boolean;\n}\n\n/** Email and password from flags, the first line of stdin (`--password-stdin`) or a prompt. */\nexport async function readCredentials(\n opts: { email?: string; passwordStdin?: boolean },\n io: Stdio = { stdin: process.stdin, isTTY: process.stdin.isTTY === true },\n): Promise<Credentials> {\n const noTerminal = () => new KvboxError(\"stdin is not a terminal: pass --email and --password-stdin\");\n let email = opts.email;\n if (email === undefined) {\n if (!io.isTTY) throw noTerminal();\n email = await prompt(\"email: \", { input: process.stdin, output: process.stderr });\n }\n let password: string;\n if (opts.passwordStdin) password = await firstLine(io.stdin);\n else if (io.isTTY) password = await promptSecret(\"password: \", { input: process.stdin, output: process.stderr });\n else throw noTerminal();\n if (email === \"\") throw new KvboxError(\"email is empty\");\n if (password === \"\") throw new KvboxError(\"password is empty\");\n return { email, password };\n}\n\n/** The login itself, minus the prompting: key, request, session file. Returns what was stored. */\nexport async function runLogin(url: string, creds: Credentials, p: Paths = paths(), hostname: string = osHostname()): Promise<Session> {\n const publicKey = await ensureSshKey(p, hostname);\n const client = new ServerClient({ kind: \"cloud\", url, token: \"\" }, { autoStart: false });\n let res;\n try {\n res = await client.login({ email: creds.email, password: creds.password, publicKey });\n } finally {\n await client.close();\n }\n const session: Session = { url, token: res.token, user: res.user.username };\n if (res.sshCert !== undefined && res.sshCertExpires !== undefined) {\n await writeCert(res.sshCert, p);\n session.sshCertExpires = res.sshCertExpires;\n if (res.sshCertPrincipals !== undefined) session.sshCertPrincipals = res.sshCertPrincipals;\n }\n await writeSession(session, p);\n return session;\n}\n\n/**\n * This machine's kvbox SSH key, generated on first use (`ssh-keygen -t ed25519`, no passphrase,\n * comment `kvbox@<hostname>` so it is recognisable in a box's authorized_keys). Returns the public key line.\n */\nexport async function ensureSshKey(p: Paths = paths(), hostname: string = osHostname()): Promise<string> {\n const pubPath = `${p.sshKey}.pub`;\n const pub = await readFile(pubPath, \"utf8\").catch(() => null);\n if (pub !== null) return pub.trim();\n await mkdir(p.ssh, { recursive: true, mode: 0o700 });\n const havePrivate = await readFile(p.sshKey).then(() => true, () => false);\n const args = havePrivate\n ? [\"-y\", \"-f\", p.sshKey] // private key without its .pub: derive it instead of overwriting the key\n : [\"-q\", \"-t\", \"ed25519\", \"-N\", \"\", \"-C\", `kvbox@${hostname}`, \"-f\", p.sshKey];\n const res = spawnSync(\"ssh-keygen\", args, { stdio: [\"ignore\", \"pipe\", \"pipe\"], encoding: \"utf8\" });\n if (res.error) {\n if ((res.error as NodeJS.ErrnoException).code === \"ENOENT\") throw new KvboxError(\"ssh-keygen not found; install OpenSSH\");\n throw new KvboxError(`could not run ssh-keygen: ${res.error.message}`);\n }\n if (res.status !== 0) throw new KvboxError(`ssh-keygen failed: ${res.stderr.trim()}`);\n if (havePrivate) await writeFile(pubPath, res.stdout.trim() + \"\\n\");\n return (await readFile(pubPath, \"utf8\")).trim();\n}\n\ninterface PromptIo {\n input: Readable;\n output: Writable;\n}\n\nexport async function prompt(question: string, io: PromptIo): Promise<string> {\n const rl = createInterface({ input: io.input, output: io.output });\n return (await askLine(rl, question)).trim();\n}\n\n/** A prompt that does not echo: readline in terminal mode writing to a sink; the question goes to `output` by hand. */\nexport async function promptSecret(question: string, io: PromptIo): Promise<string> {\n const sink = new Writable({ write: (_chunk, _enc, cb) => cb() });\n const rl = createInterface({ input: io.input, output: sink, terminal: true });\n io.output.write(question);\n try {\n return await askLine(rl, question);\n } finally {\n io.output.write(\"\\n\");\n }\n}\n\nasync function firstLine(stream: Readable): Promise<string> {\n const rl = createInterface({ input: stream });\n try {\n for await (const line of rl) return line.trim();\n return \"\";\n } finally {\n rl.close();\n }\n}\n","/**\n * Interactive questions for commands that set something up (`kvbox deploy`): a list to pick from\n * with the arrow keys and a line of text with a default. Node built-ins only (raw mode on stdin,\n * a few ANSI sequences on stderr), so the CLI keeps its five runtime libraries.\n *\n * Every question is a terminal thing: a command asks only on a TTY and takes defaults or flags\n * otherwise (`-y`). Answered, a question collapses to one line, `✓ Name myapp`, so the terminal\n * reads like a summary afterwards. Ctrl-C (or Ctrl-D) throws `KvboxError(\"cancelled\", 130)`, so the\n * command's cleanup runs and the exit code is an interrupted command's.\n */\nimport { createInterface, type Interface } from \"node:readline/promises\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { color } from \"./output.js\";\n\nexport interface Choice<T extends string> {\n value: T;\n label: string;\n /** A few dim words after the label: what picking it means. */\n hint?: string;\n}\n\n/** Whether questions can be asked at all: both ends must be a terminal. */\nexport function interactive(): boolean {\n return process.stdin.isTTY === true && process.stderr.isTTY === true;\n}\n\nconst ESC = \"\\x1b\";\nconst ENTER = \"\\r\";\nconst CTRL_C = \"\\x03\";\nconst CTRL_D = \"\\x04\";\n\n/** The cancel every question ends in. */\nexport const cancelled = (): KvboxError => new KvboxError(\"cancelled\", 130);\n\n/**\n * The keys in one chunk from a raw-mode stdin: an escape sequence (`ESC [ A`, or `ESC O A` from a\n * terminal in application-cursor mode) is one key, anything else one character each. A paste or\n * two fast keys arrive as one chunk; every key in it counts.\n */\nexport function keysIn(chunk: string): string[] {\n const keys: string[] = [];\n for (let i = 0; i < chunk.length; ) {\n if (chunk[i] === ESC && (chunk[i + 1] === \"[\" || chunk[i + 1] === \"O\") && i + 2 < chunk.length) {\n keys.push(chunk.slice(i, i + 3));\n i += 3;\n } else {\n keys.push(chunk[i]!);\n i += 1;\n }\n }\n return keys;\n}\n\nconst isUp = (k: string) => k === `${ESC}[A` || k === `${ESC}OA` || k === \"k\";\nconst isDown = (k: string) => k === `${ESC}[B` || k === `${ESC}OB` || k === \"j\";\n\n// eslint-disable-next-line no-control-regex\nconst ANSI = /\\x1b\\[[0-9;]*[A-Za-z]/g;\n/** Terminal rows a line takes once wrapped at the terminal's width (a narrow pane wraps a long hint). */\nexport function rows(line: string, columns = process.stderr.columns ?? 80): number {\n const width = line.replace(ANSI, \"\").length;\n return Math.max(1, Math.ceil(width / Math.max(1, columns)));\n}\n\n/** The line a settled question leaves behind. */\nfunction settled(message: string, answer: string): string {\n return `${color.green(\"✓\")} ${color.bold(message)} ${color.cyan(answer)}`;\n}\n\n/** Pick one of `choices` with ↑/↓ (or j/k), Enter to confirm. `initial` is the index highlighted first. */\nexport async function select<T extends string>(message: string, choices: readonly Choice<T>[], initial = 0): Promise<T> {\n const out = process.stderr;\n const inp = process.stdin;\n let index = Math.min(Math.max(initial, 0), choices.length - 1);\n let drawn = 0;\n\n const render = (): void => {\n if (drawn > 0) out.write(`${ESC}[${drawn}A`);\n const lines = [\n `${color.green(\"?\")} ${color.bold(message)} ${color.dim(\"↑↓ to move, enter to pick\")}`,\n ...choices.map((c, i) => {\n const hint = c.hint ? color.dim(` ${c.hint}`) : \"\";\n return i === index ? `${color.cyan(`❯ ${c.label}`)}${hint}` : ` ${c.label}${hint}`;\n }),\n ];\n out.write(`\\r${ESC}[J${lines.join(\"\\n\")}\\n`);\n drawn = lines.reduce((n, l) => n + rows(l), 0);\n };\n\n inp.setRawMode(true);\n inp.resume();\n inp.setEncoding(\"utf8\");\n render();\n let done = false;\n try {\n return await new Promise<T>((resolve, reject) => {\n const onData = (chunk: string): void => {\n for (const key of keysIn(chunk)) {\n if (isUp(key)) index = (index - 1 + choices.length) % choices.length;\n else if (isDown(key)) index = (index + 1) % choices.length;\n else if (key === ENTER || key === \"\\n\") {\n inp.off(\"data\", onData);\n done = true;\n resolve(choices[index]!.value);\n return;\n } else if (key === CTRL_C || key === CTRL_D) {\n inp.off(\"data\", onData);\n reject(cancelled());\n return;\n } else continue;\n render();\n }\n };\n inp.on(\"data\", onData);\n });\n } finally {\n inp.setRawMode(false);\n inp.pause();\n out.write(`${ESC}[${drawn}A\\r${ESC}[J${done ? `${settled(message, choices[index]!.label)}\\n` : \"\"}`);\n }\n}\n\nexport interface TextOptions {\n /** Taken when the user just presses Enter; shown dim in the prompt. */\n default?: string;\n /** Why an answer is not acceptable, or undefined when it is; the question is asked again. */\n validate?: (answer: string) => string | undefined;\n}\n\n/** One line of text. Empty takes the default; an answer `validate` rejects is explained and asked again. */\nexport async function text(message: string, opts: TextOptions = {}): Promise<string> {\n const out = process.stderr;\n for (;;) {\n const hint = opts.default !== undefined ? ` ${color.dim(`(${opts.default})`)}` : \"\";\n const question = `${color.green(\"?\")} ${color.bold(message)}${hint} ${color.dim(\"›\")} `;\n const rl = createInterface({ input: process.stdin, output: out });\n const raw = (await askLine(rl, question)).trim();\n const answer = raw === \"\" && opts.default !== undefined ? opts.default : raw;\n const problem = opts.validate?.(answer);\n // readline moved to the next line: rewrite the question (as many rows as it wrapped to) as its settled form.\n out.write(`${ESC}[${rows(question + raw)}A\\r${ESC}[J`);\n if (problem === undefined) {\n out.write(`${settled(message, answer)}\\n`);\n return answer;\n }\n out.write(`${color.yellow(\"!\")} ${problem}\\n`);\n }\n}\n\n/**\n * One question on a readline interface, closing it afterwards. Ctrl-C in terminal mode rejects the\n * question (ABORT_ERR); Ctrl-D or EOF only closes the interface and would leave the question pending\n * forever, so a close before the answer is treated the same way: the user cancelled (exit 130).\n */\nexport async function askLine(rl: Interface, question: string): Promise<string> {\n let onClose = () => {};\n const closed = new Promise<never>((_, reject) => {\n onClose = () => reject(cancelled());\n rl.once(\"close\", onClose);\n });\n try {\n return await Promise.race([rl.question(question).catch(abortIsCancel), closed]);\n } finally {\n rl.off(\"close\", onClose);\n rl.close();\n }\n}\n\nfunction abortIsCancel(err: unknown): never {\n if ((err as NodeJS.ErrnoException).code === \"ABORT_ERR\") throw cancelled();\n throw err;\n}\n","import { Command } from \"commander\";\nimport { paths, type Paths } from \"@kvbox/shared/paths\";\nimport { removeCert } from \"../cert.js\";\nimport { ServerClient } from \"../client.js\";\nimport { info } from \"../output.js\";\nimport { clearSession, hostOf, readSession } from \"../session.js\";\n\n/** kvbox logout — revoke the token at the control plane (best effort) and forget the session: back to local mode. */\nexport const logoutCommand = new Command(\"logout\")\n .description(\"log out of the control plane; commands target this machine's kvbox-server again\")\n .action(async () => {\n const p = paths();\n const session = await readSession(p).catch(() => null);\n switch (await runLogout(p)) {\n case \"none\":\n info(\"not logged in\");\n break;\n case \"unreadable\":\n info(`logged out (${p.cli} was unreadable and is gone)`);\n break;\n case \"cleared\":\n info(`logged out of ${hostOf(session?.url ?? \"\")}`);\n }\n });\n\n/**\n * The logout itself. An unreadable cli.json is cleared too: logout is the way out that\n * readSession's error points at, so it must never refuse.\n */\nexport async function runLogout(p: Paths = paths()): Promise<\"none\" | \"cleared\" | \"unreadable\"> {\n let session;\n try {\n session = await readSession(p);\n } catch {\n await clearSession(p);\n await removeCert(p);\n return \"unreadable\";\n }\n if (!session) return \"none\";\n const client = new ServerClient({ kind: \"cloud\", url: session.url, token: session.token }, { autoStart: false });\n try {\n await client.logout();\n } catch {\n // unreachable or already revoked: the local file is what matters\n } finally {\n await client.close();\n }\n await clearSession(p);\n await removeCert(p); // the certificate belonged to this login; the key stays for the next one\n return \"cleared\";\n}\n","import { Command } from \"commander\";\nimport { json } from \"../output.js\";\nimport { hostOf, readSession, type Session } from \"../session.js\";\n\n/** kvbox whoami [--json] — the stored login, without a network call. --json: { user, url, sshCertExpires } or null. */\nexport const whoamiCommand = new Command(\"whoami\")\n .description(\"show which account and control plane commands target (or local mode)\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { json?: boolean }) => {\n const session = await readSession();\n if (opts.json) {\n json(session ? { user: session.user, url: session.url, sshCertExpires: session.sshCertExpires ?? null } : null);\n return;\n }\n process.stdout.write(describeSession(session) + \"\\n\");\n });\n\n/** \"ghalex on api.kvbox.sh\" plus the certificate's expiry day. */\nexport function describeSession(session: Session | null): string {\n if (!session) return \"not logged in (local mode)\";\n const lines = [`${session.user} on ${hostOf(session.url)}`];\n if (session.sshCertExpires) lines.push(`certificate valid until ${session.sshCertExpires.slice(0, 10)}`);\n return lines.join(\"\\n\");\n}\n","import { Command } from \"commander\";\nimport { lsCommand } from \"./ls.js\";\nimport { newCommand } from \"./new.js\";\nimport { rmCommand } from \"./rm.js\";\n\nexport const snapshotsCommand = new Command(\"snapshots\")\n .aliases([\"snapshot\", \"snap\"])\n .description(\"freeze running boxes into snapshots and manage them\")\n .addCommand(newCommand)\n .addCommand(lsCommand)\n .addCommand(rmCommand);\n\nfor (const cmd of snapshotsCommand.commands) cmd.option(\"--org <slug>\", \"act in this org (- for your personal boxes)\");\n","import { Command } from \"commander\";\nimport { clientFor } from \"../../client.js\";\nimport { age, boxName, gbShort, info, json, shape, shortRef, slugOf, table } from \"../../output.js\";\n\n/** kvbox snapshots ls [--all] [--json] — the user's and their orgs' snapshots (`--org <slug>` for one org, `--all` the whole platform for a platform admin). --json output: Snapshot[] */\nexport const lsCommand = new Command(\"ls\")\n .description(\"list snapshots (yours and your orgs'; --org <slug> for one org)\")\n .option(\"-a, --all\", \"every snapshot on the platform (platform admins only)\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { all?: boolean; json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const cloud = client.target.kind === \"cloud\";\n const snaps = await client.listSnapshots({ all: opts.all });\n if (opts.json) {\n json(snaps);\n return;\n }\n if (snaps.length === 0) {\n info(\"no snapshots yet; freeze a running box with: kvbox snapshots new <box> <name>\");\n return;\n }\n const org = client.target.kind === \"cloud\" ? client.target.org : undefined;\n if (org !== undefined) info(`snapshots of ${org}`);\n // Base image version stays in --json; a restore checks it, a reader rarely needs it.\n table(\n snaps.map((s) => ({\n ...(cloud ? { owner: slugOf(s.owner) === client.target.user ? \"private\" : slugOf(s.owner) } : {}),\n name: boxName(s.name),\n \"from box\": shortRef(s.source, s.owner),\n shape: shape(s.vcpu, s.memMib),\n \"on disk\": gbShort(s.sizeBytes),\n created: age(s.createdAt),\n })),\n );\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { clientFor } from \"../../client.js\";\nimport { color, gb, info, json, spin } from \"../../output.js\";\n\n/** kvbox snapshots new <box> <name> [--json] — --json output: Snapshot */\nexport const newCommand = new Command(\"new\")\n .description(\"freeze a running box (memory + disk) into a snapshot; the box keeps running\")\n .argument(\"<box>\", \"box name\")\n .argument(\"<name>\", \"snapshot name\")\n .option(\"--json\", \"print the snapshot as JSON\")\n .action(async (box: string, name: string, opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const snap = await spin(`saving snapshot ${name} from box ${box} (memory + disk)…`, client.createSnapshot({ box, name }));\n if (opts.json) json(snap);\n else info(`${color.green(\"✓\")} snapshot ${name} saved from box ${box} (${gb(snap.sizeBytes)} on disk); start a warm clone with: kvbox new --from ${name}`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { clientFor } from \"../../client.js\";\nimport { color, confirm, info, spin } from \"../../output.js\";\n\n/** kvbox snapshots rm <name> [-y] — destructive: asks y/N on a TTY, needs -y otherwise */\nexport const rmCommand = new Command(\"rm\")\n .description(\"delete a snapshot (boxes made from it are not affected)\")\n .argument(\"<name>\", \"snapshot name\")\n .option(\"-y, --yes\", \"do not ask for confirmation\")\n .action(async (name: string, opts: { yes?: boolean }, cmd: Command) => {\n if (!(await confirm(`Delete snapshot ${name}?`, opts.yes ?? false))) {\n info(\"cancelled\");\n process.exitCode = 1;\n return;\n }\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n await spin(`deleting snapshot ${name}…`, client.deleteSnapshot(name));\n info(`${color.green(\"✓\")} snapshot ${name} deleted`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { lsCommand } from \"./ls.js\";\nimport { membersCommand } from \"./members.js\";\nimport { newCommand } from \"./new.js\";\nimport { rmCommand } from \"./rm.js\";\nimport { roleCommand } from \"./role.js\";\n\n/** kvbox org … — orgs own boxes like a user does; members work in them by role (control plane only). */\nexport const orgCommand = new Command(\"org\")\n .description(\"orgs: shared slugs that own boxes, with owners, admins and members\")\n .addCommand(lsCommand)\n .addCommand(newCommand)\n .addCommand(membersCommand)\n .addCommand(roleCommand)\n .addCommand(rmCommand);\n","import { Command } from \"commander\";\nimport type { OrgMembership } from \"@kvbox/shared/api\";\nimport { age, boxName, info, json, table } from \"../../output.js\";\nimport { cloudClientFor } from \"./context.js\";\n\n/** kvbox org ls [--json] — the user's orgs with their role in each. --json: OrgMembership[] */\nexport const lsCommand = new Command(\"ls\")\n .description(\"list the orgs you belong to and your role in each\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { json?: boolean }, cmd: Command) => {\n const client = await cloudClientFor(cmd.optsWithGlobals());\n try {\n const orgs = await client.listOrgs();\n if (opts.json) {\n json(orgs);\n return;\n }\n if (orgs.length === 0) {\n info(\"you are in no org yet; make one with: kvbox org new <slug>\");\n return;\n }\n table(orgRows(orgs));\n } finally {\n await client.close();\n }\n });\n\nexport function orgRows(orgs: OrgMembership[]): Record<string, string>[] {\n return orgs.map((o) => ({ org: boxName(o.slug), name: o.name, role: o.role, since: age(o.createdAt) }));\n}\n","import { KvboxError } from \"@kvbox/shared/errors\";\nimport { clientFor, type GlobalOptions, type ServerClient, type Target } from \"../../client.js\";\n\nconst NOT_LOGGED_IN = \"orgs live on the control plane: kvbox login first\";\n\n/** A client for an org command: the control plane or nothing (never the local daemon, which has no orgs). */\nexport async function cloudClientFor(opts: GlobalOptions): Promise<ServerClient> {\n const client = await clientFor(opts, { autoStart: false });\n if (client.target.kind === \"local\") {\n await client.close();\n throw new KvboxError(NOT_LOGGED_IN);\n }\n return client;\n}\n\n/** The org a members or role command acts on: `--org` on the command or before it, else a plain error. */\nexport function orgFor(opts: { org?: string | undefined }, target: Target): string {\n if (target.kind === \"local\") throw new KvboxError(NOT_LOGGED_IN);\n const slug = opts.org ?? target.org;\n if (slug === undefined) throw new KvboxError(\"no org: pass --org <slug>\");\n return slug;\n}\n","import { Command, Option } from \"commander\";\nimport { ORG_ROLES, type OrgRole } from \"@kvbox/shared/api\";\nimport { age, boxName, color, confirm, info, json, table } from \"../../output.js\";\nimport { cloudClientFor, orgFor } from \"./context.js\";\n\ntype Opts = { org?: string; json?: boolean };\n\n/** kvbox org members ls [--org <slug>] [--json] — --json: OrgMember[] */\nconst lsCommand = new Command(\"ls\")\n .description(\"list an org's members and their roles\")\n .option(\"-o, --org <slug>\", \"the org (or --org before the command)\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: Opts, cmd: Command) => {\n const client = await cloudClientFor(cmd.optsWithGlobals());\n try {\n const org = await client.getOrg(orgFor(opts, client.target));\n if (opts.json) {\n json(org.members);\n return;\n }\n info(`${org.slug} (${org.name})`);\n table(org.members.map((m) => ({ user: boxName(m.username), name: m.name, role: m.role, since: age(m.addedAt) })));\n } finally {\n await client.close();\n }\n });\n\n/** kvbox org members add <user> [--role <role>] [--org <slug>] */\nconst addCommand = new Command(\"add\")\n .description(\"add a user to an org (admins and owners; only an owner can add an owner)\")\n .argument(\"<user>\", \"their username\")\n .addOption(new Option(\"-r, --role <role>\", \"their role\").choices(ORG_ROLES).default(\"member\"))\n .option(\"-o, --org <slug>\", \"the org (or --org before the command)\")\n .action(async (user: string, opts: Opts & { role: OrgRole }, cmd: Command) => {\n const client = await cloudClientFor(cmd.optsWithGlobals());\n try {\n const slug = orgFor(opts, client.target);\n await client.addMember(slug, { username: user, role: opts.role });\n info(`${color.green(\"✓\")} ${user} is now a ${opts.role} of ${slug}`);\n } finally {\n await client.close();\n }\n });\n\n/** kvbox org members rm <user> [--org <slug>] [-y] — y/N on a TTY, -y otherwise; removing yourself is leaving */\nconst rmCommand = new Command(\"rm\")\n .description(\"remove a member (or leave: remove yourself)\")\n .argument(\"<user>\", \"their username\")\n .option(\"-o, --org <slug>\", \"the org (or --org before the command)\")\n .option(\"-y, --yes\", \"do not ask for confirmation\")\n .action(async (user: string, opts: Opts & { yes?: boolean }, cmd: Command) => {\n const client = await cloudClientFor(cmd.optsWithGlobals());\n try {\n const slug = orgFor(opts, client.target);\n if (!(await confirm(`Remove ${user} from ${slug}?`, opts.yes ?? false))) {\n info(\"cancelled\");\n process.exitCode = 1;\n return;\n }\n const self = client.target.kind === \"cloud\" && client.target.user === user;\n await client.removeMember(slug, user);\n info(`${color.green(\"✓\")} ${self ? `you left ${slug}` : `${user} removed from ${slug}`}`);\n } finally {\n await client.close();\n }\n });\n\nexport const membersCommand = new Command(\"members\")\n .description(\"who is in an org and what they may do\")\n .addCommand(lsCommand)\n .addCommand(addCommand)\n .addCommand(rmCommand);\n","import { Command } from \"commander\";\nimport { color, info, json } from \"../../output.js\";\nimport { cloudClientFor } from \"./context.js\";\n\n/** kvbox org new <slug> [--name <name>] [--json] — the caller becomes the org's owner. --json: CloudOrg */\nexport const newCommand = new Command(\"new\")\n .description(\"create an org; you become its owner (the slug is permanent, the name is not)\")\n .argument(\"<slug>\", \"the org's slug: lowercase, like a username (acme)\")\n .option(\"-n, --name <name>\", \"display name (default: the slug)\")\n .option(\"--json\", \"print the org as JSON\")\n .action(async (slug: string, opts: { name?: string; json?: boolean }, cmd: Command) => {\n const client = await cloudClientFor(cmd.optsWithGlobals());\n try {\n const org = await client.createOrg({ slug, name: opts.name ?? slug });\n if (opts.json) {\n json(org);\n return;\n }\n info(`${color.green(\"✓\")} org ${color.bold(org.slug)} created (${org.name}); you are its owner`);\n info(` work in it with: kvbox org use ${org.slug} (then bare box names are ${org.slug}'s)`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { color, confirm, info } from \"../../output.js\";\nimport { cloudClientFor } from \"./context.js\";\n\n/** kvbox org rm <slug> [-y] — owners only; refused while the org still has boxes, snapshots or volumes */\nexport const rmCommand = new Command(\"rm\")\n .description(\"delete an org (owners only; remove its boxes and snapshots first)\")\n .argument(\"<slug>\", \"the org\")\n .option(\"-y, --yes\", \"do not ask for confirmation\")\n .action(async (slug: string, opts: { yes?: boolean }, cmd: Command) => {\n if (!(await confirm(`Delete org ${slug}? Its members lose access; its slug stays taken.`, opts.yes ?? false))) {\n info(\"cancelled\");\n process.exitCode = 1;\n return;\n }\n const client = await cloudClientFor(cmd.optsWithGlobals());\n try {\n await client.deleteOrg(slug);\n info(`${color.green(\"✓\")} org ${slug} deleted`);\n } finally {\n await client.close();\n }\n });\n","import { Argument, Command } from \"commander\";\nimport { ORG_ROLES, type OrgRole } from \"@kvbox/shared/api\";\nimport { color, info } from \"../../output.js\";\nimport { cloudClientFor, orgFor } from \"./context.js\";\n\n/** kvbox org role <user> <role> [--org <slug>] — owners only; the last owner cannot step down */\nexport const roleCommand = new Command(\"role\")\n .description(\"change a member's role (owners only)\")\n .argument(\"<user>\", \"their username\")\n .addArgument(new Argument(\"<role>\", \"owner, admin or member\").choices(ORG_ROLES))\n .option(\"-o, --org <slug>\", \"the org (default: the current context)\")\n .action(async (user: string, role: OrgRole, opts: { org?: string }, cmd: Command) => {\n const client = await cloudClientFor(cmd.optsWithGlobals());\n try {\n const slug = orgFor(opts, client.target);\n await client.setRole(slug, user, role);\n info(`${color.green(\"✓\")} ${user} is now a ${role} of ${slug}`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport type { Balance, BoxUsage, UsageReport } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { round, sumUsage } from \"@kvbox/shared/usage\";\nimport { clientFor } from \"../client.js\";\nimport { boxName, color, duration, hours, info, json, slugOf, status, table } from \"../output.js\";\nimport { money } from \"./vm/usage.js\";\n\n/**\n * kvbox usage [--since <date>] [--until <date>] [--all] [--by-user] [--json] — every box of yours over the window\n * (this calendar month by default), removed ones included, with totals. Through a control plane it\n * covers you and your orgs (`--org <slug>` for one org, `--all` every slug for a platform admin) and is priced with its price list; on\n * this machine it is the host's ledger (priced only when config.json has `pricing`).\n * `--by-user` (control plane only, #60) sums the same boxes per user who made them, typically with `--org`.\n * Volumes (#91) are listed under the boxes, priced per hour of existence plus per GiB-hour of their size,\n * whether a box has them or not; they are never per user, so `--by-user` prints them as they are.\n * --json output: the UsageReport object { window, boxes: BoxUsage[], volumes?: VolumeUsage[], totals },\n * a VolumeUsage being { id, name, owner, ownerKind?, sizeGib, status: \"present\" | \"removed\", volumeHours,\n * volumeGibHours, cost?, historyFrom }; `totals` has volumeHours and volumeGibHours, and `totals.cost`\n * covers boxes and volumes together (each table's own total row is the sum of its rows).\n * With --by-user { window, users: UserUsage[], volumes?, totals }, a UserUsage being { user: string | null,\n * boxes: number, seconds, vcpuHours, ramGibHours, diskGibHours, cost? }. `user` is null for boxes\n * whose maker is unknown: removed ones (the ledger does not record who made a box) and ones made\n * outside the control plane.\n */\nexport const usageCommand = new Command(\"usage\")\n .description(\"what your boxes and volumes used this month (or --since/--until): running time, vCPU-h, RAM and disk GiB-h, cost\")\n .option(\"--since <date>\", \"count from this date, e.g. 2026-10-01 (default: the 1st of this month)\")\n .option(\"--until <date>\", \"count up to this date (default: now)\")\n .option(\"--org <slug>\", \"one org's boxes only\")\n .option(\"-a, --all\", \"every box on the platform (platform admins only)\")\n .option(\"--by-user\", \"one line per user who made the boxes (e.g. who spent what in --org)\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { since?: string; until?: string; org?: string; all?: boolean; byUser?: boolean; json?: boolean }, cmd: Command) => {\n for (const [name, value] of [\n [\"since\", opts.since],\n [\"until\", opts.until],\n ] as const) {\n if (value !== undefined && Number.isNaN(Date.parse(value))) throw new KvboxError(`--${name} ${value}: not a date; write it like 2026-10-19 or 2026-10-19T08:00:00Z`);\n }\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n // On this machine there are no orgs: a silently ignored --org would print the whole host as if it were one.\n if (client.target.kind === \"local\" && cmd.optsWithGlobals<{ org?: string }>().org) throw new KvboxError(\"--org needs a control plane: kvbox login, or drop --org\");\n if (client.target.kind === \"local\" && opts.byUser) throw new KvboxError(\"--by-user needs a control plane: kvbox login, or drop --by-user\");\n const report = await client.usageReport(opts.since, opts.until, opts.all);\n const perUser = opts.byUser ? byUser(report) : undefined;\n if (opts.json) {\n json(perUser ?? report);\n return;\n }\n const cloud = client.target.kind === \"cloud\" ? { me: client.target.user } : undefined;\n info(`${day(report.window.from)} to ${day(report.window.to)}`);\n const volumes = report.volumes ?? [];\n if (report.boxes.length === 0 && volumes.length === 0) info(\"no usage in this window\");\n else if (report.boxes.length > 0) table(perUser ? userRows(perUser) : usageRows(report, cloud));\n // Volumes (#91) under the boxes: an hour of a volume is billed whatever it holds and whether a box\n // has it. Nobody \"made\" the hours of a volume, so --by-user shows them as they are, not per user.\n if (volumes.length > 0) {\n info(volumes.length === 1 ? \"1 volume\" : `${volumes.length} volumes`);\n table(volumeRows(report, cloud));\n }\n // Each table's total is its own rows'; the report's cost is both together.\n if (volumes.length > 0 && report.totals.cost !== undefined) info(`total: ${money(report.totals.cost.amount, report.totals.cost.currency)} ${color.dim(\"(boxes and volumes, estimated)\")}`);\n if (cloud) {\n const line = await creditLine(client, cloud.me);\n if (line !== undefined) info(line);\n }\n } finally {\n await client.close();\n }\n });\n\nconst day = (iso: string) => iso.slice(0, 10);\n\n/**\n * The prepaid balance under the table (#76): the caller's own with no `--org`, the org's with it.\n * A control plane without the route (older than #76) answers an error: then there is no line.\n */\nasync function creditLine(client: { balance(): Promise<Balance> }, me: string | undefined): Promise<string | undefined> {\n let b: Balance;\n try {\n b = await client.balance();\n } catch (err) {\n if (err instanceof KvboxError) return undefined;\n throw err;\n }\n const whose = b.slug === me ? \"private\" : b.slug;\n const left = money(b.balance, b.currency);\n const line = `credit: ${b.balance > 0 ? left : color.red(left)} left ${color.dim(`(${whose})`)}`;\n // Suspended (#76): the control plane hibernated the boxes at zero; a top-up brings them back.\n return b.suspendedAt ? `${line} ${color.red(\"out of credit: boxes hibernated until you top up\")}` : line;\n}\n\n/** The OWNER cell, like `kvbox ls`: `private` for the user's own, else the slug and its kind. */\nfunction ownerCell(b: Pick<BoxUsage, \"owner\" | \"ownerKind\">, me: string | undefined): string {\n const slug = slugOf(b.owner);\n if (slug === me) return \"private\";\n return b.ownerKind === undefined ? slug : `${slug} ${color.dim(b.ownerKind)}`;\n}\n\n/**\n * One row per box plus a totals row; an OWNER column first through a control plane. A removed box\n * is marked, its figures are its final ones. The COST column is there when the report is priced; the\n * total row's cost is the boxes' alone (`totals.cost` has the volumes too, #91: the line under the tables).\n */\nexport function usageRows(report: UsageReport, cloud?: { me?: string | undefined }): Record<string, string>[] {\n const priced = report.totals.cost !== undefined;\n const rows = report.boxes.map((b) => ({\n ...(cloud ? { owner: ownerCell(b, cloud.me) } : {}),\n name: boxName(b.name),\n status: b.status === \"removed\" ? color.dim(\"removed\") : status(b.status),\n running: duration(b.seconds.running),\n \"vcpu-h\": hours(b.vcpuHours),\n \"ram GiB-h\": hours(b.ramGibHours),\n \"disk GiB-h\": hours(b.diskGibHours),\n ...(priced ? { cost: money(b.cost?.amount ?? 0, report.totals.cost!.currency) } : {}),\n }));\n const t = report.totals;\n rows.push({\n ...(cloud ? { owner: \"\" } : {}),\n name: color.bold(\"total\"),\n status: \"\",\n running: duration(t.seconds.running),\n \"vcpu-h\": hours(t.vcpuHours),\n \"ram GiB-h\": hours(t.ramGibHours),\n \"disk GiB-h\": hours(t.diskGibHours),\n ...(priced ? { cost: `${money(sumCost(report.boxes), t.cost!.currency)} ${color.dim(\"(estimated)\")}` } : {}),\n });\n return rows;\n}\n\n/** The rows' own costs added up, so a table's total is what its rows show. */\nconst sumCost = (rows: readonly { cost?: { amount: number } | undefined }[]): number => round(rows.reduce((n, r) => n + (r.cost?.amount ?? 0), 0), 4);\n\n/**\n * One row per volume (#91) plus a totals row of the volumes alone: the hours it existed, its GiB-hours\n * (size, not what it holds), and the cost when priced. The report's total under the table has both.\n */\nexport function volumeRows(report: UsageReport, cloud?: { me?: string | undefined }): Record<string, string>[] {\n const priced = report.totals.cost !== undefined;\n const volumes = report.volumes ?? [];\n const currency = report.totals.cost?.currency ?? \"\";\n const rows = volumes.map((v) => ({\n ...(cloud ? { owner: ownerCell(v, cloud.me) } : {}),\n volume: boxName(v.name),\n status: v.status === \"removed\" ? color.dim(\"removed\") : \"present\",\n size: `${v.sizeGib}GB`,\n hours: hours(v.volumeHours),\n \"GiB-h\": hours(v.volumeGibHours),\n ...(priced ? { cost: money(v.cost?.amount ?? 0, currency) } : {}),\n }));\n rows.push({\n ...(cloud ? { owner: \"\" } : {}),\n volume: color.bold(\"total\"),\n status: \"\",\n size: \"\",\n hours: hours(report.totals.volumeHours ?? 0),\n \"GiB-h\": hours(report.totals.volumeGibHours ?? 0),\n ...(priced ? { cost: money(sumCost(volumes), currency) } : {}),\n });\n return rows;\n}\n\nexport interface UserUsage {\n /** The username that made the boxes; null when unknown (removed boxes, boxes made outside the control plane). */\n user: string | null;\n boxes: number;\n seconds: BoxUsage[\"seconds\"];\n vcpuHours: number;\n ramGibHours: number;\n diskGibHours: number;\n cost?: { amount: number; currency: string };\n}\n\n/** The report's boxes summed per maker (#60), by name with the unknown last; the volumes (#91) and the totals are the report's. */\nexport function byUser(report: UsageReport): { window: UsageReport[\"window\"]; users: UserUsage[]; volumes?: UsageReport[\"volumes\"]; totals: UsageReport[\"totals\"] } {\n const groups = new Map<string | null, BoxUsage[]>();\n for (const b of report.boxes) {\n const user = b.createdBy ?? null;\n const list = groups.get(user);\n if (list === undefined) groups.set(user, [b]);\n else list.push(b);\n }\n const currency = report.totals.cost?.currency;\n const users = [...groups].map(([user, boxes]): UserUsage => {\n const { cost: _none, ...sum } = sumUsage(boxes);\n const u: UserUsage = { user, boxes: boxes.length, ...sum };\n if (currency !== undefined) u.cost = { amount: round(boxes.reduce((n, b) => n + (b.cost?.amount ?? 0), 0), 4), currency };\n return u;\n });\n users.sort((a, b) => (a.user === null ? 1 : b.user === null ? -1 : a.user.localeCompare(b.user)));\n return { window: report.window, users, ...(report.volumes === undefined ? {} : { volumes: report.volumes }), totals: report.totals };\n}\n\n/** One row per maker plus the totals row (the users' costs added up: the boxes' alone); removed boxes and ones the control plane did not make go under `unknown`. */\nexport function userRows(r: ReturnType<typeof byUser>): Record<string, string>[] {\n const priced = r.totals.cost !== undefined;\n const cells = (t: Pick<UserUsage, \"seconds\" | \"vcpuHours\" | \"ramGibHours\" | \"diskGibHours\">) => ({\n running: duration(t.seconds.running),\n \"vcpu-h\": hours(t.vcpuHours),\n \"ram GiB-h\": hours(t.ramGibHours),\n \"disk GiB-h\": hours(t.diskGibHours),\n });\n const rows = r.users.map((u) => ({\n user: u.user ?? color.dim(\"unknown\"),\n boxes: String(u.boxes),\n ...cells(u),\n ...(priced ? { cost: money(u.cost?.amount ?? 0, r.totals.cost!.currency) } : {}),\n }));\n rows.push({\n user: color.bold(\"total\"),\n boxes: String(r.users.reduce((n, u) => n + u.boxes, 0)),\n ...cells(r.totals),\n ...(priced ? { cost: `${money(sumCost(r.users), r.totals.cost!.currency)} ${color.dim(\"(estimated)\")}` } : {}),\n });\n return rows;\n}\n","/**\n * Summing a box's usage ledger: one pure function over its state-change rows, used by the host\n * (`kvbox vm usage`, `GET /usage`) and by the control plane over the rows it pulled (#42). A row\n * opens an interval that lasts until the next row; the sizes ride on every row so a rescale\n * changes the rate from that moment on. Pricing is per resource-hour (decision \"Usage is priced\n * per resource-hour\").\n */\nimport { z } from \"zod\";\nimport type { BoxStatus, BoxUsage, VolumeUsage } from \"./api.js\";\n\nexport type UsageState = \"running\" | \"standby\" | \"hibernated\" | \"stopped\";\n\n/** One state change of a box. */\nexport interface UsageEvent {\n at: string;\n state: UsageState;\n vcpu: number;\n memMib: number;\n diskGib: number;\n /** What made it: new, start, stop, pause, resume, hibernate, wake, rescale, update, rm, server (a stop the server did not see). */\n by: string;\n}\n\n/**\n * What an hour of each resource costs. A volume (#91) is an hour of its existence plus an hour of each\n * GiB of its size; a price list from before volumes charges nothing for them.\n */\nexport const PricingSchema = z.object({\n currency: z.string().min(1),\n vcpuHour: z.number().nonnegative(),\n ramGibHour: z.number().nonnegative(),\n diskGibHour: z.number().nonnegative(),\n volumeHour: z.number().nonnegative().default(0),\n volumeGibHour: z.number().nonnegative().default(0),\n});\nexport type Pricing = z.infer<typeof PricingSchema>;\n\nexport interface UsageWindow {\n from: string;\n to: string;\n pricing?: Pricing | undefined;\n}\n\nexport interface UsageTotals {\n seconds: Record<UsageState, number>;\n vcpuHours: number;\n ramGibHours: number;\n diskGibHours: number;\n cost?: { amount: number; currency: string };\n /** Stops the server did not witness (Firecracker died, host rebooted) and dated to when it noticed. */\n estimatedStops: number;\n /** The first recorded moment, null when nothing is recorded. */\n historyFrom: string | null;\n}\n\nconst HOUR_MS = 3_600_000;\n\nexport const round = (n: number, places: number) => Math.round(n * 10 ** places) / 10 ** places;\n\n/**\n * Each event opens an interval that lasts until the next one (or `to`); intervals are clipped to the\n * window, so the event before `from` supplies the state the window starts in. Time before the first\n * event belongs to no state: it was never recorded. Running hours earn vCPU and RAM; standby hours\n * earn RAM (the memory is still held) but no vCPU; every hour the box exists earns disk (its overlay\n * is there while it is hibernated or stopped too). A repeated state continues it.\n */\nexport function computeUsage(events: readonly UsageEvent[], w: UsageWindow): UsageTotals {\n const sorted = [...events].sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));\n const from = Date.parse(w.from);\n const to = Date.parse(w.to);\n const ms: Record<UsageState, number> = { running: 0, standby: 0, hibernated: 0, stopped: 0 };\n let vcpuHours = 0;\n let ramGibHours = 0;\n let diskGibHours = 0;\n sorted.forEach((e, i) => {\n const start = Math.max(Date.parse(e.at), from);\n const next = sorted[i + 1];\n const end = Math.min(next === undefined ? to : Date.parse(next.at), to);\n if (end <= start) return;\n const h = (end - start) / HOUR_MS;\n ms[e.state] += end - start;\n if (e.state === \"running\") vcpuHours += h * e.vcpu;\n if (e.state === \"running\" || e.state === \"standby\") ramGibHours += (h * e.memMib) / 1024;\n diskGibHours += h * e.diskGib;\n });\n const totals: UsageTotals = {\n seconds: {\n running: Math.round(ms.running / 1000),\n standby: Math.round(ms.standby / 1000),\n hibernated: Math.round(ms.hibernated / 1000),\n stopped: Math.round(ms.stopped / 1000),\n },\n vcpuHours: round(vcpuHours, 3),\n ramGibHours: round(ramGibHours, 3),\n diskGibHours: round(diskGibHours, 3),\n estimatedStops: sorted.filter((e) => e.state === \"stopped\" && e.by === \"server\" && e.at >= w.from).length,\n historyFrom: sorted[0]?.at ?? null,\n };\n if (w.pricing !== undefined) totals.cost = { amount: round(costOf(totals, w.pricing), 4), currency: w.pricing.currency };\n return totals;\n}\n\n/** The price of a set of resource-hours; totals over several boxes are summed the same way. */\nexport function costOf(t: Pick<UsageTotals, \"vcpuHours\" | \"ramGibHours\" | \"diskGibHours\">, pricing: Pricing): number {\n return t.vcpuHours * pricing.vcpuHour + t.ramGibHours * pricing.ramGibHour + t.diskGibHours * pricing.diskGibHour;\n}\n\n/** Add up several boxes' totals (hours and seconds; the cost is recomputed from the hours when priced). */\nexport function sumUsage(items: readonly Pick<UsageTotals, \"seconds\" | \"vcpuHours\" | \"ramGibHours\" | \"diskGibHours\">[], pricing?: Pricing): Omit<UsageTotals, \"estimatedStops\" | \"historyFrom\"> {\n const sum: Omit<UsageTotals, \"estimatedStops\" | \"historyFrom\"> = {\n seconds: { running: 0, standby: 0, hibernated: 0, stopped: 0 },\n vcpuHours: 0,\n ramGibHours: 0,\n diskGibHours: 0,\n };\n for (const t of items) {\n for (const s of Object.keys(sum.seconds) as UsageState[]) sum.seconds[s] += t.seconds[s];\n sum.vcpuHours += t.vcpuHours;\n sum.ramGibHours += t.ramGibHours;\n sum.diskGibHours += t.diskGibHours;\n }\n sum.vcpuHours = round(sum.vcpuHours, 3);\n sum.ramGibHours = round(sum.ramGibHours, 3);\n sum.diskGibHours = round(sum.diskGibHours, 3);\n if (pricing !== undefined) sum.cost = { amount: round(costOf(sum, pricing), 4), currency: pricing.currency };\n return sum;\n}\n\n/**\n * The window a `GET /usage` call asks for: `since` and `until` as the user wrote them (any Date.parse\n * form), defaulting to the start of the current calendar month (UTC, what a bill covers) and now.\n */\nexport function usageWindow(since: string | undefined, until: string | undefined, now = new Date()): { from: string; to: string } {\n const parse = (name: string, value: string): string => {\n const t = Date.parse(value);\n if (Number.isNaN(t)) throw new Error(`${name}: \"${value}\" is not a date; write it like 2026-10-19 or 2026-10-19T08:00:00Z`);\n return new Date(t).toISOString();\n };\n const from = since === undefined ? new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString() : parse(\"since\", since);\n const to = until === undefined ? now.toISOString() : parse(\"until\", until);\n return { from, to };\n}\n\n/** A ledger row as the host stores it: the event plus whose box it is. */\nexport interface LedgerRow extends UsageEvent {\n /** The host ledger the row came from, when rows of several hosts are mixed: box ids are only unique within one. */\n ledger?: string;\n boxId: string;\n owner: string;\n name: string;\n}\n\n/**\n * Rows of many boxes → one `BoxUsage` per box id, in owner/name order: the report both the host\n * (`GET /usage`) and the control plane build. A box's `rm` row ends its time: nothing accrues after\n * it, and a box gone before the window opened (or made after it closed) is left out. `live` says what\n * a box that still exists is doing now; one not in it reads its state off its last row, `removed`\n * when that row is the `rm`. A name removed and made again is two boxes (two ids); rows carrying a\n * `ledger` are grouped by ledger and box id, so two hosts' boxes never merge.\n */\nexport function groupUsage(\n rows: readonly LedgerRow[],\n window: { from: string; to: string },\n pricing: Pricing | undefined,\n live: ReadonlyMap<string, BoxStatus> = new Map(),\n): BoxUsage[] {\n const byBox = new Map<string, LedgerRow[]>();\n for (const r of rows) {\n const key = r.ledger === undefined ? r.boxId : `${r.ledger}:${r.boxId}`;\n const list = byBox.get(key);\n if (list === undefined) byBox.set(key, [r]);\n else list.push(r);\n }\n const out: BoxUsage[] = [];\n for (const events of byBox.values()) {\n events.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));\n const first = events[0]!;\n const last = events[events.length - 1]!;\n const id = last.boxId;\n const removed = last.by === \"rm\" && !live.has(id);\n const to = removed && last.at < window.to ? last.at : window.to;\n if (first.at >= to || (removed && last.at <= window.from)) continue;\n const totals = computeUsage(events, { from: window.from, to, pricing });\n const status: BoxUsage[\"status\"] = live.get(id) ?? (removed ? \"removed\" : last.state);\n out.push({ id, name: last.name, owner: last.owner, status, ...totals });\n }\n return out.sort(usageOrder);\n}\n\n/** The order `groupUsage` returns boxes in: owner, name, then the older of a name made twice first. */\nexport const usageOrder = (a: Pick<BoxUsage, \"owner\" | \"name\" | \"historyFrom\">, b: Pick<BoxUsage, \"owner\" | \"name\" | \"historyFrom\">): number =>\n a.owner.localeCompare(b.owner) || a.name.localeCompare(b.name) || (a.historyFrom ?? \"\").localeCompare(b.historyFrom ?? \"\");\n\n// ---- volumes (#91) -------------------------------------------------------------------------------\n\n/** One change of a volume: made, resized, or removed. The size rides on every row like a box's. */\nexport interface VolumeEvent {\n at: string;\n sizeGib: number;\n by: \"create\" | \"resize\" | \"rm\";\n}\n\n/** A volume ledger row as the host stores it: the event plus whose volume it is. */\nexport interface VolumeLedgerRow extends VolumeEvent {\n /** The host ledger the row came from, when rows of several hosts are mixed: volume ids are only unique within one. */\n ledger?: string;\n volumeId: string;\n owner: string;\n name: string;\n}\n\nexport interface VolumeTotals {\n volumeHours: number;\n volumeGibHours: number;\n cost?: { amount: number; currency: string };\n}\n\n/**\n * A volume costs for every hour it exists, whatever it holds and whether a box has it: each row opens\n * an interval that lasts until the next one (or `to`), the `rm` row ends the time, intervals are clipped\n * to the window. The GiB-hours are of the size, a reservation on the host's disk.\n */\nexport function computeVolumeUsage(events: readonly VolumeEvent[], w: UsageWindow): VolumeTotals {\n const sorted = [...events].sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));\n const from = Date.parse(w.from);\n const to = Date.parse(w.to);\n let hours = 0;\n let gibHours = 0;\n sorted.forEach((e, i) => {\n if (e.by === \"rm\") return;\n const start = Math.max(Date.parse(e.at), from);\n const next = sorted[i + 1];\n const end = Math.min(next === undefined ? to : Date.parse(next.at), to);\n if (end <= start) return;\n const h = (end - start) / HOUR_MS;\n hours += h;\n gibHours += h * e.sizeGib;\n });\n const totals: VolumeTotals = { volumeHours: round(hours, 3), volumeGibHours: round(gibHours, 3) };\n if (w.pricing !== undefined) totals.cost = { amount: round(volumeCostOf(totals, w.pricing), 4), currency: w.pricing.currency };\n return totals;\n}\n\nexport function volumeCostOf(t: Pick<VolumeTotals, \"volumeHours\" | \"volumeGibHours\">, pricing: Pricing): number {\n return t.volumeHours * pricing.volumeHour + t.volumeGibHours * pricing.volumeGibHour;\n}\n\n/**\n * Rows of many volumes → one `VolumeUsage` per volume id, like `groupUsage`: a volume whose `rm` row is\n * before the window, or whose first row is after it, is left out; a name removed and made again is two.\n */\nexport function groupVolumeUsage(rows: readonly VolumeLedgerRow[], window: { from: string; to: string }, pricing: Pricing | undefined): VolumeUsage[] {\n const byVolume = new Map<string, VolumeLedgerRow[]>();\n for (const r of rows) {\n const key = r.ledger === undefined ? r.volumeId : `${r.ledger}:${r.volumeId}`;\n const list = byVolume.get(key);\n if (list === undefined) byVolume.set(key, [r]);\n else list.push(r);\n }\n const out: VolumeUsage[] = [];\n for (const events of byVolume.values()) {\n events.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));\n const first = events[0]!;\n const last = events[events.length - 1]!;\n const removed = last.by === \"rm\";\n const to = removed && last.at < window.to ? last.at : window.to;\n if (first.at >= to || (removed && last.at <= window.from)) continue;\n const totals = computeVolumeUsage(events, { from: window.from, to, pricing });\n out.push({ id: last.volumeId, name: last.name, owner: last.owner, sizeGib: last.sizeGib, status: removed ? \"removed\" : \"present\", ...totals, historyFrom: first.at });\n }\n return out.sort(usageOrder);\n}\n\n/** Totals of a report: the boxes' sums plus the volumes', one cost for both when priced. */\nexport function reportTotals(\n boxes: readonly Pick<UsageTotals, \"seconds\" | \"vcpuHours\" | \"ramGibHours\" | \"diskGibHours\">[],\n volumes: readonly Pick<VolumeTotals, \"volumeHours\" | \"volumeGibHours\">[],\n pricing?: Pricing,\n): Omit<UsageTotals, \"estimatedStops\" | \"historyFrom\"> & Pick<VolumeTotals, \"volumeHours\" | \"volumeGibHours\"> {\n const { cost: _boxes, ...sum } = sumUsage(boxes);\n const vol = { volumeHours: round(volumes.reduce((n, v) => n + v.volumeHours, 0), 3), volumeGibHours: round(volumes.reduce((n, v) => n + v.volumeGibHours, 0), 3) };\n const out = { ...sum, ...vol };\n if (pricing !== undefined) return { ...out, cost: { amount: round(costOf(sum, pricing) + volumeCostOf(vol, pricing), 4), currency: pricing.currency } };\n return out;\n}\n","import { Command } from \"commander\";\nimport type { Balance } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { clientFor } from \"../client.js\";\nimport { boxName, color, json, table } from \"../output.js\";\nimport { money } from \"./vm/usage.js\";\n\n/**\n * kvbox credit [--org <slug>] [--json] — the prepaid credit left (#76): yours and every org's you\n * are in, or one org's with `--org`. A control plane only; topping up is the admin's or the app's.\n * --json output: Balance[] { slug, balance, currency, topUps, spent, since, suspendedAt }.\n */\nexport const creditCommand = new Command(\"credit\")\n .description(\"the prepaid credit left on your account and on each of your orgs\")\n .option(\"--org <slug>\", \"one org only\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });\n try {\n if (client.target.kind === \"local\") throw new KvboxError(\"credit lives on the control plane: kvbox login first\");\n const me = client.target.user;\n const balances =\n client.target.org !== undefined\n ? [await client.balance()]\n : await Promise.all([undefined, ...(await client.listOrgs()).map((o) => o.slug)].map((org) => client.balance(org)));\n if (opts.json) {\n json(balances);\n return;\n }\n table(balances.map((b) => creditRow(b, me)));\n } finally {\n await client.close();\n }\n });\n\nfunction creditRow(b: Balance, me: string | undefined): Record<string, string> {\n const left = money(b.balance, b.currency);\n return {\n owner: b.slug === me ? \"private\" : boxName(b.slug),\n credit: b.balance > 0 ? left : color.red(left),\n \"topped up\": money(b.topUps, b.currency),\n spent: money(b.spent, b.currency),\n // Suspended (#76): the sweep hibernated the boxes at zero; a top-up brings them back.\n state: b.suspendedAt ? color.red(\"suspended\") : b.since === null ? color.dim(\"never topped up\") : \"ok\",\n };\n}\n","import { readFile } from \"node:fs/promises\";\nimport { basename, resolve } from \"node:path\";\nimport { Command, Option } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { assertSubdomain, subdomainProblem } from \"@kvbox/shared/names\";\nimport { SIZE_NAMES, SIZES } from \"@kvbox/shared/sizes\";\nimport { ensureCert, renewAfterRefusal } from \"../../cert.js\";\nimport { clientFor, me, orgOption, sshEndpoint, wakeUp, type GlobalOptions, type ServerClient } from \"../../client.js\";\nimport { color, gb, info, json, slugOf, spin } from \"../../output.js\";\nimport { interactive, select, text } from \"../../prompt.js\";\nimport { displayName } from \"../vm/new.js\";\nimport { BOX_NAME_RE, CONFIG_FILE, nameFromDir, readConfig, subdomainFor, writeConfig, type DeployConfig } from \"./config.js\";\nimport { DEPLOY_AUTO_HIBERNATE_SEC } from \"./config.js\";\nimport { IMAGE_TOO_OLD, shipping, SSH_FAILED } from \"./ship.js\";\nimport { detectTemplate, TEMPLATE_IDS, TEMPLATES, templateById, type PackageJson, type Template } from \"./templates/index.js\";\n\n/**\n * kvbox deploy [dir] [-t react|nextjs] [-n name] [--sub name] [-s xs|s|m|l] [--org slug] [-y] [--json]\n *\n * The first time, a few questions (template, box name, HTTPS name, size), each with a default,\n * saved to kvbox.json in the app's directory; after that, no questions: the file is the answer and a\n * flag overrides one field and is saved too. Then: build (React: here; Next.js: in the box), make\n * the box if it is not there (the template's size, hibernating after an hour idle; wake it if it\n * sleeps), ship into it and give it its address. Off a terminal the first run needs `-y` (defaults)\n * or the flags: agents deploy with `kvbox deploy -y --json`.\n *\n * The box is the caller's own, or the `--org` org's (saved as `org` in kvbox.json); an org's box\n * of the same name is never taken by a bare name here, since `deploy` creates what it does not find.\n *\n * --json output: {box, created, template, url, dist?, files, bytes}; `box` is bare for the caller's\n * own box, `slug/name` otherwise; `dist` only when a build output directory was shipped. On this\n * machine's own host there is no HTTPS name: `url` is http://<ip>.\n */\nexport const deployCommand = new Command(\"deploy\")\n .description(\"put the app in this directory (React or Next.js) on a box with its own HTTPS address; redeploy by running it again\")\n .argument(\"[dir]\", \"the app's directory (default: the current one)\")\n .addOption(new Option(\"-t, --template <template>\", \"what kind of app it is (detected from package.json when not given)\").choices(TEMPLATE_IDS))\n .option(\"-n, --name <name>\", \"the box's name (default: the directory's name)\")\n .option(\"--sub <subdomain>\", \"its HTTPS name, https://<subdomain>.kvbox.app (default: the box's name)\")\n .addOption(new Option(\"-s, --size <size>\", \"size of the box when it has to be made\").choices(SIZE_NAMES))\n .option(\"-y, --yes\", \"ask nothing: take the defaults for whatever the flags and kvbox.json leave open\")\n .option(\"--json\", \"print the result as JSON\")\n .option(\"--org <slug>\", \"deploy into this org's boxes (saved to kvbox.json)\")\n .action(async (dirArg: string | undefined, opts: DeployOptions, cmd: Command) => {\n const dir = resolve(dirArg ?? \".\");\n const pkg = await readPackageJson(dir);\n const saved = await readConfig(dir);\n // The org comes from the flag (before or after `deploy`), else from the file: the client has to\n // know it before anything is listed, so it is the one place the org is read.\n const globals = cmd.optsWithGlobals<GlobalOptions>();\n const orgFlag = orgOption(globals);\n const org = orgFlag ?? saved?.org;\n const client = await clientFor({ ...(globals.local ? { local: true } : {}), ...(org !== undefined ? { org } : {}) });\n try {\n const cloud = client.target.kind === \"cloud\";\n // On this machine there are no orgs: a silently ignored --org would deploy to the host owner's box as if it were one.\n if (!cloud && org !== undefined) throw new KvboxError(\"--org needs a control plane: kvbox login, or drop --org\");\n const { config, template, fresh } = await settle(dir, pkg, saved, opts, orgFlag, cloud);\n // A box that already answers under another name keeps it: said now, before anything is built or saved.\n if (cloud && config.subdomain !== undefined) await refuseOtherAddress(client, config);\n await writeConfig(dir, config);\n if (fresh) info(` ${color.dim(`saved to ${CONFIG_FILE}; next time kvbox deploy asks nothing`)}\\n`);\n\n info(`${color.bold(\"Building\")} ${color.cyan(config.name)} ${color.dim(`(${template.label})`)}`);\n const built = await template.build({ dir, pkg, dist: config.dist });\n if (built.dist !== undefined && built.dist !== config.dist) await writeConfig(dir, { ...config, dist: built.dist });\n const size = await shipping.measure(built.outDir, built.exclude);\n info(\"\");\n\n const { box: found, ref, created } = await findOrCreate(client, config);\n // The box trusts the CA for its owner: settle the certificate before waking (and billing) a box.\n const cert = await ensureCert(client, undefined, undefined, { owner: found.owner });\n const wasRunning = !created && found.status === \"running\";\n const box = created || wasRunning ? found : await wakeUp(client, found, ref);\n const ep = sshEndpoint(box, client.target);\n if (!wasRunning) await spin(`waiting for ${ref} to accept SSH…`, shipping.waitForSsh(ep));\n\n const shipIt = () => shipping.ship(ep, built.outDir, template.remote(built), built.exclude);\n const doing = built.dist === undefined ? `shipping ${built.what} (${size.files} files, ${gb(size.bytes)}) to ${ref} and building there, a minute or two…` : `shipping ${built.what} (${size.files} files, ${gb(size.bytes)}) to ${ref}…`;\n let result = await spin(doing, shipIt);\n if (result.status === SSH_FAILED && (await renewAfterRefusal(client, cert, box.owner))) {\n info(\"renewed your SSH certificate, trying again…\");\n result = await spin(doing, shipIt);\n }\n if (result.status === SSH_FAILED) throw new KvboxError(`box ${ref}: could not reach it over SSH (still booting?)${result.output ? `\\n${result.output.trim()}` : \"\"}`, SSH_FAILED);\n if (result.status === IMAGE_TOO_OLD) {\n throw new KvboxError(\n `box ${ref} runs an image too old for the ${template.label} template (base v0.8.0 or newer). ` +\n `Update the box (kvbox vm update ${ref}) once its host has the new image, or deploy under another name (--name) to get a fresh box`,\n );\n }\n if (result.status !== 0) throw new KvboxError(`deploying to ${ref} failed (exit ${result.status}):\\n${result.output.trim()}`);\n\n let url = `http://${box.ip}`;\n if (cloud) {\n const got = await address(client, box, ref, config, template);\n url = got.url;\n // The address the box really has is the one to remember.\n if (got.subdomain !== config.subdomain) await writeConfig(dir, { ...config, subdomain: got.subdomain, ...(built.dist !== undefined && built.dist !== config.dist ? { dist: built.dist } : {}) });\n }\n\n if (opts.json) {\n json({ box: ref, created, template: template.id, url, ...(built.dist !== undefined ? { dist: built.dist } : {}), files: size.files, bytes: size.bytes });\n return;\n }\n process.stdout.write(`${url}\\n`);\n info(`${color.green(\"✓\")} ${color.bold(config.name)} is live at ${color.bold(url)}`);\n info(` box ${ref}${created ? \" (new)\" : \"\"} · ${template.label} · ${size.files} files, ${gb(size.bytes)}`);\n info(` redeploy: kvbox deploy${dirArg !== undefined ? ` ${dirArg}` : \"\"}`);\n } finally {\n await client.close();\n }\n });\n\ninterface DeployOptions {\n template?: string;\n name?: string;\n sub?: string;\n size?: string;\n yes?: boolean;\n json?: boolean;\n}\n\nasync function readPackageJson(dir: string): Promise<PackageJson | undefined> {\n try {\n return JSON.parse(await readFile(resolve(dir, \"package.json\"), \"utf8\")) as PackageJson;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw new KvboxError(`${resolve(dir, \"package.json\")}: ${(err as Error).message}`);\n }\n}\n\n/**\n * The settings for this deploy: kvbox.json, overridden by flags; whatever is still open is asked\n * (first run on a terminal), or defaulted (`-y`), or refused with the flags named. A saved\n * subdomain belongs to the saved box: a `--name` or `--org` that changes the box leaves it behind.\n */\nasync function settle(dir: string, pkg: PackageJson | undefined, saved: DeployConfig | undefined, opts: DeployOptions, orgFlag: string | undefined, cloud: boolean): Promise<{ config: DeployConfig; template: Template; fresh: boolean }> {\n const detected = detectTemplate(pkg);\n if (opts.name !== undefined && !BOX_NAME_RE.test(opts.name)) throw new KvboxError(`--name ${opts.name}: ${NAME_RULE}`);\n if (opts.sub !== undefined) assertSubdomain(opts.sub);\n const renamed = saved !== undefined && ((opts.name !== undefined && opts.name !== saved.name) || (orgFlag !== undefined && orgFlag !== saved.org));\n const savedSub = renamed ? undefined : saved?.subdomain;\n const defaults = {\n template: opts.template ?? saved?.template ?? detected?.id,\n name: opts.name ?? saved?.name ?? nameFromDir(basename(dir)),\n subdomain: opts.sub ?? savedSub,\n size: opts.size ?? saved?.size,\n };\n /** The size when nothing says one: the template's. */\n const sizeFor = (t: Template | undefined) => defaults.size ?? t?.size ?? \"xs\";\n // A saved file answers everything it holds; only a first run (or a renamed box's address) has open questions.\n const open = {\n template: opts.template === undefined && saved?.template === undefined,\n name: opts.name === undefined && saved?.name === undefined,\n subdomain: cloud && opts.sub === undefined && savedSub === undefined,\n size: opts.size === undefined && saved === undefined,\n };\n const anyOpen = open.template || open.name || open.subdomain || open.size;\n const fresh = saved === undefined;\n\n if (anyOpen && !opts.yes && !interactive()) {\n const sub = defaults.subdomain ?? subdomainFor(defaults.name);\n throw new KvboxError(\n `kvbox deploy asks a few questions the first time, and this is not a terminal. ` +\n `Pass -y to take the defaults (${defaults.template ?? \"template?\"}, box ${defaults.name}${cloud ? `, https://${sub}.kvbox.app` : \"\"}, size ${sizeFor(defaults.template !== undefined ? templateById(defaults.template) : undefined)}), ` +\n `or answer with --template, --name${cloud ? \", --sub\" : \"\"} and --size`,\n );\n }\n const ask = anyOpen && !opts.yes;\n if (ask && fresh) info(`${color.bold(\"kvbox deploy\")} ${color.dim(dir)}\\n`);\n\n let templateId = defaults.template;\n if (open.template && ask) {\n const initial = detected ? TEMPLATES.indexOf(detected) : 0;\n templateId = await select(\"Template\", TEMPLATES.map((t) => ({ value: t.id, label: t.label, hint: t === detected ? `${t.hint} · detected` : t.hint })), initial);\n }\n if (templateId === undefined) throw new KvboxError(`could not tell what kind of app ${dir} is (no package.json of a Vite, Create React App or Next.js project): say it with --template ${TEMPLATE_IDS.join(\"|\")}`);\n const template = templateById(templateId);\n\n let name = defaults.name;\n if (open.name && ask) name = await text(\"Box name\", { default: defaults.name, validate: (a) => (BOX_NAME_RE.test(a) ? undefined : NAME_RULE) });\n\n let subdomain = defaults.subdomain ?? (cloud ? subdomainFor(name) : undefined);\n if (open.subdomain && ask) {\n subdomain = await text(\"Address\", {\n default: subdomainFor(name),\n validate: (a) => {\n const problem = subdomainProblem(a);\n return problem ? `that name ${problem}` : undefined;\n },\n });\n info(` ${color.dim(`https://${subdomain}.kvbox.app`)}`);\n }\n\n let size = sizeFor(template);\n if (open.size && ask) {\n size = await select(\"Box size\", SIZE_NAMES.map((s) => ({ value: s, label: s, hint: `${SIZES[s].vcpu} vCPU, ${SIZES[s].memMib / 1024} GB RAM, ${SIZES[s].diskGib} GB disk` })), SIZE_NAMES.indexOf(template.size));\n }\n\n const org = orgFlag ?? saved?.org;\n const config: DeployConfig = {\n template: template.id,\n name,\n ...(org !== undefined ? { org } : {}),\n ...(subdomain !== undefined ? { subdomain } : {}),\n size,\n ...(saved?.dist !== undefined ? { dist: saved.dist } : {}),\n };\n return { config, template, fresh };\n}\n\nconst NAME_RULE = \"1-12 chars, lowercase letters, digits and '-', starting with a letter or digit\";\n\n/**\n * The box named in kvbox.json, made when it does not exist. The listing is the client's (the\n * `--org` org's boxes, else everything readable), but only the right slug's box counts: the\n * caller's own, or the org's. Nothing else of that name is touched.\n */\nasync function findOrCreate(client: ServerClient, config: DeployConfig) {\n const user = me(client);\n const slug = config.org ?? user;\n const named = (await client.listMachines()).filter((b) => b.name === config.name);\n let box = slug === undefined ? named[0] : named.find((b) => slugOf(b.owner) === slug);\n let created = false;\n if (!box) {\n box = await spin(`booting a new box ${config.name}…`, client.createMachine({ name: config.name, ...(config.size !== undefined ? { size: config.size } : {}), autoHibernateSec: DEPLOY_AUTO_HIBERNATE_SEC }));\n created = true;\n info(`${color.green(\"✓\")} box ${color.bold(config.name)} is up: ${box.vcpu} vCPU, ${gb(box.memMib * 1024 ** 2)} RAM, ${gb(box.diskBytes)} disk`);\n }\n return { box, ref: displayName(box, user), created };\n}\n\n/** The HTTPS address the box of that name (the caller's own, or the org's) already has, if any. */\nasync function existingAddress(client: ServerClient, config: DeployConfig) {\n const slug = config.org ?? me(client);\n return (await client.listSubdomains()).find((s) => s.box === config.name && s.owner === slug);\n}\n\n/**\n * A box that already answers under another name keeps it: moving it is the user's call\n * (`kvbox vm proxy release`), not something to do behind a warning, and not worth a build first.\n */\nasync function refuseOtherAddress(client: ServerClient, config: DeployConfig): Promise<void> {\n const have = await existingAddress(client, config);\n if (!have || have.subdomain === config.subdomain) return;\n const ref = config.org !== undefined ? `${config.org}/${config.name}` : config.name;\n throw new KvboxError(\n `box ${ref} already answers at ${have.url}, not ${config.subdomain}. ` +\n `To keep the address: kvbox deploy --sub ${have.subdomain}. To move it: kvbox vm proxy release ${ref}, then deploy again`,\n );\n}\n\n/**\n * The box's HTTPS address: the one it has, moved to the template's port if needed, else the one\n * kvbox.json names, claimed now.\n */\nasync function address(client: ServerClient, box: { name: string; owner: string }, ref: string, config: DeployConfig, template: Template): Promise<{ url: string; subdomain: string }> {\n const have = (await client.listSubdomains()).find((s) => s.box === box.name && s.owner === slugOf(box.owner));\n if (have) {\n if (have.port !== template.port) await client.setSubdomainPort(ref, { port: template.port });\n return { url: have.url, subdomain: have.subdomain };\n }\n const wanted = config.subdomain ?? subdomainFor(config.name);\n try {\n const sub = await spin(`claiming https://${wanted}.kvbox.app…`, client.claimSubdomain(ref, { name: wanted, port: template.port }));\n return { url: sub.url, subdomain: sub.subdomain };\n } catch (err) {\n if (!(err instanceof KvboxError)) throw err;\n throw new KvboxError(`${err.message}\\nthe app is on box ${ref} but has no address yet: pick another with kvbox deploy --sub <name> (saved to ${CONFIG_FILE})`);\n }\n}\n","/**\n * `kvbox.json`, the deploy settings kept next to the app: written by the first `kvbox deploy`\n * from its questions, read by every later one so a redeploy asks nothing. Hand-editable; a bad\n * file is refused with the field named.\n *\n * { \"template\": \"react\", \"name\": \"myapp\", \"subdomain\": \"myapp\", \"size\": \"s\", \"dist\": \"dist\" }\n * plus \"org\": \"acme\" when the box is an org's.\n */\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { z } from \"zod\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { subdomainProblem } from \"@kvbox/shared/names\";\nimport { SIZE_NAMES } from \"@kvbox/shared/sizes\";\nimport { ORG_SLUG_RE } from \"../../client.js\";\nimport { TEMPLATE_IDS } from \"./templates/index.js\";\n\n/** A deployed site sleeps after an hour without traffic; a visit wakes it (#80). */\nexport const DEPLOY_AUTO_HIBERNATE_SEC = 3600;\nexport const CONFIG_FILE = \"kvbox.json\";\n\n/** The server's rule for a box name (core/machines.ts), checked here so a typo fails before the build. */\nexport const BOX_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;\n\nexport const DeployConfigSchema = z.object({\n template: z.enum(TEMPLATE_IDS),\n name: z.string().regex(BOX_NAME_RE, \"1-12 chars, lowercase letters, digits and '-', starting with a letter or digit\"),\n /** The org whose box it is; absent for the user's own. */\n org: z.string().regex(ORG_SLUG_RE, \"not an org slug\").optional(),\n /** The HTTPS name (`<subdomain>.kvbox.app`); absent when deploying to this machine's own host. */\n subdomain: z.string().check((ctx) => {\n const problem = subdomainProblem(ctx.value);\n if (problem) ctx.issues.push({ code: \"custom\", message: problem, input: ctx.value });\n }).optional(),\n size: z.enum(SIZE_NAMES as [string, ...string[]]).optional(),\n /** The build output directory, relative to the app; the template's default when absent. */\n dist: z.string().optional(),\n});\nexport type DeployConfig = z.infer<typeof DeployConfigSchema>;\n\n/** The config in `dir`, or undefined when there is none. */\nexport async function readConfig(dir: string): Promise<DeployConfig | undefined> {\n const path = join(dir, CONFIG_FILE);\n let raw: string;\n try {\n raw = await readFile(path, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw err;\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n throw new KvboxError(`${path}: not valid JSON`);\n }\n const parsed = DeployConfigSchema.safeParse(json);\n if (!parsed.success) {\n const issue = parsed.error.issues[0]!;\n throw new KvboxError(`${path}: ${issue.path.join(\".\") || \"file\"}: ${issue.message}`);\n }\n return parsed.data;\n}\n\nexport async function writeConfig(dir: string, config: DeployConfig): Promise<void> {\n await writeFile(join(dir, CONFIG_FILE), JSON.stringify(config, null, 2) + \"\\n\");\n}\n\n/** A box name made from a directory name: lowercased, anything else becomes '-', cut to the limit. */\nexport function nameFromDir(dirName: string): string {\n const slug = dirName.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 12).replace(/-+$/, \"\");\n return slug === \"\" ? \"app\" : slug;\n}\n\n/** The HTTPS name a box name suggests: itself when the subdomain rules allow it, else `<name>-site`. */\nexport function subdomainFor(name: string): string {\n return subdomainProblem(name) === null ? name : `${name}-site`;\n}\n","/** The package manager a Node project uses, told by its lockfile; shared by the templates. */\nimport { access } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nexport type PackageManager = \"pnpm\" | \"yarn\" | \"bun\" | \"npm\";\n\nexport async function packageManager(dir: string): Promise<PackageManager> {\n const has = (f: string) => access(join(dir, f)).then(() => true, () => false);\n if (await has(\"pnpm-lock.yaml\")) return \"pnpm\";\n if (await has(\"yarn.lock\")) return \"yarn\";\n if ((await has(\"bun.lockb\")) || (await has(\"bun.lock\"))) return \"bun\";\n return \"npm\";\n}\n\n/** `<pm> run <script>` as that manager says it. */\nexport function runScript(pm: PackageManager, script: string): string[] {\n return pm === \"yarn\" ? [script] : [\"run\", script];\n}\n","/**\n * Next.js template: an app with its own server. Nothing is built here: the source is shipped\n * (without node_modules, .next and .git) and the box installs, builds and runs it with the\n * project's own package manager, as a systemd service `kvbox-app` on port 3000. The box has\n * Node.js 22 and npm; pnpm and yarn come through corepack. Building in the box keeps the result\n * independent of this machine and leaves the whole project there for `kvbox connect`.\n */\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { packageManager, type PackageManager } from \"./pm.js\";\nimport type { BuildContext, BuildResult, PackageJson, Template } from \"./types.js\";\n\n/** Where the app lives in the box; a deploy stages beside it and swaps. */\nexport const APP_DIR = \"/srv/app/current\";\nexport const SERVICE = \"kvbox-app\";\nconst PORT = 3000;\n\n/** The box's commands for each manager; bun is not in the image, so its project installs with npm. */\nfunction commands(pm: PackageManager): { setup: string[]; install: string; build: string; start: string } {\n switch (pm) {\n case \"pnpm\":\n return { setup: [\"sudo -n corepack enable pnpm\"], install: \"pnpm install --frozen-lockfile\", build: \"pnpm run build\", start: \"pnpm run start\" };\n case \"yarn\":\n return { setup: [\"sudo -n corepack enable yarn\"], install: \"yarn install --frozen-lockfile\", build: \"yarn build\", start: \"yarn start\" };\n case \"bun\":\n return { setup: [], install: \"npm install\", build: \"npm run build\", start: \"npm run start\" };\n case \"npm\":\n return { setup: [], install: \"if [ -f package-lock.json ]; then npm ci; else npm install; fi\", build: \"npm run build\", start: \"npm run start\" };\n }\n}\n\nexport const nextjsTemplate: Template = {\n id: \"nextjs\",\n label: \"Next.js\",\n hint: \"source shipped; installed, built and run in the box on port 3000\",\n size: \"s\",\n port: PORT,\n\n detect(pkg: PackageJson | undefined): boolean {\n if (!pkg) return false;\n return \"next\" in { ...pkg.dependencies, ...pkg.devDependencies };\n },\n\n /** No local build: the box does it. Only the scripts it will need are checked here. */\n async build(ctx: BuildContext): Promise<BuildResult> {\n for (const script of [\"build\", \"start\"]) {\n if (typeof ctx.pkg?.scripts?.[script] !== \"string\") throw new KvboxError(`${ctx.dir}: package.json has no \"${script}\" script; Next.js needs \"build\": \"next build\" and \"start\": \"next start\"`);\n }\n const pm = await packageManager(ctx.dir);\n return { outDir: ctx.dir, exclude: [\"node_modules\", \".next\", \".git\"], pm, what: \"the source\" };\n },\n\n /**\n * The source lands in a staging directory and is installed and built there while the old app\n * keeps serving; only then is it swapped into place and the service restarted, so a failed\n * install or build leaves the running app alone. The unit is rewritten every time, so a changed\n * package manager or start script takes effect. /srv/app is the kvbox user's (image v0.8.0+).\n */\n remote(built: BuildResult): string {\n const c = commands(built.pm);\n const unit = [\n \"[Unit]\",\n \"Description=kvbox deploy: the app in \" + APP_DIR,\n \"After=network.target\",\n \"\",\n \"[Service]\",\n \"User=kvbox\",\n `WorkingDirectory=${APP_DIR}`,\n `ExecStart=/usr/bin/env ${c.start}`,\n `Environment=NODE_ENV=production PORT=${PORT}`,\n \"Restart=always\",\n \"RestartSec=2\",\n \"\",\n \"[Install]\",\n \"WantedBy=multi-user.target\",\n ];\n return [\n \"set -e\",\n \"test -d /srv/app -a -w /srv/app || exit 3\",\n \"rm -rf /srv/app/.incoming /srv/app/.old\",\n \"mkdir -p /srv/app/.incoming\",\n \"tar -xf - -C /srv/app/.incoming\",\n \"cd /srv/app/.incoming\",\n // Not NODE_ENV=production here: the install would skip devDependencies, which the build needs (TypeScript, Tailwind).\n \"export CI=1 NEXT_TELEMETRY_DISABLED=1\",\n ...c.setup,\n c.install,\n c.build,\n \"cd /\",\n `sudo -n tee /etc/systemd/system/${SERVICE}.service >/dev/null <<'UNIT'`,\n ...unit,\n \"UNIT\",\n `if [ -e ${APP_DIR} ]; then mv ${APP_DIR} /srv/app/.old; fi`,\n `mv /srv/app/.incoming ${APP_DIR}`,\n \"sudo -n systemctl daemon-reload\",\n `sudo -n systemctl enable --quiet ${SERVICE}`,\n `sudo -n systemctl restart ${SERVICE}`,\n \"rm -rf /srv/app/.old\",\n ].join(\"\\n\");\n },\n};\n","/**\n * React template: a static single-page app. Built on this machine with the project's own `build`\n * script (Vite, CRA or anything that leaves a directory of files), the output directory is shipped\n * to `/srv/app/dist` in the box and nginx serves it on port 80. nginx comes with the base image\n * (v0.8.0 and later), wired to that directory and off until the first deploy turns it on.\n */\nimport { spawn } from \"node:child_process\";\nimport { access } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { color, info } from \"../../../output.js\";\nimport { packageManager, runScript, type PackageManager } from \"./pm.js\";\nimport type { BuildContext, BuildResult, PackageJson, Template } from \"./types.js\";\n\n/** Where a React build lands, by tool: Vite's `dist`, Create React App's `build`. */\nconst OUT_DIRS = [\"dist\", \"build\"];\n\n/**\n * Run the project's `build` script where the user can watch it: both of its streams go to stderr,\n * because stdout is the command's result (the URL, or `--json`). A non-zero exit is the error.\n */\nexport async function runBuild(dir: string, pm: PackageManager): Promise<void> {\n const args = runScript(pm, \"build\");\n info(`${color.dim(\"$\")} ${pm} ${args.join(\" \")}`);\n const status = await new Promise<number>((resolve, reject) => {\n const child = spawn(pm, args, { cwd: dir, stdio: [\"ignore\", process.stderr, process.stderr], shell: process.platform === \"win32\" });\n child.once(\"error\", (err) => reject(new KvboxError(`could not run ${pm}: ${err.message}`)));\n child.once(\"close\", (code) => resolve(code ?? 1));\n });\n if (status !== 0) throw new KvboxError(`the build failed (${pm} exited ${status}); nothing was deployed`);\n}\n\nexport const reactTemplate: Template = {\n id: \"react\",\n label: \"React\",\n hint: \"static site: built here, served by nginx in the box\",\n size: \"xs\",\n port: 80,\n\n /** A Vite or Create React App project. A framework with its own server (Next.js, Remix, Expo) is not a static site. */\n detect(pkg: PackageJson | undefined): boolean {\n if (!pkg) return false;\n const deps = { ...pkg.dependencies, ...pkg.devDependencies };\n if (!(\"react\" in deps) || \"next\" in deps || \"@remix-run/react\" in deps || \"expo\" in deps) return false;\n return \"vite\" in deps || \"react-scripts\" in deps;\n },\n\n async build(ctx: BuildContext): Promise<BuildResult> {\n if (typeof ctx.pkg?.scripts?.[\"build\"] !== \"string\") throw new KvboxError(`${ctx.dir}: package.json has no \"build\" script`);\n const pm = await packageManager(ctx.dir);\n await runBuild(ctx.dir, pm);\n const candidates = ctx.dist !== undefined ? [ctx.dist] : OUT_DIRS;\n for (const dist of candidates) {\n const outDir = join(ctx.dir, dist);\n if (await access(join(outDir, \"index.html\")).then(() => true, () => false)) return { outDir, dist, exclude: [], pm, what: `${dist}/` };\n }\n throw new KvboxError(\n `the build left no ${candidates.join(\" or \")}/index.html. The React template ships a directory of static files; ` +\n `set \"dist\" in kvbox.json to the build output directory, or pick the right template with --template`,\n );\n },\n\n /**\n * The archive lands in a staging directory, which then becomes /srv/app/dist in one move; the\n * old site is kept beside it until the new one is in place, so a failed step never leaves nginx\n * without a root and a visitor never sees a half-copied site. Files get read permission for\n * nginx's user, whatever umask the build ran under. /srv/app is the kvbox user's (image v0.8.0+);\n * the missing site file means an older image.\n */\n remote(): string {\n return [\n \"set -e\",\n \"test -e /etc/nginx/sites-enabled/kvbox-app || exit 3\",\n \"rm -rf /srv/app/.incoming /srv/app/.old\",\n \"mkdir -p /srv/app/.incoming\",\n \"tar -xf - -C /srv/app/.incoming\",\n \"chmod -R a+rX /srv/app/.incoming\",\n \"if [ -e /srv/app/dist ]; then mv /srv/app/dist /srv/app/.old; fi\",\n \"mv /srv/app/.incoming /srv/app/dist\",\n \"rm -rf /srv/app/.old\",\n \"sudo -n systemctl enable --now --quiet nginx\",\n \"sudo -n systemctl reload nginx\",\n ].join(\"\\n\");\n },\n};\n","/** The deploy templates, one file each; a new kind of app is a new file and a line here. */\nimport { nextjsTemplate } from \"./nextjs.js\";\nimport { reactTemplate } from \"./react.js\";\nimport type { PackageJson, Template } from \"./types.js\";\n\nexport const TEMPLATES: readonly Template[] = [reactTemplate, nextjsTemplate];\n\nexport const TEMPLATE_IDS = TEMPLATES.map((t) => t.id) as [string, ...string[]];\n\nexport function templateById(id: string): Template {\n const t = TEMPLATES.find((x) => x.id === id);\n if (!t) throw new Error(`no template ${id}`);\n return t;\n}\n\n/** The first template that recognizes the app, or undefined. */\nexport function detectTemplate(pkg: PackageJson | undefined): Template | undefined {\n return TEMPLATES.find((t) => t.detect(pkg));\n}\n\nexport type { BuildContext, BuildResult, PackageJson, Template } from \"./types.js\";\nexport type { PackageManager } from \"./pm.js\";\n","/**\n * Shipping a directory into a box: `tar` on this machine, piped into `ssh` running the template's\n * script in the box. No library and nothing new in the image: tar and ssh are on every machine\n * the CLI runs on (Windows 10+ has both), and the box side is the same `ssh` every command uses.\n */\nimport { spawn } from \"node:child_process\";\nimport { readdir, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { sshArgs, waitForSsh, type SshEndpoint } from \"../../client.js\";\n\n/** Exit status the template's script uses for \"this box's image is too old\". */\nexport const IMAGE_TOO_OLD = 3;\n/** ssh's own status when it could not connect or the session broke. */\nexport const SSH_FAILED = 255;\n\nexport interface Shipped {\n files: number;\n bytes: number;\n}\n\n/** How many files and bytes a directory holds, for the summary line; excluded names are not entered. */\nexport async function measure(dir: string, exclude: string[] = []): Promise<Shipped> {\n const total = { files: 0, bytes: 0 };\n const walk = async (d: string): Promise<void> => {\n for (const entry of await readdir(d, { withFileTypes: true })) {\n if (exclude.includes(entry.name)) continue;\n const path = join(d, entry.name);\n if (entry.isDirectory()) await walk(path);\n else if (entry.isFile()) {\n total.files += 1;\n total.bytes += (await stat(path)).size;\n }\n }\n };\n await walk(dir);\n return total;\n}\n\n/**\n * `tar -cf - -C <dir> . | ssh <box> '<remote>'`: the archive holds the directory's contents, so\n * the remote script extracts straight into its staging directory whatever the directory is called\n * here. An excluded name is left out at any depth (every `node_modules`, not only the top one). Resolves with the remote script's exit status; ssh's output is kept and returned so a\n * failure can show it. ssh exiting before it has read the archive (the script refused the image,\n * the connection was refused) is a normal outcome: the status is the answer, so the broken pipe\n * tar then hits is expected and tar is let go.\n */\nexport async function ship(ep: SshEndpoint, dir: string, remote: string, exclude: string[] = []): Promise<{ status: number; output: string }> {\n const tar = spawn(\"tar\", [\"-cf\", \"-\", ...exclude.map((e) => `--exclude=${e}`), \"-C\", dir, \".\"], { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n const ssh = spawn(\"ssh\", [...sshArgs(ep), remote], { stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n tar.stdout.pipe(ssh.stdin);\n const chunks: Buffer[] = [];\n ssh.stdout.on(\"data\", (c: Buffer) => chunks.push(c));\n ssh.stderr.on(\"data\", (c: Buffer) => chunks.push(c));\n tar.stderr.on(\"data\", (c: Buffer) => chunks.push(c));\n // EPIPE when ssh is gone: expected, see above. Without a listener it is an uncaught exception.\n ssh.stdin.on(\"error\", () => {});\n tar.stdout.on(\"error\", () => {});\n // tar failing (a vanished file) must surface as a broken pipe on the ssh side, not a hang.\n tar.once(\"error\", () => ssh.stdin.end());\n tar.once(\"close\", (code) => { if (code !== 0) ssh.stdin.end(); });\n\n const tarDone = new Promise<void>((resolve) => tar.once(\"close\", () => resolve()));\n const status = await new Promise<number>((resolve, reject) => {\n ssh.once(\"error\", (err) => reject(new KvboxError(`could not run ssh: ${err.message}`)));\n ssh.once(\"close\", (code, signal) => {\n // Whatever tar still has to say goes nowhere now; let it finish instead of blocking on a full pipe.\n tar.stdout.unpipe(ssh.stdin);\n tar.stdout.resume();\n tar.kill();\n resolve(code ?? (signal === \"SIGINT\" ? 130 : 1));\n });\n });\n await tarDone;\n return { status, output: Buffer.concat(chunks).toString(\"utf8\") };\n}\n\n/** The pieces the command shells out through; tests replace them. */\nexport const shipping = { ship, measure, waitForSsh };\n","import { Command } from \"commander\";\nimport { attachCommand } from \"./attach.js\";\nimport { createCommand } from \"./create.js\";\nimport { detachCommand } from \"./detach.js\";\nimport { lsCommand } from \"./ls.js\";\nimport { rmCommand } from \"./rm.js\";\n\nexport const volumeCommand = new Command(\"volume\")\n .aliases([\"volumes\", \"vol\"])\n .description(\"disks of their own: create one, attach it to a box at /mnt/<name>, move it to another box later\")\n .addCommand(createCommand)\n .addCommand(lsCommand)\n .addCommand(attachCommand)\n .addCommand(detachCommand)\n .addCommand(rmCommand);\n\nfor (const cmd of volumeCommand.commands) cmd.option(\"--org <slug>\", \"act in this org (- for your personal volumes)\");\n","import { Command } from \"commander\";\nimport { volumeMountPath } from \"@kvbox/shared/paths\";\nimport { clientFor } from \"../../client.js\";\nimport { color, info, json, spin } from \"../../output.js\";\n\n/**\n * kvbox volume attach <volume> <box> [--json] — the box gets the volume as a disk, mounted at\n * /mnt/<volume>. Firecracker takes drives at boot only, so a running box is restarted. --json output: Machine\n */\nexport const attachCommand = new Command(\"attach\")\n .description(\"attach a volume to a box at /mnt/<volume> (a running box is restarted to take it)\")\n .argument(\"<volume>\", \"volume name\")\n .argument(\"<box>\", \"box name\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (volume: string, box: string, opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const machine = await spin(`attaching volume ${volume} to box ${box} (a running box is restarted)…`, client.attachVolume(volume, { box }));\n if (opts.json) {\n json(machine);\n return;\n }\n // The server names the mount; `volume` may be an owner/name ref, which is not the mount's name.\n const path = machine.volumes?.find((v) => volume === v.name || volume.endsWith(`/${v.name}`))?.mountPath ?? volumeMountPath(volume.slice(volume.lastIndexOf(\"/\") + 1));\n info(`${color.green(\"✓\")} volume ${volume} attached to box ${box}`);\n info(machine.status === \"running\" ? ` the box was restarted; the volume is at ${path} inside it` : ` box ${box} is ${machine.status}; the volume is at ${path} once it runs`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { MAX_VOLUME_GIB } from \"@kvbox/shared/api\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { parseMib } from \"@kvbox/shared/sizes\";\nimport { clientFor } from \"../../client.js\";\nimport { color, info, json, spin } from \"../../output.js\";\n\n/** \"50\", \"50G\", \"50GB\" -> 50; whole GB only. */\nexport function parseGib(text: string): number {\n const mib = parseMib(text);\n if (mib === undefined || mib % 1024 !== 0) throw new KvboxError(`--size ${text}: write whole GB, like 50 or 50GB`);\n const gib = mib / 1024;\n if (gib > MAX_VOLUME_GIB) throw new KvboxError(`--size ${text}: a volume is at most ${MAX_VOLUME_GIB} GB`);\n return gib;\n}\n\n/**\n * kvbox volume create <name> --size <gb> [--box <box>] [--json] — --json output: Volume.\n * `--box` matters through a control plane (#91): a volume lives on one host and attaches only to a box\n * there, so it is made on that box's host; without it, on the host with the most room for volumes.\n */\nexport const createCommand = new Command(\"create\")\n .alias(\"new\")\n .description(\"create a volume: an empty disk of its own, ready to attach to a box\")\n .argument(\"<name>\", \"volume name (1-12 chars; the box mounts it at /mnt/<name>)\")\n .requiredOption(\"--size <gb>\", \"size in GB, like 50 or 50GB (whole GB; it only occupies what is written)\")\n .option(\"--box <box>\", \"the box it is for: made on that box's host (a volume attaches only to a box on its own host)\")\n .option(\"--json\", \"print the volume as JSON\")\n .action(async (name: string, opts: { size: string; box?: string; json?: boolean }, cmd: Command) => {\n const sizeGib = parseGib(opts.size);\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const vol = await spin(`creating volume ${name} (${sizeGib} GB)…`, client.createVolume({ name, sizeGib, ...(opts.box !== undefined ? { box: opts.box } : {}) }));\n if (opts.json) json(vol);\n else info(`${color.green(\"✓\")} volume ${name} created (${vol.sizeGib} GB); attach it to a box with: kvbox volume attach ${name} ${opts.box ?? \"<box>\"}`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { clientFor } from \"../../client.js\";\nimport { color, info, json, spin } from \"../../output.js\";\n\n/** kvbox volume detach <volume> <box> [--json] — the volume keeps its data; a running box is restarted. --json output: Machine */\nexport const detachCommand = new Command(\"detach\")\n .description(\"detach a volume from a box; its data is kept (a running box is restarted)\")\n .argument(\"<volume>\", \"volume name\")\n .argument(\"<box>\", \"box name\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (volume: string, box: string, opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const machine = await spin(`detaching volume ${volume} from box ${box} (a running box is restarted)…`, client.detachVolume(volume, { box }));\n if (opts.json) {\n json(machine);\n return;\n }\n info(`${color.green(\"✓\")} volume ${volume} detached from box ${box}; its data is kept${machine.status === \"running\" ? \" (the box was restarted)\" : \"\"}`);\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { clientFor } from \"../../client.js\";\nimport { age, boxName, gbShort, info, json, slugOf, table } from \"../../output.js\";\n\n/** kvbox volume ls [--all] [--json] — the user's and their orgs' volumes (`--org <slug>` for one org). --json output: Volume[] */\nexport const lsCommand = new Command(\"ls\")\n .alias(\"list\")\n .description(\"list volumes: size, what they occupy, which box has them\")\n .option(\"-a, --all\", \"every volume on the platform (platform admins only)\")\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { all?: boolean; json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const cloud = client.target.kind === \"cloud\";\n const vols = await client.listVolumes({ all: opts.all });\n if (opts.json) {\n json(vols);\n return;\n }\n if (vols.length === 0) {\n info(\"no volumes yet; make one with: kvbox volume create <name> --size 50GB\");\n return;\n }\n const org = cloud ? client.target.org : undefined;\n if (org !== undefined) info(`volumes of ${org}`);\n table(\n vols.map((v) => ({\n ...(cloud ? { owner: slugOf(v.owner) === client.target.user ? \"private\" : slugOf(v.owner) } : {}),\n name: boxName(v.name),\n size: `${v.sizeGib}GB`,\n used: gbShort(v.usedBytes),\n \"attached to\": v.attachedTo ?? \"-\",\n created: age(v.createdAt),\n })),\n );\n } finally {\n await client.close();\n }\n });\n","import { Command } from \"commander\";\nimport { clientFor } from \"../../client.js\";\nimport { color, confirm, info, spin } from \"../../output.js\";\n\n/** kvbox volume rm <name> [-y] — destructive: asks y/N on a TTY, needs -y otherwise. Only a detached volume goes. */\nexport const rmCommand = new Command(\"rm\")\n .alias(\"remove\")\n .description(\"delete a volume and everything on it (detach it first)\")\n .argument(\"<name>\", \"volume name\")\n .option(\"-y, --yes\", \"do not ask for confirmation\")\n .action(async (name: string, opts: { yes?: boolean }, cmd: Command) => {\n if (!(await confirm(`Delete volume ${name} and everything on it?`, opts.yes ?? false))) {\n info(\"cancelled\");\n process.exitCode = 1;\n return;\n }\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n await spin(`deleting volume ${name}…`, client.deleteVolume(name));\n info(`${color.green(\"✓\")} volume ${name} deleted`);\n } finally {\n await client.close();\n }\n });\n","/** Entry point: parse argv, map KvboxError to an exit code. */\nimport { color } from \"./output.js\";\nimport { buildProgram } from \"./program.js\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\n\ntry {\n await buildProgram().parseAsync(process.argv);\n} catch (err) {\n if (err instanceof KvboxError) {\n process.stderr.write(color.red(`error: ${err.message}`) + \"\\n\");\n process.exit(err.exitCode);\n }\n throw err;\n}\n"],"mappings":";;;AACO,IAAM,aAAN,cAAyB,MAAM;AAAA,EACpC,YACE,SACgB,WAAmB,GACnC;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AAAA,EAJkB;AAKpB;AA0BO,IAAM,oBAAN,cAAgC,WAAW;AAAA;AAAA,EAEhD,YAAY,MAAc,MAAc,OAA0B,UAAU,MAAM;AAChF,UAAM,MAAM,UAAU,SAAS,MAAM,CAAC,CAAC,OAAO,MAAM,CAAC,CAAC,IAAI,IAAI,KAAK,GAAG,MAAM,CAAC,CAAC,IAAI,IAAI;AACtF,UAAM,GAAG,IAAI,IAAI,IAAI,cAAc,MAAM,MAAM,GAAG,EAAE,EAAE,KAAK,IAAI,CAAC,QAAQ,MAAM,GAAG,EAAE,CAAC,oBAAoB,GAAG,IAAI,CAAC;AAChH,SAAK,OAAO;AAAA,EACd;AACF;;;ACxCA,OAAO,QAAQ;AAER,IAAM,QAAQ,GAAG,aAAa,QAAQ,OAAO,UAAU,QAAQ,CAAC,QAAQ,IAAI,UAAU,CAAC;AAEvF,SAAS,KAAK,OAAsB;AACzC,UAAQ,OAAO,MAAM,KAAK,UAAU,OAAO,MAAM,CAAC,IAAI,IAAI;AAC5D;AAGA,IAAM,OAAO;AAEb,IAAM,QAAQ,CAAC,MAAc,EAAE,QAAQ,MAAM,EAAE,EAAE;AAG1C,SAAS,MAAMA,OAA4D,SAA0B;AAC1G,MA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AAU;AAC7B,UAAQ,WAAWC,aAAY;AAC/B,UAAQ,WAAW,aAAa;AAChC,UAAQ,WAAW,aAAa;AAEhC,aAAW,OAAO,UAAW,SAAQ,WAAW,GAAG;AAEnD,SAAO;AACT;;;A+ElCA,IAAI;AACF,QAAM,aAAa,EAAE,WAAW,QAAQ,IAAI;AAC9C,SAAS,KAAK;AACZ,MAAI,eAAe,YAAY;AAC7B,YAAQ,OAAO,MAAM,MAAM,IAAI,UAAU,IAAI,OAAO,EAAE,IAAI,IAAI;AAC9D,YAAQ,KAAK,IAAI,QAAQ;AAAA,EAC3B;AACA,QAAM;AACR;","names":["rows","createInterface","day","text","me","Command","require","Command","spawnSync","Command","readFile","rm","writeFile","text","writeFile","rm","readFile","mkdir","readFile","z","z","text","z","text","readFileSync","text","text","json","z","resolve","readFile","mkdir","text","Command","spawnSync","spawn","Command","SSH_FAILED","spawn","status","resolve","Command","Command","Option","Command","Option","Command","Command","me","Command","text","Command","rows","width","Command","Command","Command","Command","Command","text","Command","Command","Command","Command","rows","Command","lsCommand","Command","rows","Command","Command","Command","Command","Command","Command","Command","lsCommand","Command","Option","Command","Option","text","Command","Command","Command","rmCommand","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","rows","Command","Command","Command","rmCommand","Command","Command","spawn","readFile","sleep","readFile","sleep","resolve","spawn","Command","Command","Command","Command","Command","Command","startCommand","Command","Command","Command","Command","stopCommand","Command","Command","Command","Command","startCommand","stopCommand","spawnSync","mkdir","readFile","writeFile","createInterface","Command","ANSI","width","resolve","Command","readFile","mkdir","spawnSync","writeFile","createInterface","Command","Command","Command","Command","Command","Command","lsCommand","Command","Command","newCommand","Command","Command","rmCommand","Command","Command","newCommand","lsCommand","rmCommand","Command","Command","lsCommand","Command","Command","Option","lsCommand","Command","addCommand","Option","rmCommand","Command","newCommand","Command","Command","rmCommand","Command","Command","Command","Command","lsCommand","newCommand","rmCommand","Command","z","usageCommand","Command","day","me","ownerCell","rows","Command","Command","me","readFile","resolve","Command","Option","readFile","writeFile","join","z","join","spawn","access","join","status","resolve","spawn","join","access","z","join","readFile","json","writeFile","spawn","stat","join","SSH_FAILED","join","stat","spawn","resolve","status","Command","Option","resolve","SSH_FAILED","readFile","Command","Command","Command","Command","parseGib","text","Command","Command","Command","Command","lsCommand","Command","Command","rmCommand","Command","Command","lsCommand","rmCommand","Command","usageCommand"]}