Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ Types: the code is plain JavaScript typed with JSDoc comments (`/** @param {stri

`boxery help`, `boxery help --all` and `boxery COMMAND [ACTION] --help` are rendered (`help/index.mjs`, through `controller/usage.mjs`) from the `help` each command carries in `controller/cli.mjs`'s `COMMANDS` table, next to its handler: a new command needs its help to exist at all. boxery-host's help is the same kind of table, in `host/help.mjs` (its handlers are in `host/cli.mjs`, which refuses to load with a command that has no help). Write the summary as one short line; longer explanations go in `details`, `flags` and `examples`, which only its own `--help` shows. `test/help-drift.test.mjs` keeps it honest: a command's help must list exactly the `--flags` its code compares against (flags the host parses are checked against `boxery-host help`), examples must use real commands and documented flags, the same holds for every `boxery-host` command, `docs` anchors must exist, the command reference in `docs/cli.md` must be current (`npm run docs:cli` regenerates it), and `boxery help` and `boxery help --all` are pinned in `test/fixtures/boxery-help.txt` and `boxery-help-all.txt` (`BOXERY_UPDATE_GOLDEN=1 node --test test/help-drift.test.mjs` rewrites it after you review the change).

Controller-owned follow-up commands use `hint(COMMAND, ARGS, {host})` from `controller/lib.mjs`: it validates the canonical command/family action against `COMMANDS`, shell-quotes arguments and retains the explicit host. Name the action explicitly (`access ls` or `access apply`, not the ambiguous legacy `grants`); keep placeholders outside argument arrays. Do not rewrite subprocess output or import controller helpers into core/MCP/pi. Shared approval messages and `BOXERY_CLI` remain compatible.

`test/cli-contracts.test.mjs` checks contracts and their inheritance, scope routing, help boundaries, optional hosts and SSH-qualified targets against an unconfigured temporary home.

`test/cli-families.test.mjs` runs the real CLI against a stub `boxery-host` and a stub `ssh` in temporary profiles, and checks that every family action and its older spelling produce the same output, exit status, ssh and host calls and saved state; that help and mistakes touch no host, profile or grant; that `host`'s registry actions refuse `--host` while its maintenance actions follow it; that `access ls` is read-only; and that grant approval, grant stores and leases stay per profile. Add a pair there when you add an action.
Expand Down
42 changes: 21 additions & 21 deletions controller/cli.mjs

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions controller/grants.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import { closeSync, openSync, readFileSync, readSync, writeSync } from "node:fs"
import path from "node:path";
import { formatGrants, hostBackend, vmGrants } from "../core/boxery-core.mjs";
import { parseGrantArgs } from "../core/grant-approval.mjs";
import { addGrants, applyGrants, grantCommand, grantPrompt, listGrants, revokeGrants, storedSpecs } from "../core/grants.mjs";
import { addGrants, applyGrants, grantArgs, grantPrompt, listGrants, revokeGrants, storedSpecs } from "../core/grants.mjs";
import { reapplyPushed } from "../core/grant-operations.mjs";
import { CliError, VALID_VM, die, needHost, needVm, note, say, usage, warn } from "./lib.mjs";
import { CliError, VALID_VM, die, hint, needHost, needVm, note, say, usage, warn } from "./lib.mjs";
import { blockedOnPerson } from "./status.mjs";
/** @import { GrantSpec } from "../core/boxery-core.mjs" */
/** @import { Selected } from "./lib.mjs" */
Expand Down Expand Up @@ -42,7 +42,7 @@ function ask(s, vm, specs) {
if (unattended(s)) return;
let tty;
try { tty = openSync("/dev/tty", "r+"); }
catch { die(`grants need a person. Ask the user to run the command below, or use vm_grant:\n${specs.map((g) => grantCommand("grant", vm, s.host.name, g)).join("\n")}`); }
catch { die(`grants need a person. Ask the user to run the command below, or use vm_grant:\n${specs.map((g) => hint("access grant", grantArgs("grant", vm, g), { host: s.host.name })).join("\n")}`); }
let answer = "";
// Blocked on the person: the terminal's status says so, and Ctrl-C ends the command here (controller/status.mjs).
blockedOnPerson("permission", () => {
Expand Down
4 changes: 2 additions & 2 deletions controller/hosts.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import { describeHosts, profileFromDirectory, registeredHosts, resolveHost } from "../core/boxery-core.mjs";
import { profileConfig } from "../core/profile.mjs";
import { RegistryError, VALID_ALIAS, addHostLocked, checkedDefault, destination, isRegistered, needAlias, recordBackend, removeHostLocked, setDefault, setup, withRegistryLock } from "../core/registry.mjs";
import { BOXERY, CliError, USAGE, die, note, say, usage } from "./lib.mjs";
import { CliError, USAGE, die, hint, note, say, usage } from "./lib.mjs";
/** @import { HostProfile } from "../core/boxery-core.mjs" */
/** @import { RegistryIO } from "../core/registry.mjs" */

Expand Down Expand Up @@ -78,7 +78,7 @@ export async function setupNamed(args) {
export async function backendCommand(host, args) {
if (args.length) usage("backend");
const b = await recordBackend(host);
if (!b) die(`could not read the host's backend (does it predate 'boxery-host backend'? see: ${BOXERY} version)`);
if (!b) die(`could not read the host's backend (does it predate 'boxery-host backend'? see: ${hint("version")})`);
say(b);
}

Expand Down
6 changes: 3 additions & 3 deletions controller/jobs.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import { JOBS_NODE, VALID_JOB } from "../core/boxery-core.mjs";
import { closeMaster } from "../core/profile.mjs";
import { CliError, die, duration, needVm, note, num, quit, say, usage, vmSsh, vmSshCapture, WAIT_LOST, WAIT_TIMEOUT, warn } from "./lib.mjs";
import { CliError, die, duration, hint, needVm, note, num, quit, say, usage, vmSsh, vmSshCapture, WAIT_LOST, WAIT_TIMEOUT, warn } from "./lib.mjs";
/** @import { Selected } from "./lib.mjs" */


Expand All @@ -34,7 +34,7 @@ const jobsVmCapture = (s, name, args, o) => vmSshCapture(s, helper(name, args),
const exit = (rc) => { if (rc) throw new CliError("", rc); };

/** @param {string | undefined} id */
const needJob = (id) => (VALID_JOB.test(id ?? "") ? /** @type {string} */ (id) : die(`invalid job id: ${id ?? ""} (see: boxery jobs NAME)`));
const needJob = (id) => (VALID_JOB.test(id ?? "") ? /** @type {string} */ (id) : die(`invalid job id: ${id ?? ""} (see: ${hint("job ls")} NAME)`));

/** run --bg: start ARGV (each word's bytes) in the VM as a job, in CWD (bytes, or null: ~/project); its id.
* @param {Selected} s @param {string} name @param {Buffer[]} argv @param {Buffer | null} cwd */
Expand Down Expand Up @@ -108,7 +108,7 @@ export async function waitJob(s, [vm, job, ...rest]) {
// waiting doesn't affect the job (tmux in the VM): reconnect and keep waiting, within --timeout.
if (!reached) die(`cannot reach ${name}`);
if (deadline != null && Date.now() / 1000 >= deadline) { warn(`cannot reach ${name}; --timeout passed (the job may still be running)`); quit(WAIT_TIMEOUT); }
if (++drops > 60) die(`cannot reach ${name}; giving up (the job may still be running: boxery jobs ${name})`);
if (++drops > 60) die(`cannot reach ${name}; giving up (the job may still be running: ${hint("job ls", [name])})`);
warn(`lost the connection to ${name}; reconnecting (the job keeps running)`);
await closeMaster(name);
await new Promise((res) => setTimeout(res, 5000));
Expand Down
4 changes: 2 additions & 2 deletions controller/leases.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { execFileSync } from "node:child_process";
import { constants } from "node:os";
import { acquireLease, leaseRows, localLeases, releaseLease, renewLease } from "../core/leases.mjs";
import { BOXERY, USAGE, die, hostFailed, note, quit, say, usage } from "./lib.mjs";
import { USAGE, die, hint, hostFailed, note, quit, say, usage } from "./lib.mjs";
/** @import { Selected } from "./lib.mjs" */

/** Like `date`: the local format people read elsewhere in the CLI. @param {number} t unix seconds */
Expand Down Expand Up @@ -46,7 +46,7 @@ export async function leaseCommand(_s, command, args) {
try { r = await acquireLease({ ttl: o.ttl ?? 1800, wait: o.wait ?? 0, ...(o.holder !== undefined ? { holder: o.holder } : {}) }, cli); }
catch (e) { if (interrupted && /** @type {Error} */ (e).name === "AbortError") quit(interrupted); hostFailed(e); }
finally { for (const [sig, h] of handlers) process.off(sig, h); }
note(`==> leased ${r.name} (lease ${r.id}, expires in ${r.expires - Math.floor(Date.now() / 1000)}s; renew with: ${BOXERY} renew ${r.name})`);
note(`==> leased ${r.name} (lease ${r.id}, expires in ${r.expires - Math.floor(Date.now() / 1000)}s; renew with: ${hint("lease renew", [r.name])})`);
return say(`${r.name} ${r.id}`);
}
case "renew": {
Expand Down
7 changes: 6 additions & 1 deletion controller/lib.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Shared plumbing for the controller CLI's commands (controller/cli.mjs): errors and exit codes, argument
// checks, the selected host profile, and processes that share this terminal (ssh, boxery-host).
import { usageText } from "./usage.mjs";
import { commandRef, usageText } from "./usage.mjs";
import { spawn } from "node:child_process";
import { constants } from "node:os";
import { profileFromDirectory, vmProblem, withHost } from "../core/boxery-core.mjs";
Expand Down Expand Up @@ -28,11 +28,16 @@ export const quit = (exitCode) => { throw new CliError("", exitCode); };
* get (core/ssh-config.mjs remoteCommand; host/util.mjs hint). (Plain ls asks every host with `boxery`:
* its host output is --json, with no hints.) */
export let BOXERY = "boxery";
let hintHost = "";
/** @param {string} explicitHost the NAME of --host NAME, or "" */
export function invokedAs(explicitHost) {
hintHost = explicitHost;
BOXERY = explicitHost ? `boxery --host ${explicitHost}` : "boxery";
process.env.BOXERY_CLI = BOXERY;
}
/** A canonical hint using the caller's explicit host, or a specific host for grouped output and grant requests.
* @param {string} command @param {string[]} [args] @param {{host?: string}} [options] */
export const hint = (command, args = [], { host = hintHost } = {}) => commandRef(command, args, host ? ["--host", host] : []);
/** @param {string} message */
export const warn = (message) => { process.stderr.write(`boxery: ${message}\n`); };
/** A line on stdout. @param {string} text */
Expand Down
4 changes: 2 additions & 2 deletions controller/ls.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import { realpathSync } from "node:fs";
import { describeHosts, listGrants, withHost } from "../core/boxery-core.mjs";
import * as lifecycle from "../core/lifecycle.mjs";
import { BOXERY, die, hostFailed, needHost, note, quit, say, select, usage, warn } from "./lib.mjs";
import { die, hint, hostFailed, needHost, note, quit, say, select, usage, warn } from "./lib.mjs";
/** @import { Selected } from "./lib.mjs" */

/** A row of listVms, as docs/cli.md describes `ls --json`.
Expand Down Expand Up @@ -119,7 +119,7 @@ function print(sections, { onlyRunning, refresh, grouped }) {
const unchecked = sec.vms.filter((v) => running(v) && v.guest?.checked_at == null).map((v) => v.name);
if (unchecked.length && !refresh) notes.push(`==> ${who}guest software not checked yet: ${unchecked.join(", ")} (ls --refresh reads it)`);
const outdated = sec.vms.filter((v) => v.guest?.status === "outdated").map((v) => v.name);
if (outdated.length) notes.push(`==> ${who}outdated guest software on ${outdated.join(", ")}; update with: ${grouped ? `boxery --host ${sec.name}` : BOXERY} patch NAME|--all`);
if (outdated.length) notes.push(`==> ${who}outdated guest software on ${outdated.join(", ")}; update with: ${hint("patch", [], grouped ? { host: sec.name } : {})} NAME (or ${hint("patch", ["--all"], grouped ? { host: sec.name } : {})})`);
}
say(out.join("\n") || none);
if (notes.length) note(notes.join("\n"));
Expand Down
4 changes: 4 additions & 0 deletions controller/usage.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ export const unknownCommand = (table, word) => help.unknownCommand(CLI, table, w

/** The command table (cli.mjs registers it as it loads), for usage errors raised in the modules it calls. @type {Record<string, HelpEntry>} */
let TABLE = {};
/** A copyable canonical command, checked against the same table used for dispatch and help.
* @param {string} command @param {string[]} [args] @param {string[]} [prefix] */
export const commandRef = (command, args = [], prefix = []) => help.commandRef(CLI, TABLE, command, args, prefix);

/** A family's usage lines are its actions' (and its `list` the action names): filled in here, so the two can't differ. @param {Record<string, HelpEntry>} table */
export function registerCommands(table) {
TABLE = table;
Expand Down
12 changes: 9 additions & 3 deletions core/grants.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,15 @@ export function missingPiGrant(vm, { settings = "", projectSettings = "", models
return `llm:${route}`;
}

/** @param {"grant" | "revoke"} verb @param {string} vm @param {string} host @param {GrantSpec} g */
export function grantCommand(verb, vm, host, g) {
/** Grant arguments shared by front-ends that choose their own command spelling.
* @param {"grant" | "revoke"} verb @param {string} vm @param {GrantSpec} g */
export function grantArgs(verb, vm, g) {
const spec = verb === "revoke" && g.kind === "file" ? `file:${g.local}` : g.spec;
return ["boxery", "--host", host, verb, vm, spec, ...(verb === "grant" ? [...(g.readonly ? ["--readonly"] : []), ...(g.cmd ? ["--cmd", g.cmd] : []), ...(g.auth ? ["--auth", g.auth] : [])] : [])].map(quoteWord).join(" ");
return [vm, spec, ...(verb === "grant" ? [...(g.readonly ? ["--readonly"] : []), ...(g.cmd ? ["--cmd", g.cmd] : []), ...(g.auth ? ["--auth", g.auth] : [])] : [])];
}
/** Shared approval messages retain their existing command format.
* @param {"grant" | "revoke"} verb @param {string} vm @param {string} host @param {GrantSpec} g */
export function grantCommand(verb, vm, host, g) {
return ["boxery", "--host", host, verb, ...grantArgs(verb, vm, g)].map(quoteWord).join(" ");
}

4 changes: 3 additions & 1 deletion docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,9 @@ Generated from the help `boxery help --all` shows (`controller/cli.mjs`); edit i

`boxery-host help` lists every command; `boxery-host COMMAND --help` shows one. Generated from the same help (`host/help.mjs`); edit it there, then `npm run docs:cli`. `--profile NAME` before any command runs it in a second profile on this host (`~/.config/boxery-NAME`: its own backend, state, proxy port and services); `--profile NAME init --backend B` creates it with a free proxy port. `upgrade` keeps the code and each profile's state from before in `$BOXERY_CONF/pre-upgrade/` after a success too.

Commands in messages name what you typed. The follow-up commands `boxery` prints (`run --bg`'s logs and wait, `prompt`, `acquire`, `ls`) keep your `--host NAME`; and when `boxery` runs a host command for you, it passes `BOXERY_CLI` (`boxery`, or `boxery --host NAME` if you gave one), so a host error suggests `boxery --host lab snap-rm demo s1` rather than `boxery-host snap-rm demo s1`. Commands only boxery-host has (`init`, …) keep its name. Called directly, boxery-host names itself.
Controller-generated follow-up hints use the canonical command families (`job logs`, `job wait`, `lease renew`, `access grant`) and shell-quote dynamic arguments so they can be copied safely. They keep an explicit `--host NAME`; grant approval requests name the host even when it was the default, so another controller cannot accidentally grant on a different host. Everyday `run`, `ssh`, `attach` and `prompt` stay short. Shared approval prompts and core/host messages may still name working legacy aliases.

When `boxery` runs a host command, it passes the unchanged `BOXERY_CLI` prefix (`boxery`, or `boxery --host NAME` if you gave one), so a host error suggests `boxery --host lab snap-rm demo s1` rather than `boxery-host snap-rm demo s1`. Commands only boxery-host has (`init`, …) keep its name. Called directly, boxery-host names itself.

<!-- BEGIN generated: boxery-host commands (npm run docs:cli) -->

Expand Down
16 changes: 16 additions & 0 deletions help/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,22 @@ export function resolve(table, name) {
return e.alias ? (Object.hasOwn(table, e.alias) ? e.alias : null) : name;
}

/** One shell word, safe to copy literally, including empty strings and embedded quotes. @param {string} value */
export const shellWord = (value) => /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;

/** A validated command reference, not a rewrite of output. Callers choose the action explicitly: grants serves
* both access ls and access apply. PREFIX is argv (e.g. --host NAME), never an executable shell fragment.
* @param {Cli} cli @param {Record<string, HelpEntry>} table @param {string} command
* @param {string[]} [args] @param {string[]} [prefix] */
export function commandRef(cli, table, command, args = [], prefix = []) {
const words = command.split(" "), name = resolve(table, words[0]);
if (!name || words.length > 2 || words.some((w) => !w)) throw new Error(`unknown command reference: ${command}`);
const e = table[name];
if (words.length === 2 && (!e.actions || !Object.hasOwn(e.actions, words[1]))) throw new Error(`unknown command reference: ${command}`);
if (cli.hidden?.includes(e.help?.group ?? "")) throw new Error(`use a canonical family action instead of ${command}`);
return [cli.program, ...prefix, name, ...words.slice(1), ...args].map(shellWord).join(" ");
}

/** The name nearest WORD, when one is close. @param {string} word @param {string[]} names */
function nearest(word, names) {
return names.map((n) => /** @type {const} */ ([n, distance(word, n)])).filter(([n, d]) => d <= Math.max(1, Math.floor(n.length / 3)) || (word.length >= 3 && n.startsWith(word))).sort((a, b) => a[1] - b[1] || a[0].localeCompare(b[0]))[0];
Expand Down
Loading
Loading