agental 0.11.0 → 0.14.0

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.
Files changed (2) hide show
  1. package/dist/cli.js +793 -132
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -39,14 +39,14 @@ var init_cli_operator = __esm({
39
39
 
40
40
  // ../src/cli.ts
41
41
  import { randomUUID as randomUUID2 } from "node:crypto";
42
- import { readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "node:fs";
43
- import os5 from "node:os";
42
+ import { readFileSync as readFileSync4, writeFileSync as writeFileSync4 } from "node:fs";
43
+ import os6 from "node:os";
44
44
  import { readFile } from "node:fs/promises";
45
45
  import { parseArgs } from "node:util";
46
46
 
47
47
  // ../src/cli-build.ts
48
48
  var PUBLISHED = true;
49
- var CLI_VERSION = true ? "0.11.0" : "dev";
49
+ var CLI_VERSION = true ? "0.14.0" : "dev";
50
50
  var DEFAULT_API_URL = true ? "https://agental.io" : "http://127.0.0.1:8741";
51
51
  var PACKAGE_NAME = "agental";
52
52
  var USER_AGENT = `agental-cli/${CLI_VERSION}`;
@@ -473,15 +473,15 @@ function reachOf(key2, full) {
473
473
  if (key2.sandboxIds.length === 0 && key2.templateIds.length === 0) {
474
474
  return key2.seesAll ? "every account" : "all of the account";
475
475
  }
476
- const sandboxes = key2.sandboxIds;
477
- const templates = key2.templateIds;
476
+ const sandboxes2 = key2.sandboxIds;
477
+ const templates2 = key2.templateIds;
478
478
  if (!full) {
479
479
  const one = (ids, noun) => ids.length === 1 ? `${noun} ${ids[0]}` : `${ids.length} ${noun}s`;
480
- return [...sandboxes.length > 0 ? [one(sandboxes, "sandbox")] : [], ...templates.length > 0 ? [one(templates, "template")] : []].join(", ");
480
+ return [...sandboxes2.length > 0 ? [one(sandboxes2, "sandbox")] : [], ...templates2.length > 0 ? [one(templates2, "template")] : []].join(", ");
481
481
  }
482
482
  return [
483
- ...sandboxes.length > 0 ? [`${sandboxes.length === 1 ? "sandbox" : "sandboxes"} ${sandboxes.join(", ")}`] : [],
484
- ...templates.length > 0 ? [`${templates.length === 1 ? "template" : "templates"} ${templates.join(", ")} and the sandboxes on ${templates.length === 1 ? "it" : "them"}`] : []
483
+ ...sandboxes2.length > 0 ? [`${sandboxes2.length === 1 ? "sandbox" : "sandboxes"} ${sandboxes2.join(", ")}`] : [],
484
+ ...templates2.length > 0 ? [`${templates2.length === 1 ? "template" : "templates"} ${templates2.join(", ")} and the sandboxes on ${templates2.length === 1 ? "it" : "them"}`] : []
485
485
  ].join("; ");
486
486
  }
487
487
  function expiryOf(key2) {
@@ -550,9 +550,9 @@ function grantFrom(options) {
550
550
  }
551
551
  function expiryFrom(given, now = Date.now()) {
552
552
  const text = given.trim();
553
- const span = /^(\d+)([dh])$/.exec(text);
554
- if (span && Number(span[1]) > 0) {
555
- return at(now + Number(span[1]) * (span[2] === "d" ? 24 : 1) * HOUR_MS);
553
+ const span2 = /^(\d+)([dh])$/.exec(text);
554
+ if (span2 && Number(span2[1]) > 0) {
555
+ return at(now + Number(span2[1]) * (span2[2] === "d" ? 24 : 1) * HOUR_MS);
556
556
  }
557
557
  const moment = /^\d{4}-\d{2}-\d{2}/.test(text) ? Date.parse(text) : Number.NaN;
558
558
  if (Number.isNaN(moment)) {
@@ -565,12 +565,12 @@ async function templateIdsOf(client, words2) {
565
565
  return words2;
566
566
  }
567
567
  const body = await ask2(client, "GET", "/v1/templates");
568
- const templates = Array.isArray(body?.templates) ? body.templates : [];
568
+ const templates2 = Array.isArray(body?.templates) ? body.templates : [];
569
569
  return words2.map((word) => {
570
570
  if (word.startsWith("tpl_")) {
571
571
  return word;
572
572
  }
573
- const found = templates.find((one) => one.name === word);
573
+ const found = templates2.find((one) => one.name === word);
574
574
  if (!found || typeof found.id !== "string") {
575
575
  throw new Error(`There is no template ${word}. agental templates lists them.`);
576
576
  }
@@ -1072,7 +1072,7 @@ function accessIn(record) {
1072
1072
  return typeof user === "string" && typeof hostKey === "string" && typeof host === "string" && typeof port === "number" ? { user, hostKey, host, port } : null;
1073
1073
  }
1074
1074
  async function reach(client, sandboxId, waitMs = 0) {
1075
- const until = Date.now() + waitMs;
1075
+ const until2 = Date.now() + waitMs;
1076
1076
  for (; ; ) {
1077
1077
  try {
1078
1078
  const access = accessIn(await ask3(client, "GET", sandboxId, "")) ?? accessIn(await ask3(client, "PUT", sandboxId, ""));
@@ -1082,7 +1082,7 @@ async function reach(client, sandboxId, waitMs = 0) {
1082
1082
  }
1083
1083
  throw new Refused2("ssh_unavailable", "SSH was turned on, and the API gave no address to connect to.");
1084
1084
  } catch (error) {
1085
- if (!(error instanceof Refused2) || !ON_ITS_WAY.has(error.code) || Date.now() + LOOK_AGAIN_EVERY_MS > until) {
1085
+ if (!(error instanceof Refused2) || !ON_ITS_WAY.has(error.code) || Date.now() + LOOK_AGAIN_EVERY_MS > until2) {
1086
1086
  throw error;
1087
1087
  }
1088
1088
  await new Promise((resolve) => setTimeout(resolve, LOOK_AGAIN_EVERY_MS));
@@ -1403,8 +1403,8 @@ async function ensureSkills(options, site) {
1403
1403
  }
1404
1404
  return done(`agent skills installed for the coding agents on this computer ${dim(`\xB7 again with npx skills add ${site} -g`)}`);
1405
1405
  }
1406
- function ordered(sandboxes) {
1407
- return sandboxes.filter((sandbox) => sandbox["status"] !== "deleted").sort((a, b) => Number(b["status"] === "running") - Number(a["status"] === "running") || String(b["createdAt"]).localeCompare(String(a["createdAt"])));
1406
+ function ordered(sandboxes2) {
1407
+ return sandboxes2.filter((sandbox) => sandbox["status"] !== "deleted").sort((a, b) => Number(b["status"] === "running") - Number(a["status"] === "running") || String(b["createdAt"]).localeCompare(String(a["createdAt"])));
1408
1408
  }
1409
1409
  async function yes(question) {
1410
1410
  const lines = createInterface({ input: process.stdin, output: process.stdout });
@@ -1417,16 +1417,16 @@ async function yes(question) {
1417
1417
  }
1418
1418
  async function atTheLimit(base, key2, term, message) {
1419
1419
  const listed = await api(base, key2, "GET", "/v1/sandboxes");
1420
- const sandboxes = ordered(Array.isArray(listed.body["sandboxes"]) ? listed.body["sandboxes"] : []);
1420
+ const sandboxes2 = ordered(Array.isArray(listed.body["sandboxes"]) ? listed.body["sandboxes"] : []);
1421
1421
  term.say(`
1422
1422
  ${bold("No new sandbox:")} ${message}`);
1423
- const running = sandboxes.find((sandbox) => sandbox["status"] === "running");
1423
+ const running = sandboxes2.find((sandbox) => sandbox["status"] === "running");
1424
1424
  if (term.interactive && running && await yes(` Open ${bold(String(running["name"]))} (${String(running["id"])}) instead? [Y/n] `)) {
1425
1425
  return { id: String(running["id"]), name: String(running["name"]), size: String(running["size"]), existing: true };
1426
1426
  }
1427
- if (sandboxes.length > 0) {
1428
- const width = Math.max(...sandboxes.map((sandbox) => String(sandbox["name"]).length));
1429
- for (const sandbox of sandboxes) {
1427
+ if (sandboxes2.length > 0) {
1428
+ const width = Math.max(...sandboxes2.map((sandbox) => String(sandbox["name"]).length));
1429
+ for (const sandbox of sandboxes2) {
1430
1430
  term.say(` ${String(sandbox["id"])} ${String(sandbox["name"]).padEnd(width)} ${String(sandbox["status"])}`);
1431
1431
  }
1432
1432
  }
@@ -1454,8 +1454,8 @@ async function saveCard(base, key2, term, message) {
1454
1454
  openBrowser(page);
1455
1455
  term.say(` ${dim("If it did not open:")} ${page}`);
1456
1456
  term.say(` ${dim("waiting for your card to be saved\u2026 (Ctrl-C to stop)")}`);
1457
- const until = Date.now() + CARD_MS;
1458
- while (Date.now() < until) {
1457
+ const until2 = Date.now() + CARD_MS;
1458
+ while (Date.now() < until2) {
1459
1459
  await sleep(CARD_LOOK_MS);
1460
1460
  const billing2 = await api(base, key2, "GET", "/v1/billing").catch(() => null);
1461
1461
  if (billing2?.status === 200 && billing2.body["needsPlan"] === false) {
@@ -1470,11 +1470,11 @@ async function saveCard(base, key2, term, message) {
1470
1470
  async function newSandbox(base, key2, term) {
1471
1471
  const name = `sh-${randomBytes3(3).toString("hex")}`;
1472
1472
  const idempotencyKey = `cli-sh-${randomUUID()}`;
1473
- const until = Date.now() + READY_MS;
1473
+ const until2 = Date.now() + READY_MS;
1474
1474
  let made;
1475
1475
  for (; ; ) {
1476
1476
  made = await api(base, key2, "POST", "/v1/sandboxes", { name }, { "Idempotency-Key": idempotencyKey });
1477
- if (made.status !== 202 || Date.now() > until) {
1477
+ if (made.status !== 202 || Date.now() > until2) {
1478
1478
  break;
1479
1479
  }
1480
1480
  await sleep(2e3);
@@ -1508,7 +1508,7 @@ async function newSandbox(base, key2, term) {
1508
1508
  const id = String(made.body["id"]);
1509
1509
  let status = String(made.body["status"]);
1510
1510
  while (status !== "running") {
1511
- if (status === "error" || Date.now() > until) {
1511
+ if (status === "error" || Date.now() > until2) {
1512
1512
  throw new Error(`${id} is ${status}, not running. agental list shows it, and agental delete ${id} removes it.`);
1513
1513
  }
1514
1514
  await sleep(2e3);
@@ -1632,6 +1632,12 @@ async function onboard(base, options) {
1632
1632
  nextSteps(term, [[`agental ssh ${sandbox.id}`, "back in"], stopLine]);
1633
1633
  }
1634
1634
 
1635
+ // ../src/cli-completion.ts
1636
+ import { createHash as createHash2 } from "node:crypto";
1637
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "node:fs";
1638
+ import os5 from "node:os";
1639
+ import path4 from "node:path";
1640
+
1635
1641
  // ../src/cli-help.ts
1636
1642
  function isTerminal(stream) {
1637
1643
  return stream.isTTY === true || process.env["AGENTAL_TERMINAL"] === "1";
@@ -1696,7 +1702,13 @@ var COMMANDS = [
1696
1702
  { name: "auto-stop", summary: "Say when a running sandbox stops by itself, or that it never does.", examples: ["agental auto-stop sbx_2a9a47e50daec64a --in 2h", "agental auto-stop sbx_2a9a47e50daec64a --never"] },
1697
1703
  { name: "jobs", summary: "Follow or cancel the work started on many sandboxes at once." },
1698
1704
  { name: "tags", summary: "Read, add or remove a sandbox's tags.", examples: ["agental tags sbx_2a9a47e50daec64a add ci"] },
1699
- { name: "meta", summary: "Read, set or unset a sandbox's metadata.", examples: ["agental meta sbx_2a9a47e50daec64a set owner=ian"] },
1705
+ {
1706
+ name: "meta",
1707
+ summary: "Read, set or unset a sandbox's metadata.",
1708
+ usage: ["agental meta show <sandbox-id> [--json]", "agental meta set <sandbox-id> <key>=<value>... [--json]", "agental meta unset <sandbox-id> <key>... [--json]"],
1709
+ examples: ["agental meta set sbx_2a9a47e50daec64a owner=ian"],
1710
+ also: "meta <sandbox-id> [set <key>=<value>... | unset <key>...]"
1711
+ },
1700
1712
  { name: "regions", summary: "List where sandboxes run, and how much room each has now." },
1701
1713
  { name: "network", summary: "Say what a sandbox may reach outside itself.", examples: ["agental network sbx_2a9a47e50daec64a --allow github.com,registry.npmjs.org", "agental network sbx_2a9a47e50daec64a --none"] },
1702
1714
  { name: "egress", summary: "Say where a sandbox's web traffic leaves from, or read your residential egress.", examples: ["agental egress sbx_2a9a47e50daec64a residential de"] },
@@ -1727,6 +1739,57 @@ var COMMANDS = [
1727
1739
  { name: "logout", summary: "Delete this computer's key from your account and from here." },
1728
1740
  { name: "whoami", summary: "Who the command is signed in as, and with which key." },
1729
1741
  { name: "version", summary: "Print the version of agental." },
1742
+ {
1743
+ name: "completion",
1744
+ summary: "Print the script that completes agental's commands, flags, sandboxes and templates when Tab is pressed.",
1745
+ examples: ["source <(agental completion zsh) # in ~/.zshrc, after compinit", "source <(agental completion bash) # in ~/.bashrc", "agental completion fish | source # in ~/.config/fish/config.fish"]
1746
+ },
1747
+ {
1748
+ name: "sandbox",
1749
+ summary: "Your sandboxes, as agental sandbox <verb>: each is the same as the command without sandbox in front.",
1750
+ usage: [
1751
+ "agental sandbox list [flags]",
1752
+ "agental sandbox create --name <name> [flags]",
1753
+ "agental sandbox start|stop|delete|recover <sandbox-id> [flags]",
1754
+ "agental sandbox exec <sandbox-id> -- <command> [args...]",
1755
+ "agental sandbox shell <sandbox-id>",
1756
+ "agental sandbox summary [flags]"
1757
+ ],
1758
+ examples: ["agental sandbox list", "agental sandbox stop sbx_2a9a47e50daec64a"],
1759
+ also: "list, create, start, stop, delete, recover, exec, shell and summary: agental create --help says create's flags"
1760
+ },
1761
+ { name: "region", summary: "Where sandboxes run, and how much room each has now.", usage: ["agental region list [--json]"], also: "regions" },
1762
+ {
1763
+ name: "tag",
1764
+ summary: "Read, add or remove a sandbox's tags.",
1765
+ usage: ["agental tag list <sandbox-id> [--json]", "agental tag add <sandbox-id> <tag>... [--json]", "agental tag rm <sandbox-id> <tag>... [--json]"],
1766
+ examples: ["agental tag add sbx_2a9a47e50daec64a ci"],
1767
+ also: "tags <sandbox-id> [add|rm <tag>...]"
1768
+ },
1769
+ {
1770
+ name: "secret",
1771
+ summary: "Keep values and files out of a sandbox, or out of every sandbox of a template.",
1772
+ usage: [
1773
+ "agental secret list (<sandbox-id> | --template <template>) [--json]",
1774
+ "agental secret set (<sandbox-id> | --template <template>) <NAME>=<value>... [--host <host>[,<host>...] | --plain]",
1775
+ "agental secret get (<sandbox-id> | --template <template>) <NAME> [--json]",
1776
+ "agental secret unset (<sandbox-id> | --template <template>) <NAME>...",
1777
+ "agental secret hosts (<sandbox-id> | --template <template>) <NAME> --host <host>[,<host>...] [--json]",
1778
+ "agental secret put-file (<sandbox-id> | --template <template>) <path> (<local-file> | --text <text>)",
1779
+ "agental secret get-file|rm-file (<sandbox-id> | --template <template>) <path>"
1780
+ ],
1781
+ examples: ["agental secret set --template default GITHUB_TOKEN=ghp_\u2026 --host github.com,api.github.com", "agental secret list sbx_2a9a47e50daec64a"],
1782
+ also: "secrets <sandbox-id> <verb>"
1783
+ },
1784
+ { name: "job", summary: "Follow or cancel the work started on many sandboxes at once.", usage: ["agental job list [--json]", "agental job show <job-id> [--json]", "agental job cancel <job-id>"], also: "jobs" },
1785
+ {
1786
+ name: "member",
1787
+ summary: "The members of a team: list them, remove one, invite someone.",
1788
+ usage: ["agental member list [--json]", "agental member remove <member> [--revoke-keys] [--json]", "agental member invite <email> [--role member|admin] [--json]"],
1789
+ examples: ["agental member invite ana@example.com --role admin"],
1790
+ also: "members and invite"
1791
+ },
1792
+ { name: "operator", summary: "What only whoever runs the service may run: suspend, unsuspend, suspensions and smoke.", usage: ["agental operator suspend|unsuspend|suspensions|smoke ..."], operator: true },
1730
1793
  { name: "suspend", summary: "Suspend an account.", operator: true },
1731
1794
  { name: "unsuspend", summary: "Lift an account's suspension.", operator: true },
1732
1795
  { name: "suspensions", summary: "List suspended accounts.", operator: true },
@@ -1749,32 +1812,38 @@ var MAP = [
1749
1812
  ["start, stop, delete", "one sandbox, or every one --where finds"],
1750
1813
  ["recover, auto-stop", "get a stuck one going, say when one stops"],
1751
1814
  ["schedule", "run a command on a timer"],
1752
- ["secrets", "values and files kept out of the sandbox"],
1815
+ ["secret", "values and files kept out of the sandbox"],
1753
1816
  ["network, egress", "what it may reach, and the address it leaves from"],
1754
- ["tags, meta, summary", "label sandboxes and find them again"],
1817
+ ["tag, meta, summary", "label sandboxes and find them again"],
1755
1818
  ["metrics", "CPU, memory and disk over time"],
1756
1819
  ["email", "an email address of its own"],
1757
1820
  ["desktop, browser", "a screen and a Chrome in the sandbox"],
1758
1821
  ["scp, ssh-config", "files, and SSH from any tool"],
1759
- ["jobs, regions", "work on many at once, and where they run"]
1822
+ ["job, region", "work on many at once, and where they run"]
1760
1823
  ]
1761
1824
  ],
1762
1825
  [
1763
1826
  "Account",
1764
1827
  [
1765
- ["templates, template", "what new sandboxes start from"],
1828
+ ["template", "what new sandboxes start from"],
1766
1829
  ["billing", "plan, credits, invoices and card"],
1767
1830
  ["headroom", "how close you run to your plan's limits"],
1768
- ["keys, key", "API keys"],
1769
- ["org, members, invite", "teams"],
1770
- ["webhooks, webhook", "events sent to an address of yours"],
1831
+ ["key", "API keys"],
1832
+ ["org, member", "teams"],
1833
+ ["webhook", "events sent to an address of yours"],
1771
1834
  ["telemetry", "metrics and events sent to your collector"],
1772
1835
  ["ci, claude", "GitHub Actions and Claude agents on sandboxes"],
1773
1836
  ["data-retention", "how long your sandboxes' history is kept"],
1774
1837
  ["account", "everything agental keeps about you"]
1775
1838
  ]
1776
1839
  ],
1777
- ["You", [["login, logout, whoami", "who the command is signed in as"]]]
1840
+ [
1841
+ "You",
1842
+ [
1843
+ ["login, logout, whoami", "who the command is signed in as"],
1844
+ ["completion", "Tab completion for zsh, bash and fish"]
1845
+ ]
1846
+ ]
1778
1847
  ];
1779
1848
  var DOCS = "https://agental.io/docs/cli";
1780
1849
  function shortHelp() {
@@ -1787,6 +1856,7 @@ function shortHelp() {
1787
1856
  lines.push(` ${painted}${" ".repeat(width - names.length)}${what}`);
1788
1857
  }
1789
1858
  }
1859
+ lines.push("", faint("Each thing takes list, show, add or create, update and delete, as agental key list."));
1790
1860
  lines.push("", faint(`agental <command> --help its flags and examples`), faint(`agental help --all everything, as one page`), faint(DOCS), "");
1791
1861
  return lines.join("\n");
1792
1862
  }
@@ -1850,7 +1920,7 @@ function commandHelp(name, reference, operator) {
1850
1920
  return null;
1851
1921
  }
1852
1922
  const width = Math.min(Math.max(process.stdout.columns ?? 100, 60), 110);
1853
- const usages = usageOf(reference).get(name) ?? [];
1923
+ const usages = [...LISTED[name] ? [`agental ${name} list [--json]`] : [], ...found.usage ?? usageOf(reference).get(name) ?? []];
1854
1924
  const lines = [found.summary, ""];
1855
1925
  if (usages.length > 0) {
1856
1926
  lines.push(strong("Usage"));
@@ -1866,13 +1936,16 @@ function commandHelp(name, reference, operator) {
1866
1936
  const pad3 = Math.max(...found.flags.map(([flag]) => flag.length)) + 2;
1867
1937
  lines.push(strong("Flags"), ...found.flags.map(([flag, what]) => ` ${flag.padEnd(pad3)}${what}`), "");
1868
1938
  }
1939
+ if (found.also) {
1940
+ lines.push(faint(`Also typed as agental ${found.also}.`), "");
1941
+ }
1869
1942
  lines.push(faint(`More: agental help --all, or ${DOCS}`), "");
1870
1943
  return lines.join("\n");
1871
1944
  }
1872
1945
  function nearest(word, words2) {
1873
1946
  let best = null;
1874
1947
  let bestDistance = Infinity;
1875
- for (const candidate of words2) {
1948
+ for (const candidate of words2.filter((each) => each !== word)) {
1876
1949
  const distance = editDistance(word.toLowerCase(), candidate);
1877
1950
  if (distance < bestDistance) {
1878
1951
  best = candidate;
@@ -1906,6 +1979,399 @@ function noSuchCommand(word, operator) {
1906
1979
  ${faint("agental help lists every command.", stream)}
1907
1980
  `;
1908
1981
  }
1982
+ var LISTED = { template: "templates", key: "keys", webhook: "webhooks" };
1983
+ var SANDBOX_VERBS = /* @__PURE__ */ new Set(["list", "create", "start", "stop", "delete", "recover", "exec", "shell", "summary"]);
1984
+ var SECRET_VERBS = /* @__PURE__ */ new Set(["list", "get", "set", "unset", "hosts", "get-file", "put-file", "rm-file"]);
1985
+ var OPERATOR_VERBS = /* @__PURE__ */ new Set(["suspend", "unsuspend", "suspensions", "smoke"]);
1986
+ function spelledOut(args, operator = false) {
1987
+ const [thing, verb, ...rest] = args;
1988
+ const wrong = (verbs) => {
1989
+ throw new Error(`${thing} takes ${verbs}. agental ${thing} --help shows each.`);
1990
+ };
1991
+ switch (thing) {
1992
+ case "sandbox":
1993
+ return verb !== void 0 && SANDBOX_VERBS.has(verb) ? [verb, ...rest] : wrong("list, create, start, stop, delete, recover, exec, shell or summary");
1994
+ case "region":
1995
+ return verb === "list" ? ["regions", ...rest] : wrong("list");
1996
+ case "job":
1997
+ return verb === "list" || verb === "show" || verb === "cancel" ? ["jobs", verb, ...rest] : wrong("list, show or cancel");
1998
+ case "member":
1999
+ if (verb === "invite") {
2000
+ return ["invite", ...rest];
2001
+ }
2002
+ return verb === "list" || verb === "remove" ? ["members", verb, ...rest] : wrong("list, remove or invite");
2003
+ case "tag": {
2004
+ const { sandbox, others } = sandboxIn(rest);
2005
+ if (sandbox === void 0 || verb !== "list" && verb !== "add" && verb !== "rm") {
2006
+ return wrong("list, add or rm, then the sandbox");
2007
+ }
2008
+ return ["tags", sandbox, ...verb === "list" ? [] : [verb], ...others];
2009
+ }
2010
+ case "meta": {
2011
+ if (verb !== "show" && verb !== "list" && verb !== "set" && verb !== "unset") {
2012
+ return args;
2013
+ }
2014
+ const { sandbox, others } = sandboxIn(rest);
2015
+ if (sandbox === void 0) {
2016
+ return wrong("show, set or unset, then the sandbox");
2017
+ }
2018
+ return ["meta", sandbox, ...verb === "set" || verb === "unset" ? [verb] : [], ...others];
2019
+ }
2020
+ case "secret": {
2021
+ if (verb === void 0 || !SECRET_VERBS.has(verb)) {
2022
+ return wrong("list, get, set, unset, hosts, get-file, put-file or rm-file, then the sandbox or --template <template>");
2023
+ }
2024
+ const at4 = rest.findIndex((word) => word === "--template" || word === "-t" || word.startsWith("--template="));
2025
+ if (at4 >= 0) {
2026
+ const given = rest[at4];
2027
+ const pair = given.startsWith("--template=") ? [given] : rest.slice(at4, at4 + 2);
2028
+ return ["secrets", ...pair, ...verb === "list" ? [] : [verb], ...rest.filter((_, index) => index < at4 || index >= at4 + pair.length)];
2029
+ }
2030
+ const { sandbox, others } = sandboxIn(rest, ["--host", "--text"]);
2031
+ if (sandbox === void 0) {
2032
+ return wrong("list, get, set, unset, hosts, get-file, put-file or rm-file, then the sandbox or --template <template>");
2033
+ }
2034
+ return ["secrets", sandbox, ...verb === "list" ? [] : [verb], ...others];
2035
+ }
2036
+ case "schedule":
2037
+ return verb === "list" ? ["schedules", ...rest] : args;
2038
+ case "operator":
2039
+ if (verb !== void 0 && OPERATOR_VERBS.has(verb)) {
2040
+ return [verb, ...rest];
2041
+ }
2042
+ return operator ? wrong("suspend, unsuspend, suspensions or smoke") : args;
2043
+ default:
2044
+ return thing !== void 0 && Object.hasOwn(LISTED, thing) && verb === "list" ? [LISTED[thing], ...rest] : args;
2045
+ }
2046
+ }
2047
+ function sandboxIn(words2, valued = []) {
2048
+ for (let index = 0; index < words2.length; index++) {
2049
+ const word = words2[index];
2050
+ if (word === "--") {
2051
+ break;
2052
+ }
2053
+ if (word.startsWith("-")) {
2054
+ index += valued.includes(word) ? 1 : 0;
2055
+ continue;
2056
+ }
2057
+ return { sandbox: word, others: words2.filter((_, at4) => at4 !== index) };
2058
+ }
2059
+ return { sandbox: void 0, others: words2 };
2060
+ }
2061
+
2062
+ // ../src/cli-completion.ts
2063
+ var SHELLS = ["zsh", "bash", "fish"];
2064
+ var SUBCOMMANDS = {
2065
+ billing: ["prices", "invoices", "card", "top-up", "auto-reload"],
2066
+ // Each thing that lists as its plural lists as itself too.
2067
+ template: ["list"],
2068
+ key: ["list"],
2069
+ webhook: ["list"],
2070
+ schedule: ["list"],
2071
+ headroom: ["budget"],
2072
+ egress: ["budget", "use-case"],
2073
+ telemetry: ["set", "test", "unset"],
2074
+ ci: ["set", "reset"],
2075
+ org: ["list", "use", "create"],
2076
+ members: ["list", "remove"],
2077
+ jobs: ["list", "show", "cancel"],
2078
+ account: ["export"],
2079
+ help: []
2080
+ };
2081
+ function partsOf(usage) {
2082
+ const line = usage.replace(/ {3,}\S.*$/, "").replace(/^agental /, "");
2083
+ const parts = [];
2084
+ let depth = 0;
2085
+ let part = "";
2086
+ for (const char of line) {
2087
+ depth += char === "[" || char === "(" ? 1 : char === "]" || char === ")" ? -1 : 0;
2088
+ if (char === " " && depth === 0) {
2089
+ if (part) {
2090
+ parts.push(part);
2091
+ }
2092
+ part = "";
2093
+ } else {
2094
+ part += char;
2095
+ }
2096
+ }
2097
+ if (part) {
2098
+ parts.push(part);
2099
+ }
2100
+ return parts;
2101
+ }
2102
+ function wordsOf(part) {
2103
+ const inner = part.replace(/^[[(]/, "").replace(/[\])]\.*$/, "");
2104
+ const first = inner.split(" ")[0] ?? "";
2105
+ if (first.startsWith("-") || first.startsWith("<") || first === "") {
2106
+ return [];
2107
+ }
2108
+ return first.split("|").filter((word) => /^[a-z][a-z-]*$/.test(word));
2109
+ }
2110
+ function flagsOf(usages) {
2111
+ const flags2 = /* @__PURE__ */ new Map();
2112
+ for (const usage of usages) {
2113
+ for (const found of usage.matchAll(/(--[a-z][a-z-]*)(?:[ =]([^\s\]|)]+(?:\|[^\s\]|)]+)*))?/g)) {
2114
+ const flag = found[1];
2115
+ const value = found[2] && !found[2].startsWith("-") ? found[2] : null;
2116
+ if (!flags2.has(flag) || flags2.get(flag) === null && value !== null) {
2117
+ flags2.set(flag, value);
2118
+ }
2119
+ }
2120
+ }
2121
+ return flags2;
2122
+ }
2123
+ var SANDBOX = /^<sandbox-id>/;
2124
+ var SANDBOX_VERBS2 = /* @__PURE__ */ new Set(["list", "create", "start", "stop", "delete", "recover", "exec", "shell", "summary"]);
2125
+ var TEMPLATE = /^<template>/;
2126
+ async function complete(typed, reference, operator, fetchJson) {
2127
+ if (typed[0] === "sandbox" && typed.length > 2 && SANDBOX_VERBS2.has(typed[1])) {
2128
+ return complete(typed.slice(1), reference, operator, fetchJson);
2129
+ }
2130
+ const words2 = typed.length === 0 ? [""] : [...typed];
2131
+ const equals = words2.lastIndexOf("=");
2132
+ if (equals > 0 && equals >= words2.length - 2 && words2[equals - 1]?.startsWith("--")) {
2133
+ words2.splice(equals, 1);
2134
+ if (equals === words2.length) {
2135
+ words2.push("");
2136
+ }
2137
+ }
2138
+ const whole = /^(--[a-z][a-z-]*)=(.*)$/.exec(words2[words2.length - 1]);
2139
+ if (whole) {
2140
+ words2.splice(words2.length - 1, 1, whole[1], whole[2]);
2141
+ }
2142
+ const current = words2[words2.length - 1];
2143
+ const before = words2.slice(0, -1);
2144
+ const commands = COMMANDS.filter((each) => operator || !each.operator);
2145
+ const starting = (candidates2) => candidates2.filter((each) => each.value.startsWith(current)).map((each) => whole ? { ...each, value: `${whole[1]}=${each.value}` } : each);
2146
+ if (before.includes("--")) {
2147
+ return [];
2148
+ }
2149
+ if (before.length === 0) {
2150
+ return starting([...commands.map((each) => ({ value: each.name, about: each.summary })), { value: "help", about: "the map of the commands, or one command's help" }]);
2151
+ }
2152
+ const name = before[0];
2153
+ const found = commands.find((each) => each.name === name);
2154
+ if (!found && name !== "help") {
2155
+ return [];
2156
+ }
2157
+ if (name === "help") {
2158
+ return before.length === 1 ? starting([...commands.map((each) => ({ value: each.name, about: each.summary })), { value: "--all", about: "everything, as one page" }]) : [];
2159
+ }
2160
+ const usages = [...found?.usage ?? [], ...usageOf(reference).get(name) ?? []];
2161
+ const flags2 = flagsOf(usages);
2162
+ const last = before[before.length - 1];
2163
+ const valueOf = flags2.get(last) ?? (last === "-t" ? "<template>" : last === "-s" ? "tiny|small|medium|large" : void 0);
2164
+ if (valueOf !== void 0 && valueOf !== null) {
2165
+ if (TEMPLATE.test(valueOf)) {
2166
+ return starting(await templates(fetchJson));
2167
+ }
2168
+ if (SANDBOX.test(valueOf)) {
2169
+ return starting(await sandboxes(fetchJson));
2170
+ }
2171
+ const choices = valueOf.split("|").filter((word) => /^[a-z0-9][a-z0-9.-]*$/i.test(word));
2172
+ return starting(choices.map((value) => ({ value })));
2173
+ }
2174
+ if (current.startsWith("-")) {
2175
+ return starting([...[...flags2.keys()].sort().map((value) => ({ value })), { value: "--help", about: "this command's help" }]);
2176
+ }
2177
+ const positionals = [];
2178
+ for (let index = 1; index < before.length; index++) {
2179
+ const word = before[index];
2180
+ if (word.startsWith("-")) {
2181
+ index += flags2.get(word) || word === "-t" || word === "-s" || word === "-n" ? 1 : 0;
2182
+ continue;
2183
+ }
2184
+ positionals.push(word);
2185
+ }
2186
+ const candidates = /* @__PURE__ */ new Map();
2187
+ let wantsSandbox = false;
2188
+ let wantsTemplate = false;
2189
+ for (const usage of usages) {
2190
+ const parts = partsOf(usage).slice(1);
2191
+ const fits = positionals.every((word, index) => {
2192
+ const part2 = parts[index];
2193
+ if (part2 === void 0) {
2194
+ return false;
2195
+ }
2196
+ const choices = wordsOf(part2);
2197
+ return choices.length === 0 || choices.includes(word);
2198
+ });
2199
+ const part = parts[positionals.length];
2200
+ if (!fits || part === void 0) {
2201
+ continue;
2202
+ }
2203
+ for (const word of wordsOf(part)) {
2204
+ candidates.set(word, { value: word });
2205
+ }
2206
+ const inner = part.replace(/^[[(]/, "");
2207
+ wantsSandbox ||= SANDBOX.test(inner);
2208
+ wantsTemplate ||= TEMPLATE.test(inner);
2209
+ }
2210
+ if (positionals.length === 0) {
2211
+ for (const word of SUBCOMMANDS[name] ?? []) {
2212
+ candidates.set(word, { value: word });
2213
+ }
2214
+ }
2215
+ if (name === "billing" && positionals[0] === "card" && positionals.length === 1) {
2216
+ candidates.set("save", { value: "save", about: "save a card, charged nothing" });
2217
+ }
2218
+ const asked2 = [...wantsSandbox ? await sandboxes(fetchJson) : [], ...wantsTemplate ? await templates(fetchJson) : []];
2219
+ return starting([...candidates.values(), ...asked2]);
2220
+ }
2221
+ async function sandboxes(api2) {
2222
+ const body = await cached("sandboxes", api2.as, () => api2.get("/v1/sandboxes?limit=200"));
2223
+ return (body?.sandboxes ?? []).filter((each) => typeof each["id"] === "string").sort((a, b) => Number(b["status"] === "running") - Number(a["status"] === "running")).map((each) => ({ value: each["id"], about: [each["name"], each["status"]].filter((word) => typeof word === "string" && word).join(", ") }));
2224
+ }
2225
+ async function templates(api2) {
2226
+ const body = await cached("templates", api2.as, () => api2.get("/v1/templates"));
2227
+ const listed = Array.isArray(body) ? body : body?.templates ?? [];
2228
+ return listed.filter((each) => typeof each["name"] === "string").map((each) => ({ value: each["name"], about: each["default"] === true ? "the default" : void 0 }));
2229
+ }
2230
+ var KEPT_MS = 3e4;
2231
+ async function cached(what, as, ask8) {
2232
+ const folder = path4.join(process.env["XDG_CACHE_HOME"] || path4.join(os5.homedir(), ".cache"), "agental");
2233
+ const file = path4.join(folder, `complete-${what}-${createHash2("sha256").update(as).digest("hex").slice(0, 16)}.json`);
2234
+ try {
2235
+ const kept2 = JSON.parse(readFileSync3(file, "utf8"));
2236
+ if (Date.now() - kept2.at < KEPT_MS) {
2237
+ return kept2.body;
2238
+ }
2239
+ } catch {
2240
+ }
2241
+ let body = null;
2242
+ try {
2243
+ body = await ask8();
2244
+ } catch {
2245
+ return null;
2246
+ }
2247
+ try {
2248
+ mkdirSync3(folder, { recursive: true, mode: 448 });
2249
+ writeFileSync3(file, JSON.stringify({ at: Date.now(), body }), { mode: 384 });
2250
+ } catch {
2251
+ }
2252
+ return body;
2253
+ }
2254
+ var SAFE_VALUE = /^[A-Za-z0-9._:@\/+,=%-]+$/;
2255
+ function linesOf(candidates) {
2256
+ const shown = candidates.filter((each) => SAFE_VALUE.test(each.value));
2257
+ const plain3 = (text) => text.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ");
2258
+ return shown.map((each) => each.about ? `${each.value} ${plain3(each.about)}` : each.value).join("\n") + (shown.length > 0 ? "\n" : "");
2259
+ }
2260
+ function scriptFor(shell2) {
2261
+ switch (shell2) {
2262
+ case "zsh":
2263
+ return `#compdef agental
2264
+ # agental's tab completion for zsh. Add to ~/.zshrc, after compinit:
2265
+ # source <(agental completion zsh)
2266
+ _agental() {
2267
+ local -a lines described
2268
+ local line
2269
+ lines=("\${(@f)$(agental __complete -- "\${(@)words[2,CURRENT]}" 2>/dev/null)}")
2270
+ for line in "\${lines[@]}"; do
2271
+ [[ -z "$line" ]] && continue
2272
+ if [[ "$line" == *$'\\t'* ]]; then
2273
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
2274
+ else
2275
+ described+=("\${line//:/\\\\:}")
2276
+ fi
2277
+ done
2278
+ if (( \${#described} )); then
2279
+ _describe -t agental 'agental' described
2280
+ else
2281
+ _default
2282
+ fi
2283
+ }
2284
+ if (( $+functions[compdef] )); then
2285
+ compdef _agental agental
2286
+ fi
2287
+ `;
2288
+ case "bash":
2289
+ return `# agental's tab completion for bash. Add to ~/.bashrc:
2290
+ # source <(agental completion bash)
2291
+ _agental() {
2292
+ local line
2293
+ COMPREPLY=()
2294
+ while IFS= read -r line; do
2295
+ COMPREPLY+=("\${line%%$'\\t'*}")
2296
+ done < <(agental __complete -- "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null)
2297
+ }
2298
+ complete -o default -F _agental agental
2299
+ `;
2300
+ case "fish":
2301
+ return `# agental's tab completion for fish. Add to ~/.config/fish/config.fish:
2302
+ # agental completion fish | source
2303
+ complete -c agental -f -a '(agental __complete -- (commandline -opc)[2..-1] (commandline -ct) 2>/dev/null)'
2304
+ `;
2305
+ }
2306
+ }
2307
+
2308
+ // ../src/cli-table.ts
2309
+ var plain2 = (text) => text.replace(/\x1b\[[0-9;]*m/g, "");
2310
+ function windowWidth() {
2311
+ const columns = process.stdout.columns;
2312
+ return typeof columns === "number" && columns >= 40 ? columns : 120;
2313
+ }
2314
+ function cutMiddle(text, room) {
2315
+ if (text.length <= room || room < 5) {
2316
+ return text;
2317
+ }
2318
+ const keep = room - 1;
2319
+ const head = Math.ceil(keep / 2);
2320
+ return `${text.slice(0, head)}\u2026${text.slice(text.length - (keep - head))}`;
2321
+ }
2322
+ function fitted(rows, options = {}) {
2323
+ const width = options.width ?? windowWidth();
2324
+ const columns = Math.max(0, ...rows.map((row) => row.length));
2325
+ const widths = Array.from({ length: columns }, (_, column) => Math.max(0, ...rows.map((row) => plain2(row[column] ?? "").length)));
2326
+ const total = widths.reduce((sum, each) => sum + each, 0) + 2 * (columns - 1);
2327
+ const cut = options.give !== void 0 && total > width ? options.give : -1;
2328
+ if (cut >= 0) {
2329
+ widths[cut] = Math.min(widths[cut] ?? 0, Math.max(12, (widths[cut] ?? 0) - (total - width)));
2330
+ }
2331
+ return rows.map(
2332
+ (row, index) => row.map((cell, column) => {
2333
+ const fit = column === cut ? cutMiddle(cell, widths[column] ?? 0) : cell;
2334
+ const padded = column === row.length - 1 ? fit : fit + " ".repeat(Math.max(0, (widths[column] ?? 0) - plain2(fit).length));
2335
+ return options.paint ? options.paint(padded, index, column) : padded;
2336
+ }).join(" ").trimEnd()
2337
+ ).map((line) => `${line}
2338
+ `).join("");
2339
+ }
2340
+ function ago(iso, now = Date.now()) {
2341
+ const ms = now - Date.parse(iso);
2342
+ if (!Number.isFinite(ms)) {
2343
+ return null;
2344
+ }
2345
+ const said = span(ms);
2346
+ return said === "moments" ? "just now" : `${said} ago`;
2347
+ }
2348
+ function until(iso, now = Date.now()) {
2349
+ const ms = Date.parse(iso) - now;
2350
+ if (!Number.isFinite(ms)) {
2351
+ return null;
2352
+ }
2353
+ const said = span(ms);
2354
+ return said === "moments" ? "any moment now" : `in ${said}`;
2355
+ }
2356
+ function span(ms) {
2357
+ const minutes = Math.max(0, Math.round(ms / 6e4));
2358
+ const say = (count, unit) => `${count} ${unit}${count === 1 ? "" : "s"}`;
2359
+ if (minutes < 1) {
2360
+ return "moments";
2361
+ }
2362
+ if (minutes < 60) {
2363
+ return say(minutes, "minute");
2364
+ }
2365
+ const hours = Math.round(minutes / 60);
2366
+ if (hours < 36) {
2367
+ return say(hours, "hour");
2368
+ }
2369
+ const days = Math.round(hours / 24);
2370
+ if (days < 60) {
2371
+ return say(days, "day");
2372
+ }
2373
+ return say(Math.round(days / 30), "month");
2374
+ }
1909
2375
 
1910
2376
  // ../src/cli-teams.ts
1911
2377
  var ORG_USAGE = "org takes list, use <organization> or create <name>. agental org --help shows each.";
@@ -2277,12 +2743,12 @@ async function schedule(client, positionals, options) {
2277
2743
  throw new Error(USAGE3);
2278
2744
  }
2279
2745
  const id = await idOf2(client, sandboxId, target, what);
2280
- const path4 = `${base}/${encodeURIComponent(id)}`;
2746
+ const path5 = `${base}/${encodeURIComponent(id)}`;
2281
2747
  if (what === "show") {
2282
- print3(await ask5(client, "GET", path4), options.json);
2748
+ print3(await ask5(client, "GET", path5), options.json);
2283
2749
  } else if (what === "runs") {
2284
2750
  const limit = options.limit === void 0 ? "" : `?limit=${encodeURIComponent(options.limit)}`;
2285
- const runs = (await ask5(client, "GET", `${path4}/runs${limit}`))?.runs ?? [];
2751
+ const runs = (await ask5(client, "GET", `${path5}/runs${limit}`))?.runs ?? [];
2286
2752
  if (options.json) {
2287
2753
  process.stdout.write(`${JSON.stringify(runs, null, 2)}
2288
2754
  `);
@@ -2304,7 +2770,7 @@ async function schedule(client, positionals, options) {
2304
2770
  );
2305
2771
  }
2306
2772
  } else if (what === "run") {
2307
- const run2 = await ask5(client, "POST", `${path4}/run`);
2773
+ const run2 = await ask5(client, "POST", `${path5}/run`);
2308
2774
  if (options.json) {
2309
2775
  process.stdout.write(`${JSON.stringify(run2, null, 2)}
2310
2776
  `);
@@ -2314,9 +2780,9 @@ async function schedule(client, positionals, options) {
2314
2780
  `);
2315
2781
  }
2316
2782
  } else if (what === "pause" || what === "resume") {
2317
- print3(await ask5(client, "PATCH", path4, { enabled: what === "resume" }), options.json);
2783
+ print3(await ask5(client, "PATCH", path5, { enabled: what === "resume" }), options.json);
2318
2784
  } else if (what === "delete") {
2319
- await ask5(client, "DELETE", path4);
2785
+ await ask5(client, "DELETE", path5);
2320
2786
  process.stdout.write(`Deleted ${id}, with its runs.
2321
2787
  `);
2322
2788
  } else {
@@ -2324,7 +2790,7 @@ async function schedule(client, positionals, options) {
2324
2790
  if (Object.keys(changes).length === 0) {
2325
2791
  throw new Error("schedule update needs something to change: --every, --cron, --at, --tz, --name, --timeout, --overlap, --if-stopped, --keep-memory or --disk-only, --delete-after or --keep-sandbox, or a new command after --.");
2326
2792
  }
2327
- print3(await ask5(client, "PATCH", path4, changes), options.json);
2793
+ print3(await ask5(client, "PATCH", path5, changes), options.json);
2328
2794
  }
2329
2795
  return;
2330
2796
  }
@@ -2802,7 +3268,7 @@ function needId2(id, what) {
2802
3268
  }
2803
3269
 
2804
3270
  // ../src/cli-shell.ts
2805
- import { createHash as createHash2, randomBytes as randomBytes4 } from "node:crypto";
3271
+ import { createHash as createHash3, randomBytes as randomBytes4 } from "node:crypto";
2806
3272
  var TERMINAL_PROTOCOL = "agental.terminal.v1";
2807
3273
  var TICKET_PROTOCOL_PREFIX = "ticket.";
2808
3274
  var VERIFIER_PROTOCOL_PREFIX = "verifier.";
@@ -2814,15 +3280,15 @@ function clamp(value, fallback) {
2814
3280
  function sizeOf(stdout) {
2815
3281
  return stdout.isTTY ? { cols: clamp(stdout.columns, 80), rows: clamp(stdout.rows, 24) } : { cols: 80, rows: 24 };
2816
3282
  }
2817
- function webSocketUrl(base, path4) {
2818
- if (typeof path4 !== "string" || !path4.startsWith("/") || path4.startsWith("//") || /[\\\s]/.test(path4)) {
3283
+ function webSocketUrl(base, path5) {
3284
+ if (typeof path5 !== "string" || !path5.startsWith("/") || path5.startsWith("//") || /[\\\s]/.test(path5)) {
2819
3285
  throw new Error("The API gave the terminal a path that is not one on its own address.");
2820
3286
  }
2821
3287
  const url = new URL(base);
2822
3288
  if (url.protocol !== "https:" && url.protocol !== "http:") {
2823
3289
  throw new Error(`A terminal is opened on an http: or https: API, not ${url.protocol}`);
2824
3290
  }
2825
- return `${url.protocol === "https:" ? "wss:" : "ws:"}//${url.host}${url.pathname.replace(/\/+$/, "")}${path4}`;
3291
+ return `${url.protocol === "https:" ? "wss:" : "ws:"}//${url.host}${url.pathname.replace(/\/+$/, "")}${path5}`;
2826
3292
  }
2827
3293
  function whyClosed(code, reason, error) {
2828
3294
  const said = error?.message || reason;
@@ -2850,7 +3316,7 @@ async function shell(client, id, streams = process) {
2850
3316
  const { stdin, stdout, stderr } = streams;
2851
3317
  const size = sizeOf(stdout);
2852
3318
  const verifier = randomBytes4(32).toString("base64url");
2853
- const challenge = createHash2("sha256").update(verifier).digest("base64url");
3319
+ const challenge = createHash3("sha256").update(verifier).digest("base64url");
2854
3320
  const response = await client.request(`/v1/sandboxes/${encodeURIComponent(id)}/terminal`, { method: "POST", body: JSON.stringify({ ...size, challenge }) });
2855
3321
  const body = await response.json().catch(() => null);
2856
3322
  if (!response.ok || typeof body?.ticket !== "string") {
@@ -3042,6 +3508,7 @@ var FREE = {
3042
3508
  /** Small sandboxes an account on the free plan runs and starts at once before it has paid for anything. */
3043
3509
  unpaidUnits: 2
3044
3510
  };
3511
+ var PLAN_NAMES = { free: "Free", plan100: "Fleet", plan500: "Platform", plan2000: "Scale" };
3045
3512
  var TOP_UP_DOLLARS = { min: 15, max: 1e5 };
3046
3513
  var TOP_UP_BONUS = { fromDollars: 200, fromPercent: 2, toDollars: 1e4, toPercent: 25 };
3047
3514
  function topUpBonusPercent(dollars) {
@@ -3073,7 +3540,7 @@ function words(text) {
3073
3540
  return found;
3074
3541
  }
3075
3542
  function whereQuery(text, query = new URLSearchParams()) {
3076
- const plain2 = [];
3543
+ const plain3 = [];
3077
3544
  for (const word of words(text)) {
3078
3545
  const time = /^(made|stopped)([<>])(.+)$/.exec(word);
3079
3546
  if (time) {
@@ -3089,7 +3556,7 @@ function whereQuery(text, query = new URLSearchParams()) {
3089
3556
  }
3090
3557
  const pair = /^(-?)([a-z0-9][a-z0-9_.-]*):(.*)$/.exec(word);
3091
3558
  if (!pair) {
3092
- plain2.push(word);
3559
+ plain3.push(word);
3093
3560
  continue;
3094
3561
  }
3095
3562
  const [, not, key2, value] = pair;
@@ -3151,8 +3618,8 @@ function whereQuery(text, query = new URLSearchParams()) {
3151
3618
  query.append(key2, value);
3152
3619
  }
3153
3620
  }
3154
- if (plain2.length > 0) {
3155
- query.set("q", plain2.join(" "));
3621
+ if (plain3.length > 0) {
3622
+ query.set("q", plain3.join(" "));
3156
3623
  }
3157
3624
  return query;
3158
3625
  }
@@ -3222,7 +3689,7 @@ async function helpAsked(args) {
3222
3689
  topic = void 0;
3223
3690
  } else if (first !== void 0 && first.startsWith("-") && ours.some(asked2)) {
3224
3691
  topic = void 0;
3225
- } else if (first !== void 0 && (SSH_COMMANDS[first] ? asked2(second) : ours.some(asked2))) {
3692
+ } else if (first !== void 0 && (Object.hasOwn(SSH_COMMANDS, first) ? asked2(second) : ours.some(asked2))) {
3226
3693
  topic = first;
3227
3694
  } else {
3228
3695
  return false;
@@ -3240,14 +3707,51 @@ async function helpAsked(args) {
3240
3707
  process.stdout.write(one);
3241
3708
  return true;
3242
3709
  }
3710
+ async function completionAsked(args) {
3711
+ const [first, second, ...rest] = args;
3712
+ if (first === "__complete") {
3713
+ const typed = second === "--" ? rest : args.slice(1);
3714
+ try {
3715
+ const api2 = {
3716
+ as: `${apiBase()} ${maybeApiKey() ?? ""}`,
3717
+ get: async (pathname) => {
3718
+ if (!maybeApiKey()) {
3719
+ throw new Error("not signed in");
3720
+ }
3721
+ const response = await request(pathname, { method: "GET", signal: AbortSignal.timeout(800) });
3722
+ if (!response.ok) {
3723
+ throw new Error(String(response.status));
3724
+ }
3725
+ return await readBody(response);
3726
+ }
3727
+ };
3728
+ const lines = linesOf(await complete(typed, await helpText(), !PUBLISHED, api2));
3729
+ await new Promise((resolve) => process.stdout.write(lines, () => resolve()));
3730
+ } catch {
3731
+ }
3732
+ process.exit(0);
3733
+ }
3734
+ if (first === "completion" && !args.includes("--help") && !args.includes("-h")) {
3735
+ if (!SHELLS.includes(second) || rest.length > 0) {
3736
+ throw new Error(`completion takes the shell to complete in, ${SHELLS.join(", ")}: as source <(agental completion zsh) in ~/.zshrc.`);
3737
+ }
3738
+ process.stdout.write(scriptFor(second));
3739
+ return true;
3740
+ }
3741
+ return false;
3742
+ }
3243
3743
  async function main() {
3744
+ if (await completionAsked(process.argv.slice(2))) {
3745
+ return;
3746
+ }
3244
3747
  if (await helpAsked(process.argv.slice(2))) {
3245
3748
  return;
3246
3749
  }
3750
+ process.argv.splice(2, process.argv.length - 2, ...spelledOut(process.argv.slice(2), !PUBLISHED));
3247
3751
  if (await setUp(process.argv.slice(2))) {
3248
3752
  return;
3249
3753
  }
3250
- const overSsh = SSH_COMMANDS[process.argv[2] ?? ""];
3754
+ const overSsh = Object.hasOwn(SSH_COMMANDS, process.argv[2] ?? "") ? SSH_COMMANDS[process.argv[2] ?? ""] : void 0;
3251
3755
  if (overSsh) {
3252
3756
  await overSsh({ request }, process.argv.slice(3));
3253
3757
  return;
@@ -3362,6 +3866,8 @@ async function main() {
3362
3866
  sort: { type: "string" },
3363
3867
  role: { type: "string" },
3364
3868
  "revoke-keys": { type: "boolean", default: false },
3869
+ // agental list in a terminal: every column, as piped.
3870
+ wide: { type: "boolean", default: false },
3365
3871
  help: { type: "boolean", short: "h", default: false }
3366
3872
  }
3367
3873
  });
@@ -3375,7 +3881,7 @@ async function main() {
3375
3881
  await create({ ...values, template: once(values.template, "--template") });
3376
3882
  return;
3377
3883
  case "list":
3378
- await list2(values.json, whereQuery(values.where ?? "", labelsFilter(values)), values.sort, values.limit);
3884
+ await list2(values.json, whereQuery(values.where ?? "", labelsFilter(values)), values.sort, values.limit, values.wide);
3379
3885
  return;
3380
3886
  case "jobs":
3381
3887
  await jobs(positionals.slice(1), values.json);
@@ -3652,17 +4158,17 @@ async function sshKeys(id, keyId, remove3, json) {
3652
4158
  if (!id) {
3653
4159
  throw new Error("ssh-keys requires <sandbox-id>");
3654
4160
  }
3655
- const path4 = `/v1/sandboxes/${encodeURIComponent(id)}/ssh/keys`;
4161
+ const path5 = `/v1/sandboxes/${encodeURIComponent(id)}/ssh/keys`;
3656
4162
  if (remove3) {
3657
4163
  if (!keyId) {
3658
4164
  throw new Error("ssh-keys --remove requires <key-id>, as ssh-keys lists it");
3659
4165
  }
3660
- await call2(`${path4}/${encodeURIComponent(keyId)}`, { method: "DELETE" });
4166
+ await call2(`${path5}/${encodeURIComponent(keyId)}`, { method: "DELETE" });
3661
4167
  process.stdout.write(`${keyId} may log in to ${id} no longer.
3662
4168
  `);
3663
4169
  return;
3664
4170
  }
3665
- const body = await call2(path4, { method: "GET" });
4171
+ const body = await call2(path5, { method: "GET" });
3666
4172
  const keys = body?.keys ?? [];
3667
4173
  if (json) {
3668
4174
  process.stdout.write(`${JSON.stringify(keys, null, 2)}
@@ -3676,10 +4182,10 @@ function publicKeysFrom(given) {
3676
4182
  if (SSH_PUBLIC_KEY.test(each.trim())) {
3677
4183
  return [each.trim()];
3678
4184
  }
3679
- const file = each.startsWith("~/") ? `${os5.homedir()}${each.slice(1)}` : each;
4185
+ const file = each.startsWith("~/") ? `${os6.homedir()}${each.slice(1)}` : each;
3680
4186
  let text;
3681
4187
  try {
3682
- text = readFileSync3(file, "utf8");
4188
+ text = readFileSync4(file, "utf8");
3683
4189
  } catch {
3684
4190
  throw new Error(`${each} is neither a public key nor a file that can be read. Give a key line, as ssh-ed25519 AAAA... you@laptop, or its file, as ~/.ssh/id_ed25519.pub.`);
3685
4191
  }
@@ -3730,8 +4236,8 @@ async function regions(asJson) {
3730
4236
  }
3731
4237
  process.stdout.write("* where a sandbox is made when no region is named\n");
3732
4238
  }
3733
- async function list2(asJson, filter, sort, limit) {
3734
- const sandboxes = [];
4239
+ async function list2(asJson, filter, sort, limit, wide = false) {
4240
+ const sandboxes2 = [];
3735
4241
  let cursor = null;
3736
4242
  do {
3737
4243
  const query = new URLSearchParams(filter);
@@ -3747,7 +4253,7 @@ async function list2(asJson, filter, sort, limit) {
3747
4253
  if (!response.ok) {
3748
4254
  fail(response.status, body);
3749
4255
  }
3750
- sandboxes.push(...readSandboxes(body));
4256
+ sandboxes2.push(...readSandboxes(body));
3751
4257
  const next = body && typeof body === "object" ? body["nextCursor"] : null;
3752
4258
  cursor = typeof next === "string" ? next : null;
3753
4259
  if (limit !== void 0 && cursor !== null) {
@@ -3757,20 +4263,24 @@ async function list2(asJson, filter, sort, limit) {
3757
4263
  }
3758
4264
  } while (cursor !== null);
3759
4265
  if (asJson) {
3760
- process.stdout.write(`${JSON.stringify(sandboxes, null, 2)}
4266
+ process.stdout.write(`${JSON.stringify(sandboxes2, null, 2)}
3761
4267
  `);
3762
4268
  return;
3763
4269
  }
3764
- if (sandboxes.length === 0) {
4270
+ if (sandboxes2.length === 0) {
3765
4271
  process.stdout.write(filter.size > 0 ? "No sandboxes match.\n" : "No sandboxes.\n");
3766
4272
  return;
3767
4273
  }
3768
- const names = sandboxes.some((sandbox) => typeof sandbox["templateId"] === "string") ? await templateNames() : /* @__PURE__ */ new Map();
3769
- const tagged = sandboxes.some((sandbox) => Array.isArray(sandbox["tags"]));
4274
+ const names = sandboxes2.some((sandbox) => typeof sandbox["templateId"] === "string") ? await templateNames() : /* @__PURE__ */ new Map();
4275
+ if (isTerminal(process.stdout) && !wide) {
4276
+ process.stdout.write(sandboxesForPeople(sandboxes2, names, sort !== void 0));
4277
+ return;
4278
+ }
4279
+ const tagged = sandboxes2.some((sandbox) => Array.isArray(sandbox["tags"]));
3770
4280
  const header = [...["ID", "NAME", "SIZE", "STATUS"].map(pad2), "VM ", pad2("TEMPLATE"), tagged ? pad2("OUTBOUND") : "OUTBOUND", ...tagged ? ["TAGS"] : []].join(" ");
3771
4281
  process.stdout.write(`${header}
3772
4282
  `);
3773
- for (const sandbox of sandboxes) {
4283
+ for (const sandbox of sandboxes2) {
3774
4284
  const rule = sandbox["network"];
3775
4285
  const templateId = typeof sandbox["templateId"] === "string" ? sandbox["templateId"] : null;
3776
4286
  const row = [
@@ -3917,11 +4427,11 @@ async function bulk(action, filter, options, yes2, asJson, confirm) {
3917
4427
  }
3918
4428
  async function jobs(positionals, asJson) {
3919
4429
  const [verb, id] = positionals;
3920
- const path4 = verb === void 0 || verb === "list" ? "/v1/sandbox-jobs" : verb === "show" && id ? `/v1/sandbox-jobs/${encodeURIComponent(id)}` : verb === "cancel" && id ? `/v1/sandbox-jobs/${encodeURIComponent(id)}/cancel` : null;
3921
- if (path4 === null) {
4430
+ const path5 = verb === void 0 || verb === "list" ? "/v1/sandbox-jobs" : verb === "show" && id ? `/v1/sandbox-jobs/${encodeURIComponent(id)}` : verb === "cancel" && id ? `/v1/sandbox-jobs/${encodeURIComponent(id)}/cancel` : null;
4431
+ if (path5 === null) {
3922
4432
  throw new Error("jobs takes list, show <job-id> or cancel <job-id>");
3923
4433
  }
3924
- const response = await request(path4, { method: verb === "cancel" ? "POST" : "GET" });
4434
+ const response = await request(path5, { method: verb === "cancel" ? "POST" : "GET" });
3925
4435
  const body = await readBody(response);
3926
4436
  if (!response.ok) {
3927
4437
  fail(response.status, body);
@@ -4148,18 +4658,18 @@ async function autoStop(id, inText, at4, never, asJson) {
4148
4658
  if ([inText !== void 0, at4 !== void 0, never].filter(Boolean).length > 1) {
4149
4659
  throw new Error("--in, --at and --never say different things: give one.");
4150
4660
  }
4151
- const path4 = `/v1/sandboxes/${encodeURIComponent(id)}/auto-stop`;
4661
+ const path5 = `/v1/sandboxes/${encodeURIComponent(id)}/auto-stop`;
4152
4662
  let body;
4153
4663
  if (never) {
4154
- body = await call2(path4, { method: "DELETE" });
4664
+ body = await call2(path5, { method: "DELETE" });
4155
4665
  } else if (inText === void 0 && at4 === void 0) {
4156
- body = await call2(path4, { method: "GET" });
4666
+ body = await call2(path5, { method: "GET" });
4157
4667
  } else {
4158
4668
  const inSeconds = inText === void 0 ? void 0 : seconds(inText);
4159
4669
  if (inSeconds === null) {
4160
4670
  throw new Error("--in is a time from now, such as 30m, 2h or 1d");
4161
4671
  }
4162
- body = await call2(path4, { method: "PUT", body: JSON.stringify(inSeconds === void 0 ? { at: at4 } : { inSeconds }) });
4672
+ body = await call2(path5, { method: "PUT", body: JSON.stringify(inSeconds === void 0 ? { at: at4 } : { inSeconds }) });
4163
4673
  }
4164
4674
  if (asJson) {
4165
4675
  process.stdout.write(`${JSON.stringify(body, null, 2)}
@@ -4215,7 +4725,7 @@ async function screenshot(id, file, options) {
4215
4725
  fail(response.status, await readBody(response));
4216
4726
  }
4217
4727
  const picture = Buffer.from(await response.arrayBuffer());
4218
- writeFileSync3(file, picture);
4728
+ writeFileSync4(file, picture);
4219
4729
  const size = pictureSize(picture);
4220
4730
  process.stderr.write(`A picture of the screen of ${id} is in ${file}: ${size ? `${size.width} by ${size.height}, ` : ""}${picture.length} bytes.
4221
4731
  `);
@@ -4250,7 +4760,7 @@ async function clipboard(id, text) {
4250
4760
  process.stdout.write(String(body.text ?? ""));
4251
4761
  return;
4252
4762
  }
4253
- const given = text === "-" ? readFileSync3(0, "utf8") : text;
4763
+ const given = text === "-" ? readFileSync4(0, "utf8") : text;
4254
4764
  const response = await request(at4, { method: "PUT", body: JSON.stringify({ text: given }) });
4255
4765
  if (!response.ok) {
4256
4766
  fail(response.status, await readBody(response));
@@ -4398,10 +4908,10 @@ async function labels(what, holder, positionals, asJson) {
4398
4908
  throw new Error(`${command2} requires <${holder}>: ${usage}`);
4399
4909
  }
4400
4910
  const id = holder === "template" ? (await templateNamed(named)).id : named;
4401
- const path4 = `/v1/${holder === "template" ? "templates" : "sandboxes"}/${encodeURIComponent(id)}`;
4911
+ const path5 = `/v1/${holder === "template" ? "templates" : "sandboxes"}/${encodeURIComponent(id)}`;
4402
4912
  let body;
4403
4913
  if (action === void 0) {
4404
- body = await call2(path4, { method: "GET" });
4914
+ body = await call2(path5, { method: "GET" });
4405
4915
  } else if (what === "tags" && (action === "add" || action === "rm")) {
4406
4916
  const tags = listedIn(words2).map((tag) => tag.toLowerCase());
4407
4917
  if (tags.length === 0) {
@@ -4412,14 +4922,14 @@ async function labels(what, holder, positionals, asJson) {
4412
4922
  throw new Error(`A tag is lowercase letters, digits and hyphens, 1 to 63 characters, not starting or ending with a hyphen, not ${JSON.stringify(bad2)}.`);
4413
4923
  }
4414
4924
  for (const tag of tags) {
4415
- body = await call2(`${path4}/tags/${encodeURIComponent(tag)}`, { method: action === "add" ? "PUT" : "DELETE" });
4925
+ body = await call2(`${path5}/tags/${encodeURIComponent(tag)}`, { method: action === "add" ? "PUT" : "DELETE" });
4416
4926
  }
4417
4927
  } else if (what === "meta" && (action === "set" || action === "unset")) {
4418
4928
  if (words2.length === 0) {
4419
4929
  throw new Error(`${command2} ${action} requires ${action === "set" ? "<key>=<value>" : "<key>"}...`);
4420
4930
  }
4421
4931
  const metadata = action === "set" ? metadataGiven(words2) : Object.fromEntries(words2.map((key2) => [key2, null]));
4422
- body = await call2(path4, { method: "PATCH", body: JSON.stringify({ metadata }) });
4932
+ body = await call2(path5, { method: "PATCH", body: JSON.stringify({ metadata }) });
4423
4933
  } else {
4424
4934
  throw new Error(`${command2} takes ${usage}`);
4425
4935
  }
@@ -4446,9 +4956,9 @@ async function network(positionals, values) {
4446
4956
  if (values.allow !== void 0 && values.none) {
4447
4957
  throw new Error("--allow and --none say two things: give one.");
4448
4958
  }
4449
- const path4 = `/v1/sandboxes/${encodeURIComponent(id)}/network`;
4959
+ const path5 = `/v1/sandboxes/${encodeURIComponent(id)}/network`;
4450
4960
  const allow = values.none ? [] : values.allow === void 0 ? void 0 : listedIn(values.allow);
4451
- const body = await call2(path4, allow === void 0 ? { method: "GET" } : { method: "PUT", body: JSON.stringify({ allow }) });
4961
+ const body = await call2(path5, allow === void 0 ? { method: "GET" } : { method: "PUT", body: JSON.stringify({ allow }) });
4452
4962
  if (values.json) {
4453
4963
  process.stdout.write(`${JSON.stringify(body, null, 2)}
4454
4964
  `);
@@ -4509,7 +5019,7 @@ async function egress(positionals, values) {
4509
5019
  const missing = Array.isArray(account3["missing"]) ? account3["missing"].map(String) : [];
4510
5020
  const needs = {
4511
5021
  plan: "a plan of Fleet ($100 a month) or larger: agental billing",
4512
- card: "a card saved: agental billing card",
5022
+ card: "a card saved: agental billing card save",
4513
5023
  use_case: 'what your sandboxes will use it for: agental egress use-case "<what for>"'
4514
5024
  };
4515
5025
  const refused = account3["refused"];
@@ -4524,9 +5034,9 @@ async function egress(positionals, values) {
4524
5034
  `);
4525
5035
  return;
4526
5036
  }
4527
- const path4 = `/v1/sandboxes/${encodeURIComponent(first)}/egress`;
5037
+ const path5 = `/v1/sandboxes/${encodeURIComponent(first)}/egress`;
4528
5038
  const how = `egress takes <sandbox-id>, and then nothing, box, or residential <country> [sticky|rotating], as agental egress ${first} residential de.`;
4529
- const body = await call2(path4, rest.length === 0 ? { method: "GET" } : { method: "PUT", body: JSON.stringify(egressFrom(rest, how)) });
5039
+ const body = await call2(path5, rest.length === 0 ? { method: "GET" } : { method: "PUT", body: JSON.stringify(egressFrom(rest, how)) });
4530
5040
  print4(body, `${first}: ${egressInWords(body)}
4531
5041
  `);
4532
5042
  }
@@ -4577,6 +5087,17 @@ async function listTemplates(asJson) {
4577
5087
  const listed = await templatesListed();
4578
5088
  if (asJson) {
4579
5089
  process.stdout.write(`${JSON.stringify(listed, null, 2)}
5090
+ `);
5091
+ return;
5092
+ }
5093
+ if (isTerminal(process.stdout)) {
5094
+ const rows = [
5095
+ ["ID", "NAME", "START", "SANDBOXES"],
5096
+ ...listed.map((each) => [each.id, each.default ? `${each.name} (default)` : each.name, `${each.start?.size ?? ""}${each.start?.snapshotId ? ` from ${each.start.snapshotId}` : ""}`, String(each.sandboxes ?? 0)])
5097
+ ];
5098
+ process.stdout.write(fitted(rows, { give: 1, paint: (cell, row) => row === 0 ? faint(cell) : cell }));
5099
+ process.stdout.write(`
5100
+ ${faint("The default is used when a sandbox is made without naming one. agental template show <name> says more.")}
4580
5101
  `);
4581
5102
  return;
4582
5103
  }
@@ -4653,7 +5174,7 @@ async function template(positionals, values) {
4653
5174
  }
4654
5175
  case "start": {
4655
5176
  const found = await templateNamed(need(first, "<template>"));
4656
- const path4 = `/v1/templates/${encodeURIComponent(found.id)}/start`;
5177
+ const path5 = `/v1/templates/${encodeURIComponent(found.id)}/start`;
4657
5178
  if (values.snapshot !== void 0 && values["new-machine"]) {
4658
5179
  throw new Error("--snapshot and --new-machine say two things: give one.");
4659
5180
  }
@@ -4663,12 +5184,12 @@ async function template(positionals, values) {
4663
5184
  const ttlSeconds = ttlOption(values.ttl);
4664
5185
  let start;
4665
5186
  if (values.size === void 0 && values.snapshot === void 0 && !values["new-machine"] && ttlSeconds === void 0) {
4666
- start = await call2(path4, { method: "GET" });
5187
+ start = await call2(path5, { method: "GET" });
4667
5188
  } else {
4668
- const current = await call2(path4, { method: "GET" });
5189
+ const current = await call2(path5, { method: "GET" });
4669
5190
  const snapshotId = values["new-machine"] ? null : values.snapshot ?? current?.snapshotId ?? null;
4670
5191
  const ttl = ttlSeconds === void 0 ? current?.ttlSeconds ?? null : ttlSeconds;
4671
- start = await call2(path4, { method: "PUT", body: JSON.stringify({ size: values.size ?? current?.size, snapshotId, ttlSeconds: ttl }) });
5192
+ start = await call2(path5, { method: "PUT", body: JSON.stringify({ size: values.size ?? current?.size, snapshotId, ttlSeconds: ttl }) });
4672
5193
  }
4673
5194
  print4(start, `start: ${startInWords(start)}
4674
5195
  `);
@@ -4676,11 +5197,11 @@ async function template(positionals, values) {
4676
5197
  }
4677
5198
  case "network": {
4678
5199
  const found = await templateNamed(need(first, "<template>"));
4679
- const path4 = `/v1/templates/${encodeURIComponent(found.id)}/network`;
5200
+ const path5 = `/v1/templates/${encodeURIComponent(found.id)}/network`;
4680
5201
  const [mode, ...addresses] = rest;
4681
5202
  let rule;
4682
5203
  if (mode === void 0) {
4683
- rule = await call2(path4, { method: "GET" });
5204
+ rule = await call2(path5, { method: "GET" });
4684
5205
  } else {
4685
5206
  if (!OUTBOUND_MODES.some((known) => known === mode)) {
4686
5207
  throw new Error("template network requires <template>, and then nothing, open, blocked, or allowlist <address>...");
@@ -4692,7 +5213,7 @@ async function template(positionals, values) {
4692
5213
  if (mode === "allowlist" && listed.length === 0) {
4693
5214
  throw new Error(`allowlist needs at least one address, as agental template network ${first ?? ""} allowlist 203.0.113.7 198.51.100.0/24`);
4694
5215
  }
4695
- rule = await call2(path4, { method: "PUT", body: JSON.stringify(mode === "allowlist" ? { outbound: mode, allow: listed } : { outbound: mode }) });
5216
+ rule = await call2(path5, { method: "PUT", body: JSON.stringify(mode === "allowlist" ? { outbound: mode, allow: listed } : { outbound: mode }) });
4696
5217
  }
4697
5218
  print4(
4698
5219
  rule,
@@ -4703,37 +5224,37 @@ ${mode === void 0 ? "" : "A sandbox on it takes this when it next starts, or now
4703
5224
  }
4704
5225
  case "egress": {
4705
5226
  const found = await templateNamed(need(first, "<template>"));
4706
- const path4 = `/v1/templates/${encodeURIComponent(found.id)}/egress`;
5227
+ const path5 = `/v1/templates/${encodeURIComponent(found.id)}/egress`;
4707
5228
  const how = `template egress takes <template>, and then nothing, box, or residential <country> [sticky|rotating], as agental template egress ${first ?? ""} residential de.`;
4708
- const set = await call2(path4, rest.length === 0 ? { method: "GET" } : { method: "PUT", body: JSON.stringify(egressFrom(rest, how)) });
5229
+ const set = await call2(path5, rest.length === 0 ? { method: "GET" } : { method: "PUT", body: JSON.stringify(egressFrom(rest, how)) });
4709
5230
  print4(set, `${found.name}: ${egressInWords(set)}${rest.length === 0 ? "" : ", for sandboxes made from it from now on"}
4710
5231
  `);
4711
5232
  return;
4712
5233
  }
4713
5234
  case "ssh": {
4714
5235
  const found = await templateNamed(need(first, "<template>"));
4715
- const path4 = `/v1/templates/${encodeURIComponent(found.id)}/ssh`;
5236
+ const path5 = `/v1/templates/${encodeURIComponent(found.id)}/ssh`;
4716
5237
  const [turn] = rest;
4717
5238
  if (turn !== void 0 && turn !== "on" && turn !== "off") {
4718
5239
  throw new Error("template ssh requires <template>, and then nothing, on or off");
4719
5240
  }
4720
- const ssh2 = await call2(path4, { method: turn === "on" ? "PUT" : turn === "off" ? "DELETE" : "GET" });
5241
+ const ssh2 = await call2(path5, { method: turn === "on" ? "PUT" : turn === "off" ? "DELETE" : "GET" });
4721
5242
  print4(ssh2, `${found.name}: SSH ${templateSshInWords(ssh2)}
4722
5243
  `);
4723
5244
  return;
4724
5245
  }
4725
5246
  case "ssh-keys": {
4726
5247
  const found = await templateNamed(need(first, "<template>"));
4727
- const path4 = `/v1/templates/${encodeURIComponent(found.id)}/ssh/keys`;
5248
+ const path5 = `/v1/templates/${encodeURIComponent(found.id)}/ssh/keys`;
4728
5249
  if (values.remove) {
4729
5250
  const keyId = need(rest[0], "<template> --remove <key-id>");
4730
- await call2(`${path4}/${encodeURIComponent(keyId)}`, { method: "DELETE" });
5251
+ await call2(`${path5}/${encodeURIComponent(keyId)}`, { method: "DELETE" });
4731
5252
  process.stdout.write(`${keyId} is let in to no sandbox made from ${found.name} from now on. The sandboxes made already keep it.
4732
5253
  `);
4733
5254
  return;
4734
5255
  }
4735
5256
  for (const publicKey2 of publicKeysFrom(rest)) {
4736
- await call2(path4, { method: "POST", body: JSON.stringify({ publicKey: publicKey2 }) });
5257
+ await call2(path5, { method: "POST", body: JSON.stringify({ publicKey: publicKey2 }) });
4737
5258
  }
4738
5259
  const ssh2 = await call2(`/v1/templates/${encodeURIComponent(found.id)}/ssh`, { method: "GET" });
4739
5260
  if (values.json) {
@@ -4795,8 +5316,8 @@ up to date: ${body["upToDate"] === true ? "yes" : "no: it takes the template whe
4795
5316
  function keptOutInWords(variable) {
4796
5317
  return [`${variable.name} is kept out of the sandbox, and its value is never given back.`, `stand-in: ${variable.standIn}`, `hosts: ${variable.hosts.join(", ")}`, ""].join("\n");
4797
5318
  }
4798
- async function keptOutNow(path4) {
4799
- const response = await request(path4, { method: "GET" });
5319
+ async function keptOutNow(path5) {
5320
+ const response = await request(path5, { method: "GET" });
4800
5321
  const body = await readBody(response);
4801
5322
  if (response.status === 404) {
4802
5323
  return false;
@@ -4821,11 +5342,11 @@ async function secrets(positionals, values) {
4821
5342
  base = `/v1/sandboxes/${encodeURIComponent(sandboxId)}/secrets`;
4822
5343
  }
4823
5344
  const [action, ...args] = words2;
4824
- const fileQuery = (path4) => {
4825
- if (!path4) {
5345
+ const fileQuery = (path5) => {
5346
+ if (!path5) {
4826
5347
  throw new Error(`secrets ${action ?? ""} requires <path>`);
4827
5348
  }
4828
- return `${base}/files?path=${encodeURIComponent(path4)}`;
5349
+ return `${base}/files?path=${encodeURIComponent(path5)}`;
4829
5350
  };
4830
5351
  switch (action) {
4831
5352
  case void 0: {
@@ -4844,7 +5365,7 @@ async function secrets(positionals, values) {
4844
5365
  }
4845
5366
  process.stdout.write(
4846
5367
  [...names.map((name) => `variable ${name}${hidden2.includes(name) ? " kept out of the sandbox" : ""}
4847
- `), ...paths.map((path4) => `file ${path4}
5368
+ `), ...paths.map((path5) => `file ${path5}
4848
5369
  `)].join("")
4849
5370
  );
4850
5371
  return;
@@ -4882,11 +5403,11 @@ async function secrets(positionals, values) {
4882
5403
  }
4883
5404
  return [arg.slice(0, at4), arg.slice(at4 + 1)];
4884
5405
  });
4885
- const path4 = (name) => `${base}/variables/${encodeURIComponent(name)}`;
5406
+ const path5 = (name) => `${base}/variables/${encodeURIComponent(name)}`;
4886
5407
  if (hosts === void 0 && !values.plain) {
4887
5408
  const byTemplate = sandboxId === void 0 ? [] : (await call2(`/v1/sandboxes/${encodeURIComponent(sandboxId)}/template`, { method: "GET" }))?.hidden ?? [];
4888
5409
  for (const [name] of pairs) {
4889
- if (await keptOutNow(path4(name))) {
5410
+ if (await keptOutNow(path5(name))) {
4890
5411
  throw new Error(
4891
5412
  `${name} is kept out of the sandbox. Set without --host it would be plain, and its commands would read its value. Give its hosts again with --host to keep it out, or --plain for its commands to read it. Nothing was set.`
4892
5413
  );
@@ -4899,7 +5420,7 @@ async function secrets(positionals, values) {
4899
5420
  }
4900
5421
  }
4901
5422
  for (const [name, value] of pairs) {
4902
- const body = await call2(path4(name), { method: "PUT", body: JSON.stringify(hosts === void 0 ? { value } : { value, hosts }) });
5423
+ const body = await call2(path5(name), { method: "PUT", body: JSON.stringify(hosts === void 0 ? { value } : { value, hosts }) });
4903
5424
  process.stdout.write(
4904
5425
  body.hidden === true ? `set ${name}, kept out of the sandbox: its commands see ${body.standIn}, and its value is sent only to ${body.hosts.join(", ")}
4905
5426
  ` : `set ${name}
@@ -4941,12 +5462,12 @@ async function secrets(positionals, values) {
4941
5462
  return;
4942
5463
  }
4943
5464
  case "put-file": {
4944
- const [path4, local] = args;
4945
- if (!path4 || local === void 0 === (values.text === void 0)) {
5465
+ const [path5, local] = args;
5466
+ if (!path5 || local === void 0 === (values.text === void 0)) {
4946
5467
  throw new Error("secrets put-file requires <path>, and then a local file to read it from or --text with what it holds");
4947
5468
  }
4948
5469
  const text = values.text ?? await readFile(local ?? "", "utf8");
4949
- const body = await call2(`${base}/files`, { method: "PUT", body: JSON.stringify({ path: path4, text }) });
5470
+ const body = await call2(`${base}/files`, { method: "PUT", body: JSON.stringify({ path: path5, text }) });
4950
5471
  process.stdout.write(`put ${body.path}
4951
5472
  `);
4952
5473
  return;
@@ -4981,9 +5502,9 @@ async function metrics(id, asked2) {
4981
5502
  query.set(name, value);
4982
5503
  }
4983
5504
  }
4984
- const path4 = asked2.running ? "/v1/metrics/running" : id === void 0 ? "/v1/metrics" : `/v1/sandboxes/${encodeURIComponent(id)}/metrics`;
5505
+ const path5 = asked2.running ? "/v1/metrics/running" : id === void 0 ? "/v1/metrics" : `/v1/sandboxes/${encodeURIComponent(id)}/metrics`;
4985
5506
  const search = query.toString();
4986
- const response = await request(search === "" ? path4 : `${path4}?${search}`, { method: "GET" });
5507
+ const response = await request(search === "" ? path5 : `${path5}?${search}`, { method: "GET" });
4987
5508
  const body = await readBody(response);
4988
5509
  if (!response.ok) {
4989
5510
  fail(response.status, body);
@@ -5006,11 +5527,11 @@ async function metrics(id, asked2) {
5006
5527
  ` : table3([["AT", ...FIGURE_HEADINGS], ...points.map((point) => [String(point["at"] ?? ""), ...figuresOf(point)])])
5007
5528
  );
5008
5529
  } else {
5009
- const sandboxes = readList(body, "sandboxes");
5530
+ const sandboxes2 = readList(body, "sandboxes");
5010
5531
  process.stdout.write(
5011
- sandboxes.length === 0 ? "No sandboxes.\n" : table3([
5532
+ sandboxes2.length === 0 ? "No sandboxes.\n" : table3([
5012
5533
  ["ID", "NAME", "SIZE", ...FIGURE_HEADINGS],
5013
- ...sandboxes.map((sandbox) => [String(sandbox["sandboxId"] ?? ""), String(sandbox["name"] ?? ""), String(sandbox["size"] ?? ""), ...figuresOf(sandbox["reading"])])
5534
+ ...sandboxes2.map((sandbox) => [String(sandbox["sandboxId"] ?? ""), String(sandbox["name"] ?? ""), String(sandbox["size"] ?? ""), ...figuresOf(sandbox["reading"])])
5014
5535
  ])
5015
5536
  );
5016
5537
  }
@@ -5032,7 +5553,7 @@ async function account2(positionals, out) {
5032
5553
  process.stdout.write(text);
5033
5554
  return;
5034
5555
  }
5035
- writeFileSync3(out, text, { mode: 384 });
5556
+ writeFileSync4(out, text, { mode: 384 });
5036
5557
  process.stdout.write(`Written to ${out}.
5037
5558
  `);
5038
5559
  }
@@ -5111,9 +5632,9 @@ async function ci(positionals, options) {
5111
5632
  if (repo === void 0 || !/^[^/\s]+\/[^/\s]+$/.test(repo)) {
5112
5633
  throw new Error(`ci ${what} needs the repository, as agental ci ${what} acme/app`);
5113
5634
  }
5114
- const path4 = `/v1/runs-on/repositories/${repo.split("/").map(encodeURIComponent).join("/")}`;
5635
+ const path5 = `/v1/runs-on/repositories/${repo.split("/").map(encodeURIComponent).join("/")}`;
5115
5636
  if (what === "reset") {
5116
- const response = await request(path4, { method: "DELETE" });
5637
+ const response = await request(path5, { method: "DELETE" });
5117
5638
  if (!response.ok) {
5118
5639
  fail(response.status, await readBody(response));
5119
5640
  }
@@ -5135,7 +5656,7 @@ async function ci(positionals, options) {
5135
5656
  if (options.template !== void 0) {
5136
5657
  templateId = options.template === "default" ? null : (await templateNamed(options.template)).id;
5137
5658
  }
5138
- const saved = await asked(path4, { method: "PUT", body: JSON.stringify({ poolMax, templateId }) });
5659
+ const saved = await asked(path5, { method: "PUT", body: JSON.stringify({ poolMax, templateId }) });
5139
5660
  if (options.json) {
5140
5661
  process.stdout.write(`${JSON.stringify(saved, null, 2)}
5141
5662
  `);
@@ -5214,8 +5735,8 @@ async function billing(positionals, asJson, limit) {
5214
5735
  const [what, amount, ...rest] = positionals;
5215
5736
  const kinds = ["prices", "invoices", "card", "top-up", "auto-reload"];
5216
5737
  const near = what !== void 0 && !kinds.includes(what) ? nearest(what, kinds) : null;
5217
- const usage = `${near ? `billing has no ${what}: did you mean billing ${near}? ` : ""}billing takes nothing, prices, invoices, card, top-up <dollars>, or auto-reload <dollars | off>`;
5218
- if (rest.length > 0 || what !== "top-up" && what !== "auto-reload" && amount !== void 0) {
5738
+ const usage = `${near ? `billing has no ${what}: did you mean billing ${near}? ` : ""}billing takes nothing, prices, invoices, card, card save, top-up <dollars>, or auto-reload <dollars | off>`;
5739
+ if (rest.length > 0 || what !== "top-up" && what !== "auto-reload" && !(what === "card" && amount === "save") && amount !== void 0) {
5219
5740
  throw new Error(usage);
5220
5741
  }
5221
5742
  if (limit !== void 0 && what !== "invoices") {
@@ -5235,10 +5756,16 @@ async function billing(positionals, asJson, limit) {
5235
5756
  }
5236
5757
  case "prices": {
5237
5758
  const body = await asked("/v1/billing/plans", { method: "GET" });
5238
- print4(body, () => describePrices(body));
5759
+ print4(body, () => isTerminal(process.stdout) ? pricesForPeople(body) : describePrices(body));
5239
5760
  return;
5240
5761
  }
5241
5762
  case "card": {
5763
+ if (amount === void 0) {
5764
+ const body2 = await asked("/v1/billing/card", { method: "GET" });
5765
+ print4(body2, () => body2.card ? `${describeCard(body2.card)}
5766
+ ` : "No card saved. agental billing card save prints the page to save one on, charged nothing.\n");
5767
+ return;
5768
+ }
5242
5769
  const body = await asked("/v1/billing/checkout", { method: "POST", body: JSON.stringify({ card: true }) });
5243
5770
  print4(
5244
5771
  body,
@@ -5300,7 +5827,7 @@ function describeBilling(body, card = null) {
5300
5827
  if (free && body.plan) {
5301
5828
  lines.push(["Plan", "free: nothing a month. What runs is paid from your credits, at list price."]);
5302
5829
  if (!free.cardSaved) {
5303
- lines.push(["Card", "none saved. Save one, charged nothing, to run sandboxes and be given the free plan's credit: agental billing card."]);
5830
+ lines.push(["Card", "none saved. Save one, charged nothing, to run sandboxes and be given the free plan's credit: agental billing card save."]);
5304
5831
  } else if (card) {
5305
5832
  lines.push(["Card", describeCard(card)]);
5306
5833
  }
@@ -5343,13 +5870,13 @@ function describeBilling(body, card = null) {
5343
5870
  if (!body.canRun && body.reason) {
5344
5871
  lines.push([
5345
5872
  "Running",
5346
- body.reason === "out_of_credit" ? `no: ${free ? "your credits are" : "the plan's credits and the top-ups are"} used. agental billing top-up <dollars> buys more.` : body.reason === "billing_required" ? "no: save a card first, charged nothing, with agental billing card." : `no: ${body.reason}`
5873
+ body.reason === "out_of_credit" ? `no: ${free ? "your credits are" : "the plan's credits and the top-ups are"} used. agental billing top-up <dollars> buys more.` : body.reason === "billing_required" ? "no: save a card first, charged nothing, with agental billing card save." : `no: ${body.reason}`
5347
5874
  ]);
5348
5875
  }
5349
5876
  if (body.lapse) {
5350
5877
  lines.push([
5351
5878
  "Deleted on",
5352
- body.lapse.reason === "unpaid" ? `${dayOf(body.lapse.deletesAt)}: your sandboxes and snapshots, as the account owes for what it used past its plan. agental billing top-up <dollars> buys enough to pay it and keep them.` : body.lapse.reason === "out_of_credit" ? `${dayOf(body.lapse.deletesAt)}: your sandboxes and snapshots, as your credits are used. agental billing top-up <dollars> keeps them.` : `${dayOf(body.lapse.deletesAt)}: your sandboxes and snapshots, as the account has no card saved. agental billing card saves one, charged nothing, to keep them.`
5879
+ body.lapse.reason === "unpaid" ? `${dayOf(body.lapse.deletesAt)}: your sandboxes and snapshots, as the account owes for what it used past its plan. agental billing top-up <dollars> buys enough to pay it and keep them.` : body.lapse.reason === "out_of_credit" ? `${dayOf(body.lapse.deletesAt)}: your sandboxes and snapshots, as your credits are used. agental billing top-up <dollars> keeps them.` : `${dayOf(body.lapse.deletesAt)}: your sandboxes and snapshots, as the account has no card saved. agental billing card save saves one, charged nothing, to keep them.`
5353
5880
  ]);
5354
5881
  }
5355
5882
  if (body.testMode) {
@@ -5465,6 +5992,78 @@ function describeAutoReload(autoReload) {
5465
5992
  const adds = topUp && topUp.bonusMicros > 0 ? ` for ${wholeMoney(topUp.micros)} of credits, a bonus of ${topUp.bonusPercent}%,` : "";
5466
5993
  return `${wholeMoney(autoReload.dollars * 1e6)}${adds} charged to your saved card when your credits run out, before anything is stopped. At most 3 times a day.`;
5467
5994
  }
5995
+ function pricesForPeople(body) {
5996
+ const out = [];
5997
+ const count = (value) => value === void 0 || value === null ? "" : value.toLocaleString("en-US");
5998
+ const section = (title, rows, notes) => {
5999
+ const table4 = fitted(rows, { paint: (cell, row) => row === 0 ? faint(cell) : cell }).trimEnd().split("\n");
6000
+ out.push(strong(title), ...table4.map((line) => ` ${line}`), ...notes.map((note) => ` ${faint(note)}`), "");
6001
+ };
6002
+ if (body.tiers?.length) {
6003
+ section(
6004
+ "Plans",
6005
+ [
6006
+ ["", "A MONTH", "CREDITS BACK", "RUN AT ONCE", "START FREE", "SIZES"],
6007
+ ...body.tiers.map((tier) => [
6008
+ (tier.id ? PLAN_NAMES[tier.id] : void 0) ?? (tier.dollarsPerMonth === 0 ? "Free" : `$${tier.dollarsPerMonth.toLocaleString("en-US")}`),
6009
+ wholeMoney(tier.dollarsPerMonth * 1e6),
6010
+ tier.dollarsPerMonth === 0 ? body.free ? `${wholeMoney(body.free.creditMicros)}, once` : "none" : wholeMoney(tier.includedMicros),
6011
+ count(tier.runningUnits ?? tier.sandboxesAtOnce),
6012
+ count(tier.freeBurstUnits),
6013
+ tier.sizes === void 0 ? "" : tier.sizes.length === body.plans.length ? "every size" : tier.sizes.join(", ")
6014
+ ])
6015
+ ],
6016
+ [
6017
+ ...body.free ? [`Free needs a card saved, charged nothing; it runs ${body.free.unpaidUnits} at once until your first top-up.`] : [],
6018
+ ...body.tiers.some((tier) => tier.runningUnits !== void 0) ? ["Counted in small sandboxes: a medium is 2, a large 4, a tiny half."] : []
6019
+ ]
6020
+ );
6021
+ }
6022
+ section(
6023
+ "Sizes",
6024
+ [
6025
+ ["", "VCPU", "MEMORY", "AN HOUR", ...body.storage ? ["STOPPED, AN HOUR"] : []],
6026
+ ...body.plans.map((size) => [
6027
+ size.size,
6028
+ String(size.vcpu),
6029
+ `${size.memoryMb / 1024} GiB`,
6030
+ `$${size.listPriceMicrosPerHour / 1e6}`,
6031
+ ...body.storage ? [size.stoppedMicrosPerHour === void 0 ? "" : `$${size.stoppedMicrosPerHour / 1e6}`] : []
6032
+ ])
6033
+ ],
6034
+ [`Charged by the second.${body.storage ? ` Stopped, a sandbox costs ${body.storage.stoppedPercent}% while its disk is kept.` : ""}`]
6035
+ );
6036
+ if (body.topUps?.length) {
6037
+ const range = body.topUpRange;
6038
+ section(
6039
+ "Top-ups",
6040
+ [
6041
+ ["PAY", "GET", ""],
6042
+ ...body.topUps.map((topUp) => [
6043
+ wholeMoney(topUp.dollars * 1e6),
6044
+ wholeMoney(topUp.micros ?? topUp.dollars * 1e6),
6045
+ topUp.bonusPercent ? good(`+${topUp.bonusPercent}%`) : ""
6046
+ ])
6047
+ ],
6048
+ [
6049
+ `${range ? `Any whole amount from ${wholeMoney(range.minDollars * 1e6)} to ${wholeMoney(range.maxDollars * 1e6)}. ` : ""}${body.topUpBonus ? `A bonus from ${wholeMoney(body.topUpBonus.fromDollars * 1e6)}. ` : ""}They never expire.`
6050
+ ]
6051
+ );
6052
+ }
6053
+ const also = [];
6054
+ if (body.burstFee) {
6055
+ also.push(["Bursts", `$0.027 a small started past your free starts, at most ${wholeMoney(body.burstFee.defaultBudgetMicros)} a month unless you set a budget`]);
6056
+ }
6057
+ if (body.storage) {
6058
+ also.push(["Snapshots", `the ${body.storage.freeSnapshots} oldest free, then $${(body.storage.snapshotMicrosPerHour * 730 / 1e6).toFixed(2)} a month each`]);
6059
+ }
6060
+ if (also.length > 0) {
6061
+ out.push(strong("Also"), ...fitted(also).trimEnd().split("\n").map((line) => ` ${line}`), "");
6062
+ }
6063
+ out.push(faint("agental billing top-up <dollars> \xB7 agental headroom budget <dollars> \xB7 https://agental.io/pricing"));
6064
+ return `${out.join("\n")}
6065
+ `;
6066
+ }
5468
6067
  function describePrices(body) {
5469
6068
  const out = [];
5470
6069
  if (body.tiers?.length) {
@@ -5621,8 +6220,8 @@ function duration(ms) {
5621
6220
  const minutes = Math.round(ms / 6e4);
5622
6221
  return minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h${minutes % 60 === 0 ? "" : ` ${minutes % 60} min`}`;
5623
6222
  }
5624
- async function asked(path4, init) {
5625
- const response = await request(path4, init);
6223
+ async function asked(path5, init) {
6224
+ const response = await request(path5, init);
5626
6225
  const body = await readBody(response);
5627
6226
  if (!response.ok) {
5628
6227
  fail(response.status, body);
@@ -5700,6 +6299,64 @@ function table3(rows) {
5700
6299
  return rows.map((row) => `${row.map((cell, column) => cell.padEnd(widths[column] ?? 0, " ")).join(" ").trimEnd()}
5701
6300
  `).join("");
5702
6301
  }
6302
+ var ACTIVE = /* @__PURE__ */ new Set(["running", "starting", "stopping", "restoring", "creating"]);
6303
+ function sandboxesForPeople(sandboxes2, names, sorted) {
6304
+ const text = (value) => typeof value === "string" ? value : "";
6305
+ const changed = (sandbox) => Date.parse(text(sandbox["stoppedAt"]) || text(sandbox["updatedAt"]) || text(sandbox["createdAt"])) || 0;
6306
+ const shown = sorted ? sandboxes2 : [...sandboxes2].sort((a, b) => Number(ACTIVE.has(text(b["status"]))) - Number(ACTIVE.has(text(a["status"]))) || changed(b) - changed(a));
6307
+ const outbound = (sandbox) => {
6308
+ const rule = sandbox["network"];
6309
+ return rule && typeof rule === "object" ? text(rule["outbound"]) : "";
6310
+ };
6311
+ const differs = (read2) => new Set(shown.map(read2)).size > 1;
6312
+ const showVm = differs((sandbox) => String(sandbox["vmIsolation"] === true));
6313
+ const showOutbound = differs(outbound);
6314
+ const showTags = shown.some((sandbox) => Array.isArray(sandbox["tags"]) && sandbox["tags"].length > 0);
6315
+ const status = (sandbox) => {
6316
+ const word = text(sandbox["status"]) || "unknown";
6317
+ const stops = word === "running" ? until(text(sandbox["autoStopAt"])) : null;
6318
+ const stopped = word === "stopped" ? ago(text(sandbox["stoppedAt"])) : null;
6319
+ return stops ? `running, stops ${stops}` : stopped ? `stopped ${stopped}` : word;
6320
+ };
6321
+ const rows = [
6322
+ ["", "ID", "NAME", "SIZE", "TEMPLATE", "STATUS", ...showVm ? ["VM"] : [], ...showOutbound ? ["OUTBOUND"] : [], ...showTags ? ["TAGS"] : []],
6323
+ ...shown.map((sandbox) => {
6324
+ const templateId = text(sandbox["templateId"]);
6325
+ return [
6326
+ ACTIVE.has(text(sandbox["status"])) ? "\u25CF" : "\u25CB",
6327
+ text(sandbox["id"]),
6328
+ text(sandbox["name"]),
6329
+ text(sandbox["size"]),
6330
+ templateId ? names.get(templateId) ?? templateId : "-",
6331
+ status(sandbox),
6332
+ ...showVm ? [sandbox["vmIsolation"] === true ? "yes" : "no"] : [],
6333
+ ...showOutbound ? [outbound(sandbox)] : [],
6334
+ ...showTags ? [Array.isArray(sandbox["tags"]) ? sandbox["tags"].join(",") : ""] : []
6335
+ ];
6336
+ })
6337
+ ];
6338
+ const body = fitted(rows, {
6339
+ give: 2,
6340
+ paint: (cell, row, column) => {
6341
+ if (row === 0) {
6342
+ return faint(cell);
6343
+ }
6344
+ const active = ACTIVE.has(text(shown[row - 1]?.["status"]));
6345
+ if (column === 0 || column === 5) {
6346
+ return active ? good(cell) : faint(cell);
6347
+ }
6348
+ return column === 2 && active ? strong(cell) : cell;
6349
+ }
6350
+ });
6351
+ const byStatus = /* @__PURE__ */ new Map();
6352
+ for (const sandbox of shown) {
6353
+ byStatus.set(text(sandbox["status"]) || "unknown", (byStatus.get(text(sandbox["status"]) || "unknown") ?? 0) + 1);
6354
+ }
6355
+ const counts = `${[...byStatus].sort(([a], [b]) => Number(ACTIVE.has(b)) - Number(ACTIVE.has(a))).map(([word, count]) => `${count} ${word}`).join(", ")}.`;
6356
+ return `${body}
6357
+ ${counts} ${faint("--wide for every column, --json for scripts")}
6358
+ `;
6359
+ }
5703
6360
  function boxNamed(value) {
5704
6361
  if (value !== void 0 && value.trim() === "") {
5705
6362
  throw new Error("--box takes the id or the name of a box");
@@ -5806,6 +6463,7 @@ Setting up
5806
6463
  agental logout
5807
6464
  agental whoami [--json]
5808
6465
  agental --version
6466
+ agental completion zsh|bash|fish
5809
6467
 
5810
6468
  Usage
5811
6469
  agental create --name <name> [--template <template>] [--size tiny|small|medium|large] [--region <region>[,<region>...]] [--ttl <time> | --ttl default] [--idempotency-key <key>]
@@ -5888,7 +6546,7 @@ Usage
5888
6546
  agental key show <key> [--json]
5889
6547
  agental key allow-from <key> (<address-or-range>... | --anywhere) [--json]
5890
6548
  agental key delete <key>
5891
- agental billing [prices | card | top-up <dollars> | auto-reload <dollars | off>] [--json]
6549
+ agental billing [prices | card [save] | top-up <dollars> | auto-reload <dollars | off>] [--json]
5892
6550
  agental billing invoices [--limit <n>] [--json]
5893
6551
  agental headroom [--from <day or date-time>] [--to <day or date-time>] [--step 10m|hour|day] [--json]
5894
6552
  agental headroom budget <dollars> | budget default [--json]
@@ -5928,6 +6586,9 @@ in a terminal it offers to open your newest running sandbox instead, and otherwi
5928
6586
  login signs in through the browser: the page asks you to allow this computer, and the command is
5929
6587
  given an API key of its own, named CLI on <this computer>, which is in the console under API keys.
5930
6588
  --key reads a key from standard input instead, for a computer with no browser.
6589
+ completion prints a script that completes agental's commands, flags, sandboxes and templates
6590
+ when Tab is pressed: source <(agental completion zsh) in ~/.zshrc, source <(agental completion
6591
+ bash) in ~/.bashrc, or agental completion fish | source in ~/.config/fish/config.fish.
5931
6592
  The key is kept in ~/.config/agental/credentials.json, readable by you alone. logout deletes the
5932
6593
  key from your account and that file. whoami says who the command is signed in as, and with which
5933
6594
  key. AGENTAL_API_KEY, when it is set, is used in place of what is kept.