@kvbox/cli 0.5.7 → 0.5.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/kvbox.js CHANGED
@@ -147,7 +147,7 @@ async function spin(message, work, opts = {}) {
147
147
  }
148
148
 
149
149
  // src/program.ts
150
- import { Command as Command38 } from "commander";
150
+ import { Command as Command39 } from "commander";
151
151
 
152
152
  // ../shared/src/version.ts
153
153
  import { createRequire } from "module";
@@ -162,7 +162,7 @@ function versionOf(srcFileUrl, injected) {
162
162
  }
163
163
 
164
164
  // src/version.ts
165
- var VERSION = versionOf(import.meta.url, true ? "0.5.7" : void 0);
165
+ var VERSION = versionOf(import.meta.url, true ? "0.5.8" : void 0);
166
166
 
167
167
  // src/commands/vm/index.ts
168
168
  import { Command as Command15 } from "commander";
@@ -773,11 +773,11 @@ var ServerClient = class {
773
773
  base;
774
774
  autoStart;
775
775
  startedOnce = false;
776
- async call(method, path, schema, body) {
776
+ async call(method, path, schema, body, org = this.target.kind === "cloud" ? this.target.org : void 0) {
777
777
  const headers = {};
778
778
  if (body !== void 0) headers["content-type"] = "application/json";
779
779
  if (this.target.kind === "cloud" && this.target.token !== "") headers["authorization"] = `Bearer ${this.target.token}`;
780
- if (this.target.kind === "cloud" && this.target.org !== void 0) headers["x-kvbox-org"] = this.target.org;
780
+ if (this.target.kind === "cloud" && org !== void 0) headers["x-kvbox-org"] = org;
781
781
  let res;
782
782
  try {
783
783
  res = await request(this.base + path, {
@@ -866,9 +866,9 @@ var ServerClient = class {
866
866
  const query = q.size === 0 ? "" : `?${q.toString()}`;
867
867
  return this.call("GET", `/usage${query}`, UsageReportSchema);
868
868
  }
869
- /** The prepaid balance of the caller's slug, or of `--org`'s (#76); a control plane only. */
870
- balance() {
871
- return this.call("GET", "/billing/balance", BalanceSchema);
869
+ /** The prepaid balance of the caller's slug, or of `org` (default: `--org`'s) (#76); a control plane only. */
870
+ balance(org) {
871
+ return this.call("GET", "/billing/balance", BalanceSchema, void 0, org);
872
872
  }
873
873
  deleteMachine(name) {
874
874
  return this.call("DELETE", `/machines/${encodeURIComponent(name)}`, z3.undefined());
@@ -2086,9 +2086,38 @@ function usageRows(report, cloud) {
2086
2086
  return rows;
2087
2087
  }
2088
2088
 
2089
+ // src/commands/credit.ts
2090
+ import { Command as Command38 } from "commander";
2091
+ var creditCommand = new Command38("credit").description("the prepaid credit left on your account and on each of your orgs").option("--org <slug>", "one org only").option("--json", "print as JSON").action(async (opts, cmd) => {
2092
+ const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
2093
+ try {
2094
+ if (client.target.kind === "local") throw new KvboxError("credit lives on the control plane: kvbox login first");
2095
+ const me2 = client.target.user;
2096
+ const balances = client.target.org !== void 0 ? [await client.balance()] : await Promise.all([void 0, ...(await client.listOrgs()).map((o) => o.slug)].map((org) => client.balance(org)));
2097
+ if (opts.json) {
2098
+ json(balances);
2099
+ return;
2100
+ }
2101
+ table(balances.map((b) => creditRow(b, me2)));
2102
+ } finally {
2103
+ await client.close();
2104
+ }
2105
+ });
2106
+ function creditRow(b, me2) {
2107
+ const left = money(b.balance, b.currency);
2108
+ return {
2109
+ owner: b.slug === me2 ? "private" : boxName(b.slug),
2110
+ credit: b.balance > 0 ? left : color.red(left),
2111
+ "topped up": money(b.topUps, b.currency),
2112
+ spent: money(b.spent, b.currency),
2113
+ // Suspended (#76): the sweep hibernated the boxes at zero; a top-up brings them back.
2114
+ state: b.suspendedAt ? color.red("suspended") : b.since === null ? color.dim("never topped up") : "ok"
2115
+ };
2116
+ }
2117
+
2089
2118
  // src/program.ts
2090
2119
  function buildProgram() {
2091
- const program = new Command38("kvbox").description("self-hosted Firecracker microVMs with Docker-like ergonomics").version(VERSION, "-v, --version").option("--local", "use this machine's kvbox-server over its socket, ignoring kvbox login").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").showHelpAfterError().enablePositionalOptions();
2120
+ const program = new Command39("kvbox").description("self-hosted Firecracker microVMs with Docker-like ergonomics").version(VERSION, "-v, --version").option("--local", "use this machine's kvbox-server over its socket, ignoring kvbox login").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").showHelpAfterError().enablePositionalOptions();
2092
2121
  program.addCommand(vmCommand);
2093
2122
  program.addCommand(snapshotsCommand);
2094
2123
  program.addCommand(serverCommand);
@@ -2097,6 +2126,7 @@ function buildProgram() {
2097
2126
  program.addCommand(whoamiCommand);
2098
2127
  program.addCommand(orgCommand);
2099
2128
  program.addCommand(usageCommand2);
2129
+ program.addCommand(creditCommand);
2100
2130
  for (const cmd of vmAliases) program.addCommand(cmd);
2101
2131
  return program;
2102
2132
  }
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/commands/vm/new.ts","../src/commands/vm/exec.ts","../src/commands/vm/hibernate.ts","../src/commands/vm/ls.ts","../src/commands/vm/pause.ts","../src/commands/vm/rescale.ts","../src/commands/vm/resume.ts","../src/commands/vm/rm.ts","../src/commands/vm/start.ts","../src/commands/vm/stop.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/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","../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 constructor(kind: string, name: string, slugs: readonly string[]) {\n super(`${kind} ${name} exists in ${slugs.slice(0, -1).join(\", \")} and ${slugs.at(-1)}; say which with --org ${slugs[0]} or ${slugs[0]}/${name}`, 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\";\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 // 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 { hibernateCommand } from \"./hibernate.js\";\nimport { lsCommand } from \"./ls.js\";\nimport { newCommand } from \"./new.js\";\nimport { pauseCommand } from \"./pause.js\";\nimport { rescaleCommand } from \"./rescale.js\";\nimport { resumeCommand } from \"./resume.js\";\nimport { rmCommand } from \"./rm.js\";\nimport { startCommand } from \"./start.js\";\nimport { stopCommand } from \"./stop.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(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(usageCommand)\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) 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 * (update, rescale and usage stay under `kvbox vm`, so the top level does not fill up).\n */\nexport const vmAliases = [newCommand, lsCommand, connectCommand, execCommand, stopCommand, startCommand, pauseCommand, resumeCommand, hibernateCommand, wakeCommand, rmCommand];\n","import { spawnSync } from \"node:child_process\";\nimport { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { ensureCert, renewAfterRefusal } from \"../../cert.js\";\nimport { 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 client.listMachines(), 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 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 CloudCaSchema,\n CloudOrgSchema,\n type CreateMachineRequest,\n type CreateOrgRequest,\n type CreateSnapshotRequest,\n HealthSchema,\n type LoginRequest,\n LoginResponseSchema,\n type Machine,\n MachineSchema,\n MachineUsageSchema,\n MeResponseSchema,\n OrgDetailSchema,\n OrgMembershipSchema,\n type OrgRole,\n type RescaleMachineRequest,\n SnapshotSchema,\n SshCaResponseSchema,\n type SshCertRequest,\n SshCertResponseSchema,\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 { 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\nconst 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\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\" | \"PATCH\" | \"DELETE\",\n path: string,\n schema: z.ZodType<T>,\n body?: unknown,\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\" && this.target.org !== undefined) headers[\"x-kvbox-org\"] = this.target.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 /** Through a control plane: every box the user can see, or the `--org` org's. */\n listMachines() {\n return this.call(\"GET\", \"/machines\", z.array(MachineSchema));\n }\n\n createMachine(req: CreateMachineRequest) {\n return this.call(\"POST\", \"/machines\", 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 /** `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) {\n const q = new URLSearchParams();\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`'s (#76); a control plane only. */\n balance() {\n return this.call(\"GET\", \"/billing/balance\", BalanceSchema);\n }\n\n deleteMachine(name: string) {\n return this.call(\"DELETE\", `/machines/${encodeURIComponent(name)}`, z.undefined());\n }\n\n listSnapshots() {\n return this.call(\"GET\", \"/snapshots\", z.array(SnapshotSchema));\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/** 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 \"-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/** The last `error: …` line of server.log, which is why a daemon that just died did not come up. */\nasync function lastErrorLine(logPath: string): Promise<string | undefined> {\n const { readFile } = await import(\"node:fs/promises\");\n const text = await readFile(logPath, \"utf8\").catch(() => \"\");\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 * 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 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 const ready = (async () => {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\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 await Promise.race([ready, 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 * 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\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\" or \"snapshot:<name>\"\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 /** 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});\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});\nexport type CreateMachineRequest = z.infer<typeof CreateMachineRequest>;\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\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\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 })\n .nullable()\n .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/** 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});\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 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","import { Command, Option } from \"commander\";\nimport type { Machine } from \"@kvbox/shared/api\";\nimport { SIZE_NAMES } from \"@kvbox/shared/sizes\";\nimport { clientFor } from \"../../client.js\";\nimport { color, gb, info, json, shortRef, slugOf, spin } from \"../../output.js\";\n\n/**\n * kvbox vm new [name] [--size s|m|l] [--from <snapshot>] [--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(\"--force\", \"skip the capacity guard\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string | undefined, opts: { size?: string; from?: string; force?: boolean; json?: boolean }, cmd: Command) => {\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 ...(opts.force ? { force: true } : {}),\n }));\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 } 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:\") ? ` from snapshot ${shortRef(box.source.slice(\"snapshot:\".length), box.owner)}` : \"\";\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","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 { 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 client.listMachines(), 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 } 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, Option } from \"commander\";\nimport type { Machine } from \"@kvbox/shared/api\";\nimport { clientFor } from \"../../client.js\";\nimport { age, boxName, color, gbShort, info, json, shape, slugOf, 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/** Where ssh reaches the box: `host:port` through the control plane (#21), its ip on this machine, `-` when unknown. */\nexport function addressOf(b: Machine): string {\n if (b.ssh !== undefined) return `${b.ssh.host}:${b.ssh.port}`;\n return b.ip === \"\" ? \"-\" : b.ip;\n}\n\n/**\n * kvbox vm ls [--json] — every box the user can see (theirs and each org's through a control plane;\n * `--org <slug>` narrows to that org). --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 .addOption(new Option(\"-a, --all\", \"kept for older scripts: the listing covers everything you can see anyway\").hideHelp())\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const boxes = await client.listMachines();\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, Option } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { SIZE_NAMES, parseMib } from \"@kvbox/shared/sizes\";\nimport { 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 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 client.listMachines(), 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 { 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 client.listMachines(), 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 { 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 { KvboxError } from \"@kvbox/shared/errors\";\nimport { 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 client.listMachines(), 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 { clientFor } from \"../../client.js\";\nimport { info, json } from \"../../output.js\";\n\n/** kvbox server status [--json] — --json output: Health (version, pid, base image new boxes get, control plane) */\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 if (opts.json) json(health);\n else {\n info(`kvbox-server ${health.version} running, pid ${health.pid}`);\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) info(`relay: ${health.relay.name} lends this machine ${health.relay.publicIp} (tunnel to ${health.relay.endpoint})`);\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 { 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 ask(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 ask(rl, question);\n } finally {\n io.output.write(\"\\n\");\n }\n}\n\n/**\n * One question, closing the interface afterwards. Ctrl-C in terminal mode rejects the question\n * (ABORT_ERR); Ctrl-D or EOF only closes the interface and would leave the question pending forever,\n * so a close before the answer is treated the same way: the user cancelled (exit 130).\n */\nasync function ask(rl: ReturnType<typeof createInterface>, question: string): Promise<string> {\n let onClose = () => {};\n const closed = new Promise<never>((_, reject) => {\n onClose = () => reject(new KvboxError(\"cancelled\", 130));\n rl.once(\"close\", onClose);\n });\n try {\n return await Promise.race([rl.question(question).catch(cancelled), closed]);\n } finally {\n rl.off(\"close\", onClose);\n rl.close();\n }\n}\n\nfunction cancelled(err: unknown): never {\n if ((err as NodeJS.ErrnoException).code === \"ABORT_ERR\") throw new KvboxError(\"cancelled\", 130);\n throw err;\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","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, Option } 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 [--json] — every snapshot the user can see (`--org <slug>` for one org). --json output: Snapshot[] */\nexport const lsCommand = new Command(\"ls\")\n .description(\"list snapshots (yours and your orgs'; --org <slug> for one org)\")\n .addOption(new Option(\"-a, --all\", \"kept for older scripts: the listing covers everything you can see anyway\").hideHelp())\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { 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();\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 { 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>] [--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 every slug you can read (`--org <slug>` for one org) 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 * --json output: the UsageReport object { window, boxes: BoxUsage[], totals }.\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(\"--json\", \"print as JSON\")\n .action(async (opts: { since?: string; until?: string; org?: string; 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 const report = await client.usageReport(opts.since, opts.until);\n if (opts.json) {\n json(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(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","/** 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,EAChD,YAAY,MAAc,MAAc,OAA0B;AAChE,UAAM,GAAG,IAAI,IAAI,IAAI,cAAc,MAAM,MAAM,GAAG,EAAE,EAAE,KAAK,IAAI,CAAC,QAAQ,MAAM,GAAG,EAAE,CAAC,0BAA0B,MAAM,CAAC,CAAC,OAAO,MAAM,CAAC,CAAC,IAAI,IAAI,IAAI,CAAC;AAClJ,SAAK,OAAO;AAAA,EACd;AACF;;;ACtCA,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;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CAAC;AACD,SAAO;AACT;;;AhD7FO,SAAS,eAAwB;AACtC,QAAM,UAAU,IAAIC,UAAQ,OAAO,EAChC,YAAY,8DAA8D,EAC1E,QAAQ,SAAS,eAAe,EAChC,OAAO,WAAW,uEAAuE,EACzF,OAAO,gBAAgB,gIAAgI,EACvJ,mBAAmB,EACnB,wBAAwB;AAE3B,UAAQ,WAAW,SAAS;AAC5B,UAAQ,WAAW,gBAAgB;AACnC,UAAQ,WAAW,aAAa;AAChC,UAAQ,WAAW,YAAY;AAC/B,UAAQ,WAAW,aAAa;AAChC,UAAQ,WAAW,aAAa;AAChC,UAAQ,WAAW,UAAU;AAC7B,UAAQ,WAAWC,aAAY;AAE/B,aAAW,OAAO,UAAW,SAAQ,WAAW,GAAG;AAEnD,SAAO;AACT;;;AiD5BA,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":["createInterface","day","me","Command","require","Command","Command","readFile","rm","writeFile","writeFile","rm","readFile","mkdir","readFile","z","z","z","json","z","readFile","mkdir","Command","spawn","Command","SSH_FAILED","spawn","status","Command","Command","Command","Command","Option","me","Command","Option","Command","Command","Command","Option","Command","Option","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","spawn","readFile","sleep","readFile","sleep","spawn","Command","Command","Command","Command","Command","Command","startCommand","Command","Command","Command","Command","stopCommand","Command","Command","Command","Command","startCommand","stopCommand","spawnSync","mkdir","readFile","writeFile","Command","Command","readFile","mkdir","spawnSync","writeFile","Command","Command","Command","Command","Command","Command","Option","lsCommand","Command","Option","Command","newCommand","Command","Command","rmCommand","Command","Command","newCommand","lsCommand","rmCommand","Command","Command","lsCommand","Command","Command","Option","lsCommand","Command","Option","rmCommand","Command","newCommand","Command","Command","rmCommand","Command","Command","Command","Command","lsCommand","newCommand","rmCommand","Command","usageCommand","Command","day","me","ownerCell","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/commands/vm/new.ts","../src/commands/vm/exec.ts","../src/commands/vm/hibernate.ts","../src/commands/vm/ls.ts","../src/commands/vm/pause.ts","../src/commands/vm/rescale.ts","../src/commands/vm/resume.ts","../src/commands/vm/rm.ts","../src/commands/vm/start.ts","../src/commands/vm/stop.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/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","../src/commands/credit.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 constructor(kind: string, name: string, slugs: readonly string[]) {\n super(`${kind} ${name} exists in ${slugs.slice(0, -1).join(\", \")} and ${slugs.at(-1)}; say which with --org ${slugs[0]} or ${slugs[0]}/${name}`, 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\";\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 // 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 { hibernateCommand } from \"./hibernate.js\";\nimport { lsCommand } from \"./ls.js\";\nimport { newCommand } from \"./new.js\";\nimport { pauseCommand } from \"./pause.js\";\nimport { rescaleCommand } from \"./rescale.js\";\nimport { resumeCommand } from \"./resume.js\";\nimport { rmCommand } from \"./rm.js\";\nimport { startCommand } from \"./start.js\";\nimport { stopCommand } from \"./stop.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(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(usageCommand)\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) 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 * (update, rescale and usage stay under `kvbox vm`, so the top level does not fill up).\n */\nexport const vmAliases = [newCommand, lsCommand, connectCommand, execCommand, stopCommand, startCommand, pauseCommand, resumeCommand, hibernateCommand, wakeCommand, rmCommand];\n","import { spawnSync } from \"node:child_process\";\nimport { Command } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { ensureCert, renewAfterRefusal } from \"../../cert.js\";\nimport { 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 client.listMachines(), 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 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 CloudCaSchema,\n CloudOrgSchema,\n type CreateMachineRequest,\n type CreateOrgRequest,\n type CreateSnapshotRequest,\n HealthSchema,\n type LoginRequest,\n LoginResponseSchema,\n type Machine,\n MachineSchema,\n MachineUsageSchema,\n MeResponseSchema,\n OrgDetailSchema,\n OrgMembershipSchema,\n type OrgRole,\n type RescaleMachineRequest,\n SnapshotSchema,\n SshCaResponseSchema,\n type SshCertRequest,\n SshCertResponseSchema,\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 { 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\nconst 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\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\" | \"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 /** Through a control plane: every box the user can see, or the `--org` org's. */\n listMachines() {\n return this.call(\"GET\", \"/machines\", z.array(MachineSchema));\n }\n\n createMachine(req: CreateMachineRequest) {\n return this.call(\"POST\", \"/machines\", 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 /** `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) {\n const q = new URLSearchParams();\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 listSnapshots() {\n return this.call(\"GET\", \"/snapshots\", z.array(SnapshotSchema));\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/** 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 \"-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/** The last `error: …` line of server.log, which is why a daemon that just died did not come up. */\nasync function lastErrorLine(logPath: string): Promise<string | undefined> {\n const { readFile } = await import(\"node:fs/promises\");\n const text = await readFile(logPath, \"utf8\").catch(() => \"\");\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 * 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 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 const ready = (async () => {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\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 await Promise.race([ready, 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 * 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\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\" or \"snapshot:<name>\"\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 /** 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});\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});\nexport type CreateMachineRequest = z.infer<typeof CreateMachineRequest>;\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\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\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 })\n .nullable()\n .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/** 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});\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 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","import { Command, Option } from \"commander\";\nimport type { Machine } from \"@kvbox/shared/api\";\nimport { SIZE_NAMES } from \"@kvbox/shared/sizes\";\nimport { clientFor } from \"../../client.js\";\nimport { color, gb, info, json, shortRef, slugOf, spin } from \"../../output.js\";\n\n/**\n * kvbox vm new [name] [--size s|m|l] [--from <snapshot>] [--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(\"--force\", \"skip the capacity guard\")\n .option(\"--json\", \"print the box as JSON\")\n .action(async (name: string | undefined, opts: { size?: string; from?: string; force?: boolean; json?: boolean }, cmd: Command) => {\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 ...(opts.force ? { force: true } : {}),\n }));\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 } 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:\") ? ` from snapshot ${shortRef(box.source.slice(\"snapshot:\".length), box.owner)}` : \"\";\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","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 { 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 client.listMachines(), 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 } 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, Option } from \"commander\";\nimport type { Machine } from \"@kvbox/shared/api\";\nimport { clientFor } from \"../../client.js\";\nimport { age, boxName, color, gbShort, info, json, shape, slugOf, 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/** Where ssh reaches the box: `host:port` through the control plane (#21), its ip on this machine, `-` when unknown. */\nexport function addressOf(b: Machine): string {\n if (b.ssh !== undefined) return `${b.ssh.host}:${b.ssh.port}`;\n return b.ip === \"\" ? \"-\" : b.ip;\n}\n\n/**\n * kvbox vm ls [--json] — every box the user can see (theirs and each org's through a control plane;\n * `--org <slug>` narrows to that org). --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 .addOption(new Option(\"-a, --all\", \"kept for older scripts: the listing covers everything you can see anyway\").hideHelp())\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { json?: boolean }, cmd: Command) => {\n const client = await clientFor(cmd.optsWithGlobals());\n try {\n const boxes = await client.listMachines();\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, Option } from \"commander\";\nimport { KvboxError } from \"@kvbox/shared/errors\";\nimport { SIZE_NAMES, parseMib } from \"@kvbox/shared/sizes\";\nimport { 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 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 client.listMachines(), 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 { 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 client.listMachines(), 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 { 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 { KvboxError } from \"@kvbox/shared/errors\";\nimport { 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 client.listMachines(), 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 { clientFor } from \"../../client.js\";\nimport { info, json } from \"../../output.js\";\n\n/** kvbox server status [--json] — --json output: Health (version, pid, base image new boxes get, control plane) */\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 if (opts.json) json(health);\n else {\n info(`kvbox-server ${health.version} running, pid ${health.pid}`);\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) info(`relay: ${health.relay.name} lends this machine ${health.relay.publicIp} (tunnel to ${health.relay.endpoint})`);\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 { 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 ask(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 ask(rl, question);\n } finally {\n io.output.write(\"\\n\");\n }\n}\n\n/**\n * One question, closing the interface afterwards. Ctrl-C in terminal mode rejects the question\n * (ABORT_ERR); Ctrl-D or EOF only closes the interface and would leave the question pending forever,\n * so a close before the answer is treated the same way: the user cancelled (exit 130).\n */\nasync function ask(rl: ReturnType<typeof createInterface>, question: string): Promise<string> {\n let onClose = () => {};\n const closed = new Promise<never>((_, reject) => {\n onClose = () => reject(new KvboxError(\"cancelled\", 130));\n rl.once(\"close\", onClose);\n });\n try {\n return await Promise.race([rl.question(question).catch(cancelled), closed]);\n } finally {\n rl.off(\"close\", onClose);\n rl.close();\n }\n}\n\nfunction cancelled(err: unknown): never {\n if ((err as NodeJS.ErrnoException).code === \"ABORT_ERR\") throw new KvboxError(\"cancelled\", 130);\n throw err;\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","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, Option } 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 [--json] — every snapshot the user can see (`--org <slug>` for one org). --json output: Snapshot[] */\nexport const lsCommand = new Command(\"ls\")\n .description(\"list snapshots (yours and your orgs'; --org <slug> for one org)\")\n .addOption(new Option(\"-a, --all\", \"kept for older scripts: the listing covers everything you can see anyway\").hideHelp())\n .option(\"--json\", \"print as JSON\")\n .action(async (opts: { 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();\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 { 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>] [--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 every slug you can read (`--org <slug>` for one org) 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 * --json output: the UsageReport object { window, boxes: BoxUsage[], totals }.\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(\"--json\", \"print as JSON\")\n .action(async (opts: { since?: string; until?: string; org?: string; 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 const report = await client.usageReport(opts.since, opts.until);\n if (opts.json) {\n json(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(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","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","/** 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,EAChD,YAAY,MAAc,MAAc,OAA0B;AAChE,UAAM,GAAG,IAAI,IAAI,IAAI,cAAc,MAAM,MAAM,GAAG,EAAE,EAAE,KAAK,IAAI,CAAC,QAAQ,MAAM,GAAG,EAAE,CAAC,0BAA0B,MAAM,CAAC,CAAC,OAAO,MAAM,CAAC,CAAC,IAAI,IAAI,IAAI,CAAC;AAClJ,SAAK,OAAO;AAAA,EACd;AACF;;;ACtCA,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,MAAM,MAA4D,SAA0B;AAC1G,MAAI,KAAK,WAAW,EAAG;AACvB,QAAM,OAAO,WAAW,OAAO,KAAK,KAAK,CAAC,CAAE;AAC5C,QAAM,QAAQ,KAAK,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM,OAAO,EAAE,CAAC,KAAK,EAAE,CAAC,CAAC;AACjE,QAAM,SAAS,KAAK,IAAI,CAAC,GAAG,MAAM,KAAK,IAAI,EAAE,QAAQ,GAAG,MAAM,IAAI,CAAC,MAAM,MAAM,EAAE,CAAC,C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WAAW,UAAU;AAC7B,UAAQ,WAAWC,aAAY;AAC/B,UAAQ,WAAW,aAAa;AAEhC,aAAW,OAAO,UAAW,SAAQ,WAAW,GAAG;AAEnD,SAAO;AACT;;;AkD9BA,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":["createInterface","day","me","Command","require","Command","Command","readFile","rm","writeFile","writeFile","rm","readFile","mkdir","readFile","z","z","z","json","z","readFile","mkdir","Command","spawn","Command","SSH_FAILED","spawn","status","Command","Command","Command","Command","Option","me","Command","Option","Command","Command","Command","Option","Command","Option","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","Command","spawn","readFile","sleep","readFile","sleep","spawn","Command","Command","Command","Command","Command","Command","startCommand","Command","Command","Command","Command","stopCommand","Command","Command","Command","Command","startCommand","stopCommand","spawnSync","mkdir","readFile","writeFile","Command","Command","readFile","mkdir","spawnSync","writeFile","Command","Command","Command","Command","Command","Command","Option","lsCommand","Command","Option","Command","newCommand","Command","Command","rmCommand","Command","Command","newCommand","lsCommand","rmCommand","Command","Command","lsCommand","Command","Command","Option","lsCommand","Command","Option","rmCommand","Command","newCommand","Command","Command","rmCommand","Command","Command","Command","Command","lsCommand","newCommand","rmCommand","Command","usageCommand","Command","day","me","ownerCell","Command","Command","me","Command","usageCommand"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kvbox/cli",
3
- "version": "0.5.7",
3
+ "version": "0.5.8",
4
4
  "description": "kvbox CLI: manage Firecracker microVM hosts with Docker-like commands. Thin client; the host runs @kvbox/server.",
5
5
  "type": "module",
6
6
  "license": "MIT",