agental 0.53.0 → 0.56.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 +865 -238
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -6363,15 +6363,15 @@ var require_parser = __commonJS({
6363
6363
  var node_process = __require("process");
6364
6364
  var cst = require_cst();
6365
6365
  var lexer = require_lexer();
6366
- function includesToken(list5, type) {
6367
- for (let i = 0; i < list5.length; ++i)
6368
- if (list5[i].type === type)
6366
+ function includesToken(list6, type) {
6367
+ for (let i = 0; i < list6.length; ++i)
6368
+ if (list6[i].type === type)
6369
6369
  return true;
6370
6370
  return false;
6371
6371
  }
6372
- function findNonEmptyIndex(list5) {
6373
- for (let i = 0; i < list5.length; ++i) {
6374
- switch (list5[i].type) {
6372
+ function findNonEmptyIndex(list6) {
6373
+ for (let i = 0; i < list6.length; ++i) {
6374
+ switch (list6[i].type) {
6375
6375
  case "space":
6376
6376
  case "comment":
6377
6377
  case "newline":
@@ -7404,14 +7404,14 @@ var init_cli_operator = __esm({
7404
7404
 
7405
7405
  // ../src/cli.ts
7406
7406
  import { randomUUID as randomUUID3 } from "node:crypto";
7407
- import { readFileSync as readFileSync7, writeFileSync as writeFileSync5 } from "node:fs";
7407
+ import { readFileSync as readFileSync8, writeFileSync as writeFileSync5 } from "node:fs";
7408
7408
  import os7 from "node:os";
7409
7409
  import { readFile as readFile2 } from "node:fs/promises";
7410
7410
  import { parseArgs } from "node:util";
7411
7411
 
7412
7412
  // ../src/cli-build.ts
7413
7413
  var PUBLISHED = true;
7414
- var CLI_VERSION = true ? "0.53.0" : "dev";
7414
+ var CLI_VERSION = true ? "0.56.0" : "dev";
7415
7415
  var DEFAULT_API_URL = true ? "https://agental.io" : "http://127.0.0.1:8741";
7416
7416
  var PACKAGE_NAME = "agental";
7417
7417
  var USER_AGENT = `agental-cli/${CLI_VERSION}`;
@@ -7468,6 +7468,14 @@ function saveCredentials(credentials, env = process.env) {
7468
7468
  function removeCredentials(env = process.env) {
7469
7469
  rmSync(credentialsPath(env), { force: true });
7470
7470
  }
7471
+ function guildTokenHere(fallbackUrl, env = process.env) {
7472
+ const token = env["AGENTAL_SANDBOX_TOKEN"]?.trim();
7473
+ const named = env["AGENTAL_API_URL"]?.trim();
7474
+ if (!token || !named || resolveApi(fallbackUrl, null, env).key !== null) {
7475
+ return null;
7476
+ }
7477
+ return token;
7478
+ }
7471
7479
  function resolveApi(fallbackUrl, fallbackKey, env = process.env) {
7472
7480
  const trim = (value) => value.replace(/\/+$/, "");
7473
7481
  const namedUrl = env["AGENTAL_API_URL"]?.trim() || void 0;
@@ -7916,6 +7924,9 @@ var KEY_ACTIONS = [
7916
7924
  "template.write",
7917
7925
  "bucket.read",
7918
7926
  "bucket.write",
7927
+ "guild.read",
7928
+ "guild.write",
7929
+ "guild.join",
7919
7930
  "key.manage",
7920
7931
  "account.read",
7921
7932
  "account.admin",
@@ -7939,7 +7950,7 @@ var FULL_SANDBOX = [
7939
7950
  ];
7940
7951
  var PRESETS = {
7941
7952
  // Every read, apart from secrets and mail, which are the two an agent should be given by name.
7942
- "read-only": ["sandbox.read", "file.read", "job.read", "snapshot.read", "template.read", "bucket.read", "account.read"],
7953
+ "read-only": ["sandbox.read", "file.read", "job.read", "snapshot.read", "template.read", "bucket.read", "guild.read", "account.read"],
7943
7954
  "full-sandbox": [...FULL_SANDBOX, "job.read", "job.write", "job.run"],
7944
7955
  // A CI system runs the jobs it is given and reads how they went; it does not make them.
7945
7956
  ci: [...FULL_SANDBOX, "sandbox.create", "sandbox.fork", "sandbox.resume", "sandbox.delete-own", "job.read", "job.run"],
@@ -7971,8 +7982,8 @@ function keyOf(body) {
7971
7982
  throw new Error("The answer was not an API key.");
7972
7983
  }
7973
7984
  const key2 = body;
7974
- const list5 = (value) => Array.isArray(value) ? value.map(String) : [];
7975
- return { ...key2, actions: list5(key2.actions), sandboxIds: list5(key2.sandboxIds), templateIds: list5(key2.templateIds), allowFrom: list5(key2.allowFrom) };
7985
+ const list6 = (value) => Array.isArray(value) ? value.map(String) : [];
7986
+ return { ...key2, actions: list6(key2.actions), sandboxIds: list6(key2.sandboxIds), templateIds: list6(key2.templateIds), allowFrom: list6(key2.allowFrom) };
7976
7987
  }
7977
7988
  function keysOf(body) {
7978
7989
  const listed2 = body?.apiKeys;
@@ -8290,10 +8301,10 @@ async function whoIs(base, key2) {
8290
8301
  throw error;
8291
8302
  }
8292
8303
  }
8293
- async function pushRequest(base, ask13) {
8304
+ async function pushRequest(base, ask14) {
8294
8305
  let made;
8295
8306
  try {
8296
- made = await call(base, "POST", "/v1/cli-sign-ins", ask13);
8307
+ made = await call(base, "POST", "/v1/cli-sign-ins", ask14);
8297
8308
  } catch (error) {
8298
8309
  if (error instanceof Refused && (error.status === 401 || error.status === 404)) {
8299
8310
  throw new Error(`${base} does not sign the command in through the browser. Make a key in its console, under API keys, and run agental login --key.`);
@@ -8305,7 +8316,7 @@ async function pushRequest(base, ask13) {
8305
8316
  async function listen() {
8306
8317
  let arrived = () => {
8307
8318
  };
8308
- let answer4 = () => {
8319
+ let answer6 = () => {
8309
8320
  };
8310
8321
  const next = new Promise((resolve) => arrived = resolve);
8311
8322
  let taken = false;
@@ -8320,7 +8331,7 @@ async function listen() {
8320
8331
  return;
8321
8332
  }
8322
8333
  taken = true;
8323
- answer4 = (to) => response.writeHead(302, { location: to, "cache-control": "no-store" }).end();
8334
+ answer6 = (to) => response.writeHead(302, { location: to, "cache-control": "no-store" }).end();
8324
8335
  arrived(url);
8325
8336
  });
8326
8337
  await new Promise((resolve, reject) => {
@@ -8328,7 +8339,7 @@ async function listen() {
8328
8339
  server2.listen(0, "127.0.0.1", resolve);
8329
8340
  });
8330
8341
  const { port } = server2.address();
8331
- return { server: server2, redirectUri: `http://127.0.0.1:${port}/callback`, next, answer: (to) => answer4(to) };
8342
+ return { server: server2, redirectUri: `http://127.0.0.1:${port}/callback`, next, answer: (to) => answer6(to) };
8332
8343
  }
8333
8344
  async function browserSignIn(base, term, organizationId) {
8334
8345
  const verifier = randomBytes2(32).toString("base64url");
@@ -8643,9 +8654,9 @@ function addToToml(agent, folder, url) {
8643
8654
  function run(command3, args, cwd) {
8644
8655
  return new Promise((resolve) => {
8645
8656
  execFile(command3, args, { encoding: "utf8", timeout: 6e4, cwd, shell: process.platform === "win32" }, (error, stdout, stderr) => {
8646
- const out = `${stdout}${stderr}`.trim();
8647
- const missing = error?.code === "ENOENT" || process.platform === "win32" && /is not recognized as an internal or external command/i.test(out);
8648
- resolve({ ok: !error, out, missing });
8657
+ const out2 = `${stdout}${stderr}`.trim();
8658
+ const missing = error?.code === "ENOENT" || process.platform === "win32" && /is not recognized as an internal or external command/i.test(out2);
8659
+ resolve({ ok: !error, out: out2, missing });
8649
8660
  });
8650
8661
  });
8651
8662
  }
@@ -8693,8 +8704,8 @@ function claudeDesktopHere(places, platform = process.platform, env = process.en
8693
8704
  function addToClaudeLink(url) {
8694
8705
  return `https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=${CONNECTOR_NAME}&connectorUrl=${encodeURIComponent(url)}`;
8695
8706
  }
8696
- function names(list5) {
8697
- return list5.length < 2 ? list5[0] ?? "" : `${list5.slice(0, -1).join(", ")} and ${list5.at(-1)}`;
8707
+ function names(list6) {
8708
+ return list6.length < 2 ? list6[0] ?? "" : `${list6.slice(0, -1).join(", ")} and ${list6.at(-1)}`;
8698
8709
  }
8699
8710
  async function ensureConnector(site2, places = placesFrom()) {
8700
8711
  const url = `${site2}/v1/mcp`;
@@ -8996,9 +9007,9 @@ async function api(base, key2, method, pathname, body, headers = {}) {
8996
9007
  }
8997
9008
  return { status: response.status, body: parsed && typeof parsed === "object" ? parsed : {} };
8998
9009
  }
8999
- function errorOf(answer4) {
9000
- const error = answer4.body["error"] && typeof answer4.body["error"] === "object" ? answer4.body["error"] : {};
9001
- return { code: String(error["code"] ?? `http_${answer4.status}`), message: String(error["message"] ?? `HTTP ${answer4.status}`) };
9010
+ function errorOf(answer6) {
9011
+ const error = answer6.body["error"] && typeof answer6.body["error"] === "object" ? answer6.body["error"] : {};
9012
+ return { code: String(error["code"] ?? `http_${answer6.status}`), message: String(error["message"] ?? `HTTP ${answer6.status}`) };
9002
9013
  }
9003
9014
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
9004
9015
  function real(file) {
@@ -9421,6 +9432,7 @@ var COMMANDS = [
9421
9432
  [" --ttl <time>", "stop it after this long, as 30m or 2h"],
9422
9433
  [" --allow <addresses>", "reach only these addresses, comma-separated"],
9423
9434
  [" --egress <egress>", "box, or residential:<country>[:sticky|rotating]"],
9435
+ [" --tailnet <tags> | off", "join the tailnet tagged so (tag:ci), or off for none"],
9424
9436
  [" --spot", "half the price, in spare room taken back when needed"],
9425
9437
  [" --on-reclaim <what>", "with --spot: stop (default) or delete"],
9426
9438
  [" --warn-at <chance>", "with --spot: warn at this chance, as 0.5 or 50%"],
@@ -9583,6 +9595,72 @@ var COMMANDS = [
9583
9595
  { name: "regions", summary: "List where sandboxes run, and how much room each has now." },
9584
9596
  { 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"] },
9585
9597
  { name: "egress", summary: "Say where a sandbox's web traffic leaves from, or read your residential egress.", examples: ["agental egress sbx_2a9a47e50daec64a residential de"] },
9598
+ {
9599
+ name: "tailscale",
9600
+ summary: "Connect the account's Tailscale OAuth client, its secret sealed on this machine, or say or disconnect it.",
9601
+ usage: ["agental tailscale [status] [--json]", "agental tailscale connect --client-id <id>", "agental tailscale disconnect [--yes]"],
9602
+ examples: ["agental tailscale connect --client-id kAbCdEf2CNTRL"],
9603
+ flags: [
9604
+ ["--client-id <id>", "connect: the OAuth client's id (scopes auth_keys, devices:core); secret read hidden"],
9605
+ ["--yes", "disconnect: without asking; every sandbox is taken off the tailnet"]
9606
+ ]
9607
+ },
9608
+ {
9609
+ name: "guild",
9610
+ summary: "Set up a guild, where agents work together under identities of its design, or join one as an agent.",
9611
+ usage: [
9612
+ "agental guild [list] | show <guild> | delete <guild> [--yes]",
9613
+ "agental guild create <guild> --roles <name[:seats],...> [--brief <text>] [--form <file.json>]",
9614
+ "agental guild attach <guild> <template> [--roles <role,...>] | detach <guild> <template>",
9615
+ "agental guild mine",
9616
+ "agental guild join <guild> --as <name> --role <role> [--answer <key=value>]...",
9617
+ "agental guild members <guild> | leave <guild> <identity> | handover <guild> <identity> <sandbox>"
9618
+ ],
9619
+ examples: [
9620
+ 'agental guild create marketing --roles "blog manager:1,reviewer:2" --brief "Reviewers answer pass or fail."',
9621
+ "agental guild attach marketing writers",
9622
+ "agental guild join marketing --as Atlas --role reviewer --answer model=claude"
9623
+ ],
9624
+ flags: [
9625
+ ["--roles <name[:seats],...>", "create: the roles, each with its seats; attach: the roles its sandboxes may take"],
9626
+ ["--brief <text>", "create: what the guild is for, read by every member"],
9627
+ ["--form <file.json>", "create: the fields an agent fills in to join, as the API takes them"],
9628
+ ["--as <name>", "join: the name you will be known by in the guild"],
9629
+ ["--role <role>", "join: one of the guild's roles with a free seat"],
9630
+ ["--answer <key=value>", "join: an answer to the guild's form (may be given again)"],
9631
+ ["--yes", "delete: without asking"]
9632
+ ]
9633
+ },
9634
+ {
9635
+ name: "subscriptions",
9636
+ summary: "Sign in to Claude, ChatGPT (Codex), GitHub Copilot or Grok Build on agental's servers, which keep it sealed; list or delete them.",
9637
+ usage: ["agental subscriptions [list] [--json]", "agental subscriptions sign-in claude|codex|copilot|grok", "agental subscriptions delete <agent> [--yes]"],
9638
+ examples: ["agental subscriptions sign-in codex", "agental subscriptions delete grok --yes"],
9639
+ flags: [["--yes", "delete: without asking; it is taken off every template and sandbox that uses it"]]
9640
+ },
9641
+ {
9642
+ name: "agents",
9643
+ summary: "Say or set how a template or a sandbox reaches each coding agent's vendor: off, the account's subscription, or its API key.",
9644
+ usage: ["agental agents --template <template> [<agent> off|subscription|api_key] [--json]", "agental agents --sandbox <sandbox-id> [<agent> off|subscription|api_key|template] [--json]"],
9645
+ examples: ["agental agents --template default claude subscription", "agental agents --sandbox sbx_2a9a47e50daec64a codex template"],
9646
+ flags: [
9647
+ ["--template <template>", "the template, by id or name"],
9648
+ ["--sandbox <sandbox-id>", "the sandbox: template follows its template again"]
9649
+ ]
9650
+ },
9651
+ {
9652
+ name: "tailnet",
9653
+ summary: "Join a sandbox to the account's tailnet as a node, change how, or take it off.",
9654
+ usage: ["agental tailnet <sandbox> [--json]", "agental tailnet <sandbox> join --tag <tag> [--accept <range>] [--exit-node <ip>] [--keep-address] [--node-name <name>]", "agental tailnet <sandbox> off"],
9655
+ examples: ["agental tailnet build join --tag tag:ci", "agental tailnet build join --tag tag:ci --accept 10.1.0.0/16 --keep-address"],
9656
+ flags: [
9657
+ ["--tag <tag:name>", "join: a tag the OAuth client owns (may be given again)"],
9658
+ ["--accept <range>", "join: a subnet route of the tailnet it takes, /8 or narrower (may be given again)"],
9659
+ ["--exit-node <address>", "join: its other traffic leaves through this tailnet address"],
9660
+ ["--keep-address", "join: keep its tailnet address across stops and moves"],
9661
+ ["--node-name <name>", "join: its name on the tailnet; the sandbox's own by default"]
9662
+ ]
9663
+ },
9586
9664
  {
9587
9665
  name: "spot",
9588
9666
  summary: "Read a spot sandbox's chance of being stopped, change what a reclaim does to it, or turn off spot.",
@@ -10032,11 +10110,11 @@ function spelledOut(args, operator = false) {
10032
10110
  if (verb === void 0 || !SECRET_VERBS.has(verb)) {
10033
10111
  return wrong("list, get, set, unset, hosts, get-file, put-file or rm-file, then the sandbox or --template <template>");
10034
10112
  }
10035
- const at4 = rest.findIndex((word) => word === "--template" || word === "-t" || word.startsWith("--template="));
10036
- if (at4 >= 0) {
10037
- const given = rest[at4];
10038
- const pair = given.startsWith("--template=") ? [given] : rest.slice(at4, at4 + 2);
10039
- return ["secrets", ...pair, ...verb === "list" ? [] : [verb], ...rest.filter((_, index) => index < at4 || index >= at4 + pair.length)];
10113
+ const at5 = rest.findIndex((word) => word === "--template" || word === "-t" || word.startsWith("--template="));
10114
+ if (at5 >= 0) {
10115
+ const given = rest[at5];
10116
+ const pair = given.startsWith("--template=") ? [given] : rest.slice(at5, at5 + 2);
10117
+ return ["secrets", ...pair, ...verb === "list" ? [] : [verb], ...rest.filter((_, index) => index < at5 || index >= at5 + pair.length)];
10040
10118
  }
10041
10119
  const { sandbox, others } = sandboxIn(rest, ["--host", "--text"]);
10042
10120
  if (sandbox === void 0) {
@@ -10063,7 +10141,7 @@ function sandboxIn(words2, valued = []) {
10063
10141
  index += valued.includes(word) ? 1 : 0;
10064
10142
  continue;
10065
10143
  }
10066
- return { sandbox: word, others: words2.filter((_, at4) => at4 !== index) };
10144
+ return { sandbox: word, others: words2.filter((_, at5) => at5 !== index) };
10067
10145
  }
10068
10146
  return { sandbox: void 0, others: words2 };
10069
10147
  }
@@ -10080,6 +10158,9 @@ var SUBCOMMANDS = {
10080
10158
  job: ["list"],
10081
10159
  limits: ["budget"],
10082
10160
  egress: ["budget", "use-case"],
10161
+ tailscale: ["status", "connect", "disconnect"],
10162
+ guild: ["list", "show", "create", "delete", "attach", "detach", "mine", "join", "members", "leave", "handover"],
10163
+ subscriptions: ["list", "sign-in", "delete"],
10083
10164
  telemetry: ["set", "test", "unset"],
10084
10165
  ci: ["jobs", "set", "reset"],
10085
10166
  org: ["list", "use", "create"],
@@ -10311,7 +10392,7 @@ async function jobs(api2) {
10311
10392
  });
10312
10393
  }
10313
10394
  var KEPT_MS = 3e4;
10314
- async function cached(what, as, ask13) {
10395
+ async function cached(what, as, ask14) {
10315
10396
  const folder = path5.join(process.env["XDG_CACHE_HOME"] || path5.join(os6.homedir(), ".cache"), "agental");
10316
10397
  const file = path5.join(folder, `complete-${what}-${createHash2("sha256").update(as).digest("hex").slice(0, 16)}.json`);
10317
10398
  try {
@@ -10323,7 +10404,7 @@ async function cached(what, as, ask13) {
10323
10404
  }
10324
10405
  let body = null;
10325
10406
  try {
10326
- body = await ask13();
10407
+ body = await ask14();
10327
10408
  } catch {
10328
10409
  return null;
10329
10410
  }
@@ -10487,12 +10568,12 @@ async function organizations(client) {
10487
10568
  const me = await ask5(client, "GET", "/v1/me");
10488
10569
  return { organizations: Array.isArray(listed2) ? listed2 : [], acting: String(me["activeOrganizationId"] ?? "") };
10489
10570
  }
10490
- function organizationNamed(list5, given) {
10491
- const byId = list5.find((organization) => organization.id === given);
10571
+ function organizationNamed(list6, given) {
10572
+ const byId = list6.find((organization) => organization.id === given);
10492
10573
  if (byId) {
10493
10574
  return byId;
10494
10575
  }
10495
- const byName = list5.filter((organization) => organization.name.toLowerCase() === given.toLowerCase());
10576
+ const byName = list6.filter((organization) => organization.name.toLowerCase() === given.toLowerCase());
10496
10577
  if (byName.length === 1 && byName[0]) {
10497
10578
  return byName[0];
10498
10579
  }
@@ -10505,14 +10586,14 @@ async function org(client, positionals, options, signInTo) {
10505
10586
  const [verb = "list", ...rest] = positionals;
10506
10587
  switch (verb) {
10507
10588
  case "list": {
10508
- const { organizations: list5, acting } = await organizations(client);
10589
+ const { organizations: list6, acting } = await organizations(client);
10509
10590
  if (options.json) {
10510
- print2(true, { organizations: list5.map((organization) => ({ ...organization, acting: organization.id === acting })) }, "");
10591
+ print2(true, { organizations: list6.map((organization) => ({ ...organization, acting: organization.id === acting })) }, "");
10511
10592
  return;
10512
10593
  }
10513
10594
  process.stdout.write(` ${[pad("ID", 22), pad("NAME", 24), "ROLE"].join(" ")}
10514
10595
  `);
10515
- for (const organization of list5) {
10596
+ for (const organization of list6) {
10516
10597
  const role = organization.personal ? "your own" : organization.role ?? "";
10517
10598
  process.stdout.write(`${organization.id === acting ? "*" : " "} ${[pad(organization.id, 22), pad(organization.name, 24), role].join(" ")}
10518
10599
  `);
@@ -10525,8 +10606,8 @@ async function org(client, positionals, options, signInTo) {
10525
10606
  if (!given) {
10526
10607
  throw new Error("org use takes the organization's id or name: agental org use Acme.");
10527
10608
  }
10528
- const { organizations: list5, acting } = await organizations(client);
10529
- const chosen = organizationNamed(list5, given);
10609
+ const { organizations: list6, acting } = await organizations(client);
10610
+ const chosen = organizationNamed(list6, given);
10530
10611
  if (chosen.id === acting) {
10531
10612
  process.stdout.write(`This command's key acts in ${chosen.name} already.
10532
10613
  `);
@@ -10556,15 +10637,15 @@ agental org use ${organization.id} signs this command in to it.
10556
10637
  }
10557
10638
  }
10558
10639
  async function actingTeam(client) {
10559
- const { organizations: list5, acting } = await organizations(client);
10560
- const team = list5.find((organization) => organization.id === acting);
10640
+ const { organizations: list6, acting } = await organizations(client);
10641
+ const team = list6.find((organization) => organization.id === acting);
10561
10642
  if (!team) {
10562
10643
  throw new Error("This command's key acts in no organization you are in. agental org use <organization> signs it in to one.");
10563
10644
  }
10564
10645
  return team;
10565
10646
  }
10566
- function memberNamed(list5, given) {
10567
- const found = list5.find((member) => member.userId === given || member.email?.toLowerCase() === given.toLowerCase());
10647
+ function memberNamed(list6, given) {
10648
+ const found = list6.find((member) => member.userId === given || member.email?.toLowerCase() === given.toLowerCase());
10568
10649
  if (!found) {
10569
10650
  throw new Error(`No member ${given} in this team. agental members lists them.`);
10570
10651
  }
@@ -10574,7 +10655,7 @@ async function members(client, positionals, options) {
10574
10655
  const [verb = "list", target] = positionals;
10575
10656
  const team = await actingTeam(client);
10576
10657
  const listed2 = await ask5(client, "GET", `/v1/organizations/${encodeURIComponent(team.id)}/members`);
10577
- const list5 = Array.isArray(listed2["members"]) ? listed2["members"] : [];
10658
+ const list6 = Array.isArray(listed2["members"]) ? listed2["members"] : [];
10578
10659
  switch (verb) {
10579
10660
  case "list": {
10580
10661
  if (options.json) {
@@ -10586,7 +10667,7 @@ async function members(client, positionals, options) {
10586
10667
  `);
10587
10668
  process.stdout.write(`${[pad("ID", 34), pad("EMAIL", 30), pad("ROLE", 8), "ADDED"].join(" ")}
10588
10669
  `);
10589
- for (const member of list5) {
10670
+ for (const member of list6) {
10590
10671
  process.stdout.write(`${[pad(member.userId, 34), pad(member.email ?? member.name ?? "", 30), pad(member.role, 8), member.addedAt.slice(0, 10)].join(" ")}
10591
10672
  `);
10592
10673
  }
@@ -10596,7 +10677,7 @@ async function members(client, positionals, options) {
10596
10677
  if (!target) {
10597
10678
  throw new Error("members remove takes the member's id or email: agental members remove cy@example.com.");
10598
10679
  }
10599
- const member = memberNamed(list5, target);
10680
+ const member = memberNamed(list6, target);
10600
10681
  const query = options.revokeKeys ? "?revokeKeys=true" : "";
10601
10682
  const removed = await ask5(client, "DELETE", `/v1/organizations/${encodeURIComponent(team.id)}/members/${encodeURIComponent(member.userId)}${query}`);
10602
10683
  const revoked = Number(removed["revokedKeys"] ?? 0);
@@ -11877,8 +11958,8 @@ function exitOf2(command3) {
11877
11958
  }
11878
11959
  }
11879
11960
  function moment(iso) {
11880
- const at4 = new Date(iso).toISOString().replace(/\.\d+Z$/, "Z");
11881
- return isTerminal(process.stdout) ? ago(iso) ?? at4 : at4;
11961
+ const at5 = new Date(iso).toISOString().replace(/\.\d+Z$/, "Z");
11962
+ return isTerminal(process.stdout) ? ago(iso) ?? at5 : at5;
11882
11963
  }
11883
11964
  function tookOf2(command3) {
11884
11965
  const began = Date.parse(command3.startedAt);
@@ -11942,7 +12023,7 @@ function show(command3, sandbox, asJson) {
11942
12023
  function put(stream, data) {
11943
12024
  return new Promise((resolve, reject) => stream.write(data, (error) => error ? reject(error) : resolve()));
11944
12025
  }
11945
- async function readOutput(client, path6, at4, follow2, wrote) {
12026
+ async function readOutput(client, path6, at5, follow2, wrote) {
11946
12027
  const controller = new AbortController();
11947
12028
  let silence = setTimeout(() => controller.abort(), SILENT_MS);
11948
12029
  const heard = () => {
@@ -11953,7 +12034,7 @@ async function readOutput(client, path6, at4, follow2, wrote) {
11953
12034
  try {
11954
12035
  let response;
11955
12036
  try {
11956
- response = await client.request(`${path6}?stdout=${at4.stdout}&stderr=${at4.stderr}${follow2 ? "&follow=1" : ""}`, { method: "GET", headers: { Accept: "text/event-stream" }, signal: controller.signal });
12037
+ response = await client.request(`${path6}?stdout=${at5.stdout}&stderr=${at5.stderr}${follow2 ? "&follow=1" : ""}`, { method: "GET", headers: { Accept: "text/event-stream" }, signal: controller.signal });
11957
12038
  } catch (error) {
11958
12039
  return { kind: "cut", why: errorText(error), progressed };
11959
12040
  }
@@ -11976,12 +12057,12 @@ async function readOutput(client, path6, at4, follow2, wrote) {
11976
12057
  case "output": {
11977
12058
  const piece = JSON.parse(data2);
11978
12059
  const raw = Buffer.from(piece.data, "base64");
11979
- const skip = Math.max(0, at4[piece.stream] - piece.offset);
12060
+ const skip = Math.max(0, at5[piece.stream] - piece.offset);
11980
12061
  if (skip < raw.length) {
11981
12062
  await put(piece.stream === "stdout" ? process.stdout : process.stderr, raw.subarray(skip));
11982
12063
  wrote();
11983
12064
  }
11984
- at4[piece.stream] = Math.max(at4[piece.stream], piece.offset + raw.length);
12065
+ at5[piece.stream] = Math.max(at5[piece.stream], piece.offset + raw.length);
11985
12066
  progressed = true;
11986
12067
  return null;
11987
12068
  }
@@ -11989,14 +12070,14 @@ async function readOutput(client, path6, at4, follow2, wrote) {
11989
12070
  const gap = JSON.parse(data2);
11990
12071
  await put(process.stderr, `[agental: bytes ${gap.from} to ${gap.to} of its ${gap.stream} were overwritten in the sandbox before they were read: each stream keeps its last 1 MiB]
11991
12072
  `);
11992
- at4[gap.stream] = Math.max(at4[gap.stream], gap.to);
12073
+ at5[gap.stream] = Math.max(at5[gap.stream], gap.to);
11993
12074
  progressed = true;
11994
12075
  return null;
11995
12076
  }
11996
12077
  case "continue": {
11997
12078
  const next = JSON.parse(data2);
11998
- at4.stdout = Math.max(at4.stdout, next.stdout);
11999
- at4.stderr = Math.max(at4.stderr, next.stderr);
12079
+ at5.stdout = Math.max(at5.stdout, next.stdout);
12080
+ at5.stderr = Math.max(at5.stderr, next.stderr);
12000
12081
  return { kind: "continue" };
12001
12082
  }
12002
12083
  case "end":
@@ -12055,13 +12136,13 @@ async function logs(client, sandbox, id, one, follow2) {
12055
12136
  process.exit(0);
12056
12137
  }
12057
12138
  });
12058
- const at4 = { stdout: 0, stderr: 0 };
12139
+ const at5 = { stdout: 0, stderr: 0 };
12059
12140
  let wrote = false;
12060
12141
  let failed = 0;
12061
12142
  let idle = 0;
12062
12143
  for (; ; ) {
12063
- const from = { ...at4 };
12064
- const read2 = await readOutput(client, `${one}/output`, at4, follow2, () => wrote = true);
12144
+ const from = { ...at5 };
12145
+ const read2 = await readOutput(client, `${one}/output`, at5, follow2, () => wrote = true);
12065
12146
  switch (read2.kind) {
12066
12147
  case "end":
12067
12148
  if (follow2) {
@@ -12074,7 +12155,7 @@ async function logs(client, sandbox, id, one, follow2) {
12074
12155
  `, process.stderr));
12075
12156
  return;
12076
12157
  }
12077
- if (at4.stdout === from.stdout && at4.stderr === from.stderr) {
12158
+ if (at5.stdout === from.stdout && at5.stderr === from.stderr) {
12078
12159
  idle += 1;
12079
12160
  await sleep2(waitBefore(idle));
12080
12161
  continue;
@@ -12774,7 +12855,7 @@ function stateOf3(webhook2) {
12774
12855
  const since = webhook2.disabledAt ? ` since ${at3(webhook2.disabledAt)}` : "";
12775
12856
  return `off${since}${webhook2.disabledReason ? `: ${webhook2.disabledReason}` : ""}`;
12776
12857
  }
12777
- function eventsFrom(options, needed) {
12858
+ function eventsFrom(options, needed2) {
12778
12859
  if (options.all && options.events !== void 0) {
12779
12860
  throw new Error("Give --events or --all, not both.");
12780
12861
  }
@@ -12782,7 +12863,7 @@ function eventsFrom(options, needed) {
12782
12863
  return [EVERY];
12783
12864
  }
12784
12865
  if (options.events === void 0) {
12785
- if (needed) {
12866
+ if (needed2) {
12786
12867
  throw new Error(`Say what to send: --events with kinds such as sandbox.stopped,sandbox.error, or --all. The kinds are ${WEBHOOK_KINDS.join(", ")}; a group of them is ${WEBHOOK_GROUPS.map((group) => `${group}.*`).join(", ")}, quoted for the shell.`);
12787
12868
  }
12788
12869
  return void 0;
@@ -13119,12 +13200,12 @@ function describe5(snapshot2) {
13119
13200
  ["Kept", `${keptOf(snapshot2)}${copied}`],
13120
13201
  ["State", snapshot2.state]
13121
13202
  ];
13122
- const out = [`${strong(snapshot2.name)} ${faint(snapshot2.id)}`, "", ...fitted(facts, { paint: (cell, _row, column) => column === 0 ? faint(cell) : cell }).trimEnd().split("\n")];
13203
+ const out2 = [`${strong(snapshot2.name)} ${faint(snapshot2.id)}`, "", ...fitted(facts, { paint: (cell, _row, column) => column === 0 ? faint(cell) : cell }).trimEnd().split("\n")];
13123
13204
  if (snapshot2.kept === STORAGE_ONLY) {
13124
- out.push("", "Its server no longer holds it. Rolling back to it, or starting a sandbox from it, fetches it first: a few minutes.");
13205
+ out2.push("", "Its server no longer holds it. Rolling back to it, or starting a sandbox from it, fetches it first: a few minutes.");
13125
13206
  }
13126
13207
  if (snapshot2.state !== "ready") {
13127
- return `${out.join("\n")}
13208
+ return `${out2.join("\n")}
13128
13209
  `;
13129
13210
  }
13130
13211
  const next = [
@@ -13132,8 +13213,8 @@ function describe5(snapshot2) {
13132
13213
  ["Start from", `agental sandbox create --snapshot ${snapshot2.id}`],
13133
13214
  ["Delete", `agental snapshot delete ${snapshot2.id}`]
13134
13215
  ];
13135
- out.push("", ...fitted(next, { paint: (cell, _row, column) => column === 0 ? faint(cell) : cell }).trimEnd().split("\n"));
13136
- return `${out.join("\n")}
13216
+ out2.push("", ...fitted(next, { paint: (cell, _row, column) => column === 0 ? faint(cell) : cell }).trimEnd().split("\n"));
13217
+ return `${out2.join("\n")}
13137
13218
  `;
13138
13219
  }
13139
13220
  async function snapshotsOfSandbox(client, word) {
@@ -13237,16 +13318,16 @@ async function snapshot(client, positionals, options) {
13237
13318
  if (found.kept === STORAGE_ONLY) {
13238
13319
  process.stderr.write("Its server no longer holds it: it is fetched from storage first, which takes a few minutes.\n");
13239
13320
  }
13240
- const answer4 = await ask10(client, "POST", `/v1/sandboxes/${encodeURIComponent(found.sandboxId)}/restore`, {
13321
+ const answer6 = await ask10(client, "POST", `/v1/sandboxes/${encodeURIComponent(found.sandboxId)}/restore`, {
13241
13322
  headers: { "Idempotency-Key": options.idempotencyKey ?? `cli-${randomUUID2()}` },
13242
13323
  body: { snapshotId: found.id }
13243
13324
  });
13244
13325
  if (options.json) {
13245
- process.stdout.write(`${JSON.stringify(answer4, null, 2)}
13326
+ process.stdout.write(`${JSON.stringify(answer6, null, 2)}
13246
13327
  `);
13247
13328
  return;
13248
13329
  }
13249
- const read2 = answer4;
13330
+ const read2 = answer6;
13250
13331
  const discarded = Array.isArray(read2?.discarded) ? read2.discarded.map(String) : [];
13251
13332
  const status = typeof read2?.sandbox?.status === "string" ? `, and ${read2.sandbox.status}` : "";
13252
13333
  process.stdout.write(`${sandbox} is as it was at ${found.name}${status}.
@@ -13286,7 +13367,7 @@ var AgentalError = class extends Error {
13286
13367
  // ../sdk/typescript/src/sealed.ts
13287
13368
  var SEALED_SUITE = "x25519-hkdf-sha256-aes256gcm";
13288
13369
  var ROOT_PUBLIC_KEYS = ["jNdFf3FKdbFQ5J-1e_NE7ZzuaNPRdci-mzlGj384Rmw"];
13289
- var SEALED_PURPOSES = ["variable", "tailscale-oauth"];
13370
+ var SEALED_PURPOSES = ["variable", "tailscale-oauth", "sign-in-code"];
13290
13371
  var KEM_ID = 32;
13291
13372
  var KDF_ID = 1;
13292
13373
  var AEAD_ID = 2;
@@ -13396,14 +13477,14 @@ async function hkdfExtract(salt, ikm) {
13396
13477
  return hmac(salt.length > 0 ? salt : new Uint8Array(32), ikm);
13397
13478
  }
13398
13479
  async function hkdfExpand(prk, info, length) {
13399
- const out = new Uint8Array(length);
13480
+ const out2 = new Uint8Array(length);
13400
13481
  let block = new Uint8Array();
13401
13482
  for (let counter = 1, filled = 0; filled < length; counter++) {
13402
13483
  block = await hmac(prk, concat(block, info, new Uint8Array([counter])));
13403
- out.set(block.subarray(0, Math.min(block.length, length - filled)), filled);
13484
+ out2.set(block.subarray(0, Math.min(block.length, length - filled)), filled);
13404
13485
  filled += block.length;
13405
13486
  }
13406
- return out;
13487
+ return out2;
13407
13488
  }
13408
13489
  async function hmac(key2, data) {
13409
13490
  const hmacKey = await subtle().importKey("raw", key2, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
@@ -13415,18 +13496,18 @@ function subtle() {
13415
13496
  return webCrypto;
13416
13497
  }
13417
13498
  function i2osp(value, length) {
13418
- const out = new Uint8Array(length);
13419
- for (let i = length - 1, v = value; i >= 0; i--, v >>>= 8) out[i] = v & 255;
13420
- return out;
13499
+ const out2 = new Uint8Array(length);
13500
+ for (let i = length - 1, v = value; i >= 0; i--, v >>>= 8) out2[i] = v & 255;
13501
+ return out2;
13421
13502
  }
13422
13503
  function concat(...parts) {
13423
- const out = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));
13504
+ const out2 = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));
13424
13505
  let offset = 0;
13425
13506
  for (const part of parts) {
13426
- out.set(part, offset);
13507
+ out2.set(part, offset);
13427
13508
  offset += part.length;
13428
13509
  }
13429
- return out;
13510
+ return out2;
13430
13511
  }
13431
13512
  function utf8(text) {
13432
13513
  return new Uint8Array(new TextEncoder().encode(text));
@@ -13574,16 +13655,19 @@ async function toSeal(client, given, options, verb) {
13574
13655
  if (!given) {
13575
13656
  throw new Error(`secret ${verb} requires <NAME>, and --host: agental secret ${verb} GITHUB_TOKEN --host api.github.com`);
13576
13657
  }
13577
- const at4 = given.indexOf("=");
13578
- const name = nameOf2(at4 < 0 ? given : given.slice(0, at4), verb);
13658
+ const at5 = given.indexOf("=");
13659
+ const name = nameOf2(at5 < 0 ? given : given.slice(0, at5), verb);
13579
13660
  const hosts = hostsOf(options.host, verb);
13580
- const value = at4 < 0 ? await client.readValue(`${name}'s value (not shown): `) : given.slice(at4 + 1);
13661
+ const value = at5 < 0 ? await client.readValue(`${name}'s value (not shown): `) : given.slice(at5 + 1);
13581
13662
  if (value.length < SHORTEST_VALUE) {
13582
13663
  throw new Error(`${name}'s value is ${value.length} characters: a secret is at least ${SHORTEST_VALUE}, and the API cannot check a sealed one, so it is refused here.`);
13583
13664
  }
13584
13665
  return { name, value, hosts };
13585
13666
  }
13586
13667
  async function sealFor(client, name, value, hosts) {
13668
+ return await sealForAccount(client, name, value, hosts, "variable");
13669
+ }
13670
+ async function sealForAccount(client, name, value, hosts, purpose) {
13587
13671
  const { keys } = await answer2(client, "/v1/secrets/key", { method: "GET" });
13588
13672
  const org2 = String((await answer2(client, "/v1/me", { method: "GET" })).activeOrganizationId ?? "");
13589
13673
  if (!org2) {
@@ -13596,7 +13680,7 @@ async function sealFor(client, name, value, hosts) {
13596
13680
  for (const key2 of mine) {
13597
13681
  await verifySealingKey(key2, client.roots ?? ROOT_KEYS);
13598
13682
  }
13599
- const sealed = await Promise.all(mine.map((key2) => seal(key2, { value, hosts, org: org2, name, purpose: "variable" }, client.roots ?? ROOT_KEYS)));
13683
+ const sealed = await Promise.all(mine.map((key2) => seal(key2, { value, hosts, org: org2, name, purpose }, client.roots ?? ROOT_KEYS)));
13600
13684
  return { sealed, org: org2 };
13601
13685
  }
13602
13686
  function nameOf2(given, verb) {
@@ -13653,8 +13737,474 @@ function refused(client, status, body) {
13653
13737
  client.fail(status, body);
13654
13738
  }
13655
13739
 
13740
+ // ../src/cli-tailscale.ts
13741
+ var SECRET_NAME = "TAILSCALE_OAUTH";
13742
+ var SECRET_HOST = "api.tailscale.com";
13743
+ async function answer3(client, pathname, init) {
13744
+ const response = await client.request(pathname, init);
13745
+ const text = await response.text();
13746
+ let body = text;
13747
+ try {
13748
+ body = text ? JSON.parse(text) : null;
13749
+ } catch {
13750
+ }
13751
+ if (!response.ok) {
13752
+ client.fail(response.status, body);
13753
+ }
13754
+ return body;
13755
+ }
13756
+ async function sandboxIdOf2(client, word) {
13757
+ if (word.startsWith("sbx_")) {
13758
+ return word;
13759
+ }
13760
+ const body = await answer3(client, `/v1/sandboxes?${new URLSearchParams({ q: word })}`, { method: "GET" });
13761
+ const listed2 = Array.isArray(body?.sandboxes) ? body.sandboxes : [];
13762
+ const named = listed2.filter((one) => one.name === word && typeof one.id === "string");
13763
+ if (named.length > 1) {
13764
+ throw new Error(`${named.length} sandboxes are named ${word}. Give the id of the one you mean: ${named.map((one) => String(one.id)).join(", ")}.`);
13765
+ }
13766
+ if (named.length === 0) {
13767
+ throw new Error(`There is no sandbox named ${word}. agental list lists them.`);
13768
+ }
13769
+ return named[0].id;
13770
+ }
13771
+ function out(flags2, body, words2) {
13772
+ process.stdout.write(flags2.json ? `${JSON.stringify(body, null, 2)}
13773
+ ` : words2);
13774
+ }
13775
+ async function tailscale(client, positionals, flags2) {
13776
+ const [verb = "status", ...rest] = positionals;
13777
+ if (rest.length > 0) {
13778
+ throw new Error("tailscale takes connect, status or disconnect, and nothing after it.");
13779
+ }
13780
+ if (verb === "status") {
13781
+ const body = await answer3(client, "/v1/integrations/tailscale", { method: "GET" });
13782
+ out(flags2, body, body.connected ? `Tailscale: connected, OAuth client ${body.clientId}, since ${body.connectedAt}
13783
+ ` : "Tailscale: not connected. agental tailscale connect --client-id <id> connects one.\n");
13784
+ return;
13785
+ }
13786
+ if (verb === "connect") {
13787
+ const clientId = flags2.clientId;
13788
+ if (!clientId) {
13789
+ throw new Error("tailscale connect takes --client-id, the OAuth client's id from Tailscale's admin console (Settings, Trust credentials), with the scopes auth_keys and devices:core.");
13790
+ }
13791
+ const secret2 = (await client.readValue("The OAuth client's secret (not shown): ")).trim();
13792
+ if (!secret2.startsWith("tskey-client-")) {
13793
+ throw new Error("That is not a Tailscale OAuth client's secret, which starts tskey-client-. Nothing was sent.");
13794
+ }
13795
+ if (!secret2.startsWith(`tskey-client-${clientId}-`)) {
13796
+ throw new Error(`That secret is not client ${clientId}'s. Nothing was sent.`);
13797
+ }
13798
+ const { sealed } = await sealForAccount(client, SECRET_NAME, secret2, [SECRET_HOST], "tailscale-oauth");
13799
+ const body = await answer3(client, "/v1/integrations/tailscale", { method: "PUT", body: JSON.stringify({ clientId, clientSecret: sealed }) });
13800
+ out(flags2, body, `Tailscale: connected, OAuth client ${body.clientId}. Its secret was sealed here; only agental's servers open it, to mint each node a key.
13801
+ `);
13802
+ return;
13803
+ }
13804
+ if (verb === "disconnect") {
13805
+ if (!flags2.yes && !await client.confirmed("Take every sandbox off the tailnet and forget the OAuth client?")) {
13806
+ throw new Error("Nothing was disconnected. --yes disconnects without asking.");
13807
+ }
13808
+ await answer3(client, "/v1/integrations/tailscale", { method: "DELETE" });
13809
+ out(flags2, { connected: false }, "Tailscale: disconnected. Every sandbox was taken off the tailnet.\n");
13810
+ return;
13811
+ }
13812
+ throw new Error("tailscale takes connect, status or disconnect.");
13813
+ }
13814
+ function joinBody(flags2, withName) {
13815
+ const tags = (flags2.tag ?? []).flatMap((each) => each.split(",")).map((each) => each.trim()).filter((each) => each !== "");
13816
+ if (tags.length === 0) {
13817
+ throw new Error("join takes --tag, one tag:name or more, which the connected OAuth client owns: --tag tag:agental.");
13818
+ }
13819
+ if (!withName && flags2.nodeName !== void 0) {
13820
+ throw new Error("A template's sandboxes are each named by their own sandbox: --node-name is for one sandbox.");
13821
+ }
13822
+ return {
13823
+ tags,
13824
+ ...flags2.accept === void 0 ? {} : { acceptRoutes: flags2.accept.flatMap((each) => each.split(",")).map((each) => each.trim()).filter((each) => each !== "") },
13825
+ ...flags2.exitNode === void 0 ? {} : { exitNode: flags2.exitNode },
13826
+ ...flags2.keepAddress ? { keepAddress: true } : {},
13827
+ ...withName && flags2.nodeName !== void 0 ? { name: flags2.nodeName } : {}
13828
+ };
13829
+ }
13830
+ function nodeInWords(node, whose) {
13831
+ if (!node.on) {
13832
+ return `${whose}: on no tailnet
13833
+ `;
13834
+ }
13835
+ return [
13836
+ `${whose}: on the tailnet${node.name ? ` as ${node.name}` : ""}, tagged ${node.tags.join(", ")}`,
13837
+ ...node.acceptRoutes.length > 0 ? [` routes: ${node.acceptRoutes.join(", ")}`] : [],
13838
+ ...node.exitNode !== null ? [` exit node: ${node.exitNode}`] : [],
13839
+ ` address: ${node.keepAddress ? "kept across stops and moves" : "new at each start"}`
13840
+ ].join("\n") + "\n";
13841
+ }
13842
+ async function tailnet(client, kind, positionals, flags2) {
13843
+ const [given, verb, ...rest] = positionals;
13844
+ if (given === void 0 || rest.length > 0) {
13845
+ throw new Error(`${kind === "sandbox" ? "tailnet" : "template tailnet"} takes <${kind}>, and then nothing, join with --tag, or off.`);
13846
+ }
13847
+ const id = kind === "sandbox" ? await sandboxIdOf2(client, given) : await client.templateId(given);
13848
+ const path6 = `/v1/${kind === "sandbox" ? "sandboxes" : "templates"}/${encodeURIComponent(id)}/tailnet`;
13849
+ const whose = kind === "sandbox" ? given : `${given}'s sandboxes from now on`;
13850
+ if (verb === void 0) {
13851
+ const node = await answer3(client, path6, { method: "GET" });
13852
+ out(flags2, node, nodeInWords(node, kind === "sandbox" ? given : `${given}'s sandboxes`));
13853
+ return;
13854
+ }
13855
+ if (verb === "join") {
13856
+ const node = await answer3(client, path6, { method: "PUT", body: JSON.stringify(joinBody(flags2, kind === "sandbox")) });
13857
+ out(flags2, node, nodeInWords(node, whose));
13858
+ return;
13859
+ }
13860
+ if (verb === "off") {
13861
+ await answer3(client, path6, { method: "DELETE" });
13862
+ out(flags2, { on: false }, `${whose}: on no tailnet
13863
+ `);
13864
+ return;
13865
+ }
13866
+ throw new Error(`${kind === "sandbox" ? "tailnet" : "template tailnet"} takes <${kind}>, and then nothing, join, or off.`);
13867
+ }
13868
+ function createTailnet(given, flags2 = {}) {
13869
+ const more = flags2.accept !== void 0 || flags2.exitNode !== void 0 || flags2.keepAddress === true || flags2.nodeName !== void 0;
13870
+ if (given === void 0) {
13871
+ if (more) {
13872
+ throw new Error("--accept, --exit-node, --keep-address and --node-name go with --tailnet <tags> on a create.");
13873
+ }
13874
+ return void 0;
13875
+ }
13876
+ if (given === "off") {
13877
+ return null;
13878
+ }
13879
+ return joinBody({ ...flags2, json: false, yes: false, tag: [given] }, true);
13880
+ }
13881
+
13882
+ // ../src/cli-guilds.ts
13883
+ import { readFileSync as readFileSync7 } from "node:fs";
13884
+ var USAGE9 = "guild takes list, show <guild>, create <guild> --roles <name[:seats],...>, delete <guild>, attach <guild> <template>, detach <guild> <template>, mine, join <guild> --as <name> --role <role>, members <guild>, leave <guild> <identity>, or handover <guild> <identity> <sandbox>. agental guild --help shows each.";
13885
+ async function ask11(client, method, pathname, body) {
13886
+ const response = await client.request(pathname, { method, ...body === void 0 ? {} : { body: JSON.stringify(body) } });
13887
+ let answered = null;
13888
+ if (response.status !== 204) {
13889
+ try {
13890
+ answered = await response.json();
13891
+ } catch {
13892
+ answered = null;
13893
+ }
13894
+ }
13895
+ if (!response.ok) {
13896
+ client.fail(response.status, answered);
13897
+ }
13898
+ return answered !== null && typeof answered === "object" ? answered : {};
13899
+ }
13900
+ function print4(json3, body, words2) {
13901
+ process.stdout.write(json3 ? `${JSON.stringify(body, null, 2)}
13902
+ ` : words2);
13903
+ }
13904
+ function at4(name) {
13905
+ return `/v1/guilds/${encodeURIComponent(name)}`;
13906
+ }
13907
+ function needed(value, what) {
13908
+ if (value === void 0 || value === "") {
13909
+ throw new Error(`${what}. ${USAGE9}`);
13910
+ }
13911
+ return value;
13912
+ }
13913
+ function rolesOf(given) {
13914
+ return given.split(",").map((part) => part.trim()).filter((part) => part !== "").map((part) => {
13915
+ const colon = part.lastIndexOf(":");
13916
+ const after = colon === -1 ? "" : part.slice(colon + 1).trim();
13917
+ return /^[0-9]+$/.test(after) ? { name: part.slice(0, colon).trim(), seats: Number(after) } : { name: part };
13918
+ });
13919
+ }
13920
+ function answersOf(given = []) {
13921
+ const answers = {};
13922
+ for (const one of given) {
13923
+ const equals = one.indexOf("=");
13924
+ if (equals < 1) {
13925
+ throw new Error(`--answer takes key=value: ${JSON.stringify(one)} is not.`);
13926
+ }
13927
+ answers[one.slice(0, equals)] = one.slice(equals + 1);
13928
+ }
13929
+ return answers;
13930
+ }
13931
+ function formFrom(file) {
13932
+ let text;
13933
+ try {
13934
+ text = readFileSync7(file, "utf8");
13935
+ } catch (error) {
13936
+ throw new Error(`--form ${file} could not be read: ${error instanceof Error ? error.message : String(error)}`);
13937
+ }
13938
+ try {
13939
+ return JSON.parse(text);
13940
+ } catch {
13941
+ throw new Error(`--form ${file} is not JSON. It is an array of fields: [{"key": "model", "label": "Which model are you?", "kind": "choice", "choices": ["claude", "codex"], "required": true}].`);
13942
+ }
13943
+ }
13944
+ function roleLine(role) {
13945
+ return `${String(role["name"])} (${role["seats"] === null ? "any number" : `${String(role["seats"])} seat${role["seats"] === 1 ? "" : "s"}`}, ${String(role["onDelete"])} at a delete)`;
13946
+ }
13947
+ function memberLine(member) {
13948
+ const held = member.holder === null ? "vacant" : member.holder === "outside" ? "held outside agental" : member.sandboxId ? `held by ${member.sandboxId}` : "held by a sandbox";
13949
+ return `${member.id} ${member.name}, ${member.role}, ${held}
13950
+ `;
13951
+ }
13952
+ async function memberNamed2(client, guild2, given) {
13953
+ const members2 = (await ask11(client, "GET", `${at4(guild2)}/members`))["members"] ?? [];
13954
+ const found = members2.find((member) => member.id === given) ?? members2.find((member) => member.name.toLowerCase() === given.toLowerCase());
13955
+ if (!found) {
13956
+ throw new Error(`Guild ${guild2} has no identity ${JSON.stringify(given)}. agental guild members ${guild2} lists them.`);
13957
+ }
13958
+ return found;
13959
+ }
13960
+ async function guild(client, positionals, options) {
13961
+ const [verb = client.onToken ? "mine" : "list", name, third, fourth] = positionals;
13962
+ switch (verb) {
13963
+ case "list": {
13964
+ const listed2 = (await ask11(client, "GET", "/v1/guilds"))["guilds"] ?? [];
13965
+ print4(options.json, listed2, listed2.length === 0 ? "No guilds. agental guild create <name> --roles <role,...> makes one.\n" : listed2.map((one) => `${String(one["name"])} ${one["roles"].map((role) => String(role["name"])).join(", ")}
13966
+ `).join(""));
13967
+ return;
13968
+ }
13969
+ case "show": {
13970
+ const found = await ask11(client, "GET", at4(needed(name, "show takes a guild")));
13971
+ const members2 = (await ask11(client, "GET", `${at4(String(found["name"]))}/members`))["members"] ?? [];
13972
+ const words2 = [
13973
+ `${String(found["name"])}
13974
+ `,
13975
+ found["brief"] ? ` ${String(found["brief"])}
13976
+ ` : "",
13977
+ `roles
13978
+ ${found["roles"].map((role) => ` ${roleLine(role)}
13979
+ `).join("")}`,
13980
+ found["form"].length ? `form
13981
+ ${found["form"].map((field) => ` ${String(field["key"])}: ${String(field["label"])}${field["required"] ? " (required)" : ""}
13982
+ `).join("")}` : "",
13983
+ `templates
13984
+ ${found["templates"].map((one) => ` ${String(one["templateId"])}${one["roles"] ? ` as ${one["roles"].join(", ")}` : ", any role"}
13985
+ `).join("") || " none\n"}`,
13986
+ `identities
13987
+ ${members2.map((member) => ` ${memberLine(member)}`).join("") || " none\n"}`
13988
+ ].join("");
13989
+ print4(options.json, { ...found, members: members2 }, words2);
13990
+ return;
13991
+ }
13992
+ case "create": {
13993
+ const body = {
13994
+ name: needed(name, "create takes a guild's name"),
13995
+ roles: rolesOf(needed(options.roles, 'create takes --roles, such as "blog manager:1,reviewer:2"')),
13996
+ ...options.brief === void 0 ? {} : { brief: options.brief },
13997
+ ...options.form === void 0 ? {} : { form: formFrom(options.form) }
13998
+ };
13999
+ const made = await ask11(client, "POST", "/v1/guilds", body);
14000
+ print4(options.json, made, `Made guild ${String(made["name"])}. agental guild attach ${String(made["name"])} <template> lets that template's sandboxes join it.
14001
+ `);
14002
+ return;
14003
+ }
14004
+ case "delete": {
14005
+ const guildName = needed(name, "delete takes a guild");
14006
+ if (!options.yes && !await client.confirmed(`Delete guild ${guildName} and every identity in it, for good? [y/N] `)) {
14007
+ throw new Error(`Nothing was deleted. agental guild delete ${guildName} --yes deletes it without asking.`);
14008
+ }
14009
+ await ask11(client, "DELETE", at4(guildName));
14010
+ print4(options.json, { deleted: name }, `Deleted guild ${String(name)}, with its identities.
14011
+ `);
14012
+ return;
14013
+ }
14014
+ case "attach": {
14015
+ const template2 = await client.templateId(needed(third, "attach takes a guild and a template"));
14016
+ const roles = options.roles === void 0 ? {} : { roles: rolesOf(options.roles).map((role) => role.name) };
14017
+ const attached = await ask11(client, "PUT", `${at4(needed(name, "attach takes a guild"))}/templates/${encodeURIComponent(template2)}`, roles);
14018
+ print4(options.json, attached, `Sandboxes of ${template2} may join ${String(name)}${attached["roles"] ? ` as ${attached["roles"].join(" or ")}` : ", in any role"}.
14019
+ `);
14020
+ return;
14021
+ }
14022
+ case "detach": {
14023
+ const template2 = await client.templateId(needed(third, "detach takes a guild and a template"));
14024
+ await ask11(client, "DELETE", `${at4(needed(name, "detach takes a guild"))}/templates/${encodeURIComponent(template2)}`);
14025
+ print4(options.json, { detached: template2 }, `Sandboxes of ${template2} may no longer join ${String(name)}.
14026
+ `);
14027
+ return;
14028
+ }
14029
+ case "mine": {
14030
+ const mine = (await ask11(client, "GET", "/v1/guilds/mine"))["guilds"] ?? [];
14031
+ const words2 = mine.map((one) => {
14032
+ const found = one["guild"];
14033
+ const open = one["rolesOpen"] === null ? "any role" : one["rolesOpen"].join(", ") || "none";
14034
+ const held = one["held"].map((member) => ` you are ${member.name}, ${member.role} (${member.id})
14035
+ `).join("");
14036
+ return `${String(found["name"])} open to you: ${open}
14037
+ ${held}`;
14038
+ }).join("");
14039
+ print4(options.json, mine, words2 || "No guild: this sandbox's template is attached to none, and it holds no identity.\n");
14040
+ return;
14041
+ }
14042
+ case "join": {
14043
+ const joined = await ask11(client, "POST", `${at4(needed(name, "join takes a guild"))}/members`, {
14044
+ name: needed(options.as, "join takes --as <the name you will be known by>"),
14045
+ role: needed(options.role, "join takes --role <one of the guild's roles>"),
14046
+ ...options.answer === void 0 ? {} : { answers: answersOf(options.answer) }
14047
+ });
14048
+ print4(options.json, joined, `You are ${String(joined["name"])}, ${String(joined["role"])} of ${String(name)} (${String(joined["id"])}).
14049
+ `);
14050
+ return;
14051
+ }
14052
+ case "members": {
14053
+ const members2 = (await ask11(client, "GET", `${at4(needed(name, "members takes a guild"))}/members`))["members"] ?? [];
14054
+ print4(options.json, members2, members2.map(memberLine).join("") || "No identities yet.\n");
14055
+ return;
14056
+ }
14057
+ case "leave": {
14058
+ const guildName = needed(name, "leave takes a guild and an identity");
14059
+ const member = await memberNamed2(client, guildName, needed(third, "leave takes a guild and an identity"));
14060
+ await ask11(client, "DELETE", `${at4(guildName)}/members/${encodeURIComponent(member.id)}`);
14061
+ print4(options.json, { left: member.id }, `${member.name} has left ${guildName}; the name and its seat are free.
14062
+ `);
14063
+ return;
14064
+ }
14065
+ case "handover": {
14066
+ const guildName = needed(name, "handover takes a guild, an identity and a sandbox");
14067
+ const member = await memberNamed2(client, guildName, needed(third, "handover takes a guild, an identity and a sandbox"));
14068
+ const sandbox = await ask11(client, "GET", `/v1/sandboxes/${encodeURIComponent(needed(fourth, "handover takes a sandbox"))}`);
14069
+ const handed = await ask11(client, "POST", `${at4(guildName)}/members/${encodeURIComponent(member.id)}/handover`, { sandboxId: String(sandbox["id"]) });
14070
+ print4(options.json, handed, `${member.name} is held by ${String(sandbox["name"] ?? sandbox["id"])} now.
14071
+ `);
14072
+ return;
14073
+ }
14074
+ default:
14075
+ throw new Error(USAGE9);
14076
+ }
14077
+ }
14078
+
14079
+ // ../src/cli-subscriptions.ts
14080
+ var AGENTS = ["claude", "codex", "copilot", "grok"];
14081
+ var USES = ["off", "subscription", "api_key"];
14082
+ var CLAUDE_TOKEN_HOST = "platform.claude.com";
14083
+ var USAGE10 = "subscriptions takes list, sign-in <agent> or delete <agent>; agents takes --template or --sandbox, and <agent> <off|subscription|api_key>. agental subscriptions --help shows each.";
14084
+ async function subscriptions(client, positionals, options) {
14085
+ const [verb, agent] = positionals;
14086
+ switch (verb) {
14087
+ case void 0:
14088
+ case "list":
14089
+ return await list4(client, options);
14090
+ case "sign-in":
14091
+ return await signIn(client, agentOf2(agent), options);
14092
+ case "delete":
14093
+ return await remove3(client, agentOf2(agent), options);
14094
+ default:
14095
+ throw new Error(`agental subscriptions ${verb} is not a command. ${USAGE10}`);
14096
+ }
14097
+ }
14098
+ async function agents(client, positionals, options) {
14099
+ if (options.template === void 0 === (options.sandbox === void 0)) {
14100
+ throw new Error("agents takes --template <template> or --sandbox <sandbox-id>, one of them.");
14101
+ }
14102
+ const path6 = options.template !== void 0 ? `/v1/templates/${encodeURIComponent(await client.templateId(options.template))}` : `/v1/sandboxes/${encodeURIComponent(options.sandbox ?? "")}`;
14103
+ const [agent, use2] = positionals;
14104
+ let choices;
14105
+ if (agent === void 0) {
14106
+ choices = (await answer4(client, `${path6}/agents`, { method: "GET" })).agents;
14107
+ } else {
14108
+ const allowed = options.sandbox !== void 0 ? [...USES, "template"] : USES;
14109
+ if (use2 === void 0 || !allowed.includes(use2)) {
14110
+ throw new Error(`agents ${agent} takes one of ${allowed.join(", ")}.`);
14111
+ }
14112
+ choices = (await answer4(client, `${path6}/agents/${agentOf2(agent)}`, { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ use: use2 }) })).agents;
14113
+ }
14114
+ if (options.json) {
14115
+ process.stdout.write(`${JSON.stringify({ agents: choices }, null, 2)}
14116
+ `);
14117
+ return;
14118
+ }
14119
+ for (const c of choices) {
14120
+ const where = c.use === "api_key" && c.kept === "variable" ? ` (its own variable ${c.secret ?? ""})` : c.secret ? ` (${c.secret})` : "";
14121
+ const from = options.sandbox !== void 0 ? ` ${c.from === "sandbox" ? "set on the sandbox" : "from its template"}` : "";
14122
+ process.stdout.write(`${c.agent} ${c.use}${where}${c.signedOut ? " signed out: sign in again" : ""}${from}
14123
+ `);
14124
+ }
14125
+ }
14126
+ async function list4(client, options) {
14127
+ const { subscriptions: all } = await answer4(client, "/v1/subscriptions", { method: "GET" });
14128
+ if (options.json) {
14129
+ process.stdout.write(`${JSON.stringify({ subscriptions: all }, null, 2)}
14130
+ `);
14131
+ return;
14132
+ }
14133
+ for (const s of all) {
14134
+ process.stdout.write(`${s.agent} ${s.state.replace("_", " ")}${s.account?.plan ? ` ${s.account.plan}` : ""}${s.why ? ` ${s.why}` : ""}
14135
+ `);
14136
+ }
14137
+ }
14138
+ async function signIn(client, agent, options) {
14139
+ let now = await answer4(client, `/v1/subscriptions/${agent}/sign-in`, { method: "POST" });
14140
+ const shown = now.signIn;
14141
+ if (shown === null) {
14142
+ throw new Error("The sign-in was not begun: the API showed nothing to approve.");
14143
+ }
14144
+ if (shown.authorizeUrl !== null) {
14145
+ process.stderr.write(`Open this page, sign in to Claude, and copy the code it shows:
14146
+ ${shown.authorizeUrl}
14147
+ `);
14148
+ const code = (await client.readValue("Paste the code: ")).trim();
14149
+ if (!code.includes("#")) {
14150
+ throw new Error("Paste the whole code the page shows, with the part after its #. Nothing was sent.");
14151
+ }
14152
+ const { sealed } = await sealForAccount(client, now.secret, code, [CLAUDE_TOKEN_HOST], "sign-in-code");
14153
+ now = await answer4(client, `/v1/subscriptions/${agent}/code`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ sealed: sealed[0] }) });
14154
+ } else {
14155
+ process.stderr.write(`Open ${shown.verificationUrl ?? ""} and enter the code ${shown.userCode ?? ""} (good until ${shown.expiresAt}). Waiting for it\u2026
14156
+ `);
14157
+ const until2 = Date.parse(shown.expiresAt) + 6e4;
14158
+ while (now.state === "signing_in" && Date.now() < until2) {
14159
+ await new Promise((resolve) => setTimeout(resolve, options.intervalMs ?? 5e3));
14160
+ now = await answer4(client, `/v1/subscriptions/${agent}`, { method: "GET" });
14161
+ }
14162
+ }
14163
+ if (options.json) {
14164
+ process.stdout.write(`${JSON.stringify(now, null, 2)}
14165
+ `);
14166
+ } else if (now.state === "signed_in") {
14167
+ process.stdout.write(`Signed in to ${agent}${now.account?.plan ? ` (${now.account.plan})` : ""}. Kept sealed as ${now.secret}; a template uses it with: agental agents --template <template> ${agent} subscription
14168
+ `);
14169
+ } else {
14170
+ process.stdout.write(`Not signed in to ${agent}${now.why ? `: ${now.why}` : ""}.
14171
+ `);
14172
+ }
14173
+ if (now.state !== "signed_in") {
14174
+ process.exitCode = 1;
14175
+ }
14176
+ }
14177
+ async function remove3(client, agent, options) {
14178
+ if (!options.yes && !await client.confirmed(`Delete the ${agent} subscription, and take it off every template and sandbox that uses it?`)) {
14179
+ process.stdout.write("Nothing was deleted.\n");
14180
+ return;
14181
+ }
14182
+ const after = await answer4(client, `/v1/subscriptions/${agent}`, { method: "DELETE" });
14183
+ if (options.json) {
14184
+ process.stdout.write(`${JSON.stringify(after, null, 2)}
14185
+ `);
14186
+ return;
14187
+ }
14188
+ process.stdout.write(`Deleted here. To end it on ${agent}'s side too: ${after.revokeAt}
14189
+ `);
14190
+ }
14191
+ function agentOf2(given) {
14192
+ if (given === void 0 || !AGENTS.includes(given)) {
14193
+ throw new Error(`Name the agent: ${AGENTS.join(", ")}.`);
14194
+ }
14195
+ return given;
14196
+ }
14197
+ async function answer4(client, path6, init) {
14198
+ const res = await client.request(path6, init);
14199
+ const body = await res.json().catch(() => null);
14200
+ if (!res.ok) {
14201
+ client.fail(res.status, body);
14202
+ }
14203
+ return body;
14204
+ }
14205
+
13656
14206
  // ../src/cli-sites.ts
13657
- var USAGE9 = "site takes a sandbox, or list, add, rm, stats or analytics, then the sandbox. agental site --help shows each.";
14207
+ var USAGE11 = "site takes a sandbox, or list, add, rm, stats or analytics, then the sandbox. agental site --help shows each.";
13658
14208
  var ANALYTICS_USAGE = "site analytics takes on or off, then the sandbox and the site's id, or org, with on or off to change it.";
13659
14209
  var REPORT_ROWS = 5;
13660
14210
  async function bodyOf2(response) {
@@ -13664,7 +14214,7 @@ async function bodyOf2(response) {
13664
14214
  return null;
13665
14215
  }
13666
14216
  }
13667
- async function ask11(client, method, pathname, body) {
14217
+ async function ask12(client, method, pathname, body) {
13668
14218
  const response = await client.request(pathname, { method, ...body === void 0 ? {} : { body: JSON.stringify(body) } });
13669
14219
  const answered = await bodyOf2(response);
13670
14220
  if (!response.ok) {
@@ -13680,7 +14230,7 @@ function routeOf(body) {
13680
14230
  }
13681
14231
  var isSite = (route) => route.public && !route.hidden;
13682
14232
  async function sitesOf(client, sandbox) {
13683
- const body = await ask11(client, "GET", `/v1/sandboxes/${encodeURIComponent(sandbox)}/host`);
14233
+ const body = await ask12(client, "GET", `/v1/sandboxes/${encodeURIComponent(sandbox)}/host`);
13684
14234
  return (Array.isArray(body?.routes) ? body.routes : []).map(routeOf).filter(isSite);
13685
14235
  }
13686
14236
  function stateOf4(route) {
@@ -13765,7 +14315,7 @@ async function siteSwitch(client, turn, words2, options) {
13765
14315
  process.exitCode = 1;
13766
14316
  return;
13767
14317
  }
13768
- const report = await ask11(client, "PUT", `/v1/host-routes/${encodeURIComponent(target)}/analytics`, { enabled: turn === "on" });
14318
+ const report = await ask12(client, "PUT", `/v1/host-routes/${encodeURIComponent(target)}/analytics`, { enabled: turn === "on" });
13769
14319
  if (options.json) {
13770
14320
  process.stdout.write(`${reportJson(report)}
13771
14321
  `);
@@ -13791,7 +14341,7 @@ async function organizationSwitch(client, words2, options) {
13791
14341
  }
13792
14342
  let setting;
13793
14343
  if (turn === void 0) {
13794
- setting = await ask11(client, "GET", "/v1/site-analytics");
14344
+ setting = await ask12(client, "GET", "/v1/site-analytics");
13795
14345
  } else {
13796
14346
  if (turn === "off" && !options.yes && !await client.confirmed("Turn site analytics off for this organization? Every site's figures are deleted now and cannot be brought back.")) {
13797
14347
  process.stderr.write("Nothing was changed. --yes goes on without asking.\n");
@@ -13843,13 +14393,13 @@ async function site(client, positionals, options) {
13843
14393
  const verb = positionals[0] === "list" || positionals[0] === "add" || positionals[0] === "rm" || positionals[0] === "stats" ? positionals[0] : null;
13844
14394
  const [sandbox, target, ...rest] = verb === null ? positionals : positionals.slice(1);
13845
14395
  if (sandbox === void 0) {
13846
- throw new Error(USAGE9);
14396
+ throw new Error(USAGE11);
13847
14397
  }
13848
14398
  switch (verb) {
13849
14399
  case null:
13850
14400
  case "list": {
13851
14401
  if (target !== void 0) {
13852
- throw new Error(USAGE9);
14402
+ throw new Error(USAGE11);
13853
14403
  }
13854
14404
  const sites = await sitesOf(client, sandbox);
13855
14405
  if (options.json) {
@@ -13869,10 +14419,10 @@ async function site(client, positionals, options) {
13869
14419
  }
13870
14420
  case "add": {
13871
14421
  if (rest.length > 0) {
13872
- throw new Error(USAGE9);
14422
+ throw new Error(USAGE11);
13873
14423
  }
13874
14424
  const port = portFrom(target);
13875
- const made = routeOf(await ask11(client, "POST", `/v1/sandboxes/${encodeURIComponent(sandbox)}/host`, { port, title: `port-${port}`, public: true }));
14425
+ const made = routeOf(await ask12(client, "POST", `/v1/sandboxes/${encodeURIComponent(sandbox)}/host`, { port, title: `port-${port}`, public: true }));
13876
14426
  if (options.json) {
13877
14427
  process.stdout.write(`${JSON.stringify(made, null, 2)}
13878
14428
  `);
@@ -13897,7 +14447,7 @@ async function site(client, positionals, options) {
13897
14447
  throw new Error(`site rm needs the sandbox and the site's id, as agental site ${sandbox} lists them.`);
13898
14448
  }
13899
14449
  const found = await siteOn(client, sandbox, target);
13900
- await ask11(client, "POST", `/v1/host-routes/${encodeURIComponent(target)}/hide`);
14450
+ await ask12(client, "POST", `/v1/host-routes/${encodeURIComponent(target)}/hide`);
13901
14451
  process.stdout.write(`Removed. ${found.url ?? `Port ${found.port}`} stops working now; adding port ${found.port} again gives a new link.
13902
14452
  `);
13903
14453
  return;
@@ -13911,7 +14461,7 @@ async function site(client, positionals, options) {
13911
14461
  throw new Error(`--range is 24h or 7d. It was given ${range}.`);
13912
14462
  }
13913
14463
  await siteOn(client, sandbox, target);
13914
- const report = await ask11(client, "GET", `/v1/host-routes/${encodeURIComponent(target)}/analytics?range=${range}`);
14464
+ const report = await ask12(client, "GET", `/v1/host-routes/${encodeURIComponent(target)}/analytics?range=${range}`);
13915
14465
  process.stdout.write(options.json ? `${reportJson(report)}
13916
14466
  ` : reportIn(report, sandbox, target));
13917
14467
  return;
@@ -13920,10 +14470,10 @@ async function site(client, positionals, options) {
13920
14470
  }
13921
14471
 
13922
14472
  // ../src/cli-claude.ts
13923
- var USAGE10 = "claude takes connect, show, update or disconnect. agental claude --help shows each.";
14473
+ var USAGE12 = "claude takes connect, show, update or disconnect. agental claude --help shows each.";
13924
14474
  var KEY_VARIABLE = "ANTHROPIC_ENVIRONMENT_KEY";
13925
14475
  var SECRET_VARIABLE = "ANTHROPIC_WEBHOOK_SIGNING_KEY";
13926
- async function ask12(client, method, pathname, body) {
14476
+ async function ask13(client, method, pathname, body) {
13927
14477
  const response = await client.request(pathname, { method, ...body === void 0 ? {} : { body: JSON.stringify(body) } });
13928
14478
  let answered = null;
13929
14479
  if (response.status !== 204) {
@@ -14005,15 +14555,15 @@ async function hidden(question) {
14005
14555
  const muted = lines;
14006
14556
  process.stderr.write(question);
14007
14557
  muted._writeToOutput = () => void 0;
14008
- lines.question("", (answer4) => {
14558
+ lines.question("", (answer6) => {
14009
14559
  lines.close();
14010
14560
  process.stderr.write("\n");
14011
- resolve(answer4.trim());
14561
+ resolve(answer6.trim());
14012
14562
  });
14013
14563
  });
14014
14564
  }
14015
14565
  async function listClaude(client, asJson) {
14016
- const body = await ask12(client, "GET", "/v1/claude/connections");
14566
+ const body = await ask13(client, "GET", "/v1/claude/connections");
14017
14567
  if (asJson) {
14018
14568
  process.stdout.write(`${JSON.stringify(body, null, 2)}
14019
14569
  `);
@@ -14035,7 +14585,7 @@ async function listClaude(client, asJson) {
14035
14585
  async function claude(client, positionals, options) {
14036
14586
  const [what, target, ...rest] = positionals;
14037
14587
  if (rest.length > 0) {
14038
- throw new Error(USAGE10);
14588
+ throw new Error(USAGE12);
14039
14589
  }
14040
14590
  switch (what) {
14041
14591
  case "connect": {
@@ -14047,7 +14597,7 @@ async function claude(client, positionals, options) {
14047
14597
  const environmentKey = await secretFrom(KEY_VARIABLE, "environment key", true);
14048
14598
  const webhookSecret = await secretFrom(SECRET_VARIABLE, "webhook signing secret", false);
14049
14599
  const made = connectionOf(
14050
- await ask12(client, "POST", "/v1/claude/connections", {
14600
+ await ask13(client, "POST", "/v1/claude/connections", {
14051
14601
  environmentId: target,
14052
14602
  environmentKey,
14053
14603
  ...webhookSecret !== void 0 ? { webhookSecret } : {},
@@ -14069,7 +14619,7 @@ async function claude(client, positionals, options) {
14069
14619
  return;
14070
14620
  }
14071
14621
  case "show": {
14072
- const found = connectionOf(await ask12(client, "GET", `/v1/claude/connections/${encodeURIComponent(needId2(target, "show"))}`));
14622
+ const found = connectionOf(await ask13(client, "GET", `/v1/claude/connections/${encodeURIComponent(needId2(target, "show"))}`));
14073
14623
  process.stdout.write(options.json ? `${JSON.stringify(found, null, 2)}
14074
14624
  ` : describe6(found));
14075
14625
  return;
@@ -14092,18 +14642,18 @@ async function claude(client, positionals, options) {
14092
14642
  if (Object.keys(patch).length === 0) {
14093
14643
  throw new Error("claude update changes --template, --keep-days, --new-key, --webhook-secret or --no-webhook-secret, and was given none of them.");
14094
14644
  }
14095
- const updated = connectionOf(await ask12(client, "PATCH", `/v1/claude/connections/${encodeURIComponent(id)}`, patch));
14645
+ const updated = connectionOf(await ask13(client, "PATCH", `/v1/claude/connections/${encodeURIComponent(id)}`, patch));
14096
14646
  process.stdout.write(options.json ? `${JSON.stringify(updated, null, 2)}
14097
14647
  ` : describe6(updated));
14098
14648
  return;
14099
14649
  }
14100
14650
  case "disconnect": {
14101
- await ask12(client, "DELETE", `/v1/claude/connections/${encodeURIComponent(needId2(target, "disconnect"))}`);
14651
+ await ask13(client, "DELETE", `/v1/claude/connections/${encodeURIComponent(needId2(target, "disconnect"))}`);
14102
14652
  process.stdout.write("Disconnected: its key and signing secret are forgotten, and no more of its work is claimed. Its sessions' sandboxes are left as they are.\n");
14103
14653
  return;
14104
14654
  }
14105
14655
  default:
14106
- throw new Error(USAGE10);
14656
+ throw new Error(USAGE12);
14107
14657
  }
14108
14658
  }
14109
14659
  function needId2(id, what) {
@@ -14154,7 +14704,7 @@ function whyClosed(code, reason2, error) {
14154
14704
  return `The terminal was closed (${code})${said ? `: ${said}` : ""}.`;
14155
14705
  }
14156
14706
  }
14157
- async function answer3(response) {
14707
+ async function answer5(response) {
14158
14708
  const body = await response.json().catch(() => null);
14159
14709
  if (!response.ok) {
14160
14710
  const error = body?.error;
@@ -14163,7 +14713,7 @@ async function answer3(response) {
14163
14713
  return body;
14164
14714
  }
14165
14715
  async function keptShells2(client, id) {
14166
- const body = await answer3(await client.request(`/v1/sandboxes/${encodeURIComponent(id)}/terminals`, { method: "GET" }));
14716
+ const body = await answer5(await client.request(`/v1/sandboxes/${encodeURIComponent(id)}/terminals`, { method: "GET" }));
14167
14717
  if (!body || !Array.isArray(body.terminals)) {
14168
14718
  throw new Error("The list of kept shells was missing terminals.");
14169
14719
  }
@@ -14217,7 +14767,7 @@ async function listShells(client, id, json3, stdout) {
14217
14767
  }
14218
14768
  async function closeShell(client, id, given, stdout) {
14219
14769
  const found = await shellNamed(client, id, given, "--close");
14220
- await answer3(await client.request(`/v1/sandboxes/${encodeURIComponent(id)}/terminals/${encodeURIComponent(found.id)}`, { method: "DELETE" }));
14770
+ await answer5(await client.request(`/v1/sandboxes/${encodeURIComponent(id)}/terminals/${encodeURIComponent(found.id)}`, { method: "DELETE" }));
14221
14771
  stdout.write(`Closed ${found.n === null ? "shell" : `shell ${found.n}`} (${found.id}).
14222
14772
  `);
14223
14773
  }
@@ -14260,16 +14810,16 @@ async function shell(client, id, options = {}, streams = process) {
14260
14810
  const verifier = randomBytes4(32).toString("base64url");
14261
14811
  const challenge = createHash3("sha256").update(verifier).digest("base64url");
14262
14812
  const interactive = stdin.isTTY === true && typeof stdin.setRawMode === "function";
14263
- const ask13 = async (keep) => await client.request(`/v1/sandboxes/${encodeURIComponent(id)}/terminal`, {
14813
+ const ask14 = async (keep) => await client.request(`/v1/sandboxes/${encodeURIComponent(id)}/terminal`, {
14264
14814
  method: "POST",
14265
14815
  body: JSON.stringify({ ...size2, challenge, ...again ? { terminal: again.id } : keep ? { keep: true } : {} })
14266
14816
  });
14267
- let response = await ask13(interactive);
14817
+ let response = await ask14(interactive);
14268
14818
  let body = await response.json().catch(() => null);
14269
14819
  if (!again && interactive && response.status === 409 && body?.error?.code === "terminal_unavailable" && /keeps \d+ terminals/.test(String(body.error.message ?? ""))) {
14270
14820
  stderr.write(`${String(body.error.message)} This one is not kept.
14271
14821
  `);
14272
- response = await ask13(false);
14822
+ response = await ask14(false);
14273
14823
  body = await response.json().catch(() => null);
14274
14824
  }
14275
14825
  if (!response.ok || typeof body?.ticket !== "string") {
@@ -14289,8 +14839,8 @@ async function shell(client, id, options = {}, streams = process) {
14289
14839
  if (socket.readyState !== WebSocket.OPEN || chunk.length === 0) {
14290
14840
  return;
14291
14841
  }
14292
- for (let at4 = 0; at4 < chunk.length; at4 += MAX_INPUT_BYTES) {
14293
- socket.send(chunk.subarray(at4, at4 + MAX_INPUT_BYTES));
14842
+ for (let at5 = 0; at5 < chunk.length; at5 += MAX_INPUT_BYTES) {
14843
+ socket.send(chunk.subarray(at5, at5 + MAX_INPUT_BYTES));
14294
14844
  }
14295
14845
  lastSent = chunk[chunk.length - 1];
14296
14846
  };
@@ -14298,16 +14848,16 @@ async function shell(client, id, options = {}, streams = process) {
14298
14848
  let closedHere = false;
14299
14849
  let detached = false;
14300
14850
  const escaped = (chunk) => {
14301
- const out = [];
14851
+ const out2 = [];
14302
14852
  for (const byte of chunk) {
14303
- const before = out.length > 0 ? out[out.length - 1] : lastSent;
14853
+ const before = out2.length > 0 ? out2[out2.length - 1] : lastSent;
14304
14854
  const atLineStart = before === 13 || before === 10;
14305
14855
  if (tilde) {
14306
14856
  tilde = false;
14307
14857
  if (byte === 46) {
14308
14858
  closedHere = true;
14309
14859
  socket.close(1e3, "closed");
14310
- return Buffer.from(out);
14860
+ return Buffer.from(out2);
14311
14861
  }
14312
14862
  if (byte === 100) {
14313
14863
  if (kept2 === null) {
@@ -14316,19 +14866,19 @@ async function shell(client, id, options = {}, streams = process) {
14316
14866
  }
14317
14867
  detached = true;
14318
14868
  socket.close(1e3, "detached");
14319
- return Buffer.from(out);
14869
+ return Buffer.from(out2);
14320
14870
  }
14321
- out.push(126);
14871
+ out2.push(126);
14322
14872
  if (byte !== 126) {
14323
- out.push(byte);
14873
+ out2.push(byte);
14324
14874
  }
14325
14875
  } else if (byte === 126 && atLineStart) {
14326
14876
  tilde = true;
14327
14877
  } else {
14328
- out.push(byte);
14878
+ out2.push(byte);
14329
14879
  }
14330
14880
  }
14331
- return Buffer.from(out);
14881
+ return Buffer.from(out2);
14332
14882
  };
14333
14883
  const typed = (chunk) => {
14334
14884
  const bytes4 = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
@@ -14524,11 +15074,11 @@ function whereQuery(text, query = new URLSearchParams()) {
14524
15074
  for (const word of words(text)) {
14525
15075
  const time = /^(made|stopped)([<>])(.+)$/.exec(word);
14526
15076
  if (time) {
14527
- const [, what, side, at4] = time;
15077
+ const [, what, side, at5] = time;
14528
15078
  if (what === "made") {
14529
- query.append(side === ">" ? "createdAfter" : "createdBefore", at4);
15079
+ query.append(side === ">" ? "createdAfter" : "createdBefore", at5);
14530
15080
  } else if (side === "<") {
14531
- query.append("stoppedBefore", at4);
15081
+ query.append("stoppedBefore", at5);
14532
15082
  } else {
14533
15083
  throw new Error(`${word}: stopped takes < only, for sandboxes stopped before a time.`);
14534
15084
  }
@@ -14886,6 +15436,13 @@ async function main() {
14886
15436
  "allow-from": { type: "string", multiple: true },
14887
15437
  // Tags as a sandbox or template is made with them, or as list finds them: given again, or with commas, for several. --tags is the same.
14888
15438
  tag: { type: "string", multiple: true },
15439
+ // Tailscale (src/cli-tailscale.ts): the OAuth client's id, a node's routes, exit node, address and name, and a create's tags.
15440
+ "client-id": { type: "string" },
15441
+ accept: { type: "string", multiple: true },
15442
+ "exit-node": { type: "string" },
15443
+ "keep-address": { type: "boolean" },
15444
+ "node-name": { type: "string" },
15445
+ tailnet: { type: "string" },
14889
15446
  tags: { type: "string", multiple: true },
14890
15447
  // Metadata as <key>=<value>, given again for each key.
14891
15448
  meta: { type: "string", multiple: true },
@@ -14903,6 +15460,12 @@ async function main() {
14903
15460
  informed: { type: "boolean", default: false },
14904
15461
  sort: { type: "string" },
14905
15462
  role: { type: "string" },
15463
+ // Guilds: the roles of a create or an attach, its brief and form, and who joins with what answers.
15464
+ roles: { type: "string" },
15465
+ brief: { type: "string" },
15466
+ form: { type: "string" },
15467
+ as: { type: "string" },
15468
+ answer: { type: "string", multiple: true },
14906
15469
  "revoke-keys": { type: "boolean", default: false },
14907
15470
  // agental list in a terminal: every column, as piped.
14908
15471
  wide: { type: "boolean", default: false },
@@ -14927,7 +15490,7 @@ async function main() {
14927
15490
  await create({ ...values, template: once(values.template, "--template") });
14928
15491
  return;
14929
15492
  case "list":
14930
- await list4(values.json, whereQuery(values.where ?? "", labelsFilter(values)), values.sort, values.limit, values.wide);
15493
+ await list5(values.json, whereQuery(values.where ?? "", labelsFilter(values)), values.sort, values.limit, values.wide);
14931
15494
  return;
14932
15495
  case "bulk-actions":
14933
15496
  await bulkActionsCommand(positionals.slice(1), values.json);
@@ -14963,7 +15526,7 @@ async function main() {
14963
15526
  await bulk("delete", whereQuery(values.where, labelsFilter(values)), {}, values.yes === true, values.json, values.confirm);
14964
15527
  return;
14965
15528
  }
14966
- await remove3(positionals[1], values["pause-jobs"] === true);
15529
+ await remove4(positionals[1], values["pause-jobs"] === true);
14967
15530
  return;
14968
15531
  case "start":
14969
15532
  if (values.where !== void 0) {
@@ -15050,6 +15613,40 @@ async function main() {
15050
15613
  case "egress":
15051
15614
  await egress(positionals.slice(1), values);
15052
15615
  return;
15616
+ case "tailscale":
15617
+ await tailscale(tailscaleClient(), positionals.slice(1), tailnetFlags(values));
15618
+ return;
15619
+ case "guild":
15620
+ case "guilds": {
15621
+ const token = guildTokenHere(DEFAULT_URL);
15622
+ if (token !== null) {
15623
+ process.env["AGENTAL_API_KEY"] = token;
15624
+ }
15625
+ await guild(
15626
+ { request, fail, confirmed, templateId: async (given) => (await templateNamed(given)).id, onToken: token !== null },
15627
+ positionals.slice(1),
15628
+ {
15629
+ json: values.json,
15630
+ yes: values.yes,
15631
+ ...values.roles === void 0 ? {} : { roles: values.roles },
15632
+ ...values.role === void 0 ? {} : { role: values.role },
15633
+ ...values.brief === void 0 ? {} : { brief: values.brief },
15634
+ ...values.form === void 0 ? {} : { form: values.form },
15635
+ ...values.as === void 0 ? {} : { as: values.as },
15636
+ ...values.answer === void 0 ? {} : { answer: values.answer }
15637
+ }
15638
+ );
15639
+ return;
15640
+ }
15641
+ case "subscriptions":
15642
+ await subscriptions(tailscaleClient(), positionals.slice(1), { json: values.json, yes: values.yes === true });
15643
+ return;
15644
+ case "agents":
15645
+ await agents(tailscaleClient(), positionals.slice(1), { json: values.json, yes: values.yes === true, ...once(values.template, "--template") === void 0 ? {} : { template: once(values.template, "--template") }, ...once(values.sandbox, "--sandbox") === void 0 ? {} : { sandbox: once(values.sandbox, "--sandbox") } });
15646
+ return;
15647
+ case "tailnet":
15648
+ await tailnet(tailscaleClient(), "sandbox", positionals.slice(1), tailnetFlags(values));
15649
+ return;
15053
15650
  case "spot":
15054
15651
  await spot(positionals.slice(1), values);
15055
15652
  return;
@@ -15201,6 +15798,12 @@ async function create(values) {
15201
15798
  }
15202
15799
  const allow = values.allow === void 0 ? void 0 : listedIn(values.allow);
15203
15800
  const egressAsked = values.egress === void 0 ? void 0 : egressFrom(values.egress.split(":"), "--egress takes box, or residential:<country>, as residential:de or residential:us:rotating.");
15801
+ const tailnetAsked = createTailnet(values.tailnet, {
15802
+ ...values.accept === void 0 ? {} : { accept: values.accept },
15803
+ ...values["exit-node"] === void 0 ? {} : { exitNode: values["exit-node"] },
15804
+ ...values["keep-address"] === void 0 ? {} : { keepAddress: values["keep-address"] },
15805
+ ...values["node-name"] === void 0 ? {} : { nodeName: values["node-name"] }
15806
+ });
15204
15807
  const sshKeys2 = values["ssh-key"] === void 0 ? void 0 : publicKeysFrom(values["ssh-key"]);
15205
15808
  const box = boxNamed(values.box);
15206
15809
  if (box !== void 0 && PUBLISHED) {
@@ -15219,6 +15822,7 @@ async function create(values) {
15219
15822
  ...regionsOption(values.region),
15220
15823
  ...allow ? { network: { allow } } : {},
15221
15824
  ...egressAsked ? { egress: egressAsked } : {},
15825
+ ...tailnetAsked === void 0 ? {} : { tailnet: tailnetAsked },
15222
15826
  ...ttlSeconds === void 0 ? {} : { ttlSeconds },
15223
15827
  ...onTimeout === void 0 ? {} : { onTimeout: onTimeout.replaceAll("-", "_") },
15224
15828
  ...spotAsked === void 0 ? {} : { spot: spotAsked },
@@ -15268,12 +15872,12 @@ function regionsOption(given) {
15268
15872
  const named = listedIn([given]);
15269
15873
  return named.length === 1 ? { region: named[0] } : { regions: named };
15270
15874
  }
15271
- async function sshKeys(id, keyId, remove4, json3) {
15875
+ async function sshKeys(id, keyId, remove5, json3) {
15272
15876
  if (!id) {
15273
15877
  throw new Error("ssh-keys requires <sandbox-id>");
15274
15878
  }
15275
15879
  const path6 = `/v1/sandboxes/${encodeURIComponent(id)}/ssh/keys`;
15276
- if (remove4) {
15880
+ if (remove5) {
15277
15881
  if (!keyId) {
15278
15882
  throw new Error("ssh-keys --remove requires <key-id>, as ssh-keys lists it");
15279
15883
  }
@@ -15299,7 +15903,7 @@ function publicKeysFrom(given) {
15299
15903
  const file = each.startsWith("~/") ? `${os7.homedir()}${each.slice(1)}` : each;
15300
15904
  let text;
15301
15905
  try {
15302
- text = readFileSync7(file, "utf8");
15906
+ text = readFileSync8(file, "utf8");
15303
15907
  } catch {
15304
15908
  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.`);
15305
15909
  }
@@ -15350,7 +15954,7 @@ async function regions(asJson) {
15350
15954
  }
15351
15955
  process.stdout.write("* where a sandbox is made when no region is named\n");
15352
15956
  }
15353
- async function list4(asJson, filter, sort, limit, wide = false) {
15957
+ async function list5(asJson, filter, sort, limit, wide = false) {
15354
15958
  const sandboxes2 = [];
15355
15959
  let cursor = null;
15356
15960
  do {
@@ -15476,6 +16080,21 @@ async function typedCount(count) {
15476
16080
  lines.close();
15477
16081
  }
15478
16082
  }
16083
+ function tailscaleClient() {
16084
+ return { request, fail, confirmed, readValue: hiddenValue, templateId: async (given) => (await templateNamed(given)).id };
16085
+ }
16086
+ function tailnetFlags(values) {
16087
+ return {
16088
+ json: values.json,
16089
+ yes: values.yes,
16090
+ ...values["client-id"] === void 0 ? {} : { clientId: values["client-id"] },
16091
+ ...values.tag === void 0 ? {} : { tag: values.tag },
16092
+ ...values.accept === void 0 ? {} : { accept: values.accept },
16093
+ ...values["exit-node"] === void 0 ? {} : { exitNode: values["exit-node"] },
16094
+ ...values["keep-address"] === void 0 ? {} : { keepAddress: values["keep-address"] },
16095
+ ...values["node-name"] === void 0 ? {} : { nodeName: values["node-name"] }
16096
+ };
16097
+ }
15479
16098
  async function hiddenValue(prompt) {
15480
16099
  if (!process.stdin.isTTY) {
15481
16100
  process.stderr.write(`${prompt.replace(/: $/, "")}: read from stdin
@@ -15650,7 +16269,7 @@ async function exec(positionals) {
15650
16269
  }
15651
16270
  process.exitCode = typeof record["exitCode"] === "number" ? record["exitCode"] : 1;
15652
16271
  }
15653
- async function remove3(id, pauseJobs) {
16272
+ async function remove4(id, pauseJobs) {
15654
16273
  if (!id) {
15655
16274
  throw new Error("delete requires <sandbox-id>");
15656
16275
  }
@@ -15732,11 +16351,11 @@ async function resize(id, size2, now, cancel, maxBurstFee, asJson) {
15732
16351
  const path6 = `/v1/sandboxes/${encodeURIComponent(id)}`;
15733
16352
  const before = await call2(path6, { method: "GET" });
15734
16353
  const name = before.name || id;
15735
- const print4 = (sandbox, line) => process.stdout.write(asJson ? `${JSON.stringify(sandbox, null, 2)}
16354
+ const print5 = (sandbox, line) => process.stdout.write(asJson ? `${JSON.stringify(sandbox, null, 2)}
15736
16355
  ` : `${line}
15737
16356
  `);
15738
16357
  if (cancel && !before.pendingSize) {
15739
- print4(before, `${name} has no size waiting: it stays a ${before.size}.`);
16358
+ print5(before, `${name} has no size waiting: it stays a ${before.size}.`);
15740
16359
  return;
15741
16360
  }
15742
16361
  const to = cancel ? before.size : size2;
@@ -15751,7 +16370,7 @@ async function resize(id, size2, now, cancel, maxBurstFee, asJson) {
15751
16370
  if (!response.ok) {
15752
16371
  if (cancel && response.status === 409 && isApiError(body) && body.error.code === "size_smaller") {
15753
16372
  const read2 = await call2(path6, { method: "GET" });
15754
- print4(read2, `${read2.name || id} is already a ${read2.size}; nothing was waiting.`);
16373
+ print5(read2, `${read2.name || id} is already a ${read2.size}; nothing was waiting.`);
15755
16374
  return;
15756
16375
  }
15757
16376
  fail(response.status, body);
@@ -15759,11 +16378,11 @@ async function resize(id, size2, now, cancel, maxBurstFee, asJson) {
15759
16378
  sayBurstFee(response);
15760
16379
  const after = body;
15761
16380
  if (restart && after.status !== "running") {
15762
- print4(after, `${name} is a ${after.size} now, but ${after.status ?? "not running"}, not running again${after.error ? `: ${after.error}` : ""}. agental start ${id} starts it.`);
16381
+ print5(after, `${name} is a ${after.size} now, but ${after.status ?? "not running"}, not running again${after.error ? `: ${after.error}` : ""}. agental start ${id} starts it.`);
15763
16382
  process.exitCode = 1;
15764
16383
  return;
15765
16384
  }
15766
- print4(
16385
+ print5(
15767
16386
  after,
15768
16387
  after.pendingSize ? `${name} becomes a ${after.pendingSize} at its next start; it runs as a ${after.size} until it is stopped.` : after.size === before.size ? `${name} stays a ${after.size}.` : restart ? `${name} is a ${after.size} now, running again.` : `${name} is a ${after.size} now; its next start boots it as one.`
15769
16388
  );
@@ -15896,25 +16515,25 @@ function timeInWords(total) {
15896
16515
  const parts = [days ? `${days}d` : "", hours ? `${hours}h` : "", minutes ? `${minutes}m` : ""].filter(Boolean);
15897
16516
  return parts.length > 0 ? parts.join(" ") : `${total}s`;
15898
16517
  }
15899
- async function autoStop(id, inText, at4, never, asJson) {
16518
+ async function autoStop(id, inText, at5, never, asJson) {
15900
16519
  if (!id) {
15901
16520
  throw new Error("auto-stop requires <sandbox-id>");
15902
16521
  }
15903
- if ([inText !== void 0, at4 !== void 0, never].filter(Boolean).length > 1) {
16522
+ if ([inText !== void 0, at5 !== void 0, never].filter(Boolean).length > 1) {
15904
16523
  throw new Error("--in, --at and --never say different things: give one.");
15905
16524
  }
15906
16525
  const path6 = `/v1/sandboxes/${encodeURIComponent(id)}/auto-stop`;
15907
16526
  let body;
15908
16527
  if (never) {
15909
16528
  body = await call2(path6, { method: "DELETE" });
15910
- } else if (inText === void 0 && at4 === void 0) {
16529
+ } else if (inText === void 0 && at5 === void 0) {
15911
16530
  body = await call2(path6, { method: "GET" });
15912
16531
  } else {
15913
16532
  const inSeconds = inText === void 0 ? void 0 : seconds(inText);
15914
16533
  if (inSeconds === null) {
15915
16534
  throw new Error("--in is a time from now, such as 30m, 2h or 1d");
15916
16535
  }
15917
- body = await call2(path6, { method: "PUT", body: JSON.stringify(inSeconds === void 0 ? { at: at4 } : { inSeconds }) });
16536
+ body = await call2(path6, { method: "PUT", body: JSON.stringify(inSeconds === void 0 ? { at: at5 } : { inSeconds }) });
15918
16537
  }
15919
16538
  if (asJson) {
15920
16539
  process.stdout.write(`${JSON.stringify(body, null, 2)}
@@ -15979,15 +16598,15 @@ function pictureSize(bytes4) {
15979
16598
  if (bytes4.length >= 24 && bytes4.toString("latin1", 1, 4) === "PNG") {
15980
16599
  return { width: bytes4.readUInt32BE(16), height: bytes4.readUInt32BE(20) };
15981
16600
  }
15982
- for (let at4 = 2; bytes4[0] === 255 && bytes4[1] === 216 && at4 + 9 <= bytes4.length; ) {
15983
- const marker = bytes4[at4 + 1];
15984
- if (bytes4[at4] !== 255) {
16601
+ for (let at5 = 2; bytes4[0] === 255 && bytes4[1] === 216 && at5 + 9 <= bytes4.length; ) {
16602
+ const marker = bytes4[at5 + 1];
16603
+ if (bytes4[at5] !== 255) {
15985
16604
  return null;
15986
16605
  }
15987
16606
  if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
15988
- return { width: bytes4.readUInt16BE(at4 + 7), height: bytes4.readUInt16BE(at4 + 5) };
16607
+ return { width: bytes4.readUInt16BE(at5 + 7), height: bytes4.readUInt16BE(at5 + 5) };
15989
16608
  }
15990
- at4 += 2 + bytes4.readUInt16BE(at4 + 2);
16609
+ at5 += 2 + bytes4.readUInt16BE(at5 + 2);
15991
16610
  }
15992
16611
  return null;
15993
16612
  }
@@ -15995,9 +16614,9 @@ async function clipboard(id, text) {
15995
16614
  if (!id) {
15996
16615
  throw new Error("desktop requires <sandbox-id>");
15997
16616
  }
15998
- const at4 = `/v1/sandboxes/${encodeURIComponent(id)}/desktop/clipboard`;
16617
+ const at5 = `/v1/sandboxes/${encodeURIComponent(id)}/desktop/clipboard`;
15999
16618
  if (text === void 0) {
16000
- const response2 = await request(at4, { method: "GET" });
16619
+ const response2 = await request(at5, { method: "GET" });
16001
16620
  const body = await readBody(response2);
16002
16621
  if (!response2.ok) {
16003
16622
  fail(response2.status, body);
@@ -16005,8 +16624,8 @@ async function clipboard(id, text) {
16005
16624
  process.stdout.write(String(body.text ?? ""));
16006
16625
  return;
16007
16626
  }
16008
- const given = text === "-" ? readFileSync7(0, "utf8") : text;
16009
- const response = await request(at4, { method: "PUT", body: JSON.stringify({ text: given }) });
16627
+ const given = text === "-" ? readFileSync8(0, "utf8") : text;
16628
+ const response = await request(at5, { method: "PUT", body: JSON.stringify({ text: given }) });
16010
16629
  if (!response.ok) {
16011
16630
  fail(response.status, await readBody(response));
16012
16631
  }
@@ -16043,9 +16662,9 @@ async function desktopLinks(id, use2, given, options) {
16043
16662
  if (!id) {
16044
16663
  throw new Error("desktop requires <sandbox-id>");
16045
16664
  }
16046
- const at4 = `/v1/sandboxes/${encodeURIComponent(id)}/desktop/links`;
16665
+ const at5 = `/v1/sandboxes/${encodeURIComponent(id)}/desktop/links`;
16047
16666
  if (use2 === "unlink") {
16048
- const response2 = await request(`${at4}/${encodeURIComponent(String(given))}`, { method: "DELETE" });
16667
+ const response2 = await request(`${at5}/${encodeURIComponent(String(given))}`, { method: "DELETE" });
16049
16668
  if (!response2.ok) {
16050
16669
  fail(response2.status, await readBody(response2));
16051
16670
  }
@@ -16054,7 +16673,7 @@ async function desktopLinks(id, use2, given, options) {
16054
16673
  return;
16055
16674
  }
16056
16675
  if (use2 === "links") {
16057
- const response2 = await request(at4, { method: "GET" });
16676
+ const response2 = await request(at5, { method: "GET" });
16058
16677
  const body2 = await readBody(response2);
16059
16678
  if (!response2.ok) {
16060
16679
  fail(response2.status, body2);
@@ -16070,7 +16689,7 @@ async function desktopLinks(id, use2, given, options) {
16070
16689
  if (expiresIn === null) {
16071
16690
  throw new Error("--expires is how long the link lasts: 600, 10m or 1h, from a minute to a day");
16072
16691
  }
16073
- const response = await request(at4, {
16692
+ const response = await request(at5, {
16074
16693
  method: "POST",
16075
16694
  body: JSON.stringify({ access: given, ...expiresIn === void 0 ? {} : { expiresIn }, ...options.keepStreams ? { cutOnExpiry: false } : {} })
16076
16695
  });
@@ -16095,7 +16714,7 @@ async function useDesktop(id, use2, given) {
16095
16714
  if (!id) {
16096
16715
  throw new Error("desktop requires <sandbox-id>");
16097
16716
  }
16098
- const at4 = `/v1/sandboxes/${encodeURIComponent(id)}/desktop/${use2}`;
16717
+ const at5 = `/v1/sandboxes/${encodeURIComponent(id)}/desktop/${use2}`;
16099
16718
  let body;
16100
16719
  if (use2 === "click") {
16101
16720
  const [x, y, button, count, ...more] = given.split(",");
@@ -16127,7 +16746,7 @@ async function useDesktop(id, use2, given) {
16127
16746
  } else {
16128
16747
  body = { keys: given };
16129
16748
  }
16130
- const response = await request(at4, { method: "POST", body: JSON.stringify(body) });
16749
+ const response = await request(at5, { method: "POST", body: JSON.stringify(body) });
16131
16750
  if (!response.ok) {
16132
16751
  fail(response.status, await readBody(response));
16133
16752
  }
@@ -16140,12 +16759,12 @@ function listedIn(given) {
16140
16759
  function metadataGiven(given) {
16141
16760
  const metadata = {};
16142
16761
  for (const each of given) {
16143
- const at4 = each.indexOf("=");
16144
- const key2 = at4 < 0 ? "" : each.slice(0, at4).trim();
16762
+ const at5 = each.indexOf("=");
16763
+ const key2 = at5 < 0 ? "" : each.slice(0, at5).trim();
16145
16764
  if (key2 === "") {
16146
16765
  throw new Error(`--meta is <key>=<value>, as --meta repo=acme/web, not ${each}`);
16147
16766
  }
16148
- metadata[key2] = each.slice(at4 + 1);
16767
+ metadata[key2] = each.slice(at5 + 1);
16149
16768
  }
16150
16769
  return metadata;
16151
16770
  }
@@ -16280,7 +16899,7 @@ function egressInWords(body) {
16280
16899
  }
16281
16900
  async function egress(positionals, values) {
16282
16901
  const [first, ...rest] = positionals;
16283
- const print4 = (body2, words2) => {
16902
+ const print5 = (body2, words2) => {
16284
16903
  process.stdout.write(values.json ? `${JSON.stringify(body2, null, 2)}
16285
16904
  ` : words2);
16286
16905
  };
@@ -16318,14 +16937,14 @@ async function egress(positionals, values) {
16318
16937
  `this month: ${money(number("spentMicros"))} of a ${money(number("budgetMicros"))} budget${account3["budgetSet"] ? "" : " (the default)"}`,
16319
16938
  ...account3["blocked"] && account3["blocked"] !== "refused" ? [`blocked now: ${String(account3["blocked"]).replaceAll("_", " ")}`] : []
16320
16939
  ];
16321
- print4(body2, `${lines.join("\n")}
16940
+ print5(body2, `${lines.join("\n")}
16322
16941
  `);
16323
16942
  return;
16324
16943
  }
16325
16944
  const path6 = `/v1/sandboxes/${encodeURIComponent(first)}/egress`;
16326
16945
  const how = `egress takes <sandbox-id>, and then nothing, box, or residential <country> [sticky|rotating], as agental egress ${first} residential de.`;
16327
16946
  const body = await call2(path6, rest.length === 0 ? { method: "GET" } : { method: "PUT", body: JSON.stringify(egressFrom(rest, how)) });
16328
- print4(body, `${first}: ${egressInWords(body)}
16947
+ print5(body, `${first}: ${egressInWords(body)}
16329
16948
  `);
16330
16949
  }
16331
16950
  function spotSettingsFrom(values) {
@@ -16444,15 +17063,15 @@ ${faint("The default is used when a sandbox is made without naming one. agental
16444
17063
  process.stdout.write("* used when a sandbox is made without naming one\n");
16445
17064
  }
16446
17065
  function showTemplate(each) {
16447
- const list5 = (items) => items && items.length > 0 ? items.join(", ") : "none";
17066
+ const list6 = (items) => items && items.length > 0 ? items.join(", ") : "none";
16448
17067
  return [
16449
17068
  `id: ${each.id}`,
16450
17069
  `name: ${each.name}${each.default ? " (default: used when a sandbox is made without naming one)" : ""}`,
16451
17070
  `start: ${startInWords(each.start)}`,
16452
- `variables: ${list5(each.variables)}`,
17071
+ `variables: ${list6(each.variables)}`,
16453
17072
  // Said only where some are. An API from before variables could be kept out of the sandbox says nothing of them.
16454
- ...each.hidden && each.hidden.length > 0 ? [`kept out: ${list5(each.hidden)}`] : [],
16455
- `files: ${list5(each.files)}`,
17073
+ ...each.hidden && each.hidden.length > 0 ? [`kept out: ${list6(each.hidden)}`] : [],
17074
+ `files: ${list6(each.files)}`,
16456
17075
  // An API from before templates held rules says nothing of one.
16457
17076
  ...each.network ? [`network: ${ruleInWords(each.network)}`] : [],
16458
17077
  // An API from before templates gave SSH says nothing of it.
@@ -16465,8 +17084,8 @@ function showTemplate(each) {
16465
17084
  }
16466
17085
  async function template(positionals, values) {
16467
17086
  const [action, first, ...rest] = positionals;
16468
- const usage = "template takes create, show, rename, delete, start, network, egress, ssh, ssh-keys, tags, meta, sandboxes, apply, of or put. agental template --help says how.";
16469
- const print4 = (body, words2) => {
17087
+ const usage = "template takes create, show, rename, delete, start, network, egress, tailnet, ssh, ssh-keys, tags, meta, sandboxes, apply, of or put. agental template --help says how.";
17088
+ const print5 = (body, words2) => {
16470
17089
  process.stdout.write(values.json ? `${JSON.stringify(body, null, 2)}
16471
17090
  ` : words2);
16472
17091
  };
@@ -16479,7 +17098,7 @@ async function template(positionals, values) {
16479
17098
  switch (action) {
16480
17099
  case "create": {
16481
17100
  const made = await call2("/v1/templates", { method: "POST", body: JSON.stringify({ name: need(first, "<name>"), ...labelsGiven(values) }) });
16482
- print4(made, showTemplate(made));
17101
+ print5(made, showTemplate(made));
16483
17102
  return;
16484
17103
  }
16485
17104
  case "tags":
@@ -16489,13 +17108,13 @@ async function template(positionals, values) {
16489
17108
  case "show": {
16490
17109
  const found = await templateNamed(need(first, "<template>"));
16491
17110
  const read2 = await call2(`/v1/templates/${encodeURIComponent(found.id)}`, { method: "GET" });
16492
- print4(read2, showTemplate(read2));
17111
+ print5(read2, showTemplate(read2));
16493
17112
  return;
16494
17113
  }
16495
17114
  case "rename": {
16496
17115
  const found = await templateNamed(need(first, "<template> <new-name>"));
16497
17116
  const renamed = await call2(`/v1/templates/${encodeURIComponent(found.id)}`, { method: "PATCH", body: JSON.stringify({ name: need(rest[0], "<template> <new-name>") }) });
16498
- print4(renamed, showTemplate(renamed));
17117
+ print5(renamed, showTemplate(renamed));
16499
17118
  return;
16500
17119
  }
16501
17120
  case "delete": {
@@ -16554,7 +17173,7 @@ async function template(positionals, values) {
16554
17173
  body: JSON.stringify({ size: values.size ?? current?.size, snapshotId, ttlSeconds: ttl, ...region === void 0 ? {} : { region }, ...spot2 === void 0 ? {} : { spot: spot2 } })
16555
17174
  });
16556
17175
  }
16557
- print4(start2, `start: ${startInWords(start2)}
17176
+ print5(start2, `start: ${startInWords(start2)}
16558
17177
  `);
16559
17178
  return;
16560
17179
  }
@@ -16578,19 +17197,22 @@ async function template(positionals, values) {
16578
17197
  }
16579
17198
  rule = await call2(path6, { method: "PUT", body: JSON.stringify(mode === "allowlist" ? { outbound: mode, allow: listed2 } : { outbound: mode }) });
16580
17199
  }
16581
- print4(
17200
+ print5(
16582
17201
  rule,
16583
17202
  `${found.name}: ${ruleInWords(rule)}
16584
17203
  ${mode === void 0 ? "" : "A sandbox on it takes this when it next starts, or now with agental template apply.\n"}`
16585
17204
  );
16586
17205
  return;
16587
17206
  }
17207
+ case "tailnet":
17208
+ await tailnet(tailscaleClient(), "template", [need(first, "<template>"), ...rest], tailnetFlags(values));
17209
+ return;
16588
17210
  case "egress": {
16589
17211
  const found = await templateNamed(need(first, "<template>"));
16590
17212
  const path6 = `/v1/templates/${encodeURIComponent(found.id)}/egress`;
16591
17213
  const how = `template egress takes <template>, and then nothing, box, or residential <country> [sticky|rotating], as agental template egress ${first ?? ""} residential de.`;
16592
17214
  const set2 = await call2(path6, rest.length === 0 ? { method: "GET" } : { method: "PUT", body: JSON.stringify(egressFrom(rest, how)) });
16593
- print4(set2, `${found.name}: ${egressInWords(set2)}${rest.length === 0 ? "" : ", for sandboxes made from it from now on"}
17215
+ print5(set2, `${found.name}: ${egressInWords(set2)}${rest.length === 0 ? "" : ", for sandboxes made from it from now on"}
16594
17216
  `);
16595
17217
  return;
16596
17218
  }
@@ -16602,7 +17224,7 @@ ${mode === void 0 ? "" : "A sandbox on it takes this when it next starts, or now
16602
17224
  throw new Error("template ssh requires <template>, and then nothing, on or off");
16603
17225
  }
16604
17226
  const ssh2 = await call2(path6, { method: turn === "on" ? "PUT" : turn === "off" ? "DELETE" : "GET" });
16605
- print4(ssh2, `${found.name}: SSH ${templateSshInWords(ssh2)}
17227
+ print5(ssh2, `${found.name}: SSH ${templateSshInWords(ssh2)}
16606
17228
  `);
16607
17229
  return;
16608
17230
  }
@@ -16633,7 +17255,7 @@ ${mode === void 0 ? "" : "A sandbox on it takes this when it next starts, or now
16633
17255
  const body = await call2(`/v1/templates/${encodeURIComponent(found.id)}/sandboxes`, { method: "GET" });
16634
17256
  const rows = body.sandboxes.map((each) => `${[pad2(String(each["id"])), pad2(String(each["name"])), pad2(String(each["status"])), each["upToDate"] === true ? "yes" : "no"].join(" ")}
16635
17257
  `);
16636
- print4(body, `${[pad2("ID"), pad2("NAME"), pad2("STATUS"), "UP TO DATE"].join(" ")}
17258
+ print5(body, `${[pad2("ID"), pad2("NAME"), pad2("STATUS"), "UP TO DATE"].join(" ")}
16637
17259
  ${rows.join("")}`);
16638
17260
  return;
16639
17261
  }
@@ -16645,7 +17267,7 @@ ${rows.join("")}`);
16645
17267
  });
16646
17268
  const failed = (body.failed ?? []).map((each) => `Not brought up to date, and held to the rule it had: ${each.sandboxId}: ${each.error}
16647
17269
  `).join("");
16648
- print4(
17270
+ print5(
16649
17271
  body,
16650
17272
  `${body.applied.length === 0 && failed === "" ? `No sandbox on ${found.name} is running. Each takes it when it next starts.
16651
17273
  ` : body.applied.length === 0 ? "" : `Brought up to date with ${found.name}: ${body.applied.join(", ")}
@@ -16659,7 +17281,7 @@ ${rows.join("")}`);
16659
17281
  case "of": {
16660
17282
  const sandboxId = need(first, "<sandbox-id>");
16661
17283
  const body = await call2(`/v1/sandboxes/${encodeURIComponent(sandboxId)}/template`, { method: "GET" });
16662
- print4(body, `template: ${String(body["name"])} (${String(body["templateId"])})
17284
+ print5(body, `template: ${String(body["name"])} (${String(body["templateId"])})
16663
17285
  up to date: ${body["upToDate"] === true ? "yes" : "no: it takes the template when it next starts, or when apply names it"}
16664
17286
  `);
16665
17287
  return;
@@ -16668,7 +17290,7 @@ up to date: ${body["upToDate"] === true ? "yes" : "no: it takes the template whe
16668
17290
  const found = await templateNamed(need(first, "<template> <sandbox-id>"));
16669
17291
  const sandboxId = need(rest[0], "<template> <sandbox-id>");
16670
17292
  const body = await call2(`/v1/sandboxes/${encodeURIComponent(sandboxId)}/template`, { method: "PUT", body: JSON.stringify({ templateId: found.id }) });
16671
- print4(body, `${sandboxId} is on ${found.name}: it has its variables and files from its next command, and is held to its outbound rule now.
17293
+ print5(body, `${sandboxId} is on ${found.name}: it has its variables and files from its next command, and is held to its outbound rule now.
16672
17294
  `);
16673
17295
  return;
16674
17296
  }
@@ -16760,11 +17382,11 @@ async function secrets(positionals, values) {
16760
17382
  throw new Error("--host takes a host, as --host api.github.com");
16761
17383
  }
16762
17384
  const pairs = args.map((arg) => {
16763
- const at4 = arg.indexOf("=");
16764
- if (at4 <= 0) {
17385
+ const at5 = arg.indexOf("=");
17386
+ if (at5 <= 0) {
16765
17387
  throw new Error(`secrets set takes <NAME>=<value>, and ${arg} has no name before an =`);
16766
17388
  }
16767
- return [arg.slice(0, at4), arg.slice(at4 + 1)];
17389
+ return [arg.slice(0, at5), arg.slice(at5 + 1)];
16768
17390
  });
16769
17391
  const path6 = (name) => `${base}/variables/${encodeURIComponent(name)}`;
16770
17392
  if (hosts === void 0 && !values.plain) {
@@ -16872,8 +17494,8 @@ async function metrics(id, asked2) {
16872
17494
  if (!response.ok) {
16873
17495
  fail(response.status, body);
16874
17496
  }
16875
- const answer4 = body && typeof body === "object" ? body : {};
16876
- const fromTo = typeof answer4["since"] === "string" && typeof answer4["until"] === "string" ? ` from ${answer4["since"]} to ${answer4["until"]}` : "";
17497
+ const answer6 = body && typeof body === "object" ? body : {};
17498
+ const fromTo = typeof answer6["since"] === "string" && typeof answer6["until"] === "string" ? ` from ${answer6["since"]} to ${answer6["until"]}` : "";
16877
17499
  if (asked2.json) {
16878
17500
  process.stdout.write(`${JSON.stringify(body, null, 2)}
16879
17501
  `);
@@ -16898,26 +17520,26 @@ async function metrics(id, asked2) {
16898
17520
  ])
16899
17521
  );
16900
17522
  }
16901
- if (answer4["complete"] === false) {
17523
+ if (answer6["complete"] === false) {
16902
17524
  process.stderr.write(
16903
17525
  id === void 0 ? "A server did not answer, so a sandbox on it has no reading here though it may have been running. Ask again in a minute.\n" : `A server did not answer, so readings may be missing: those from any time ${id} was on that server. Ask again in a minute.
16904
17526
  `
16905
17527
  );
16906
17528
  }
16907
17529
  }
16908
- async function account2(positionals, out) {
17530
+ async function account2(positionals, out2) {
16909
17531
  if (positionals[0] !== "export" || positionals.length > 1) {
16910
17532
  throw new Error("account takes export [--out <file>]. An account is closed from Settings in the console: a key cannot close one.");
16911
17533
  }
16912
17534
  const body = await asked("/v1/me/export", { method: "GET" });
16913
17535
  const text = `${JSON.stringify(body, null, 2)}
16914
17536
  `;
16915
- if (out === void 0) {
17537
+ if (out2 === void 0) {
16916
17538
  process.stdout.write(text);
16917
17539
  return;
16918
17540
  }
16919
- writeFileSync5(out, text, { mode: 384 });
16920
- process.stdout.write(`Written to ${out}.
17541
+ writeFileSync5(out2, text, { mode: 384 });
17542
+ process.stdout.write(`Written to ${out2}.
16921
17543
  `);
16922
17544
  }
16923
17545
  async function dataRetention(positionals, asJson) {
@@ -16941,8 +17563,8 @@ async function dataRetention(positionals, asJson) {
16941
17563
  `);
16942
17564
  return;
16943
17565
  }
16944
- const answer4 = body ?? {};
16945
- const days = answer4.keepDays ?? null;
17566
+ const answer6 = body ?? {};
17567
+ const days = answer6.keepDays ?? null;
16946
17568
  const kept2 = days === null ? "until their sandbox is deleted" : days === 1 ? "1 day" : `${days} days`;
16947
17569
  process.stdout.write(`${period === void 0 ? "" : "Saved. "}Command output, agent conversations and events are kept ${kept2}.
16948
17570
  `);
@@ -16950,7 +17572,7 @@ async function dataRetention(positionals, asJson) {
16950
17572
  process.stdout.write(`What is older is deleted within the hour, and cannot be brought back.
16951
17573
  `);
16952
17574
  }
16953
- const last = answer4.lastCleared;
17575
+ const last = answer6.lastCleared;
16954
17576
  if (period === void 0) {
16955
17577
  process.stdout.write(
16956
17578
  last ? `Last clean-up ${last.at}: ${last.commands} commands' output, ${last.conversations} conversations and ${last.events} events deleted.
@@ -17174,12 +17796,12 @@ async function billing(positionals, asJson, limit) {
17174
17796
  if (limit !== void 0 && what !== "invoices") {
17175
17797
  throw new Error("--limit is taken by billing invoices alone.");
17176
17798
  }
17177
- const print4 = (body, text) => process.stdout.write(asJson ? `${JSON.stringify(body, null, 2)}
17799
+ const print5 = (body, text) => process.stdout.write(asJson ? `${JSON.stringify(body, null, 2)}
17178
17800
  ` : text());
17179
17801
  switch (what) {
17180
17802
  case void 0: {
17181
17803
  const [body, card] = await Promise.all([asked("/v1/billing", { method: "GET" }), cardOnFile()]);
17182
- print4({ ...body, card }, () => describeBilling(body, card));
17804
+ print5({ ...body, card }, () => describeBilling(body, card));
17183
17805
  return;
17184
17806
  }
17185
17807
  case "invoices": {
@@ -17188,28 +17810,28 @@ async function billing(positionals, asJson, limit) {
17188
17810
  }
17189
17811
  case "compare": {
17190
17812
  const body = await asked("/v1/burst/replay", { method: "GET" });
17191
- print4(body, () => describePlanReplay(body));
17813
+ print5(body, () => describePlanReplay(body));
17192
17814
  return;
17193
17815
  }
17194
17816
  case "details": {
17195
17817
  const body = await asked("/v1/billing/details", { method: "GET" });
17196
- print4(body, () => describeDetails(body.details));
17818
+ print5(body, () => describeDetails(body.details));
17197
17819
  return;
17198
17820
  }
17199
17821
  case "prices": {
17200
17822
  const body = await asked("/v1/billing/plans", { method: "GET" });
17201
- print4(body, () => isTerminal(process.stdout) ? pricesForPeople(body) : describePrices(body));
17823
+ print5(body, () => isTerminal(process.stdout) ? pricesForPeople(body) : describePrices(body));
17202
17824
  return;
17203
17825
  }
17204
17826
  case "card": {
17205
17827
  if (amount === void 0) {
17206
17828
  const body2 = await asked("/v1/billing/card", { method: "GET" });
17207
- print4(body2, () => body2.card ? `${describeCard(body2.card)}
17829
+ print5(body2, () => body2.card ? `${describeCard(body2.card)}
17208
17830
  ` : "No card saved. agental billing card save prints the page to save one on, charged nothing.\n");
17209
17831
  return;
17210
17832
  }
17211
17833
  const body = await asked("/v1/billing/checkout", { method: "POST", body: JSON.stringify({ card: true }) });
17212
- print4(
17834
+ print5(
17213
17835
  body,
17214
17836
  () => body.url ? `Save a card for the free plan at:
17215
17837
  ${body.url}
@@ -17228,7 +17850,7 @@ Nothing is charged. Once it is saved, the account has its monthly free allowance
17228
17850
  const body = await asked("/v1/billing/checkout", { method: "POST", body: JSON.stringify({ topUp: dollars }) });
17229
17851
  const topUp = topUpByDollars(dollars);
17230
17852
  const what2 = topUp && topUp.bonusMicros > 0 ? `Pay ${wholeMoney(dollars * 1e6)} for ${wholeMoney(topUp.micros)} of credits, a bonus of ${topUp.bonusPercent}%, at:` : `Pay for ${wholeMoney(dollars * 1e6)} of credits at:`;
17231
- print4(
17853
+ print5(
17232
17854
  body,
17233
17855
  () => body.url ? `${what2}
17234
17856
  ${body.url}
@@ -17246,13 +17868,13 @@ Nothing is charged until it is paid. agental billing shows it within a minute of
17246
17868
  );
17247
17869
  }
17248
17870
  const body = await asked("/v1/billing/auto-reload", { method: "PUT", body: JSON.stringify({ dollars: off ? null : dollars }) });
17249
- print4(body, () => `${describeAutoReload(body.autoReload)}
17871
+ print5(body, () => `${describeAutoReload(body.autoReload)}
17250
17872
  `);
17251
17873
  return;
17252
17874
  }
17253
17875
  case "email-copy": {
17254
17876
  const body = await asked("/v1/billing/email-copy", { method: "GET" });
17255
- print4(
17877
+ print5(
17256
17878
  body,
17257
17879
  () => body.address === null ? "Billing emails go to the owners alone. An owner can add an address for a copy of each under Billing in the console.\n" : body.confirmed === false ? `${body.address} gets no copies yet: it has to confirm by the link sent to it. An owner can send a new one under Billing in the console.
17258
17880
  ` : body.waiting === true ? `${body.address} gets no copies for now: whoever set it is no longer an owner. An owner keeps it or removes it under Billing in the console.
@@ -17508,11 +18130,11 @@ function describeAutoReload(autoReload) {
17508
18130
  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.`;
17509
18131
  }
17510
18132
  function pricesForPeople(body) {
17511
- const out = [];
18133
+ const out2 = [];
17512
18134
  const count = (value) => value === void 0 || value === null ? "" : value.toLocaleString("en-US");
17513
18135
  const section = (title, rows, notes) => {
17514
18136
  const table4 = fitted(rows, { paint: (cell, row) => row === 0 ? faint(cell) : cell }).trimEnd().split("\n");
17515
- out.push(strong(title), ...table4.map((line) => ` ${line}`), ...notes.map((note) => ` ${faint(note)}`), "");
18137
+ out2.push(strong(title), ...table4.map((line) => ` ${line}`), ...notes.map((note) => ` ${faint(note)}`), "");
17516
18138
  };
17517
18139
  if (body.tiers?.length) {
17518
18140
  section(
@@ -17567,68 +18189,68 @@ function pricesForPeople(body) {
17567
18189
  also.push(["Snapshots", `the ${body.storage.freeSnapshots} oldest free, then $${(body.storage.snapshotMicrosPerHour * 730 / 1e6).toFixed(2)} a month each`]);
17568
18190
  }
17569
18191
  if (also.length > 0) {
17570
- out.push(strong("Also"), ...fitted(also).trimEnd().split("\n").map((line) => ` ${line}`), "");
18192
+ out2.push(strong("Also"), ...fitted(also).trimEnd().split("\n").map((line) => ` ${line}`), "");
17571
18193
  }
17572
- out.push(faint("agental billing top-up <dollars> \xB7 agental limits budget <dollars> \xB7 https://agental.io/pricing"));
17573
- return `${out.join("\n")}
18194
+ out2.push(faint("agental billing top-up <dollars> \xB7 agental limits budget <dollars> \xB7 https://agental.io/pricing"));
18195
+ return `${out2.join("\n")}
17574
18196
  `;
17575
18197
  }
17576
18198
  function describePrices(body) {
17577
- const out = [];
18199
+ const out2 = [];
17578
18200
  if (body.tiers?.length) {
17579
18201
  const withSizes = body.tiers.some((tier) => tier.sizes !== void 0);
17580
- out.push(withSizes ? "Plans, a month, and the sizes each makes" : "Plans, a month");
18202
+ out2.push(withSizes ? "Plans, a month, and the sizes each makes" : "Plans, a month");
17581
18203
  for (const tier of body.tiers) {
17582
18204
  const sizes = tier.sizes === void 0 ? "" : tier.sizes.length === body.plans.length ? "every size" : tier.sizes.join(", ");
17583
18205
  const speed = tier.runningUnits !== void 0 && tier.freeBurstUnits !== void 0 ? `${tier.runningUnits.toLocaleString("en-US")} running, ${tier.freeBurstUnits.toLocaleString("en-US")} free starts` : tier.burst ? `${(tier.burst.perQuarterMb / 1024).toLocaleString("en-US")} GiB per 15 minutes` : typeof tier.sandboxesAtOnce === "number" ? `${tier.sandboxesAtOnce.toLocaleString("en-US")} sandboxes at once` : "";
17584
18206
  const price = tier.dollarsPerMonth === 0 ? "Free" : `$${tier.dollarsPerMonth.toLocaleString("en-US")}`;
17585
18207
  const included = tier.dollarsPerMonth === 0 ? body.free ? `${wholeOrCents(body.free.allowanceMicros)} free, then as you go` : "pay as you go" : `${wholeMoney(tier.includedMicros)} of credits`;
17586
- out.push(` ${price.padEnd(8)}${included.padEnd(28)}${speed.padEnd(34)}${sizes}`.trimEnd());
18208
+ out2.push(` ${price.padEnd(8)}${included.padEnd(28)}${speed.padEnd(34)}${sizes}`.trimEnd());
17587
18209
  }
17588
18210
  if (body.free) {
17589
- out.push(
18211
+ out2.push(
17590
18212
  ` Free needs a card saved, charged nothing. Each month's first ${wholeOrCents(body.free.allowanceMicros)} of use is free: 185 hours of a small sandbox, 370 of a tiny one, or 11,100 CI minutes on small. It runs ${body.free.unpaidUnits} units at once until you buy a top-up.`
17591
18213
  );
17592
18214
  }
17593
18215
  if (body.tiers.some((tier) => tier.runningUnits !== void 0)) {
17594
- out.push(" Counted in units: a tiny sandbox is 1, a small 2, a medium 4, a large 8. Free starts are in any 15 minutes.");
18216
+ out2.push(" Counted in units: a tiny sandbox is 1, a small 2, a medium 4, a large 8. Free starts are in any 15 minutes.");
17595
18217
  }
17596
18218
  }
17597
18219
  if (body.burstFee) {
17598
- out.push(
18220
+ out2.push(
17599
18221
  `A start past your free starts in any ${body.burstFee.windowMinutes} minutes costs one hour of its price: $${body.burstFee.feeMicrosPerUnit / 1e6} a unit, $0.027 a small, $0.108 a large. At most ${wholeMoney(body.burstFee.defaultBudgetMicros)} a month unless you set another budget: agental limits budget <dollars>.`
17600
18222
  );
17601
18223
  }
17602
18224
  if (body.topUps?.length) {
17603
18225
  const range = body.topUpRange;
17604
- out.push(
18226
+ out2.push(
17605
18227
  range ? `Top-ups, any whole number of dollars from ${wholeMoney(range.minDollars * 1e6)} to ${wholeMoney(range.maxDollars * 1e6)}, used after the plan's credits. They do not expire.` : "Top-ups, used after the plan's credits. They do not expire."
17606
18228
  );
17607
18229
  if (body.topUps.some((topUp) => topUp.micros !== void 0)) {
17608
18230
  for (const topUp of body.topUps) {
17609
18231
  const bonus = topUp.bonusPercent ? `+${topUp.bonusPercent}%` : "";
17610
- out.push(` ${`$${topUp.dollars.toLocaleString("en-US")}`.padEnd(10)}${bonus.padEnd(10)}${`adds ${wholeMoney(topUp.micros ?? topUp.dollars * 1e6)}`}`);
18232
+ out2.push(` ${`$${topUp.dollars.toLocaleString("en-US")}`.padEnd(10)}${bonus.padEnd(10)}${`adds ${wholeMoney(topUp.micros ?? topUp.dollars * 1e6)}`}`);
17611
18233
  }
17612
18234
  } else {
17613
- out.push(` ${body.topUps.map((topUp) => `$${topUp.dollars}`).join(" ")}`);
18235
+ out2.push(` ${body.topUps.map((topUp) => `$${topUp.dollars}`).join(" ")}`);
17614
18236
  }
17615
18237
  if (body.topUpBonus) {
17616
18238
  const bonus = body.topUpBonus;
17617
- out.push(
18239
+ out2.push(
17618
18240
  ` From ${wholeMoney(bonus.fromDollars * 1e6)} a top-up adds a bonus: ${bonus.fromPercent}% there, growing evenly on a log scale to ${bonus.toPercent}% at ${wholeMoney(bonus.toDollars * 1e6)} and over.`
17619
18241
  );
17620
18242
  }
17621
18243
  }
17622
- out.push("Sizes, an hour at list price");
18244
+ out2.push("Sizes, an hour at list price");
17623
18245
  for (const size2 of body.plans) {
17624
- out.push(` ${size2.size.padEnd(8)}${`${size2.vcpu} vCPU, ${size2.memoryMb / 1024} GiB`.padEnd(20)}$${size2.listPriceMicrosPerHour / 1e6}`);
18246
+ out2.push(` ${size2.size.padEnd(8)}${`${size2.vcpu} vCPU, ${size2.memoryMb / 1024} GiB`.padEnd(20)}$${size2.listPriceMicrosPerHour / 1e6}`);
17625
18247
  }
17626
18248
  if (body.storage) {
17627
18249
  const month = body.storage.snapshotMicrosPerHour * 730 / 1e6;
17628
- out.push(stoppedWords(body.storage));
17629
- out.push(`Snapshots: the ${body.storage.freeSnapshots} oldest are free, and each one past them is $${month.toFixed(2)} a month, by the second.`);
18250
+ out2.push(stoppedWords(body.storage));
18251
+ out2.push(`Snapshots: the ${body.storage.freeSnapshots} oldest are free, and each one past them is $${month.toFixed(2)} a month, by the second.`);
17630
18252
  }
17631
- return `${out.join("\n")}
18253
+ return `${out2.join("\n")}
17632
18254
  `;
17633
18255
  }
17634
18256
  function stoppedWords(storage) {
@@ -17651,10 +18273,10 @@ async function showLimits(positionals, options) {
17651
18273
  `);
17652
18274
  return;
17653
18275
  }
17654
- const answer4 = body2 && typeof body2 === "object" ? body2 : {};
17655
- const spent = typeof answer4["spentMicros"] === "number" ? answer4["spentMicros"] : 0;
17656
- const budget = typeof answer4["budgetMicros"] === "number" ? answer4["budgetMicros"] : 0;
17657
- process.stdout.write(`Budget for burst fees: ${money(budget)} a month${answer4["budgetSet"] === true ? "" : " (the default)"}; ${money(spent)} spent this month.
18276
+ const answer6 = body2 && typeof body2 === "object" ? body2 : {};
18277
+ const spent = typeof answer6["spentMicros"] === "number" ? answer6["spentMicros"] : 0;
18278
+ const budget = typeof answer6["budgetMicros"] === "number" ? answer6["budgetMicros"] : 0;
18279
+ process.stdout.write(`Budget for burst fees: ${money(budget)} a month${answer6["budgetSet"] === true ? "" : " (the default)"}; ${money(spent)} spent this month.
17658
18280
  `);
17659
18281
  return;
17660
18282
  }
@@ -17684,22 +18306,22 @@ async function showLimits(positionals, options) {
17684
18306
  process.stdout.write(describeLimits(body, options.from === void 0 && options.to === void 0, options.to === void 0));
17685
18307
  }
17686
18308
  function describeLimits(body, today, endsNow) {
17687
- const answer4 = body && typeof body === "object" ? body : {};
17688
- const now = answer4["now"] && typeof answer4["now"] === "object" ? answer4["now"] : {};
18309
+ const answer6 = body && typeof body === "object" ? body : {};
18310
+ const now = answer6["now"] && typeof answer6["now"] === "object" ? answer6["now"] : {};
17689
18311
  const number = (from, name) => typeof from[name] === "number" ? from[name] : 0;
17690
18312
  const units = (mb) => {
17691
18313
  const value = mb / 2048;
17692
18314
  return (Number.isInteger(value) ? value : Math.round(value * 10) / 10).toLocaleString("en-US");
17693
18315
  };
17694
18316
  const clock = (iso) => {
17695
- const at4 = new Date(iso).toISOString();
17696
- return at4.slice(0, 10) === (/* @__PURE__ */ new Date()).toISOString().slice(0, 10) ? `${at4.slice(11, 16)} UTC` : `${at4.slice(0, 10)} ${at4.slice(11, 16)} UTC`;
18317
+ const at5 = new Date(iso).toISOString();
18318
+ return at5.slice(0, 10) === (/* @__PURE__ */ new Date()).toISOString().slice(0, 10) ? `${at5.slice(11, 16)} UTC` : `${at5.slice(0, 10)} ${at5.slice(11, 16)} UTC`;
17697
18319
  };
17698
- const range = today ? "today (UTC)" : `from ${String(answer4["from"] ?? "")} to ${String(answer4["to"] ?? "")}`;
18320
+ const range = today ? "today (UTC)" : `from ${String(answer6["from"] ?? "")} to ${String(answer6["to"] ?? "")}`;
17699
18321
  const lines = [
17700
- `running: ${units(number(now, "runningMb"))} of ${number(now, "runningUnits").toLocaleString("en-US")} units (a tiny is 1, a small 2, a medium 4, a large 8); at the running count ${duration(number(answer4, "atRunningCountMs"))} ${range}`
18322
+ `running: ${units(number(now, "runningMb"))} of ${number(now, "runningUnits").toLocaleString("en-US")} units (a tiny is 1, a small 2, a medium 4, a large 8); at the running count ${duration(number(answer6, "atRunningCountMs"))} ${range}`
17701
18323
  ];
17702
- const bursts = Array.isArray(answer4["bursts"]) ? answer4["bursts"] : [];
18324
+ const bursts = Array.isArray(answer6["bursts"]) ? answer6["bursts"] : [];
17703
18325
  const open = endsNow ? bursts.find((one) => one["endedAt"] === null && typeof one["startedAt"] === "string") : void 0;
17704
18326
  const over = number(now, "overMb") > 0;
17705
18327
  const nextStart = Array.isArray(now["nextStart"]) ? now["nextStart"] : [];
@@ -17715,7 +18337,7 @@ function describeLimits(body, today, endsNow) {
17715
18337
  const budgetMonth = now["budgetMonth"] && typeof now["budgetMonth"] === "object" ? now["budgetMonth"] : null;
17716
18338
  const since = typeof budgetMonth?.start === "string" && budgetMonth.start.slice(8, 10) !== "01" ? ` (since ${shortDayOf(budgetMonth.start)})` : "";
17717
18339
  lines.push(`fees: ${money(number(now, "spentMicros"))} this month${since} of a ${money(number(now, "budgetMicros"))} budget`);
17718
- const refused2 = answer4["refused"] && typeof answer4["refused"] === "object" ? answer4["refused"] : {};
18340
+ const refused2 = answer6["refused"] && typeof answer6["refused"] === "object" ? answer6["refused"] : {};
17719
18341
  const total = number(refused2, "total");
17720
18342
  const byReason = Array.isArray(refused2["byReason"]) ? refused2["byReason"] : [];
17721
18343
  lines.push(
@@ -17924,7 +18546,7 @@ function adminKeyHere() {
17924
18546
  return given;
17925
18547
  }
17926
18548
  try {
17927
- const saved = JSON.parse(readFileSync7(`${os7.homedir()}/.config/agental/admin-key.json`, "utf8"));
18549
+ const saved = JSON.parse(readFileSync8(`${os7.homedir()}/.config/agental/admin-key.json`, "utf8"));
17928
18550
  const forHere = typeof saved.apiUrl === "string" && saved.apiUrl.replace(/\/$/, "") === apiBase().replace(/\/$/, "");
17929
18551
  if (forHere && typeof saved.key === "string" && !(typeof saved.expiresAt === "string" && Date.parse(saved.expiresAt) <= Date.now())) {
17930
18552
  return saved.key;
@@ -17965,11 +18587,11 @@ function readSandboxes(body) {
17965
18587
  return body.sandboxes.filter((item) => Boolean(item) && typeof item === "object");
17966
18588
  }
17967
18589
  function readList(body, name) {
17968
- const list5 = body && typeof body === "object" ? body[name] : void 0;
17969
- if (!Array.isArray(list5)) {
18590
+ const list6 = body && typeof body === "object" ? body[name] : void 0;
18591
+ if (!Array.isArray(list6)) {
17970
18592
  throw new Error(`Metrics response was missing ${name}`);
17971
18593
  }
17972
- return list5.filter((item) => Boolean(item) && typeof item === "object");
18594
+ return list6.filter((item) => Boolean(item) && typeof item === "object");
17973
18595
  }
17974
18596
  function teamOptions(values) {
17975
18597
  return { json: values.json, revokeKeys: values["revoke-keys"], ...values.role === void 0 ? {} : { role: values.role } };
@@ -18064,6 +18686,10 @@ Usage
18064
18686
  agental auto-stop <sandbox-id> [--in <time> | --at <date-time> | --never] [--json]
18065
18687
  agental network <sandbox-id> [--allow <address-or-name>[,<address-or-name>...] | --none] [--json]
18066
18688
  agental egress <sandbox-id> [box | residential <country> [sticky | rotating]] [--json]
18689
+ agental tailscale [status | connect --client-id <id> | disconnect [--yes]] [--json]
18690
+ agental subscriptions [list | sign-in <agent> | delete <agent> [--yes]] [--json]
18691
+ agental agents (--template <template> | --sandbox <sandbox-id>) [<agent> off|subscription|api_key|template] [--json]
18692
+ agental tailnet <sandbox-id> [join --tag <tag>... [--accept <range>]... [--exit-node <ip>] [--keep-address] [--node-name <name>] | off] [--json]
18067
18693
  agental spot <sandbox-id> [off] [--on-reclaim delete|stop] [--warn-at <chance>] [--json]
18068
18694
  agental templates [--json]
18069
18695
  agental template create <name> [--tag <tag>[,<tag>...]]... [--meta <key>=<value>]...
@@ -18073,6 +18699,7 @@ Usage
18073
18699
  agental template start <template> [--size tiny|small|medium|large] [--snapshot <snapshot-id> | --new-machine] [--ttl <time> | --ttl default] [--region <region> | --region default] [--spot [--on-reclaim delete|stop] [--warn-at <chance>] | --standard]
18074
18700
  agental template network <template> [open | blocked | allowlist <address-or-name>...] [--json]
18075
18701
  agental template egress <template> [box | residential <country> [sticky | rotating]] [--json]
18702
+ agental template tailnet <template> [join --tag <tag>... [--accept <range>]... [--exit-node <ip>] [--keep-address] | off] [--json]
18076
18703
  agental template ssh <template> [on | off] [--json]
18077
18704
  agental template ssh-keys <template> [<public-key-or-file>... | --remove <key-id>] [--json]
18078
18705
  agental template tags <template> [add|rm <tag>...] [--json]