agental 0.13.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 +402 -99
  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.13.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) {
@@ -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
  }
@@ -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
  }
@@ -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";
@@ -1733,6 +1739,11 @@ var COMMANDS = [
1733
1739
  { name: "logout", summary: "Delete this computer's key from your account and from here." },
1734
1740
  { name: "whoami", summary: "Who the command is signed in as, and with which key." },
1735
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
+ },
1736
1747
  {
1737
1748
  name: "sandbox",
1738
1749
  summary: "Your sandboxes, as agental sandbox <verb>: each is the same as the command without sandbox in front.",
@@ -1826,7 +1837,13 @@ var MAP = [
1826
1837
  ["account", "everything agental keeps about you"]
1827
1838
  ]
1828
1839
  ],
1829
- ["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
+ ]
1830
1847
  ];
1831
1848
  var DOCS = "https://agental.io/docs/cli";
1832
1849
  function shortHelp() {
@@ -2042,6 +2059,252 @@ function sandboxIn(words2, valued = []) {
2042
2059
  return { sandbox: void 0, others: words2 };
2043
2060
  }
2044
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
+
2045
2308
  // ../src/cli-table.ts
2046
2309
  var plain2 = (text) => text.replace(/\x1b\[[0-9;]*m/g, "");
2047
2310
  function windowWidth() {
@@ -2480,12 +2743,12 @@ async function schedule(client, positionals, options) {
2480
2743
  throw new Error(USAGE3);
2481
2744
  }
2482
2745
  const id = await idOf2(client, sandboxId, target, what);
2483
- const path4 = `${base}/${encodeURIComponent(id)}`;
2746
+ const path5 = `${base}/${encodeURIComponent(id)}`;
2484
2747
  if (what === "show") {
2485
- print3(await ask5(client, "GET", path4), options.json);
2748
+ print3(await ask5(client, "GET", path5), options.json);
2486
2749
  } else if (what === "runs") {
2487
2750
  const limit = options.limit === void 0 ? "" : `?limit=${encodeURIComponent(options.limit)}`;
2488
- const runs = (await ask5(client, "GET", `${path4}/runs${limit}`))?.runs ?? [];
2751
+ const runs = (await ask5(client, "GET", `${path5}/runs${limit}`))?.runs ?? [];
2489
2752
  if (options.json) {
2490
2753
  process.stdout.write(`${JSON.stringify(runs, null, 2)}
2491
2754
  `);
@@ -2507,7 +2770,7 @@ async function schedule(client, positionals, options) {
2507
2770
  );
2508
2771
  }
2509
2772
  } else if (what === "run") {
2510
- const run2 = await ask5(client, "POST", `${path4}/run`);
2773
+ const run2 = await ask5(client, "POST", `${path5}/run`);
2511
2774
  if (options.json) {
2512
2775
  process.stdout.write(`${JSON.stringify(run2, null, 2)}
2513
2776
  `);
@@ -2517,9 +2780,9 @@ async function schedule(client, positionals, options) {
2517
2780
  `);
2518
2781
  }
2519
2782
  } else if (what === "pause" || what === "resume") {
2520
- print3(await ask5(client, "PATCH", path4, { enabled: what === "resume" }), options.json);
2783
+ print3(await ask5(client, "PATCH", path5, { enabled: what === "resume" }), options.json);
2521
2784
  } else if (what === "delete") {
2522
- await ask5(client, "DELETE", path4);
2785
+ await ask5(client, "DELETE", path5);
2523
2786
  process.stdout.write(`Deleted ${id}, with its runs.
2524
2787
  `);
2525
2788
  } else {
@@ -2527,7 +2790,7 @@ async function schedule(client, positionals, options) {
2527
2790
  if (Object.keys(changes).length === 0) {
2528
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 --.");
2529
2792
  }
2530
- print3(await ask5(client, "PATCH", path4, changes), options.json);
2793
+ print3(await ask5(client, "PATCH", path5, changes), options.json);
2531
2794
  }
2532
2795
  return;
2533
2796
  }
@@ -3005,7 +3268,7 @@ function needId2(id, what) {
3005
3268
  }
3006
3269
 
3007
3270
  // ../src/cli-shell.ts
3008
- import { createHash as createHash2, randomBytes as randomBytes4 } from "node:crypto";
3271
+ import { createHash as createHash3, randomBytes as randomBytes4 } from "node:crypto";
3009
3272
  var TERMINAL_PROTOCOL = "agental.terminal.v1";
3010
3273
  var TICKET_PROTOCOL_PREFIX = "ticket.";
3011
3274
  var VERIFIER_PROTOCOL_PREFIX = "verifier.";
@@ -3017,15 +3280,15 @@ function clamp(value, fallback) {
3017
3280
  function sizeOf(stdout) {
3018
3281
  return stdout.isTTY ? { cols: clamp(stdout.columns, 80), rows: clamp(stdout.rows, 24) } : { cols: 80, rows: 24 };
3019
3282
  }
3020
- function webSocketUrl(base, path4) {
3021
- 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)) {
3022
3285
  throw new Error("The API gave the terminal a path that is not one on its own address.");
3023
3286
  }
3024
3287
  const url = new URL(base);
3025
3288
  if (url.protocol !== "https:" && url.protocol !== "http:") {
3026
3289
  throw new Error(`A terminal is opened on an http: or https: API, not ${url.protocol}`);
3027
3290
  }
3028
- 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}`;
3029
3292
  }
3030
3293
  function whyClosed(code, reason, error) {
3031
3294
  const said = error?.message || reason;
@@ -3053,7 +3316,7 @@ async function shell(client, id, streams = process) {
3053
3316
  const { stdin, stdout, stderr } = streams;
3054
3317
  const size = sizeOf(stdout);
3055
3318
  const verifier = randomBytes4(32).toString("base64url");
3056
- const challenge = createHash2("sha256").update(verifier).digest("base64url");
3319
+ const challenge = createHash3("sha256").update(verifier).digest("base64url");
3057
3320
  const response = await client.request(`/v1/sandboxes/${encodeURIComponent(id)}/terminal`, { method: "POST", body: JSON.stringify({ ...size, challenge }) });
3058
3321
  const body = await response.json().catch(() => null);
3059
3322
  if (!response.ok || typeof body?.ticket !== "string") {
@@ -3444,7 +3707,43 @@ async function helpAsked(args) {
3444
3707
  process.stdout.write(one);
3445
3708
  return true;
3446
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
+ }
3447
3743
  async function main() {
3744
+ if (await completionAsked(process.argv.slice(2))) {
3745
+ return;
3746
+ }
3448
3747
  if (await helpAsked(process.argv.slice(2))) {
3449
3748
  return;
3450
3749
  }
@@ -3859,17 +4158,17 @@ async function sshKeys(id, keyId, remove3, json) {
3859
4158
  if (!id) {
3860
4159
  throw new Error("ssh-keys requires <sandbox-id>");
3861
4160
  }
3862
- const path4 = `/v1/sandboxes/${encodeURIComponent(id)}/ssh/keys`;
4161
+ const path5 = `/v1/sandboxes/${encodeURIComponent(id)}/ssh/keys`;
3863
4162
  if (remove3) {
3864
4163
  if (!keyId) {
3865
4164
  throw new Error("ssh-keys --remove requires <key-id>, as ssh-keys lists it");
3866
4165
  }
3867
- await call2(`${path4}/${encodeURIComponent(keyId)}`, { method: "DELETE" });
4166
+ await call2(`${path5}/${encodeURIComponent(keyId)}`, { method: "DELETE" });
3868
4167
  process.stdout.write(`${keyId} may log in to ${id} no longer.
3869
4168
  `);
3870
4169
  return;
3871
4170
  }
3872
- const body = await call2(path4, { method: "GET" });
4171
+ const body = await call2(path5, { method: "GET" });
3873
4172
  const keys = body?.keys ?? [];
3874
4173
  if (json) {
3875
4174
  process.stdout.write(`${JSON.stringify(keys, null, 2)}
@@ -3883,10 +4182,10 @@ function publicKeysFrom(given) {
3883
4182
  if (SSH_PUBLIC_KEY.test(each.trim())) {
3884
4183
  return [each.trim()];
3885
4184
  }
3886
- const file = each.startsWith("~/") ? `${os5.homedir()}${each.slice(1)}` : each;
4185
+ const file = each.startsWith("~/") ? `${os6.homedir()}${each.slice(1)}` : each;
3887
4186
  let text;
3888
4187
  try {
3889
- text = readFileSync3(file, "utf8");
4188
+ text = readFileSync4(file, "utf8");
3890
4189
  } catch {
3891
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.`);
3892
4191
  }
@@ -3938,7 +4237,7 @@ async function regions(asJson) {
3938
4237
  process.stdout.write("* where a sandbox is made when no region is named\n");
3939
4238
  }
3940
4239
  async function list2(asJson, filter, sort, limit, wide = false) {
3941
- const sandboxes = [];
4240
+ const sandboxes2 = [];
3942
4241
  let cursor = null;
3943
4242
  do {
3944
4243
  const query = new URLSearchParams(filter);
@@ -3954,7 +4253,7 @@ async function list2(asJson, filter, sort, limit, wide = false) {
3954
4253
  if (!response.ok) {
3955
4254
  fail(response.status, body);
3956
4255
  }
3957
- sandboxes.push(...readSandboxes(body));
4256
+ sandboxes2.push(...readSandboxes(body));
3958
4257
  const next = body && typeof body === "object" ? body["nextCursor"] : null;
3959
4258
  cursor = typeof next === "string" ? next : null;
3960
4259
  if (limit !== void 0 && cursor !== null) {
@@ -3964,24 +4263,24 @@ async function list2(asJson, filter, sort, limit, wide = false) {
3964
4263
  }
3965
4264
  } while (cursor !== null);
3966
4265
  if (asJson) {
3967
- process.stdout.write(`${JSON.stringify(sandboxes, null, 2)}
4266
+ process.stdout.write(`${JSON.stringify(sandboxes2, null, 2)}
3968
4267
  `);
3969
4268
  return;
3970
4269
  }
3971
- if (sandboxes.length === 0) {
4270
+ if (sandboxes2.length === 0) {
3972
4271
  process.stdout.write(filter.size > 0 ? "No sandboxes match.\n" : "No sandboxes.\n");
3973
4272
  return;
3974
4273
  }
3975
- const names = sandboxes.some((sandbox) => typeof sandbox["templateId"] === "string") ? await templateNames() : /* @__PURE__ */ new Map();
4274
+ const names = sandboxes2.some((sandbox) => typeof sandbox["templateId"] === "string") ? await templateNames() : /* @__PURE__ */ new Map();
3976
4275
  if (isTerminal(process.stdout) && !wide) {
3977
- process.stdout.write(sandboxesForPeople(sandboxes, names, sort !== void 0));
4276
+ process.stdout.write(sandboxesForPeople(sandboxes2, names, sort !== void 0));
3978
4277
  return;
3979
4278
  }
3980
- const tagged = sandboxes.some((sandbox) => Array.isArray(sandbox["tags"]));
4279
+ const tagged = sandboxes2.some((sandbox) => Array.isArray(sandbox["tags"]));
3981
4280
  const header = [...["ID", "NAME", "SIZE", "STATUS"].map(pad2), "VM ", pad2("TEMPLATE"), tagged ? pad2("OUTBOUND") : "OUTBOUND", ...tagged ? ["TAGS"] : []].join(" ");
3982
4281
  process.stdout.write(`${header}
3983
4282
  `);
3984
- for (const sandbox of sandboxes) {
4283
+ for (const sandbox of sandboxes2) {
3985
4284
  const rule = sandbox["network"];
3986
4285
  const templateId = typeof sandbox["templateId"] === "string" ? sandbox["templateId"] : null;
3987
4286
  const row = [
@@ -4128,11 +4427,11 @@ async function bulk(action, filter, options, yes2, asJson, confirm) {
4128
4427
  }
4129
4428
  async function jobs(positionals, asJson) {
4130
4429
  const [verb, id] = positionals;
4131
- 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;
4132
- 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) {
4133
4432
  throw new Error("jobs takes list, show <job-id> or cancel <job-id>");
4134
4433
  }
4135
- const response = await request(path4, { method: verb === "cancel" ? "POST" : "GET" });
4434
+ const response = await request(path5, { method: verb === "cancel" ? "POST" : "GET" });
4136
4435
  const body = await readBody(response);
4137
4436
  if (!response.ok) {
4138
4437
  fail(response.status, body);
@@ -4359,18 +4658,18 @@ async function autoStop(id, inText, at4, never, asJson) {
4359
4658
  if ([inText !== void 0, at4 !== void 0, never].filter(Boolean).length > 1) {
4360
4659
  throw new Error("--in, --at and --never say different things: give one.");
4361
4660
  }
4362
- const path4 = `/v1/sandboxes/${encodeURIComponent(id)}/auto-stop`;
4661
+ const path5 = `/v1/sandboxes/${encodeURIComponent(id)}/auto-stop`;
4363
4662
  let body;
4364
4663
  if (never) {
4365
- body = await call2(path4, { method: "DELETE" });
4664
+ body = await call2(path5, { method: "DELETE" });
4366
4665
  } else if (inText === void 0 && at4 === void 0) {
4367
- body = await call2(path4, { method: "GET" });
4666
+ body = await call2(path5, { method: "GET" });
4368
4667
  } else {
4369
4668
  const inSeconds = inText === void 0 ? void 0 : seconds(inText);
4370
4669
  if (inSeconds === null) {
4371
4670
  throw new Error("--in is a time from now, such as 30m, 2h or 1d");
4372
4671
  }
4373
- 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 }) });
4374
4673
  }
4375
4674
  if (asJson) {
4376
4675
  process.stdout.write(`${JSON.stringify(body, null, 2)}
@@ -4426,7 +4725,7 @@ async function screenshot(id, file, options) {
4426
4725
  fail(response.status, await readBody(response));
4427
4726
  }
4428
4727
  const picture = Buffer.from(await response.arrayBuffer());
4429
- writeFileSync3(file, picture);
4728
+ writeFileSync4(file, picture);
4430
4729
  const size = pictureSize(picture);
4431
4730
  process.stderr.write(`A picture of the screen of ${id} is in ${file}: ${size ? `${size.width} by ${size.height}, ` : ""}${picture.length} bytes.
4432
4731
  `);
@@ -4461,7 +4760,7 @@ async function clipboard(id, text) {
4461
4760
  process.stdout.write(String(body.text ?? ""));
4462
4761
  return;
4463
4762
  }
4464
- const given = text === "-" ? readFileSync3(0, "utf8") : text;
4763
+ const given = text === "-" ? readFileSync4(0, "utf8") : text;
4465
4764
  const response = await request(at4, { method: "PUT", body: JSON.stringify({ text: given }) });
4466
4765
  if (!response.ok) {
4467
4766
  fail(response.status, await readBody(response));
@@ -4609,10 +4908,10 @@ async function labels(what, holder, positionals, asJson) {
4609
4908
  throw new Error(`${command2} requires <${holder}>: ${usage}`);
4610
4909
  }
4611
4910
  const id = holder === "template" ? (await templateNamed(named)).id : named;
4612
- const path4 = `/v1/${holder === "template" ? "templates" : "sandboxes"}/${encodeURIComponent(id)}`;
4911
+ const path5 = `/v1/${holder === "template" ? "templates" : "sandboxes"}/${encodeURIComponent(id)}`;
4613
4912
  let body;
4614
4913
  if (action === void 0) {
4615
- body = await call2(path4, { method: "GET" });
4914
+ body = await call2(path5, { method: "GET" });
4616
4915
  } else if (what === "tags" && (action === "add" || action === "rm")) {
4617
4916
  const tags = listedIn(words2).map((tag) => tag.toLowerCase());
4618
4917
  if (tags.length === 0) {
@@ -4623,14 +4922,14 @@ async function labels(what, holder, positionals, asJson) {
4623
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)}.`);
4624
4923
  }
4625
4924
  for (const tag of tags) {
4626
- 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" });
4627
4926
  }
4628
4927
  } else if (what === "meta" && (action === "set" || action === "unset")) {
4629
4928
  if (words2.length === 0) {
4630
4929
  throw new Error(`${command2} ${action} requires ${action === "set" ? "<key>=<value>" : "<key>"}...`);
4631
4930
  }
4632
4931
  const metadata = action === "set" ? metadataGiven(words2) : Object.fromEntries(words2.map((key2) => [key2, null]));
4633
- body = await call2(path4, { method: "PATCH", body: JSON.stringify({ metadata }) });
4932
+ body = await call2(path5, { method: "PATCH", body: JSON.stringify({ metadata }) });
4634
4933
  } else {
4635
4934
  throw new Error(`${command2} takes ${usage}`);
4636
4935
  }
@@ -4657,9 +4956,9 @@ async function network(positionals, values) {
4657
4956
  if (values.allow !== void 0 && values.none) {
4658
4957
  throw new Error("--allow and --none say two things: give one.");
4659
4958
  }
4660
- const path4 = `/v1/sandboxes/${encodeURIComponent(id)}/network`;
4959
+ const path5 = `/v1/sandboxes/${encodeURIComponent(id)}/network`;
4661
4960
  const allow = values.none ? [] : values.allow === void 0 ? void 0 : listedIn(values.allow);
4662
- 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 }) });
4663
4962
  if (values.json) {
4664
4963
  process.stdout.write(`${JSON.stringify(body, null, 2)}
4665
4964
  `);
@@ -4735,9 +5034,9 @@ async function egress(positionals, values) {
4735
5034
  `);
4736
5035
  return;
4737
5036
  }
4738
- const path4 = `/v1/sandboxes/${encodeURIComponent(first)}/egress`;
5037
+ const path5 = `/v1/sandboxes/${encodeURIComponent(first)}/egress`;
4739
5038
  const how = `egress takes <sandbox-id>, and then nothing, box, or residential <country> [sticky|rotating], as agental egress ${first} residential de.`;
4740
- 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)) });
4741
5040
  print4(body, `${first}: ${egressInWords(body)}
4742
5041
  `);
4743
5042
  }
@@ -4875,7 +5174,7 @@ async function template(positionals, values) {
4875
5174
  }
4876
5175
  case "start": {
4877
5176
  const found = await templateNamed(need(first, "<template>"));
4878
- const path4 = `/v1/templates/${encodeURIComponent(found.id)}/start`;
5177
+ const path5 = `/v1/templates/${encodeURIComponent(found.id)}/start`;
4879
5178
  if (values.snapshot !== void 0 && values["new-machine"]) {
4880
5179
  throw new Error("--snapshot and --new-machine say two things: give one.");
4881
5180
  }
@@ -4885,12 +5184,12 @@ async function template(positionals, values) {
4885
5184
  const ttlSeconds = ttlOption(values.ttl);
4886
5185
  let start;
4887
5186
  if (values.size === void 0 && values.snapshot === void 0 && !values["new-machine"] && ttlSeconds === void 0) {
4888
- start = await call2(path4, { method: "GET" });
5187
+ start = await call2(path5, { method: "GET" });
4889
5188
  } else {
4890
- const current = await call2(path4, { method: "GET" });
5189
+ const current = await call2(path5, { method: "GET" });
4891
5190
  const snapshotId = values["new-machine"] ? null : values.snapshot ?? current?.snapshotId ?? null;
4892
5191
  const ttl = ttlSeconds === void 0 ? current?.ttlSeconds ?? null : ttlSeconds;
4893
- 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 }) });
4894
5193
  }
4895
5194
  print4(start, `start: ${startInWords(start)}
4896
5195
  `);
@@ -4898,11 +5197,11 @@ async function template(positionals, values) {
4898
5197
  }
4899
5198
  case "network": {
4900
5199
  const found = await templateNamed(need(first, "<template>"));
4901
- const path4 = `/v1/templates/${encodeURIComponent(found.id)}/network`;
5200
+ const path5 = `/v1/templates/${encodeURIComponent(found.id)}/network`;
4902
5201
  const [mode, ...addresses] = rest;
4903
5202
  let rule;
4904
5203
  if (mode === void 0) {
4905
- rule = await call2(path4, { method: "GET" });
5204
+ rule = await call2(path5, { method: "GET" });
4906
5205
  } else {
4907
5206
  if (!OUTBOUND_MODES.some((known) => known === mode)) {
4908
5207
  throw new Error("template network requires <template>, and then nothing, open, blocked, or allowlist <address>...");
@@ -4914,7 +5213,7 @@ async function template(positionals, values) {
4914
5213
  if (mode === "allowlist" && listed.length === 0) {
4915
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`);
4916
5215
  }
4917
- 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 }) });
4918
5217
  }
4919
5218
  print4(
4920
5219
  rule,
@@ -4925,37 +5224,37 @@ ${mode === void 0 ? "" : "A sandbox on it takes this when it next starts, or now
4925
5224
  }
4926
5225
  case "egress": {
4927
5226
  const found = await templateNamed(need(first, "<template>"));
4928
- const path4 = `/v1/templates/${encodeURIComponent(found.id)}/egress`;
5227
+ const path5 = `/v1/templates/${encodeURIComponent(found.id)}/egress`;
4929
5228
  const how = `template egress takes <template>, and then nothing, box, or residential <country> [sticky|rotating], as agental template egress ${first ?? ""} residential de.`;
4930
- 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)) });
4931
5230
  print4(set, `${found.name}: ${egressInWords(set)}${rest.length === 0 ? "" : ", for sandboxes made from it from now on"}
4932
5231
  `);
4933
5232
  return;
4934
5233
  }
4935
5234
  case "ssh": {
4936
5235
  const found = await templateNamed(need(first, "<template>"));
4937
- const path4 = `/v1/templates/${encodeURIComponent(found.id)}/ssh`;
5236
+ const path5 = `/v1/templates/${encodeURIComponent(found.id)}/ssh`;
4938
5237
  const [turn] = rest;
4939
5238
  if (turn !== void 0 && turn !== "on" && turn !== "off") {
4940
5239
  throw new Error("template ssh requires <template>, and then nothing, on or off");
4941
5240
  }
4942
- 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" });
4943
5242
  print4(ssh2, `${found.name}: SSH ${templateSshInWords(ssh2)}
4944
5243
  `);
4945
5244
  return;
4946
5245
  }
4947
5246
  case "ssh-keys": {
4948
5247
  const found = await templateNamed(need(first, "<template>"));
4949
- const path4 = `/v1/templates/${encodeURIComponent(found.id)}/ssh/keys`;
5248
+ const path5 = `/v1/templates/${encodeURIComponent(found.id)}/ssh/keys`;
4950
5249
  if (values.remove) {
4951
5250
  const keyId = need(rest[0], "<template> --remove <key-id>");
4952
- await call2(`${path4}/${encodeURIComponent(keyId)}`, { method: "DELETE" });
5251
+ await call2(`${path5}/${encodeURIComponent(keyId)}`, { method: "DELETE" });
4953
5252
  process.stdout.write(`${keyId} is let in to no sandbox made from ${found.name} from now on. The sandboxes made already keep it.
4954
5253
  `);
4955
5254
  return;
4956
5255
  }
4957
5256
  for (const publicKey2 of publicKeysFrom(rest)) {
4958
- await call2(path4, { method: "POST", body: JSON.stringify({ publicKey: publicKey2 }) });
5257
+ await call2(path5, { method: "POST", body: JSON.stringify({ publicKey: publicKey2 }) });
4959
5258
  }
4960
5259
  const ssh2 = await call2(`/v1/templates/${encodeURIComponent(found.id)}/ssh`, { method: "GET" });
4961
5260
  if (values.json) {
@@ -5017,8 +5316,8 @@ up to date: ${body["upToDate"] === true ? "yes" : "no: it takes the template whe
5017
5316
  function keptOutInWords(variable) {
5018
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");
5019
5318
  }
5020
- async function keptOutNow(path4) {
5021
- const response = await request(path4, { method: "GET" });
5319
+ async function keptOutNow(path5) {
5320
+ const response = await request(path5, { method: "GET" });
5022
5321
  const body = await readBody(response);
5023
5322
  if (response.status === 404) {
5024
5323
  return false;
@@ -5043,11 +5342,11 @@ async function secrets(positionals, values) {
5043
5342
  base = `/v1/sandboxes/${encodeURIComponent(sandboxId)}/secrets`;
5044
5343
  }
5045
5344
  const [action, ...args] = words2;
5046
- const fileQuery = (path4) => {
5047
- if (!path4) {
5345
+ const fileQuery = (path5) => {
5346
+ if (!path5) {
5048
5347
  throw new Error(`secrets ${action ?? ""} requires <path>`);
5049
5348
  }
5050
- return `${base}/files?path=${encodeURIComponent(path4)}`;
5349
+ return `${base}/files?path=${encodeURIComponent(path5)}`;
5051
5350
  };
5052
5351
  switch (action) {
5053
5352
  case void 0: {
@@ -5066,7 +5365,7 @@ async function secrets(positionals, values) {
5066
5365
  }
5067
5366
  process.stdout.write(
5068
5367
  [...names.map((name) => `variable ${name}${hidden2.includes(name) ? " kept out of the sandbox" : ""}
5069
- `), ...paths.map((path4) => `file ${path4}
5368
+ `), ...paths.map((path5) => `file ${path5}
5070
5369
  `)].join("")
5071
5370
  );
5072
5371
  return;
@@ -5104,11 +5403,11 @@ async function secrets(positionals, values) {
5104
5403
  }
5105
5404
  return [arg.slice(0, at4), arg.slice(at4 + 1)];
5106
5405
  });
5107
- const path4 = (name) => `${base}/variables/${encodeURIComponent(name)}`;
5406
+ const path5 = (name) => `${base}/variables/${encodeURIComponent(name)}`;
5108
5407
  if (hosts === void 0 && !values.plain) {
5109
5408
  const byTemplate = sandboxId === void 0 ? [] : (await call2(`/v1/sandboxes/${encodeURIComponent(sandboxId)}/template`, { method: "GET" }))?.hidden ?? [];
5110
5409
  for (const [name] of pairs) {
5111
- if (await keptOutNow(path4(name))) {
5410
+ if (await keptOutNow(path5(name))) {
5112
5411
  throw new Error(
5113
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.`
5114
5413
  );
@@ -5121,7 +5420,7 @@ async function secrets(positionals, values) {
5121
5420
  }
5122
5421
  }
5123
5422
  for (const [name, value] of pairs) {
5124
- 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 }) });
5125
5424
  process.stdout.write(
5126
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(", ")}
5127
5426
  ` : `set ${name}
@@ -5163,12 +5462,12 @@ async function secrets(positionals, values) {
5163
5462
  return;
5164
5463
  }
5165
5464
  case "put-file": {
5166
- const [path4, local] = args;
5167
- if (!path4 || local === void 0 === (values.text === void 0)) {
5465
+ const [path5, local] = args;
5466
+ if (!path5 || local === void 0 === (values.text === void 0)) {
5168
5467
  throw new Error("secrets put-file requires <path>, and then a local file to read it from or --text with what it holds");
5169
5468
  }
5170
5469
  const text = values.text ?? await readFile(local ?? "", "utf8");
5171
- 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 }) });
5172
5471
  process.stdout.write(`put ${body.path}
5173
5472
  `);
5174
5473
  return;
@@ -5203,9 +5502,9 @@ async function metrics(id, asked2) {
5203
5502
  query.set(name, value);
5204
5503
  }
5205
5504
  }
5206
- 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`;
5207
5506
  const search = query.toString();
5208
- const response = await request(search === "" ? path4 : `${path4}?${search}`, { method: "GET" });
5507
+ const response = await request(search === "" ? path5 : `${path5}?${search}`, { method: "GET" });
5209
5508
  const body = await readBody(response);
5210
5509
  if (!response.ok) {
5211
5510
  fail(response.status, body);
@@ -5228,11 +5527,11 @@ async function metrics(id, asked2) {
5228
5527
  ` : table3([["AT", ...FIGURE_HEADINGS], ...points.map((point) => [String(point["at"] ?? ""), ...figuresOf(point)])])
5229
5528
  );
5230
5529
  } else {
5231
- const sandboxes = readList(body, "sandboxes");
5530
+ const sandboxes2 = readList(body, "sandboxes");
5232
5531
  process.stdout.write(
5233
- sandboxes.length === 0 ? "No sandboxes.\n" : table3([
5532
+ sandboxes2.length === 0 ? "No sandboxes.\n" : table3([
5234
5533
  ["ID", "NAME", "SIZE", ...FIGURE_HEADINGS],
5235
- ...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"])])
5236
5535
  ])
5237
5536
  );
5238
5537
  }
@@ -5254,7 +5553,7 @@ async function account2(positionals, out) {
5254
5553
  process.stdout.write(text);
5255
5554
  return;
5256
5555
  }
5257
- writeFileSync3(out, text, { mode: 384 });
5556
+ writeFileSync4(out, text, { mode: 384 });
5258
5557
  process.stdout.write(`Written to ${out}.
5259
5558
  `);
5260
5559
  }
@@ -5333,9 +5632,9 @@ async function ci(positionals, options) {
5333
5632
  if (repo === void 0 || !/^[^/\s]+\/[^/\s]+$/.test(repo)) {
5334
5633
  throw new Error(`ci ${what} needs the repository, as agental ci ${what} acme/app`);
5335
5634
  }
5336
- const path4 = `/v1/runs-on/repositories/${repo.split("/").map(encodeURIComponent).join("/")}`;
5635
+ const path5 = `/v1/runs-on/repositories/${repo.split("/").map(encodeURIComponent).join("/")}`;
5337
5636
  if (what === "reset") {
5338
- const response = await request(path4, { method: "DELETE" });
5637
+ const response = await request(path5, { method: "DELETE" });
5339
5638
  if (!response.ok) {
5340
5639
  fail(response.status, await readBody(response));
5341
5640
  }
@@ -5357,7 +5656,7 @@ async function ci(positionals, options) {
5357
5656
  if (options.template !== void 0) {
5358
5657
  templateId = options.template === "default" ? null : (await templateNamed(options.template)).id;
5359
5658
  }
5360
- 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 }) });
5361
5660
  if (options.json) {
5362
5661
  process.stdout.write(`${JSON.stringify(saved, null, 2)}
5363
5662
  `);
@@ -5921,8 +6220,8 @@ function duration(ms) {
5921
6220
  const minutes = Math.round(ms / 6e4);
5922
6221
  return minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h${minutes % 60 === 0 ? "" : ` ${minutes % 60} min`}`;
5923
6222
  }
5924
- async function asked(path4, init) {
5925
- const response = await request(path4, init);
6223
+ async function asked(path5, init) {
6224
+ const response = await request(path5, init);
5926
6225
  const body = await readBody(response);
5927
6226
  if (!response.ok) {
5928
6227
  fail(response.status, body);
@@ -6001,10 +6300,10 @@ function table3(rows) {
6001
6300
  `).join("");
6002
6301
  }
6003
6302
  var ACTIVE = /* @__PURE__ */ new Set(["running", "starting", "stopping", "restoring", "creating"]);
6004
- function sandboxesForPeople(sandboxes, names, sorted) {
6303
+ function sandboxesForPeople(sandboxes2, names, sorted) {
6005
6304
  const text = (value) => typeof value === "string" ? value : "";
6006
6305
  const changed = (sandbox) => Date.parse(text(sandbox["stoppedAt"]) || text(sandbox["updatedAt"]) || text(sandbox["createdAt"])) || 0;
6007
- const shown = sorted ? sandboxes : [...sandboxes].sort((a, b) => Number(ACTIVE.has(text(b["status"]))) - Number(ACTIVE.has(text(a["status"]))) || changed(b) - changed(a));
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));
6008
6307
  const outbound = (sandbox) => {
6009
6308
  const rule = sandbox["network"];
6010
6309
  return rule && typeof rule === "object" ? text(rule["outbound"]) : "";
@@ -6164,6 +6463,7 @@ Setting up
6164
6463
  agental logout
6165
6464
  agental whoami [--json]
6166
6465
  agental --version
6466
+ agental completion zsh|bash|fish
6167
6467
 
6168
6468
  Usage
6169
6469
  agental create --name <name> [--template <template>] [--size tiny|small|medium|large] [--region <region>[,<region>...]] [--ttl <time> | --ttl default] [--idempotency-key <key>]
@@ -6286,6 +6586,9 @@ in a terminal it offers to open your newest running sandbox instead, and otherwi
6286
6586
  login signs in through the browser: the page asks you to allow this computer, and the command is
6287
6587
  given an API key of its own, named CLI on <this computer>, which is in the console under API keys.
6288
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.
6289
6592
  The key is kept in ~/.config/agental/credentials.json, readable by you alone. logout deletes the
6290
6593
  key from your account and that file. whoami says who the command is signed in as, and with which
6291
6594
  key. AGENTAL_API_KEY, when it is set, is used in place of what is kept.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agental",
3
- "version": "0.13.0",
3
+ "version": "0.14.0",
4
4
  "description": "The agental command: Linux sandboxes for your agents, from the terminal. npx agental@latest signs you in and installs the agent skills.",
5
5
  "license": "MIT",
6
6
  "author": "VERTIXER LTD",