agental 0.54.0 → 0.57.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 +743 -186
  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.54.0" : "dev";
7414
+ var CLI_VERSION = true ? "0.57.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;
@@ -7974,8 +7982,8 @@ function keyOf(body) {
7974
7982
  throw new Error("The answer was not an API key.");
7975
7983
  }
7976
7984
  const key2 = body;
7977
- const list5 = (value) => Array.isArray(value) ? value.map(String) : [];
7978
- 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) };
7979
7987
  }
7980
7988
  function keysOf(body) {
7981
7989
  const listed2 = body?.apiKeys;
@@ -8293,10 +8301,10 @@ async function whoIs(base, key2) {
8293
8301
  throw error;
8294
8302
  }
8295
8303
  }
8296
- async function pushRequest(base, ask13) {
8304
+ async function pushRequest(base, ask14) {
8297
8305
  let made;
8298
8306
  try {
8299
- made = await call(base, "POST", "/v1/cli-sign-ins", ask13);
8307
+ made = await call(base, "POST", "/v1/cli-sign-ins", ask14);
8300
8308
  } catch (error) {
8301
8309
  if (error instanceof Refused && (error.status === 401 || error.status === 404)) {
8302
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.`);
@@ -8308,7 +8316,7 @@ async function pushRequest(base, ask13) {
8308
8316
  async function listen() {
8309
8317
  let arrived = () => {
8310
8318
  };
8311
- let answer5 = () => {
8319
+ let answer6 = () => {
8312
8320
  };
8313
8321
  const next = new Promise((resolve) => arrived = resolve);
8314
8322
  let taken = false;
@@ -8323,7 +8331,7 @@ async function listen() {
8323
8331
  return;
8324
8332
  }
8325
8333
  taken = true;
8326
- answer5 = (to) => response.writeHead(302, { location: to, "cache-control": "no-store" }).end();
8334
+ answer6 = (to) => response.writeHead(302, { location: to, "cache-control": "no-store" }).end();
8327
8335
  arrived(url);
8328
8336
  });
8329
8337
  await new Promise((resolve, reject) => {
@@ -8331,7 +8339,7 @@ async function listen() {
8331
8339
  server2.listen(0, "127.0.0.1", resolve);
8332
8340
  });
8333
8341
  const { port } = server2.address();
8334
- return { server: server2, redirectUri: `http://127.0.0.1:${port}/callback`, next, answer: (to) => answer5(to) };
8342
+ return { server: server2, redirectUri: `http://127.0.0.1:${port}/callback`, next, answer: (to) => answer6(to) };
8335
8343
  }
8336
8344
  async function browserSignIn(base, term, organizationId) {
8337
8345
  const verifier = randomBytes2(32).toString("base64url");
@@ -8696,8 +8704,8 @@ function claudeDesktopHere(places, platform = process.platform, env = process.en
8696
8704
  function addToClaudeLink(url) {
8697
8705
  return `https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=${CONNECTOR_NAME}&connectorUrl=${encodeURIComponent(url)}`;
8698
8706
  }
8699
- function names(list5) {
8700
- 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)}`;
8701
8709
  }
8702
8710
  async function ensureConnector(site2, places = placesFrom()) {
8703
8711
  const url = `${site2}/v1/mcp`;
@@ -8999,9 +9007,9 @@ async function api(base, key2, method, pathname, body, headers = {}) {
8999
9007
  }
9000
9008
  return { status: response.status, body: parsed && typeof parsed === "object" ? parsed : {} };
9001
9009
  }
9002
- function errorOf(answer5) {
9003
- const error = answer5.body["error"] && typeof answer5.body["error"] === "object" ? answer5.body["error"] : {};
9004
- return { code: String(error["code"] ?? `http_${answer5.status}`), message: String(error["message"] ?? `HTTP ${answer5.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}`) };
9005
9013
  }
9006
9014
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
9007
9015
  function real(file) {
@@ -9597,6 +9605,63 @@ var COMMANDS = [
9597
9605
  ["--yes", "disconnect: without asking; every sandbox is taken off the tailnet"]
9598
9606
  ]
9599
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
+ "agental guild post <guild> <text> [--as <identity>] [--to <identity,...> | --to-role <role>] [--request] [--answers <request>]",
9619
+ "agental guild read <guild> [--as <identity>] [--wait-seconds <n>] [--done]",
9620
+ "agental guild requests <guild> | claim <guild> <request> | answer <guild> <request> <text> | close <guild> <request>",
9621
+ "agental guild notes <guild> [<identity>] [--text <notes>] | pause <guild> | resume <guild>"
9622
+ ],
9623
+ examples: [
9624
+ 'agental guild create marketing --roles "blog manager:1,reviewer:2" --brief "Reviewers answer pass or fail."',
9625
+ "agental guild attach marketing writers",
9626
+ "agental guild join marketing --as Atlas --role reviewer --answer model=claude",
9627
+ 'agental guild post marketing "Review a1b2c3, please." --to-role reviewer --request',
9628
+ "agental guild read marketing --wait-seconds 30 --done"
9629
+ ],
9630
+ flags: [
9631
+ ["--roles <name[:seats],...>", "create: the roles, each with its seats; attach: the roles its sandboxes may take"],
9632
+ ["--brief <text>", "create: what the guild is for, read by every member"],
9633
+ ["--form <file.json>", "create: the fields an agent fills in to join, as the API takes them"],
9634
+ ["--as <name>", "join: the name you will be known by in the guild"],
9635
+ ["--role <role>", "join: one of the guild's roles with a free seat"],
9636
+ ["--answer <key=value>", "join: an answer to the guild's form (may be given again)"],
9637
+ ["--yes", "delete: without asking"],
9638
+ ["--to <identity,...>", "post: the identities it is for, by name or ID"],
9639
+ ["--to-role <role>", "post: the role it is for"],
9640
+ ["--request", "post: a request, open until answered"],
9641
+ ["--answers <request>", "post: the request this answers and closes"],
9642
+ ["--channel <name>", "post, read: the channel; general by default"],
9643
+ ["--wait-seconds <n>", "read: wait up to n seconds (at most 30) for a message"],
9644
+ ["--done", "read: confirm you are done with what was read, so the next read starts after it"],
9645
+ ["--text <notes>", "notes: overwrite the identity's notes with this"]
9646
+ ]
9647
+ },
9648
+ {
9649
+ name: "subscriptions",
9650
+ summary: "Sign in to Claude, ChatGPT (Codex), GitHub Copilot or Grok Build on agental's servers, which keep it sealed; list or delete them.",
9651
+ usage: ["agental subscriptions [list] [--json]", "agental subscriptions sign-in claude|codex|copilot|grok", "agental subscriptions delete <agent> [--yes]"],
9652
+ examples: ["agental subscriptions sign-in codex", "agental subscriptions delete grok --yes"],
9653
+ flags: [["--yes", "delete: without asking; it is taken off every template and sandbox that uses it"]]
9654
+ },
9655
+ {
9656
+ name: "agents",
9657
+ 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.",
9658
+ usage: ["agental agents --template <template> [<agent> off|subscription|api_key] [--json]", "agental agents --sandbox <sandbox-id> [<agent> off|subscription|api_key|template] [--json]"],
9659
+ examples: ["agental agents --template default claude subscription", "agental agents --sandbox sbx_2a9a47e50daec64a codex template"],
9660
+ flags: [
9661
+ ["--template <template>", "the template, by id or name"],
9662
+ ["--sandbox <sandbox-id>", "the sandbox: template follows its template again"]
9663
+ ]
9664
+ },
9600
9665
  {
9601
9666
  name: "tailnet",
9602
9667
  summary: "Join a sandbox to the account's tailnet as a node, change how, or take it off.",
@@ -10059,11 +10124,11 @@ function spelledOut(args, operator = false) {
10059
10124
  if (verb === void 0 || !SECRET_VERBS.has(verb)) {
10060
10125
  return wrong("list, get, set, unset, hosts, get-file, put-file or rm-file, then the sandbox or --template <template>");
10061
10126
  }
10062
- const at4 = rest.findIndex((word) => word === "--template" || word === "-t" || word.startsWith("--template="));
10063
- if (at4 >= 0) {
10064
- const given = rest[at4];
10065
- const pair = given.startsWith("--template=") ? [given] : rest.slice(at4, at4 + 2);
10066
- return ["secrets", ...pair, ...verb === "list" ? [] : [verb], ...rest.filter((_, index) => index < at4 || index >= at4 + pair.length)];
10127
+ const at5 = rest.findIndex((word) => word === "--template" || word === "-t" || word.startsWith("--template="));
10128
+ if (at5 >= 0) {
10129
+ const given = rest[at5];
10130
+ const pair = given.startsWith("--template=") ? [given] : rest.slice(at5, at5 + 2);
10131
+ return ["secrets", ...pair, ...verb === "list" ? [] : [verb], ...rest.filter((_, index) => index < at5 || index >= at5 + pair.length)];
10067
10132
  }
10068
10133
  const { sandbox, others } = sandboxIn(rest, ["--host", "--text"]);
10069
10134
  if (sandbox === void 0) {
@@ -10090,7 +10155,7 @@ function sandboxIn(words2, valued = []) {
10090
10155
  index += valued.includes(word) ? 1 : 0;
10091
10156
  continue;
10092
10157
  }
10093
- return { sandbox: word, others: words2.filter((_, at4) => at4 !== index) };
10158
+ return { sandbox: word, others: words2.filter((_, at5) => at5 !== index) };
10094
10159
  }
10095
10160
  return { sandbox: void 0, others: words2 };
10096
10161
  }
@@ -10108,6 +10173,8 @@ var SUBCOMMANDS = {
10108
10173
  limits: ["budget"],
10109
10174
  egress: ["budget", "use-case"],
10110
10175
  tailscale: ["status", "connect", "disconnect"],
10176
+ guild: ["list", "show", "create", "delete", "attach", "detach", "mine", "join", "members", "leave", "handover", "post", "read", "requests", "claim", "answer", "close", "notes", "pause", "resume"],
10177
+ subscriptions: ["list", "sign-in", "delete"],
10111
10178
  telemetry: ["set", "test", "unset"],
10112
10179
  ci: ["jobs", "set", "reset"],
10113
10180
  org: ["list", "use", "create"],
@@ -10339,7 +10406,7 @@ async function jobs(api2) {
10339
10406
  });
10340
10407
  }
10341
10408
  var KEPT_MS = 3e4;
10342
- async function cached(what, as, ask13) {
10409
+ async function cached(what, as, ask14) {
10343
10410
  const folder = path5.join(process.env["XDG_CACHE_HOME"] || path5.join(os6.homedir(), ".cache"), "agental");
10344
10411
  const file = path5.join(folder, `complete-${what}-${createHash2("sha256").update(as).digest("hex").slice(0, 16)}.json`);
10345
10412
  try {
@@ -10351,7 +10418,7 @@ async function cached(what, as, ask13) {
10351
10418
  }
10352
10419
  let body = null;
10353
10420
  try {
10354
- body = await ask13();
10421
+ body = await ask14();
10355
10422
  } catch {
10356
10423
  return null;
10357
10424
  }
@@ -10515,12 +10582,12 @@ async function organizations(client) {
10515
10582
  const me = await ask5(client, "GET", "/v1/me");
10516
10583
  return { organizations: Array.isArray(listed2) ? listed2 : [], acting: String(me["activeOrganizationId"] ?? "") };
10517
10584
  }
10518
- function organizationNamed(list5, given) {
10519
- const byId = list5.find((organization) => organization.id === given);
10585
+ function organizationNamed(list6, given) {
10586
+ const byId = list6.find((organization) => organization.id === given);
10520
10587
  if (byId) {
10521
10588
  return byId;
10522
10589
  }
10523
- const byName = list5.filter((organization) => organization.name.toLowerCase() === given.toLowerCase());
10590
+ const byName = list6.filter((organization) => organization.name.toLowerCase() === given.toLowerCase());
10524
10591
  if (byName.length === 1 && byName[0]) {
10525
10592
  return byName[0];
10526
10593
  }
@@ -10533,14 +10600,14 @@ async function org(client, positionals, options, signInTo) {
10533
10600
  const [verb = "list", ...rest] = positionals;
10534
10601
  switch (verb) {
10535
10602
  case "list": {
10536
- const { organizations: list5, acting } = await organizations(client);
10603
+ const { organizations: list6, acting } = await organizations(client);
10537
10604
  if (options.json) {
10538
- print2(true, { organizations: list5.map((organization) => ({ ...organization, acting: organization.id === acting })) }, "");
10605
+ print2(true, { organizations: list6.map((organization) => ({ ...organization, acting: organization.id === acting })) }, "");
10539
10606
  return;
10540
10607
  }
10541
10608
  process.stdout.write(` ${[pad("ID", 22), pad("NAME", 24), "ROLE"].join(" ")}
10542
10609
  `);
10543
- for (const organization of list5) {
10610
+ for (const organization of list6) {
10544
10611
  const role = organization.personal ? "your own" : organization.role ?? "";
10545
10612
  process.stdout.write(`${organization.id === acting ? "*" : " "} ${[pad(organization.id, 22), pad(organization.name, 24), role].join(" ")}
10546
10613
  `);
@@ -10553,8 +10620,8 @@ async function org(client, positionals, options, signInTo) {
10553
10620
  if (!given) {
10554
10621
  throw new Error("org use takes the organization's id or name: agental org use Acme.");
10555
10622
  }
10556
- const { organizations: list5, acting } = await organizations(client);
10557
- const chosen = organizationNamed(list5, given);
10623
+ const { organizations: list6, acting } = await organizations(client);
10624
+ const chosen = organizationNamed(list6, given);
10558
10625
  if (chosen.id === acting) {
10559
10626
  process.stdout.write(`This command's key acts in ${chosen.name} already.
10560
10627
  `);
@@ -10584,15 +10651,15 @@ agental org use ${organization.id} signs this command in to it.
10584
10651
  }
10585
10652
  }
10586
10653
  async function actingTeam(client) {
10587
- const { organizations: list5, acting } = await organizations(client);
10588
- const team = list5.find((organization) => organization.id === acting);
10654
+ const { organizations: list6, acting } = await organizations(client);
10655
+ const team = list6.find((organization) => organization.id === acting);
10589
10656
  if (!team) {
10590
10657
  throw new Error("This command's key acts in no organization you are in. agental org use <organization> signs it in to one.");
10591
10658
  }
10592
10659
  return team;
10593
10660
  }
10594
- function memberNamed(list5, given) {
10595
- const found = list5.find((member) => member.userId === given || member.email?.toLowerCase() === given.toLowerCase());
10661
+ function memberNamed(list6, given) {
10662
+ const found = list6.find((member) => member.userId === given || member.email?.toLowerCase() === given.toLowerCase());
10596
10663
  if (!found) {
10597
10664
  throw new Error(`No member ${given} in this team. agental members lists them.`);
10598
10665
  }
@@ -10602,7 +10669,7 @@ async function members(client, positionals, options) {
10602
10669
  const [verb = "list", target] = positionals;
10603
10670
  const team = await actingTeam(client);
10604
10671
  const listed2 = await ask5(client, "GET", `/v1/organizations/${encodeURIComponent(team.id)}/members`);
10605
- const list5 = Array.isArray(listed2["members"]) ? listed2["members"] : [];
10672
+ const list6 = Array.isArray(listed2["members"]) ? listed2["members"] : [];
10606
10673
  switch (verb) {
10607
10674
  case "list": {
10608
10675
  if (options.json) {
@@ -10614,7 +10681,7 @@ async function members(client, positionals, options) {
10614
10681
  `);
10615
10682
  process.stdout.write(`${[pad("ID", 34), pad("EMAIL", 30), pad("ROLE", 8), "ADDED"].join(" ")}
10616
10683
  `);
10617
- for (const member of list5) {
10684
+ for (const member of list6) {
10618
10685
  process.stdout.write(`${[pad(member.userId, 34), pad(member.email ?? member.name ?? "", 30), pad(member.role, 8), member.addedAt.slice(0, 10)].join(" ")}
10619
10686
  `);
10620
10687
  }
@@ -10624,7 +10691,7 @@ async function members(client, positionals, options) {
10624
10691
  if (!target) {
10625
10692
  throw new Error("members remove takes the member's id or email: agental members remove cy@example.com.");
10626
10693
  }
10627
- const member = memberNamed(list5, target);
10694
+ const member = memberNamed(list6, target);
10628
10695
  const query = options.revokeKeys ? "?revokeKeys=true" : "";
10629
10696
  const removed = await ask5(client, "DELETE", `/v1/organizations/${encodeURIComponent(team.id)}/members/${encodeURIComponent(member.userId)}${query}`);
10630
10697
  const revoked = Number(removed["revokedKeys"] ?? 0);
@@ -11905,8 +11972,8 @@ function exitOf2(command3) {
11905
11972
  }
11906
11973
  }
11907
11974
  function moment(iso) {
11908
- const at4 = new Date(iso).toISOString().replace(/\.\d+Z$/, "Z");
11909
- return isTerminal(process.stdout) ? ago(iso) ?? at4 : at4;
11975
+ const at5 = new Date(iso).toISOString().replace(/\.\d+Z$/, "Z");
11976
+ return isTerminal(process.stdout) ? ago(iso) ?? at5 : at5;
11910
11977
  }
11911
11978
  function tookOf2(command3) {
11912
11979
  const began = Date.parse(command3.startedAt);
@@ -11970,7 +12037,7 @@ function show(command3, sandbox, asJson) {
11970
12037
  function put(stream, data) {
11971
12038
  return new Promise((resolve, reject) => stream.write(data, (error) => error ? reject(error) : resolve()));
11972
12039
  }
11973
- async function readOutput(client, path6, at4, follow2, wrote) {
12040
+ async function readOutput(client, path6, at5, follow2, wrote) {
11974
12041
  const controller = new AbortController();
11975
12042
  let silence = setTimeout(() => controller.abort(), SILENT_MS);
11976
12043
  const heard = () => {
@@ -11981,7 +12048,7 @@ async function readOutput(client, path6, at4, follow2, wrote) {
11981
12048
  try {
11982
12049
  let response;
11983
12050
  try {
11984
- response = await client.request(`${path6}?stdout=${at4.stdout}&stderr=${at4.stderr}${follow2 ? "&follow=1" : ""}`, { method: "GET", headers: { Accept: "text/event-stream" }, signal: controller.signal });
12051
+ response = await client.request(`${path6}?stdout=${at5.stdout}&stderr=${at5.stderr}${follow2 ? "&follow=1" : ""}`, { method: "GET", headers: { Accept: "text/event-stream" }, signal: controller.signal });
11985
12052
  } catch (error) {
11986
12053
  return { kind: "cut", why: errorText(error), progressed };
11987
12054
  }
@@ -12004,12 +12071,12 @@ async function readOutput(client, path6, at4, follow2, wrote) {
12004
12071
  case "output": {
12005
12072
  const piece = JSON.parse(data2);
12006
12073
  const raw = Buffer.from(piece.data, "base64");
12007
- const skip = Math.max(0, at4[piece.stream] - piece.offset);
12074
+ const skip = Math.max(0, at5[piece.stream] - piece.offset);
12008
12075
  if (skip < raw.length) {
12009
12076
  await put(piece.stream === "stdout" ? process.stdout : process.stderr, raw.subarray(skip));
12010
12077
  wrote();
12011
12078
  }
12012
- at4[piece.stream] = Math.max(at4[piece.stream], piece.offset + raw.length);
12079
+ at5[piece.stream] = Math.max(at5[piece.stream], piece.offset + raw.length);
12013
12080
  progressed = true;
12014
12081
  return null;
12015
12082
  }
@@ -12017,14 +12084,14 @@ async function readOutput(client, path6, at4, follow2, wrote) {
12017
12084
  const gap = JSON.parse(data2);
12018
12085
  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]
12019
12086
  `);
12020
- at4[gap.stream] = Math.max(at4[gap.stream], gap.to);
12087
+ at5[gap.stream] = Math.max(at5[gap.stream], gap.to);
12021
12088
  progressed = true;
12022
12089
  return null;
12023
12090
  }
12024
12091
  case "continue": {
12025
12092
  const next = JSON.parse(data2);
12026
- at4.stdout = Math.max(at4.stdout, next.stdout);
12027
- at4.stderr = Math.max(at4.stderr, next.stderr);
12093
+ at5.stdout = Math.max(at5.stdout, next.stdout);
12094
+ at5.stderr = Math.max(at5.stderr, next.stderr);
12028
12095
  return { kind: "continue" };
12029
12096
  }
12030
12097
  case "end":
@@ -12083,13 +12150,13 @@ async function logs(client, sandbox, id, one, follow2) {
12083
12150
  process.exit(0);
12084
12151
  }
12085
12152
  });
12086
- const at4 = { stdout: 0, stderr: 0 };
12153
+ const at5 = { stdout: 0, stderr: 0 };
12087
12154
  let wrote = false;
12088
12155
  let failed = 0;
12089
12156
  let idle = 0;
12090
12157
  for (; ; ) {
12091
- const from = { ...at4 };
12092
- const read2 = await readOutput(client, `${one}/output`, at4, follow2, () => wrote = true);
12158
+ const from = { ...at5 };
12159
+ const read2 = await readOutput(client, `${one}/output`, at5, follow2, () => wrote = true);
12093
12160
  switch (read2.kind) {
12094
12161
  case "end":
12095
12162
  if (follow2) {
@@ -12102,7 +12169,7 @@ async function logs(client, sandbox, id, one, follow2) {
12102
12169
  `, process.stderr));
12103
12170
  return;
12104
12171
  }
12105
- if (at4.stdout === from.stdout && at4.stderr === from.stderr) {
12172
+ if (at5.stdout === from.stdout && at5.stderr === from.stderr) {
12106
12173
  idle += 1;
12107
12174
  await sleep2(waitBefore(idle));
12108
12175
  continue;
@@ -12802,7 +12869,7 @@ function stateOf3(webhook2) {
12802
12869
  const since = webhook2.disabledAt ? ` since ${at3(webhook2.disabledAt)}` : "";
12803
12870
  return `off${since}${webhook2.disabledReason ? `: ${webhook2.disabledReason}` : ""}`;
12804
12871
  }
12805
- function eventsFrom(options, needed) {
12872
+ function eventsFrom(options, needed2) {
12806
12873
  if (options.all && options.events !== void 0) {
12807
12874
  throw new Error("Give --events or --all, not both.");
12808
12875
  }
@@ -12810,7 +12877,7 @@ function eventsFrom(options, needed) {
12810
12877
  return [EVERY];
12811
12878
  }
12812
12879
  if (options.events === void 0) {
12813
- if (needed) {
12880
+ if (needed2) {
12814
12881
  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.`);
12815
12882
  }
12816
12883
  return void 0;
@@ -13265,16 +13332,16 @@ async function snapshot(client, positionals, options) {
13265
13332
  if (found.kept === STORAGE_ONLY) {
13266
13333
  process.stderr.write("Its server no longer holds it: it is fetched from storage first, which takes a few minutes.\n");
13267
13334
  }
13268
- const answer5 = await ask10(client, "POST", `/v1/sandboxes/${encodeURIComponent(found.sandboxId)}/restore`, {
13335
+ const answer6 = await ask10(client, "POST", `/v1/sandboxes/${encodeURIComponent(found.sandboxId)}/restore`, {
13269
13336
  headers: { "Idempotency-Key": options.idempotencyKey ?? `cli-${randomUUID2()}` },
13270
13337
  body: { snapshotId: found.id }
13271
13338
  });
13272
13339
  if (options.json) {
13273
- process.stdout.write(`${JSON.stringify(answer5, null, 2)}
13340
+ process.stdout.write(`${JSON.stringify(answer6, null, 2)}
13274
13341
  `);
13275
13342
  return;
13276
13343
  }
13277
- const read2 = answer5;
13344
+ const read2 = answer6;
13278
13345
  const discarded = Array.isArray(read2?.discarded) ? read2.discarded.map(String) : [];
13279
13346
  const status = typeof read2?.sandbox?.status === "string" ? `, and ${read2.sandbox.status}` : "";
13280
13347
  process.stdout.write(`${sandbox} is as it was at ${found.name}${status}.
@@ -13314,7 +13381,7 @@ var AgentalError = class extends Error {
13314
13381
  // ../sdk/typescript/src/sealed.ts
13315
13382
  var SEALED_SUITE = "x25519-hkdf-sha256-aes256gcm";
13316
13383
  var ROOT_PUBLIC_KEYS = ["jNdFf3FKdbFQ5J-1e_NE7ZzuaNPRdci-mzlGj384Rmw"];
13317
- var SEALED_PURPOSES = ["variable", "tailscale-oauth"];
13384
+ var SEALED_PURPOSES = ["variable", "tailscale-oauth", "sign-in-code"];
13318
13385
  var KEM_ID = 32;
13319
13386
  var KDF_ID = 1;
13320
13387
  var AEAD_ID = 2;
@@ -13602,10 +13669,10 @@ async function toSeal(client, given, options, verb) {
13602
13669
  if (!given) {
13603
13670
  throw new Error(`secret ${verb} requires <NAME>, and --host: agental secret ${verb} GITHUB_TOKEN --host api.github.com`);
13604
13671
  }
13605
- const at4 = given.indexOf("=");
13606
- const name = nameOf2(at4 < 0 ? given : given.slice(0, at4), verb);
13672
+ const at5 = given.indexOf("=");
13673
+ const name = nameOf2(at5 < 0 ? given : given.slice(0, at5), verb);
13607
13674
  const hosts = hostsOf(options.host, verb);
13608
- const value = at4 < 0 ? await client.readValue(`${name}'s value (not shown): `) : given.slice(at4 + 1);
13675
+ const value = at5 < 0 ? await client.readValue(`${name}'s value (not shown): `) : given.slice(at5 + 1);
13609
13676
  if (value.length < SHORTEST_VALUE) {
13610
13677
  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.`);
13611
13678
  }
@@ -13826,8 +13893,444 @@ function createTailnet(given, flags2 = {}) {
13826
13893
  return joinBody({ ...flags2, json: false, yes: false, tag: [given] }, true);
13827
13894
  }
13828
13895
 
13896
+ // ../src/cli-guilds.ts
13897
+ import { readFileSync as readFileSync7 } from "node:fs";
13898
+ var USAGE9 = "guild takes list, show, create, delete, attach, detach, mine, join, members, leave, handover, post, read, requests, claim, answer, close, notes, pause or resume. agental guild --help shows each.";
13899
+ async function ask11(client, method, pathname, body) {
13900
+ const response = await client.request(pathname, { method, ...body === void 0 ? {} : { body: JSON.stringify(body) } });
13901
+ let answered = null;
13902
+ if (response.status !== 204) {
13903
+ try {
13904
+ answered = await response.json();
13905
+ } catch {
13906
+ answered = null;
13907
+ }
13908
+ }
13909
+ if (!response.ok) {
13910
+ client.fail(response.status, answered);
13911
+ }
13912
+ return answered !== null && typeof answered === "object" ? answered : {};
13913
+ }
13914
+ function print4(json3, body, words2) {
13915
+ process.stdout.write(json3 ? `${JSON.stringify(body, null, 2)}
13916
+ ` : words2);
13917
+ }
13918
+ function at4(name) {
13919
+ return `/v1/guilds/${encodeURIComponent(name)}`;
13920
+ }
13921
+ function needed(value, what) {
13922
+ if (value === void 0 || value === "") {
13923
+ throw new Error(`${what}. ${USAGE9}`);
13924
+ }
13925
+ return value;
13926
+ }
13927
+ function rolesOf(given) {
13928
+ return given.split(",").map((part) => part.trim()).filter((part) => part !== "").map((part) => {
13929
+ const colon = part.lastIndexOf(":");
13930
+ const after = colon === -1 ? "" : part.slice(colon + 1).trim();
13931
+ return /^[0-9]+$/.test(after) ? { name: part.slice(0, colon).trim(), seats: Number(after) } : { name: part };
13932
+ });
13933
+ }
13934
+ function answersOf(given = []) {
13935
+ const answers = {};
13936
+ for (const one of given) {
13937
+ const equals = one.indexOf("=");
13938
+ if (equals < 1) {
13939
+ throw new Error(`--answer takes key=value: ${JSON.stringify(one)} is not.`);
13940
+ }
13941
+ answers[one.slice(0, equals)] = one.slice(equals + 1);
13942
+ }
13943
+ return answers;
13944
+ }
13945
+ function formFrom(file) {
13946
+ let text;
13947
+ try {
13948
+ text = readFileSync7(file, "utf8");
13949
+ } catch (error) {
13950
+ throw new Error(`--form ${file} could not be read: ${error instanceof Error ? error.message : String(error)}`);
13951
+ }
13952
+ try {
13953
+ return JSON.parse(text);
13954
+ } catch {
13955
+ 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}].`);
13956
+ }
13957
+ }
13958
+ function roleLine(role) {
13959
+ return `${String(role["name"])} (${role["seats"] === null ? "any number" : `${String(role["seats"])} seat${role["seats"] === 1 ? "" : "s"}`}, ${String(role["onDelete"])} at a delete)`;
13960
+ }
13961
+ function memberLine(member) {
13962
+ const held = member.holder === null ? "vacant" : member.holder === "outside" ? "held outside agental" : member.sandboxId ? `held by ${member.sandboxId}` : "held by a sandbox";
13963
+ return `${member.id} ${member.name}, ${member.role}, ${held}
13964
+ `;
13965
+ }
13966
+ async function actingAs(client, guild2, given) {
13967
+ if (given !== void 0) {
13968
+ return await memberNamed2(client, guild2, given);
13969
+ }
13970
+ const answer6 = await client.request("/v1/guilds/mine", { method: "GET" });
13971
+ const mine = answer6.ok ? (await answer6.json())["guilds"] ?? [] : [];
13972
+ const held = mine.filter((one) => one["guild"]["name"] === guild2).flatMap((one) => one["held"]);
13973
+ if (held.length === 1) {
13974
+ return held[0] ?? null;
13975
+ }
13976
+ if (held.length > 1) {
13977
+ throw new Error(`You hold ${held.length} identities in ${guild2}: say which with --as ${held.map((member) => member.name).join(" | ")}.`);
13978
+ }
13979
+ return null;
13980
+ }
13981
+ function messageLine(message) {
13982
+ const to = message.toRole ? ` to ${message.toRole}` : message.to ? ` to ${message.to.length} identit${message.to.length === 1 ? "y" : "ies"}` : "";
13983
+ const what = message.kind === "request" ? ` request ${message.id}${message.request?.open ? message.request.claimedBy ? ", taken" : ", open" : `, ${message.request?.closedReason ?? "closed"}`}` : message.kind === "answer" ? ` answer to ${message.answers ?? ""}` : "";
13984
+ return `#${message.seq} ${message.from.name}${to}${what}: ${message.text}
13985
+ `;
13986
+ }
13987
+ function channelOf(options) {
13988
+ return encodeURIComponent((options.channel ?? "general").replace(/^#/, ""));
13989
+ }
13990
+ async function memberNamed2(client, guild2, given) {
13991
+ const members2 = (await ask11(client, "GET", `${at4(guild2)}/members`))["members"] ?? [];
13992
+ const found = members2.find((member) => member.id === given) ?? members2.find((member) => member.name.toLowerCase() === given.toLowerCase());
13993
+ if (!found) {
13994
+ throw new Error(`Guild ${guild2} has no identity ${JSON.stringify(given)}. agental guild members ${guild2} lists them.`);
13995
+ }
13996
+ return found;
13997
+ }
13998
+ async function guild(client, positionals, options) {
13999
+ const [verb = client.onToken ? "mine" : "list", name, third, fourth] = positionals;
14000
+ switch (verb) {
14001
+ case "list": {
14002
+ const listed2 = (await ask11(client, "GET", "/v1/guilds"))["guilds"] ?? [];
14003
+ 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(", ")}
14004
+ `).join(""));
14005
+ return;
14006
+ }
14007
+ case "show": {
14008
+ const found = await ask11(client, "GET", at4(needed(name, "show takes a guild")));
14009
+ const members2 = (await ask11(client, "GET", `${at4(String(found["name"]))}/members`))["members"] ?? [];
14010
+ const words2 = [
14011
+ `${String(found["name"])}
14012
+ `,
14013
+ found["brief"] ? ` ${String(found["brief"])}
14014
+ ` : "",
14015
+ `roles
14016
+ ${found["roles"].map((role) => ` ${roleLine(role)}
14017
+ `).join("")}`,
14018
+ found["form"].length ? `form
14019
+ ${found["form"].map((field) => ` ${String(field["key"])}: ${String(field["label"])}${field["required"] ? " (required)" : ""}
14020
+ `).join("")}` : "",
14021
+ `templates
14022
+ ${found["templates"].map((one) => ` ${String(one["templateId"])}${one["roles"] ? ` as ${one["roles"].join(", ")}` : ", any role"}
14023
+ `).join("") || " none\n"}`,
14024
+ `identities
14025
+ ${members2.map((member) => ` ${memberLine(member)}`).join("") || " none\n"}`
14026
+ ].join("");
14027
+ print4(options.json, { ...found, members: members2 }, words2);
14028
+ return;
14029
+ }
14030
+ case "create": {
14031
+ const body = {
14032
+ name: needed(name, "create takes a guild's name"),
14033
+ roles: rolesOf(needed(options.roles, 'create takes --roles, such as "blog manager:1,reviewer:2"')),
14034
+ ...options.brief === void 0 ? {} : { brief: options.brief },
14035
+ ...options.form === void 0 ? {} : { form: formFrom(options.form) }
14036
+ };
14037
+ const made = await ask11(client, "POST", "/v1/guilds", body);
14038
+ print4(options.json, made, `Made guild ${String(made["name"])}. agental guild attach ${String(made["name"])} <template> lets that template's sandboxes join it.
14039
+ `);
14040
+ return;
14041
+ }
14042
+ case "delete": {
14043
+ const guildName = needed(name, "delete takes a guild");
14044
+ if (!options.yes && !await client.confirmed(`Delete guild ${guildName} and every identity in it, for good? [y/N] `)) {
14045
+ throw new Error(`Nothing was deleted. agental guild delete ${guildName} --yes deletes it without asking.`);
14046
+ }
14047
+ await ask11(client, "DELETE", at4(guildName));
14048
+ print4(options.json, { deleted: name }, `Deleted guild ${String(name)}, with its identities.
14049
+ `);
14050
+ return;
14051
+ }
14052
+ case "attach": {
14053
+ const template2 = await client.templateId(needed(third, "attach takes a guild and a template"));
14054
+ const roles = options.roles === void 0 ? {} : { roles: rolesOf(options.roles).map((role) => role.name) };
14055
+ const attached = await ask11(client, "PUT", `${at4(needed(name, "attach takes a guild"))}/templates/${encodeURIComponent(template2)}`, roles);
14056
+ print4(options.json, attached, `Sandboxes of ${template2} may join ${String(name)}${attached["roles"] ? ` as ${attached["roles"].join(" or ")}` : ", in any role"}.
14057
+ `);
14058
+ return;
14059
+ }
14060
+ case "detach": {
14061
+ const template2 = await client.templateId(needed(third, "detach takes a guild and a template"));
14062
+ await ask11(client, "DELETE", `${at4(needed(name, "detach takes a guild"))}/templates/${encodeURIComponent(template2)}`);
14063
+ print4(options.json, { detached: template2 }, `Sandboxes of ${template2} may no longer join ${String(name)}.
14064
+ `);
14065
+ return;
14066
+ }
14067
+ case "mine": {
14068
+ const mine = (await ask11(client, "GET", "/v1/guilds/mine"))["guilds"] ?? [];
14069
+ const words2 = mine.map((one) => {
14070
+ const found = one["guild"];
14071
+ const open = one["rolesOpen"] === null ? "any role" : one["rolesOpen"].join(", ") || "none";
14072
+ const held = one["held"].map((member) => ` you are ${member.name}, ${member.role} (${member.id})
14073
+ `).join("");
14074
+ return `${String(found["name"])} open to you: ${open}
14075
+ ${held}`;
14076
+ }).join("");
14077
+ print4(options.json, mine, words2 || "No guild: this sandbox's template is attached to none, and it holds no identity.\n");
14078
+ return;
14079
+ }
14080
+ case "join": {
14081
+ const joined = await ask11(client, "POST", `${at4(needed(name, "join takes a guild"))}/members`, {
14082
+ name: needed(options.as, "join takes --as <the name you will be known by>"),
14083
+ role: needed(options.role, "join takes --role <one of the guild's roles>"),
14084
+ ...options.answer === void 0 ? {} : { answers: answersOf(options.answer) }
14085
+ });
14086
+ print4(options.json, joined, `You are ${String(joined["name"])}, ${String(joined["role"])} of ${String(name)} (${String(joined["id"])}).
14087
+ `);
14088
+ return;
14089
+ }
14090
+ case "members": {
14091
+ const members2 = (await ask11(client, "GET", `${at4(needed(name, "members takes a guild"))}/members`))["members"] ?? [];
14092
+ print4(options.json, members2, members2.map(memberLine).join("") || "No identities yet.\n");
14093
+ return;
14094
+ }
14095
+ case "leave": {
14096
+ const guildName = needed(name, "leave takes a guild and an identity");
14097
+ const member = await memberNamed2(client, guildName, needed(third, "leave takes a guild and an identity"));
14098
+ await ask11(client, "DELETE", `${at4(guildName)}/members/${encodeURIComponent(member.id)}`);
14099
+ print4(options.json, { left: member.id }, `${member.name} has left ${guildName}; the name and its seat are free.
14100
+ `);
14101
+ return;
14102
+ }
14103
+ case "handover": {
14104
+ const guildName = needed(name, "handover takes a guild, an identity and a sandbox");
14105
+ const member = await memberNamed2(client, guildName, needed(third, "handover takes a guild, an identity and a sandbox"));
14106
+ const sandbox = await ask11(client, "GET", `/v1/sandboxes/${encodeURIComponent(needed(fourth, "handover takes a sandbox"))}`);
14107
+ const handed = await ask11(client, "POST", `${at4(guildName)}/members/${encodeURIComponent(member.id)}/handover`, { sandboxId: String(sandbox["id"]) });
14108
+ print4(options.json, handed, `${member.name} is held by ${String(sandbox["name"] ?? sandbox["id"])} now.
14109
+ `);
14110
+ return;
14111
+ }
14112
+ case "post": {
14113
+ const guildName = needed(name, "post takes a guild and the text");
14114
+ const text = needed(positionals.slice(2).join(" ") || options.text, "post takes the text, after the guild");
14115
+ const as = await actingAs(client, guildName, options.as);
14116
+ const members2 = options.to === void 0 ? [] : (await ask11(client, "GET", `${at4(guildName)}/members`))["members"] ?? [];
14117
+ const to = options.to?.split(",").map((one) => one.trim()).filter((one) => one !== "").map((one) => (members2.find((member) => member.id === one || member.name.toLowerCase() === one.toLowerCase()) ?? { id: one }).id);
14118
+ const posted = await ask11(client, "POST", `${at4(guildName)}/channels/${channelOf(options)}/messages`, {
14119
+ text,
14120
+ ...as === null ? {} : { as: as.id },
14121
+ ...to === void 0 ? {} : { to },
14122
+ ...options.toRole === void 0 ? {} : { toRole: options.toRole },
14123
+ ...options.request ? { request: true } : {},
14124
+ ...options.answers === void 0 ? {} : { answers: options.answers },
14125
+ ...options.retryKey === void 0 ? {} : { retryKey: options.retryKey }
14126
+ });
14127
+ print4(options.json, posted, messageLine(posted));
14128
+ return;
14129
+ }
14130
+ case "answer": {
14131
+ const guildName = needed(name, "answer takes a guild, a request and the text");
14132
+ await guild(client, ["post", guildName, ...positionals.slice(3)], { ...options, answers: needed(third, "answer takes the request's ID") });
14133
+ return;
14134
+ }
14135
+ case "read": {
14136
+ const guildName = needed(name, "read takes a guild");
14137
+ const as = await actingAs(client, guildName, options.as);
14138
+ const query = new URLSearchParams({
14139
+ ...as === null ? {} : { as: as.id },
14140
+ ...options.after === void 0 ? {} : { after: options.after },
14141
+ ...options.waitSeconds === void 0 ? {} : { wait: options.waitSeconds }
14142
+ });
14143
+ const read2 = await ask11(client, "GET", `${at4(guildName)}/channels/${channelOf(options)}/messages?${query.toString()}`);
14144
+ const messages = read2["messages"] ?? [];
14145
+ const last = messages.at(-1);
14146
+ if (options.done && as !== null && last !== void 0) {
14147
+ await ask11(client, "POST", `${at4(guildName)}/channels/${channelOf(options)}/place`, { as: as.id, upTo: last.seq });
14148
+ }
14149
+ print4(options.json, read2, messages.map(messageLine).join("") || "No new messages.\n");
14150
+ return;
14151
+ }
14152
+ case "requests": {
14153
+ const guildName = needed(name, "requests takes a guild");
14154
+ const as = await actingAs(client, guildName, options.as);
14155
+ const found = await ask11(client, "GET", `${at4(guildName)}/requests${as === null ? "" : `?as=${encodeURIComponent(as.id)}`}`);
14156
+ const section = (title, list6) => list6.length ? `${title}
14157
+ ${list6.map((one) => ` ${messageLine(one)}`).join("")}` : "";
14158
+ print4(options.json, found, section("you owe", found["owed"]) + section("you wait on", found["waiting"]) + section("open", found["open"]) || "No open requests.\n");
14159
+ return;
14160
+ }
14161
+ case "claim": {
14162
+ const guildName = needed(name, "claim takes a guild and a request");
14163
+ const as = await actingAs(client, guildName, options.as);
14164
+ if (as === null) {
14165
+ throw new Error(`claim takes the identity you hold in ${guildName}: --as <identity>.`);
14166
+ }
14167
+ const claimed = await ask11(client, "POST", `${at4(guildName)}/requests/${encodeURIComponent(needed(third, "claim takes the request's ID"))}/claim`, { as: as.id });
14168
+ print4(options.json, claimed, `${as.name} took request ${claimed.id} for 30 minutes. Answer it with agental guild answer ${guildName} ${claimed.id} <text>.
14169
+ `);
14170
+ return;
14171
+ }
14172
+ case "close": {
14173
+ const guildName = needed(name, "close takes a guild and a request");
14174
+ const as = await actingAs(client, guildName, options.as);
14175
+ const closed = await ask11(client, "POST", `${at4(guildName)}/requests/${encodeURIComponent(needed(third, "close takes the request's ID"))}/close`, as === null ? {} : { as: as.id });
14176
+ print4(options.json, closed, `Request ${closed.id} is closed (${closed.request?.closedReason ?? "closed"}).
14177
+ `);
14178
+ return;
14179
+ }
14180
+ case "notes": {
14181
+ const guildName = needed(name, "notes takes a guild");
14182
+ const member = third === void 0 ? await actingAs(client, guildName, options.as) : await memberNamed2(client, guildName, third);
14183
+ if (member === null) {
14184
+ throw new Error(`notes takes an identity: agental guild notes ${guildName} <identity>.`);
14185
+ }
14186
+ const path6 = `${at4(guildName)}/members/${encodeURIComponent(member.id)}/notes`;
14187
+ const notes = options.text === void 0 ? await ask11(client, "GET", path6) : await ask11(client, "PUT", path6, { text: options.text });
14188
+ print4(options.json, notes, `${String(notes["text"]) || `${member.name} has no notes yet.`}
14189
+ `);
14190
+ return;
14191
+ }
14192
+ case "pause":
14193
+ case "resume": {
14194
+ const found = await ask11(client, "POST", `${at4(needed(name, `${verb} takes a guild`))}/${verb}`);
14195
+ print4(options.json, found, verb === "pause" ? `${String(name)}'s agents are paused until you resume them.
14196
+ ` : `${String(name)}'s agents may post again.
14197
+ `);
14198
+ return;
14199
+ }
14200
+ default:
14201
+ throw new Error(USAGE9);
14202
+ }
14203
+ }
14204
+
14205
+ // ../src/cli-subscriptions.ts
14206
+ var AGENTS = ["claude", "codex", "copilot", "grok"];
14207
+ var USES = ["off", "subscription", "api_key"];
14208
+ var CLAUDE_TOKEN_HOST = "platform.claude.com";
14209
+ 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.";
14210
+ async function subscriptions(client, positionals, options) {
14211
+ const [verb, agent] = positionals;
14212
+ switch (verb) {
14213
+ case void 0:
14214
+ case "list":
14215
+ return await list4(client, options);
14216
+ case "sign-in":
14217
+ return await signIn(client, agentOf2(agent), options);
14218
+ case "delete":
14219
+ return await remove3(client, agentOf2(agent), options);
14220
+ default:
14221
+ throw new Error(`agental subscriptions ${verb} is not a command. ${USAGE10}`);
14222
+ }
14223
+ }
14224
+ async function agents(client, positionals, options) {
14225
+ if (options.template === void 0 === (options.sandbox === void 0)) {
14226
+ throw new Error("agents takes --template <template> or --sandbox <sandbox-id>, one of them.");
14227
+ }
14228
+ const path6 = options.template !== void 0 ? `/v1/templates/${encodeURIComponent(await client.templateId(options.template))}` : `/v1/sandboxes/${encodeURIComponent(options.sandbox ?? "")}`;
14229
+ const [agent, use2] = positionals;
14230
+ let choices;
14231
+ if (agent === void 0) {
14232
+ choices = (await answer4(client, `${path6}/agents`, { method: "GET" })).agents;
14233
+ } else {
14234
+ const allowed = options.sandbox !== void 0 ? [...USES, "template"] : USES;
14235
+ if (use2 === void 0 || !allowed.includes(use2)) {
14236
+ throw new Error(`agents ${agent} takes one of ${allowed.join(", ")}.`);
14237
+ }
14238
+ choices = (await answer4(client, `${path6}/agents/${agentOf2(agent)}`, { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ use: use2 }) })).agents;
14239
+ }
14240
+ if (options.json) {
14241
+ process.stdout.write(`${JSON.stringify({ agents: choices }, null, 2)}
14242
+ `);
14243
+ return;
14244
+ }
14245
+ for (const c of choices) {
14246
+ const where = c.use === "api_key" && c.kept === "variable" ? ` (its own variable ${c.secret ?? ""})` : c.secret ? ` (${c.secret})` : "";
14247
+ const from = options.sandbox !== void 0 ? ` ${c.from === "sandbox" ? "set on the sandbox" : "from its template"}` : "";
14248
+ process.stdout.write(`${c.agent} ${c.use}${where}${c.signedOut ? " signed out: sign in again" : ""}${from}
14249
+ `);
14250
+ }
14251
+ }
14252
+ async function list4(client, options) {
14253
+ const { subscriptions: all } = await answer4(client, "/v1/subscriptions", { method: "GET" });
14254
+ if (options.json) {
14255
+ process.stdout.write(`${JSON.stringify({ subscriptions: all }, null, 2)}
14256
+ `);
14257
+ return;
14258
+ }
14259
+ for (const s of all) {
14260
+ process.stdout.write(`${s.agent} ${s.state.replace("_", " ")}${s.account?.plan ? ` ${s.account.plan}` : ""}${s.why ? ` ${s.why}` : ""}
14261
+ `);
14262
+ }
14263
+ }
14264
+ async function signIn(client, agent, options) {
14265
+ let now = await answer4(client, `/v1/subscriptions/${agent}/sign-in`, { method: "POST" });
14266
+ const shown = now.signIn;
14267
+ if (shown === null) {
14268
+ throw new Error("The sign-in was not begun: the API showed nothing to approve.");
14269
+ }
14270
+ if (shown.authorizeUrl !== null) {
14271
+ process.stderr.write(`Open this page, sign in to Claude, and copy the code it shows:
14272
+ ${shown.authorizeUrl}
14273
+ `);
14274
+ const code = (await client.readValue("Paste the code: ")).trim();
14275
+ if (!code.includes("#")) {
14276
+ throw new Error("Paste the whole code the page shows, with the part after its #. Nothing was sent.");
14277
+ }
14278
+ const { sealed } = await sealForAccount(client, now.secret, code, [CLAUDE_TOKEN_HOST], "sign-in-code");
14279
+ now = await answer4(client, `/v1/subscriptions/${agent}/code`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ sealed: sealed[0] }) });
14280
+ } else {
14281
+ process.stderr.write(`Open ${shown.verificationUrl ?? ""} and enter the code ${shown.userCode ?? ""} (good until ${shown.expiresAt}). Waiting for it\u2026
14282
+ `);
14283
+ const until2 = Date.parse(shown.expiresAt) + 6e4;
14284
+ while (now.state === "signing_in" && Date.now() < until2) {
14285
+ await new Promise((resolve) => setTimeout(resolve, options.intervalMs ?? 5e3));
14286
+ now = await answer4(client, `/v1/subscriptions/${agent}`, { method: "GET" });
14287
+ }
14288
+ }
14289
+ if (options.json) {
14290
+ process.stdout.write(`${JSON.stringify(now, null, 2)}
14291
+ `);
14292
+ } else if (now.state === "signed_in") {
14293
+ 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
14294
+ `);
14295
+ } else {
14296
+ process.stdout.write(`Not signed in to ${agent}${now.why ? `: ${now.why}` : ""}.
14297
+ `);
14298
+ }
14299
+ if (now.state !== "signed_in") {
14300
+ process.exitCode = 1;
14301
+ }
14302
+ }
14303
+ async function remove3(client, agent, options) {
14304
+ if (!options.yes && !await client.confirmed(`Delete the ${agent} subscription, and take it off every template and sandbox that uses it?`)) {
14305
+ process.stdout.write("Nothing was deleted.\n");
14306
+ return;
14307
+ }
14308
+ const after = await answer4(client, `/v1/subscriptions/${agent}`, { method: "DELETE" });
14309
+ if (options.json) {
14310
+ process.stdout.write(`${JSON.stringify(after, null, 2)}
14311
+ `);
14312
+ return;
14313
+ }
14314
+ process.stdout.write(`Deleted here. To end it on ${agent}'s side too: ${after.revokeAt}
14315
+ `);
14316
+ }
14317
+ function agentOf2(given) {
14318
+ if (given === void 0 || !AGENTS.includes(given)) {
14319
+ throw new Error(`Name the agent: ${AGENTS.join(", ")}.`);
14320
+ }
14321
+ return given;
14322
+ }
14323
+ async function answer4(client, path6, init) {
14324
+ const res = await client.request(path6, init);
14325
+ const body = await res.json().catch(() => null);
14326
+ if (!res.ok) {
14327
+ client.fail(res.status, body);
14328
+ }
14329
+ return body;
14330
+ }
14331
+
13829
14332
  // ../src/cli-sites.ts
13830
- var USAGE9 = "site takes a sandbox, or list, add, rm, stats or analytics, then the sandbox. agental site --help shows each.";
14333
+ var USAGE11 = "site takes a sandbox, or list, add, rm, stats or analytics, then the sandbox. agental site --help shows each.";
13831
14334
  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.";
13832
14335
  var REPORT_ROWS = 5;
13833
14336
  async function bodyOf2(response) {
@@ -13837,7 +14340,7 @@ async function bodyOf2(response) {
13837
14340
  return null;
13838
14341
  }
13839
14342
  }
13840
- async function ask11(client, method, pathname, body) {
14343
+ async function ask12(client, method, pathname, body) {
13841
14344
  const response = await client.request(pathname, { method, ...body === void 0 ? {} : { body: JSON.stringify(body) } });
13842
14345
  const answered = await bodyOf2(response);
13843
14346
  if (!response.ok) {
@@ -13853,7 +14356,7 @@ function routeOf(body) {
13853
14356
  }
13854
14357
  var isSite = (route) => route.public && !route.hidden;
13855
14358
  async function sitesOf(client, sandbox) {
13856
- const body = await ask11(client, "GET", `/v1/sandboxes/${encodeURIComponent(sandbox)}/host`);
14359
+ const body = await ask12(client, "GET", `/v1/sandboxes/${encodeURIComponent(sandbox)}/host`);
13857
14360
  return (Array.isArray(body?.routes) ? body.routes : []).map(routeOf).filter(isSite);
13858
14361
  }
13859
14362
  function stateOf4(route) {
@@ -13938,7 +14441,7 @@ async function siteSwitch(client, turn, words2, options) {
13938
14441
  process.exitCode = 1;
13939
14442
  return;
13940
14443
  }
13941
- const report = await ask11(client, "PUT", `/v1/host-routes/${encodeURIComponent(target)}/analytics`, { enabled: turn === "on" });
14444
+ const report = await ask12(client, "PUT", `/v1/host-routes/${encodeURIComponent(target)}/analytics`, { enabled: turn === "on" });
13942
14445
  if (options.json) {
13943
14446
  process.stdout.write(`${reportJson(report)}
13944
14447
  `);
@@ -13964,7 +14467,7 @@ async function organizationSwitch(client, words2, options) {
13964
14467
  }
13965
14468
  let setting;
13966
14469
  if (turn === void 0) {
13967
- setting = await ask11(client, "GET", "/v1/site-analytics");
14470
+ setting = await ask12(client, "GET", "/v1/site-analytics");
13968
14471
  } else {
13969
14472
  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.")) {
13970
14473
  process.stderr.write("Nothing was changed. --yes goes on without asking.\n");
@@ -14016,13 +14519,13 @@ async function site(client, positionals, options) {
14016
14519
  const verb = positionals[0] === "list" || positionals[0] === "add" || positionals[0] === "rm" || positionals[0] === "stats" ? positionals[0] : null;
14017
14520
  const [sandbox, target, ...rest] = verb === null ? positionals : positionals.slice(1);
14018
14521
  if (sandbox === void 0) {
14019
- throw new Error(USAGE9);
14522
+ throw new Error(USAGE11);
14020
14523
  }
14021
14524
  switch (verb) {
14022
14525
  case null:
14023
14526
  case "list": {
14024
14527
  if (target !== void 0) {
14025
- throw new Error(USAGE9);
14528
+ throw new Error(USAGE11);
14026
14529
  }
14027
14530
  const sites = await sitesOf(client, sandbox);
14028
14531
  if (options.json) {
@@ -14042,10 +14545,10 @@ async function site(client, positionals, options) {
14042
14545
  }
14043
14546
  case "add": {
14044
14547
  if (rest.length > 0) {
14045
- throw new Error(USAGE9);
14548
+ throw new Error(USAGE11);
14046
14549
  }
14047
14550
  const port = portFrom(target);
14048
- const made = routeOf(await ask11(client, "POST", `/v1/sandboxes/${encodeURIComponent(sandbox)}/host`, { port, title: `port-${port}`, public: true }));
14551
+ const made = routeOf(await ask12(client, "POST", `/v1/sandboxes/${encodeURIComponent(sandbox)}/host`, { port, title: `port-${port}`, public: true }));
14049
14552
  if (options.json) {
14050
14553
  process.stdout.write(`${JSON.stringify(made, null, 2)}
14051
14554
  `);
@@ -14070,7 +14573,7 @@ async function site(client, positionals, options) {
14070
14573
  throw new Error(`site rm needs the sandbox and the site's id, as agental site ${sandbox} lists them.`);
14071
14574
  }
14072
14575
  const found = await siteOn(client, sandbox, target);
14073
- await ask11(client, "POST", `/v1/host-routes/${encodeURIComponent(target)}/hide`);
14576
+ await ask12(client, "POST", `/v1/host-routes/${encodeURIComponent(target)}/hide`);
14074
14577
  process.stdout.write(`Removed. ${found.url ?? `Port ${found.port}`} stops working now; adding port ${found.port} again gives a new link.
14075
14578
  `);
14076
14579
  return;
@@ -14084,7 +14587,7 @@ async function site(client, positionals, options) {
14084
14587
  throw new Error(`--range is 24h or 7d. It was given ${range}.`);
14085
14588
  }
14086
14589
  await siteOn(client, sandbox, target);
14087
- const report = await ask11(client, "GET", `/v1/host-routes/${encodeURIComponent(target)}/analytics?range=${range}`);
14590
+ const report = await ask12(client, "GET", `/v1/host-routes/${encodeURIComponent(target)}/analytics?range=${range}`);
14088
14591
  process.stdout.write(options.json ? `${reportJson(report)}
14089
14592
  ` : reportIn(report, sandbox, target));
14090
14593
  return;
@@ -14093,10 +14596,10 @@ async function site(client, positionals, options) {
14093
14596
  }
14094
14597
 
14095
14598
  // ../src/cli-claude.ts
14096
- var USAGE10 = "claude takes connect, show, update or disconnect. agental claude --help shows each.";
14599
+ var USAGE12 = "claude takes connect, show, update or disconnect. agental claude --help shows each.";
14097
14600
  var KEY_VARIABLE = "ANTHROPIC_ENVIRONMENT_KEY";
14098
14601
  var SECRET_VARIABLE = "ANTHROPIC_WEBHOOK_SIGNING_KEY";
14099
- async function ask12(client, method, pathname, body) {
14602
+ async function ask13(client, method, pathname, body) {
14100
14603
  const response = await client.request(pathname, { method, ...body === void 0 ? {} : { body: JSON.stringify(body) } });
14101
14604
  let answered = null;
14102
14605
  if (response.status !== 204) {
@@ -14178,15 +14681,15 @@ async function hidden(question) {
14178
14681
  const muted = lines;
14179
14682
  process.stderr.write(question);
14180
14683
  muted._writeToOutput = () => void 0;
14181
- lines.question("", (answer5) => {
14684
+ lines.question("", (answer6) => {
14182
14685
  lines.close();
14183
14686
  process.stderr.write("\n");
14184
- resolve(answer5.trim());
14687
+ resolve(answer6.trim());
14185
14688
  });
14186
14689
  });
14187
14690
  }
14188
14691
  async function listClaude(client, asJson) {
14189
- const body = await ask12(client, "GET", "/v1/claude/connections");
14692
+ const body = await ask13(client, "GET", "/v1/claude/connections");
14190
14693
  if (asJson) {
14191
14694
  process.stdout.write(`${JSON.stringify(body, null, 2)}
14192
14695
  `);
@@ -14208,7 +14711,7 @@ async function listClaude(client, asJson) {
14208
14711
  async function claude(client, positionals, options) {
14209
14712
  const [what, target, ...rest] = positionals;
14210
14713
  if (rest.length > 0) {
14211
- throw new Error(USAGE10);
14714
+ throw new Error(USAGE12);
14212
14715
  }
14213
14716
  switch (what) {
14214
14717
  case "connect": {
@@ -14220,7 +14723,7 @@ async function claude(client, positionals, options) {
14220
14723
  const environmentKey = await secretFrom(KEY_VARIABLE, "environment key", true);
14221
14724
  const webhookSecret = await secretFrom(SECRET_VARIABLE, "webhook signing secret", false);
14222
14725
  const made = connectionOf(
14223
- await ask12(client, "POST", "/v1/claude/connections", {
14726
+ await ask13(client, "POST", "/v1/claude/connections", {
14224
14727
  environmentId: target,
14225
14728
  environmentKey,
14226
14729
  ...webhookSecret !== void 0 ? { webhookSecret } : {},
@@ -14242,7 +14745,7 @@ async function claude(client, positionals, options) {
14242
14745
  return;
14243
14746
  }
14244
14747
  case "show": {
14245
- const found = connectionOf(await ask12(client, "GET", `/v1/claude/connections/${encodeURIComponent(needId2(target, "show"))}`));
14748
+ const found = connectionOf(await ask13(client, "GET", `/v1/claude/connections/${encodeURIComponent(needId2(target, "show"))}`));
14246
14749
  process.stdout.write(options.json ? `${JSON.stringify(found, null, 2)}
14247
14750
  ` : describe6(found));
14248
14751
  return;
@@ -14265,18 +14768,18 @@ async function claude(client, positionals, options) {
14265
14768
  if (Object.keys(patch).length === 0) {
14266
14769
  throw new Error("claude update changes --template, --keep-days, --new-key, --webhook-secret or --no-webhook-secret, and was given none of them.");
14267
14770
  }
14268
- const updated = connectionOf(await ask12(client, "PATCH", `/v1/claude/connections/${encodeURIComponent(id)}`, patch));
14771
+ const updated = connectionOf(await ask13(client, "PATCH", `/v1/claude/connections/${encodeURIComponent(id)}`, patch));
14269
14772
  process.stdout.write(options.json ? `${JSON.stringify(updated, null, 2)}
14270
14773
  ` : describe6(updated));
14271
14774
  return;
14272
14775
  }
14273
14776
  case "disconnect": {
14274
- await ask12(client, "DELETE", `/v1/claude/connections/${encodeURIComponent(needId2(target, "disconnect"))}`);
14777
+ await ask13(client, "DELETE", `/v1/claude/connections/${encodeURIComponent(needId2(target, "disconnect"))}`);
14275
14778
  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");
14276
14779
  return;
14277
14780
  }
14278
14781
  default:
14279
- throw new Error(USAGE10);
14782
+ throw new Error(USAGE12);
14280
14783
  }
14281
14784
  }
14282
14785
  function needId2(id, what) {
@@ -14327,7 +14830,7 @@ function whyClosed(code, reason2, error) {
14327
14830
  return `The terminal was closed (${code})${said ? `: ${said}` : ""}.`;
14328
14831
  }
14329
14832
  }
14330
- async function answer4(response) {
14833
+ async function answer5(response) {
14331
14834
  const body = await response.json().catch(() => null);
14332
14835
  if (!response.ok) {
14333
14836
  const error = body?.error;
@@ -14336,7 +14839,7 @@ async function answer4(response) {
14336
14839
  return body;
14337
14840
  }
14338
14841
  async function keptShells2(client, id) {
14339
- const body = await answer4(await client.request(`/v1/sandboxes/${encodeURIComponent(id)}/terminals`, { method: "GET" }));
14842
+ const body = await answer5(await client.request(`/v1/sandboxes/${encodeURIComponent(id)}/terminals`, { method: "GET" }));
14340
14843
  if (!body || !Array.isArray(body.terminals)) {
14341
14844
  throw new Error("The list of kept shells was missing terminals.");
14342
14845
  }
@@ -14390,7 +14893,7 @@ async function listShells(client, id, json3, stdout) {
14390
14893
  }
14391
14894
  async function closeShell(client, id, given, stdout) {
14392
14895
  const found = await shellNamed(client, id, given, "--close");
14393
- await answer4(await client.request(`/v1/sandboxes/${encodeURIComponent(id)}/terminals/${encodeURIComponent(found.id)}`, { method: "DELETE" }));
14896
+ await answer5(await client.request(`/v1/sandboxes/${encodeURIComponent(id)}/terminals/${encodeURIComponent(found.id)}`, { method: "DELETE" }));
14394
14897
  stdout.write(`Closed ${found.n === null ? "shell" : `shell ${found.n}`} (${found.id}).
14395
14898
  `);
14396
14899
  }
@@ -14433,16 +14936,16 @@ async function shell(client, id, options = {}, streams = process) {
14433
14936
  const verifier = randomBytes4(32).toString("base64url");
14434
14937
  const challenge = createHash3("sha256").update(verifier).digest("base64url");
14435
14938
  const interactive = stdin.isTTY === true && typeof stdin.setRawMode === "function";
14436
- const ask13 = async (keep) => await client.request(`/v1/sandboxes/${encodeURIComponent(id)}/terminal`, {
14939
+ const ask14 = async (keep) => await client.request(`/v1/sandboxes/${encodeURIComponent(id)}/terminal`, {
14437
14940
  method: "POST",
14438
14941
  body: JSON.stringify({ ...size2, challenge, ...again ? { terminal: again.id } : keep ? { keep: true } : {} })
14439
14942
  });
14440
- let response = await ask13(interactive);
14943
+ let response = await ask14(interactive);
14441
14944
  let body = await response.json().catch(() => null);
14442
14945
  if (!again && interactive && response.status === 409 && body?.error?.code === "terminal_unavailable" && /keeps \d+ terminals/.test(String(body.error.message ?? ""))) {
14443
14946
  stderr.write(`${String(body.error.message)} This one is not kept.
14444
14947
  `);
14445
- response = await ask13(false);
14948
+ response = await ask14(false);
14446
14949
  body = await response.json().catch(() => null);
14447
14950
  }
14448
14951
  if (!response.ok || typeof body?.ticket !== "string") {
@@ -14462,8 +14965,8 @@ async function shell(client, id, options = {}, streams = process) {
14462
14965
  if (socket.readyState !== WebSocket.OPEN || chunk.length === 0) {
14463
14966
  return;
14464
14967
  }
14465
- for (let at4 = 0; at4 < chunk.length; at4 += MAX_INPUT_BYTES) {
14466
- socket.send(chunk.subarray(at4, at4 + MAX_INPUT_BYTES));
14968
+ for (let at5 = 0; at5 < chunk.length; at5 += MAX_INPUT_BYTES) {
14969
+ socket.send(chunk.subarray(at5, at5 + MAX_INPUT_BYTES));
14467
14970
  }
14468
14971
  lastSent = chunk[chunk.length - 1];
14469
14972
  };
@@ -14697,11 +15200,11 @@ function whereQuery(text, query = new URLSearchParams()) {
14697
15200
  for (const word of words(text)) {
14698
15201
  const time = /^(made|stopped)([<>])(.+)$/.exec(word);
14699
15202
  if (time) {
14700
- const [, what, side, at4] = time;
15203
+ const [, what, side, at5] = time;
14701
15204
  if (what === "made") {
14702
- query.append(side === ">" ? "createdAfter" : "createdBefore", at4);
15205
+ query.append(side === ">" ? "createdAfter" : "createdBefore", at5);
14703
15206
  } else if (side === "<") {
14704
- query.append("stoppedBefore", at4);
15207
+ query.append("stoppedBefore", at5);
14705
15208
  } else {
14706
15209
  throw new Error(`${word}: stopped takes < only, for sandboxes stopped before a time.`);
14707
15210
  }
@@ -15083,6 +15586,20 @@ async function main() {
15083
15586
  informed: { type: "boolean", default: false },
15084
15587
  sort: { type: "string" },
15085
15588
  role: { type: "string" },
15589
+ // Guilds: the roles of a create or an attach, its brief and form, and who joins with what answers.
15590
+ roles: { type: "string" },
15591
+ brief: { type: "string" },
15592
+ form: { type: "string" },
15593
+ as: { type: "string" },
15594
+ answer: { type: "string", multiple: true },
15595
+ // Guild messages: a role it is to, a request, the request it answers, the channel, a retry key, where to read from, and a place confirmed.
15596
+ "to-role": { type: "string" },
15597
+ request: { type: "boolean" },
15598
+ answers: { type: "string" },
15599
+ channel: { type: "string" },
15600
+ "retry-key": { type: "string" },
15601
+ after: { type: "string" },
15602
+ done: { type: "boolean" },
15086
15603
  "revoke-keys": { type: "boolean", default: false },
15087
15604
  // agental list in a terminal: every column, as piped.
15088
15605
  wide: { type: "boolean", default: false },
@@ -15107,7 +15624,7 @@ async function main() {
15107
15624
  await create({ ...values, template: once(values.template, "--template") });
15108
15625
  return;
15109
15626
  case "list":
15110
- await list4(values.json, whereQuery(values.where ?? "", labelsFilter(values)), values.sort, values.limit, values.wide);
15627
+ await list5(values.json, whereQuery(values.where ?? "", labelsFilter(values)), values.sort, values.limit, values.wide);
15111
15628
  return;
15112
15629
  case "bulk-actions":
15113
15630
  await bulkActionsCommand(positionals.slice(1), values.json);
@@ -15143,7 +15660,7 @@ async function main() {
15143
15660
  await bulk("delete", whereQuery(values.where, labelsFilter(values)), {}, values.yes === true, values.json, values.confirm);
15144
15661
  return;
15145
15662
  }
15146
- await remove3(positionals[1], values["pause-jobs"] === true);
15663
+ await remove4(positionals[1], values["pause-jobs"] === true);
15147
15664
  return;
15148
15665
  case "start":
15149
15666
  if (values.where !== void 0) {
@@ -15233,6 +15750,44 @@ async function main() {
15233
15750
  case "tailscale":
15234
15751
  await tailscale(tailscaleClient(), positionals.slice(1), tailnetFlags(values));
15235
15752
  return;
15753
+ case "guild":
15754
+ case "guilds": {
15755
+ const token = guildTokenHere(DEFAULT_URL);
15756
+ if (token !== null) {
15757
+ process.env["AGENTAL_API_KEY"] = token;
15758
+ }
15759
+ await guild(
15760
+ { request, fail, confirmed, templateId: async (given) => (await templateNamed(given)).id, onToken: token !== null },
15761
+ positionals.slice(1),
15762
+ {
15763
+ json: values.json,
15764
+ yes: values.yes,
15765
+ ...values.roles === void 0 ? {} : { roles: values.roles },
15766
+ ...values.role === void 0 ? {} : { role: values.role },
15767
+ ...values.brief === void 0 ? {} : { brief: values.brief },
15768
+ ...values.form === void 0 ? {} : { form: values.form },
15769
+ ...values.as === void 0 ? {} : { as: values.as },
15770
+ ...values.answer === void 0 ? {} : { answer: values.answer },
15771
+ ...values.to === void 0 ? {} : { to: values.to },
15772
+ ...values["to-role"] === void 0 ? {} : { toRole: values["to-role"] },
15773
+ ...values.request === void 0 ? {} : { request: values.request },
15774
+ ...values.answers === void 0 ? {} : { answers: values.answers },
15775
+ ...values.channel === void 0 ? {} : { channel: values.channel },
15776
+ ...values["retry-key"] === void 0 ? {} : { retryKey: values["retry-key"] },
15777
+ ...values["wait-seconds"] === void 0 ? {} : { waitSeconds: values["wait-seconds"] },
15778
+ ...values.after === void 0 ? {} : { after: values.after },
15779
+ ...values.done === void 0 ? {} : { done: values.done },
15780
+ ...values.text === void 0 ? {} : { text: values.text }
15781
+ }
15782
+ );
15783
+ return;
15784
+ }
15785
+ case "subscriptions":
15786
+ await subscriptions(tailscaleClient(), positionals.slice(1), { json: values.json, yes: values.yes === true });
15787
+ return;
15788
+ case "agents":
15789
+ 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") } });
15790
+ return;
15236
15791
  case "tailnet":
15237
15792
  await tailnet(tailscaleClient(), "sandbox", positionals.slice(1), tailnetFlags(values));
15238
15793
  return;
@@ -15461,12 +16016,12 @@ function regionsOption(given) {
15461
16016
  const named = listedIn([given]);
15462
16017
  return named.length === 1 ? { region: named[0] } : { regions: named };
15463
16018
  }
15464
- async function sshKeys(id, keyId, remove4, json3) {
16019
+ async function sshKeys(id, keyId, remove5, json3) {
15465
16020
  if (!id) {
15466
16021
  throw new Error("ssh-keys requires <sandbox-id>");
15467
16022
  }
15468
16023
  const path6 = `/v1/sandboxes/${encodeURIComponent(id)}/ssh/keys`;
15469
- if (remove4) {
16024
+ if (remove5) {
15470
16025
  if (!keyId) {
15471
16026
  throw new Error("ssh-keys --remove requires <key-id>, as ssh-keys lists it");
15472
16027
  }
@@ -15492,7 +16047,7 @@ function publicKeysFrom(given) {
15492
16047
  const file = each.startsWith("~/") ? `${os7.homedir()}${each.slice(1)}` : each;
15493
16048
  let text;
15494
16049
  try {
15495
- text = readFileSync7(file, "utf8");
16050
+ text = readFileSync8(file, "utf8");
15496
16051
  } catch {
15497
16052
  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.`);
15498
16053
  }
@@ -15543,7 +16098,7 @@ async function regions(asJson) {
15543
16098
  }
15544
16099
  process.stdout.write("* where a sandbox is made when no region is named\n");
15545
16100
  }
15546
- async function list4(asJson, filter, sort, limit, wide = false) {
16101
+ async function list5(asJson, filter, sort, limit, wide = false) {
15547
16102
  const sandboxes2 = [];
15548
16103
  let cursor = null;
15549
16104
  do {
@@ -15858,7 +16413,7 @@ async function exec(positionals) {
15858
16413
  }
15859
16414
  process.exitCode = typeof record["exitCode"] === "number" ? record["exitCode"] : 1;
15860
16415
  }
15861
- async function remove3(id, pauseJobs) {
16416
+ async function remove4(id, pauseJobs) {
15862
16417
  if (!id) {
15863
16418
  throw new Error("delete requires <sandbox-id>");
15864
16419
  }
@@ -15940,11 +16495,11 @@ async function resize(id, size2, now, cancel, maxBurstFee, asJson) {
15940
16495
  const path6 = `/v1/sandboxes/${encodeURIComponent(id)}`;
15941
16496
  const before = await call2(path6, { method: "GET" });
15942
16497
  const name = before.name || id;
15943
- const print4 = (sandbox, line) => process.stdout.write(asJson ? `${JSON.stringify(sandbox, null, 2)}
16498
+ const print5 = (sandbox, line) => process.stdout.write(asJson ? `${JSON.stringify(sandbox, null, 2)}
15944
16499
  ` : `${line}
15945
16500
  `);
15946
16501
  if (cancel && !before.pendingSize) {
15947
- print4(before, `${name} has no size waiting: it stays a ${before.size}.`);
16502
+ print5(before, `${name} has no size waiting: it stays a ${before.size}.`);
15948
16503
  return;
15949
16504
  }
15950
16505
  const to = cancel ? before.size : size2;
@@ -15959,7 +16514,7 @@ async function resize(id, size2, now, cancel, maxBurstFee, asJson) {
15959
16514
  if (!response.ok) {
15960
16515
  if (cancel && response.status === 409 && isApiError(body) && body.error.code === "size_smaller") {
15961
16516
  const read2 = await call2(path6, { method: "GET" });
15962
- print4(read2, `${read2.name || id} is already a ${read2.size}; nothing was waiting.`);
16517
+ print5(read2, `${read2.name || id} is already a ${read2.size}; nothing was waiting.`);
15963
16518
  return;
15964
16519
  }
15965
16520
  fail(response.status, body);
@@ -15967,11 +16522,11 @@ async function resize(id, size2, now, cancel, maxBurstFee, asJson) {
15967
16522
  sayBurstFee(response);
15968
16523
  const after = body;
15969
16524
  if (restart && after.status !== "running") {
15970
- 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.`);
16525
+ 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.`);
15971
16526
  process.exitCode = 1;
15972
16527
  return;
15973
16528
  }
15974
- print4(
16529
+ print5(
15975
16530
  after,
15976
16531
  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.`
15977
16532
  );
@@ -16104,25 +16659,25 @@ function timeInWords(total) {
16104
16659
  const parts = [days ? `${days}d` : "", hours ? `${hours}h` : "", minutes ? `${minutes}m` : ""].filter(Boolean);
16105
16660
  return parts.length > 0 ? parts.join(" ") : `${total}s`;
16106
16661
  }
16107
- async function autoStop(id, inText, at4, never, asJson) {
16662
+ async function autoStop(id, inText, at5, never, asJson) {
16108
16663
  if (!id) {
16109
16664
  throw new Error("auto-stop requires <sandbox-id>");
16110
16665
  }
16111
- if ([inText !== void 0, at4 !== void 0, never].filter(Boolean).length > 1) {
16666
+ if ([inText !== void 0, at5 !== void 0, never].filter(Boolean).length > 1) {
16112
16667
  throw new Error("--in, --at and --never say different things: give one.");
16113
16668
  }
16114
16669
  const path6 = `/v1/sandboxes/${encodeURIComponent(id)}/auto-stop`;
16115
16670
  let body;
16116
16671
  if (never) {
16117
16672
  body = await call2(path6, { method: "DELETE" });
16118
- } else if (inText === void 0 && at4 === void 0) {
16673
+ } else if (inText === void 0 && at5 === void 0) {
16119
16674
  body = await call2(path6, { method: "GET" });
16120
16675
  } else {
16121
16676
  const inSeconds = inText === void 0 ? void 0 : seconds(inText);
16122
16677
  if (inSeconds === null) {
16123
16678
  throw new Error("--in is a time from now, such as 30m, 2h or 1d");
16124
16679
  }
16125
- body = await call2(path6, { method: "PUT", body: JSON.stringify(inSeconds === void 0 ? { at: at4 } : { inSeconds }) });
16680
+ body = await call2(path6, { method: "PUT", body: JSON.stringify(inSeconds === void 0 ? { at: at5 } : { inSeconds }) });
16126
16681
  }
16127
16682
  if (asJson) {
16128
16683
  process.stdout.write(`${JSON.stringify(body, null, 2)}
@@ -16187,15 +16742,15 @@ function pictureSize(bytes4) {
16187
16742
  if (bytes4.length >= 24 && bytes4.toString("latin1", 1, 4) === "PNG") {
16188
16743
  return { width: bytes4.readUInt32BE(16), height: bytes4.readUInt32BE(20) };
16189
16744
  }
16190
- for (let at4 = 2; bytes4[0] === 255 && bytes4[1] === 216 && at4 + 9 <= bytes4.length; ) {
16191
- const marker = bytes4[at4 + 1];
16192
- if (bytes4[at4] !== 255) {
16745
+ for (let at5 = 2; bytes4[0] === 255 && bytes4[1] === 216 && at5 + 9 <= bytes4.length; ) {
16746
+ const marker = bytes4[at5 + 1];
16747
+ if (bytes4[at5] !== 255) {
16193
16748
  return null;
16194
16749
  }
16195
16750
  if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
16196
- return { width: bytes4.readUInt16BE(at4 + 7), height: bytes4.readUInt16BE(at4 + 5) };
16751
+ return { width: bytes4.readUInt16BE(at5 + 7), height: bytes4.readUInt16BE(at5 + 5) };
16197
16752
  }
16198
- at4 += 2 + bytes4.readUInt16BE(at4 + 2);
16753
+ at5 += 2 + bytes4.readUInt16BE(at5 + 2);
16199
16754
  }
16200
16755
  return null;
16201
16756
  }
@@ -16203,9 +16758,9 @@ async function clipboard(id, text) {
16203
16758
  if (!id) {
16204
16759
  throw new Error("desktop requires <sandbox-id>");
16205
16760
  }
16206
- const at4 = `/v1/sandboxes/${encodeURIComponent(id)}/desktop/clipboard`;
16761
+ const at5 = `/v1/sandboxes/${encodeURIComponent(id)}/desktop/clipboard`;
16207
16762
  if (text === void 0) {
16208
- const response2 = await request(at4, { method: "GET" });
16763
+ const response2 = await request(at5, { method: "GET" });
16209
16764
  const body = await readBody(response2);
16210
16765
  if (!response2.ok) {
16211
16766
  fail(response2.status, body);
@@ -16213,8 +16768,8 @@ async function clipboard(id, text) {
16213
16768
  process.stdout.write(String(body.text ?? ""));
16214
16769
  return;
16215
16770
  }
16216
- const given = text === "-" ? readFileSync7(0, "utf8") : text;
16217
- const response = await request(at4, { method: "PUT", body: JSON.stringify({ text: given }) });
16771
+ const given = text === "-" ? readFileSync8(0, "utf8") : text;
16772
+ const response = await request(at5, { method: "PUT", body: JSON.stringify({ text: given }) });
16218
16773
  if (!response.ok) {
16219
16774
  fail(response.status, await readBody(response));
16220
16775
  }
@@ -16251,9 +16806,9 @@ async function desktopLinks(id, use2, given, options) {
16251
16806
  if (!id) {
16252
16807
  throw new Error("desktop requires <sandbox-id>");
16253
16808
  }
16254
- const at4 = `/v1/sandboxes/${encodeURIComponent(id)}/desktop/links`;
16809
+ const at5 = `/v1/sandboxes/${encodeURIComponent(id)}/desktop/links`;
16255
16810
  if (use2 === "unlink") {
16256
- const response2 = await request(`${at4}/${encodeURIComponent(String(given))}`, { method: "DELETE" });
16811
+ const response2 = await request(`${at5}/${encodeURIComponent(String(given))}`, { method: "DELETE" });
16257
16812
  if (!response2.ok) {
16258
16813
  fail(response2.status, await readBody(response2));
16259
16814
  }
@@ -16262,7 +16817,7 @@ async function desktopLinks(id, use2, given, options) {
16262
16817
  return;
16263
16818
  }
16264
16819
  if (use2 === "links") {
16265
- const response2 = await request(at4, { method: "GET" });
16820
+ const response2 = await request(at5, { method: "GET" });
16266
16821
  const body2 = await readBody(response2);
16267
16822
  if (!response2.ok) {
16268
16823
  fail(response2.status, body2);
@@ -16278,7 +16833,7 @@ async function desktopLinks(id, use2, given, options) {
16278
16833
  if (expiresIn === null) {
16279
16834
  throw new Error("--expires is how long the link lasts: 600, 10m or 1h, from a minute to a day");
16280
16835
  }
16281
- const response = await request(at4, {
16836
+ const response = await request(at5, {
16282
16837
  method: "POST",
16283
16838
  body: JSON.stringify({ access: given, ...expiresIn === void 0 ? {} : { expiresIn }, ...options.keepStreams ? { cutOnExpiry: false } : {} })
16284
16839
  });
@@ -16303,7 +16858,7 @@ async function useDesktop(id, use2, given) {
16303
16858
  if (!id) {
16304
16859
  throw new Error("desktop requires <sandbox-id>");
16305
16860
  }
16306
- const at4 = `/v1/sandboxes/${encodeURIComponent(id)}/desktop/${use2}`;
16861
+ const at5 = `/v1/sandboxes/${encodeURIComponent(id)}/desktop/${use2}`;
16307
16862
  let body;
16308
16863
  if (use2 === "click") {
16309
16864
  const [x, y, button, count, ...more] = given.split(",");
@@ -16335,7 +16890,7 @@ async function useDesktop(id, use2, given) {
16335
16890
  } else {
16336
16891
  body = { keys: given };
16337
16892
  }
16338
- const response = await request(at4, { method: "POST", body: JSON.stringify(body) });
16893
+ const response = await request(at5, { method: "POST", body: JSON.stringify(body) });
16339
16894
  if (!response.ok) {
16340
16895
  fail(response.status, await readBody(response));
16341
16896
  }
@@ -16348,12 +16903,12 @@ function listedIn(given) {
16348
16903
  function metadataGiven(given) {
16349
16904
  const metadata = {};
16350
16905
  for (const each of given) {
16351
- const at4 = each.indexOf("=");
16352
- const key2 = at4 < 0 ? "" : each.slice(0, at4).trim();
16906
+ const at5 = each.indexOf("=");
16907
+ const key2 = at5 < 0 ? "" : each.slice(0, at5).trim();
16353
16908
  if (key2 === "") {
16354
16909
  throw new Error(`--meta is <key>=<value>, as --meta repo=acme/web, not ${each}`);
16355
16910
  }
16356
- metadata[key2] = each.slice(at4 + 1);
16911
+ metadata[key2] = each.slice(at5 + 1);
16357
16912
  }
16358
16913
  return metadata;
16359
16914
  }
@@ -16488,7 +17043,7 @@ function egressInWords(body) {
16488
17043
  }
16489
17044
  async function egress(positionals, values) {
16490
17045
  const [first, ...rest] = positionals;
16491
- const print4 = (body2, words2) => {
17046
+ const print5 = (body2, words2) => {
16492
17047
  process.stdout.write(values.json ? `${JSON.stringify(body2, null, 2)}
16493
17048
  ` : words2);
16494
17049
  };
@@ -16526,14 +17081,14 @@ async function egress(positionals, values) {
16526
17081
  `this month: ${money(number("spentMicros"))} of a ${money(number("budgetMicros"))} budget${account3["budgetSet"] ? "" : " (the default)"}`,
16527
17082
  ...account3["blocked"] && account3["blocked"] !== "refused" ? [`blocked now: ${String(account3["blocked"]).replaceAll("_", " ")}`] : []
16528
17083
  ];
16529
- print4(body2, `${lines.join("\n")}
17084
+ print5(body2, `${lines.join("\n")}
16530
17085
  `);
16531
17086
  return;
16532
17087
  }
16533
17088
  const path6 = `/v1/sandboxes/${encodeURIComponent(first)}/egress`;
16534
17089
  const how = `egress takes <sandbox-id>, and then nothing, box, or residential <country> [sticky|rotating], as agental egress ${first} residential de.`;
16535
17090
  const body = await call2(path6, rest.length === 0 ? { method: "GET" } : { method: "PUT", body: JSON.stringify(egressFrom(rest, how)) });
16536
- print4(body, `${first}: ${egressInWords(body)}
17091
+ print5(body, `${first}: ${egressInWords(body)}
16537
17092
  `);
16538
17093
  }
16539
17094
  function spotSettingsFrom(values) {
@@ -16652,15 +17207,15 @@ ${faint("The default is used when a sandbox is made without naming one. agental
16652
17207
  process.stdout.write("* used when a sandbox is made without naming one\n");
16653
17208
  }
16654
17209
  function showTemplate(each) {
16655
- const list5 = (items) => items && items.length > 0 ? items.join(", ") : "none";
17210
+ const list6 = (items) => items && items.length > 0 ? items.join(", ") : "none";
16656
17211
  return [
16657
17212
  `id: ${each.id}`,
16658
17213
  `name: ${each.name}${each.default ? " (default: used when a sandbox is made without naming one)" : ""}`,
16659
17214
  `start: ${startInWords(each.start)}`,
16660
- `variables: ${list5(each.variables)}`,
17215
+ `variables: ${list6(each.variables)}`,
16661
17216
  // Said only where some are. An API from before variables could be kept out of the sandbox says nothing of them.
16662
- ...each.hidden && each.hidden.length > 0 ? [`kept out: ${list5(each.hidden)}`] : [],
16663
- `files: ${list5(each.files)}`,
17217
+ ...each.hidden && each.hidden.length > 0 ? [`kept out: ${list6(each.hidden)}`] : [],
17218
+ `files: ${list6(each.files)}`,
16664
17219
  // An API from before templates held rules says nothing of one.
16665
17220
  ...each.network ? [`network: ${ruleInWords(each.network)}`] : [],
16666
17221
  // An API from before templates gave SSH says nothing of it.
@@ -16674,7 +17229,7 @@ function showTemplate(each) {
16674
17229
  async function template(positionals, values) {
16675
17230
  const [action, first, ...rest] = positionals;
16676
17231
  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.";
16677
- const print4 = (body, words2) => {
17232
+ const print5 = (body, words2) => {
16678
17233
  process.stdout.write(values.json ? `${JSON.stringify(body, null, 2)}
16679
17234
  ` : words2);
16680
17235
  };
@@ -16687,7 +17242,7 @@ async function template(positionals, values) {
16687
17242
  switch (action) {
16688
17243
  case "create": {
16689
17244
  const made = await call2("/v1/templates", { method: "POST", body: JSON.stringify({ name: need(first, "<name>"), ...labelsGiven(values) }) });
16690
- print4(made, showTemplate(made));
17245
+ print5(made, showTemplate(made));
16691
17246
  return;
16692
17247
  }
16693
17248
  case "tags":
@@ -16697,13 +17252,13 @@ async function template(positionals, values) {
16697
17252
  case "show": {
16698
17253
  const found = await templateNamed(need(first, "<template>"));
16699
17254
  const read2 = await call2(`/v1/templates/${encodeURIComponent(found.id)}`, { method: "GET" });
16700
- print4(read2, showTemplate(read2));
17255
+ print5(read2, showTemplate(read2));
16701
17256
  return;
16702
17257
  }
16703
17258
  case "rename": {
16704
17259
  const found = await templateNamed(need(first, "<template> <new-name>"));
16705
17260
  const renamed = await call2(`/v1/templates/${encodeURIComponent(found.id)}`, { method: "PATCH", body: JSON.stringify({ name: need(rest[0], "<template> <new-name>") }) });
16706
- print4(renamed, showTemplate(renamed));
17261
+ print5(renamed, showTemplate(renamed));
16707
17262
  return;
16708
17263
  }
16709
17264
  case "delete": {
@@ -16762,7 +17317,7 @@ async function template(positionals, values) {
16762
17317
  body: JSON.stringify({ size: values.size ?? current?.size, snapshotId, ttlSeconds: ttl, ...region === void 0 ? {} : { region }, ...spot2 === void 0 ? {} : { spot: spot2 } })
16763
17318
  });
16764
17319
  }
16765
- print4(start2, `start: ${startInWords(start2)}
17320
+ print5(start2, `start: ${startInWords(start2)}
16766
17321
  `);
16767
17322
  return;
16768
17323
  }
@@ -16786,7 +17341,7 @@ async function template(positionals, values) {
16786
17341
  }
16787
17342
  rule = await call2(path6, { method: "PUT", body: JSON.stringify(mode === "allowlist" ? { outbound: mode, allow: listed2 } : { outbound: mode }) });
16788
17343
  }
16789
- print4(
17344
+ print5(
16790
17345
  rule,
16791
17346
  `${found.name}: ${ruleInWords(rule)}
16792
17347
  ${mode === void 0 ? "" : "A sandbox on it takes this when it next starts, or now with agental template apply.\n"}`
@@ -16801,7 +17356,7 @@ ${mode === void 0 ? "" : "A sandbox on it takes this when it next starts, or now
16801
17356
  const path6 = `/v1/templates/${encodeURIComponent(found.id)}/egress`;
16802
17357
  const how = `template egress takes <template>, and then nothing, box, or residential <country> [sticky|rotating], as agental template egress ${first ?? ""} residential de.`;
16803
17358
  const set2 = await call2(path6, rest.length === 0 ? { method: "GET" } : { method: "PUT", body: JSON.stringify(egressFrom(rest, how)) });
16804
- print4(set2, `${found.name}: ${egressInWords(set2)}${rest.length === 0 ? "" : ", for sandboxes made from it from now on"}
17359
+ print5(set2, `${found.name}: ${egressInWords(set2)}${rest.length === 0 ? "" : ", for sandboxes made from it from now on"}
16805
17360
  `);
16806
17361
  return;
16807
17362
  }
@@ -16813,7 +17368,7 @@ ${mode === void 0 ? "" : "A sandbox on it takes this when it next starts, or now
16813
17368
  throw new Error("template ssh requires <template>, and then nothing, on or off");
16814
17369
  }
16815
17370
  const ssh2 = await call2(path6, { method: turn === "on" ? "PUT" : turn === "off" ? "DELETE" : "GET" });
16816
- print4(ssh2, `${found.name}: SSH ${templateSshInWords(ssh2)}
17371
+ print5(ssh2, `${found.name}: SSH ${templateSshInWords(ssh2)}
16817
17372
  `);
16818
17373
  return;
16819
17374
  }
@@ -16844,7 +17399,7 @@ ${mode === void 0 ? "" : "A sandbox on it takes this when it next starts, or now
16844
17399
  const body = await call2(`/v1/templates/${encodeURIComponent(found.id)}/sandboxes`, { method: "GET" });
16845
17400
  const rows = body.sandboxes.map((each) => `${[pad2(String(each["id"])), pad2(String(each["name"])), pad2(String(each["status"])), each["upToDate"] === true ? "yes" : "no"].join(" ")}
16846
17401
  `);
16847
- print4(body, `${[pad2("ID"), pad2("NAME"), pad2("STATUS"), "UP TO DATE"].join(" ")}
17402
+ print5(body, `${[pad2("ID"), pad2("NAME"), pad2("STATUS"), "UP TO DATE"].join(" ")}
16848
17403
  ${rows.join("")}`);
16849
17404
  return;
16850
17405
  }
@@ -16856,7 +17411,7 @@ ${rows.join("")}`);
16856
17411
  });
16857
17412
  const failed = (body.failed ?? []).map((each) => `Not brought up to date, and held to the rule it had: ${each.sandboxId}: ${each.error}
16858
17413
  `).join("");
16859
- print4(
17414
+ print5(
16860
17415
  body,
16861
17416
  `${body.applied.length === 0 && failed === "" ? `No sandbox on ${found.name} is running. Each takes it when it next starts.
16862
17417
  ` : body.applied.length === 0 ? "" : `Brought up to date with ${found.name}: ${body.applied.join(", ")}
@@ -16870,7 +17425,7 @@ ${rows.join("")}`);
16870
17425
  case "of": {
16871
17426
  const sandboxId = need(first, "<sandbox-id>");
16872
17427
  const body = await call2(`/v1/sandboxes/${encodeURIComponent(sandboxId)}/template`, { method: "GET" });
16873
- print4(body, `template: ${String(body["name"])} (${String(body["templateId"])})
17428
+ print5(body, `template: ${String(body["name"])} (${String(body["templateId"])})
16874
17429
  up to date: ${body["upToDate"] === true ? "yes" : "no: it takes the template when it next starts, or when apply names it"}
16875
17430
  `);
16876
17431
  return;
@@ -16879,7 +17434,7 @@ up to date: ${body["upToDate"] === true ? "yes" : "no: it takes the template whe
16879
17434
  const found = await templateNamed(need(first, "<template> <sandbox-id>"));
16880
17435
  const sandboxId = need(rest[0], "<template> <sandbox-id>");
16881
17436
  const body = await call2(`/v1/sandboxes/${encodeURIComponent(sandboxId)}/template`, { method: "PUT", body: JSON.stringify({ templateId: found.id }) });
16882
- 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.
17437
+ 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.
16883
17438
  `);
16884
17439
  return;
16885
17440
  }
@@ -16971,11 +17526,11 @@ async function secrets(positionals, values) {
16971
17526
  throw new Error("--host takes a host, as --host api.github.com");
16972
17527
  }
16973
17528
  const pairs = args.map((arg) => {
16974
- const at4 = arg.indexOf("=");
16975
- if (at4 <= 0) {
17529
+ const at5 = arg.indexOf("=");
17530
+ if (at5 <= 0) {
16976
17531
  throw new Error(`secrets set takes <NAME>=<value>, and ${arg} has no name before an =`);
16977
17532
  }
16978
- return [arg.slice(0, at4), arg.slice(at4 + 1)];
17533
+ return [arg.slice(0, at5), arg.slice(at5 + 1)];
16979
17534
  });
16980
17535
  const path6 = (name) => `${base}/variables/${encodeURIComponent(name)}`;
16981
17536
  if (hosts === void 0 && !values.plain) {
@@ -17083,8 +17638,8 @@ async function metrics(id, asked2) {
17083
17638
  if (!response.ok) {
17084
17639
  fail(response.status, body);
17085
17640
  }
17086
- const answer5 = body && typeof body === "object" ? body : {};
17087
- const fromTo = typeof answer5["since"] === "string" && typeof answer5["until"] === "string" ? ` from ${answer5["since"]} to ${answer5["until"]}` : "";
17641
+ const answer6 = body && typeof body === "object" ? body : {};
17642
+ const fromTo = typeof answer6["since"] === "string" && typeof answer6["until"] === "string" ? ` from ${answer6["since"]} to ${answer6["until"]}` : "";
17088
17643
  if (asked2.json) {
17089
17644
  process.stdout.write(`${JSON.stringify(body, null, 2)}
17090
17645
  `);
@@ -17109,7 +17664,7 @@ async function metrics(id, asked2) {
17109
17664
  ])
17110
17665
  );
17111
17666
  }
17112
- if (answer5["complete"] === false) {
17667
+ if (answer6["complete"] === false) {
17113
17668
  process.stderr.write(
17114
17669
  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.
17115
17670
  `
@@ -17152,8 +17707,8 @@ async function dataRetention(positionals, asJson) {
17152
17707
  `);
17153
17708
  return;
17154
17709
  }
17155
- const answer5 = body ?? {};
17156
- const days = answer5.keepDays ?? null;
17710
+ const answer6 = body ?? {};
17711
+ const days = answer6.keepDays ?? null;
17157
17712
  const kept2 = days === null ? "until their sandbox is deleted" : days === 1 ? "1 day" : `${days} days`;
17158
17713
  process.stdout.write(`${period === void 0 ? "" : "Saved. "}Command output, agent conversations and events are kept ${kept2}.
17159
17714
  `);
@@ -17161,7 +17716,7 @@ async function dataRetention(positionals, asJson) {
17161
17716
  process.stdout.write(`What is older is deleted within the hour, and cannot be brought back.
17162
17717
  `);
17163
17718
  }
17164
- const last = answer5.lastCleared;
17719
+ const last = answer6.lastCleared;
17165
17720
  if (period === void 0) {
17166
17721
  process.stdout.write(
17167
17722
  last ? `Last clean-up ${last.at}: ${last.commands} commands' output, ${last.conversations} conversations and ${last.events} events deleted.
@@ -17385,12 +17940,12 @@ async function billing(positionals, asJson, limit) {
17385
17940
  if (limit !== void 0 && what !== "invoices") {
17386
17941
  throw new Error("--limit is taken by billing invoices alone.");
17387
17942
  }
17388
- const print4 = (body, text) => process.stdout.write(asJson ? `${JSON.stringify(body, null, 2)}
17943
+ const print5 = (body, text) => process.stdout.write(asJson ? `${JSON.stringify(body, null, 2)}
17389
17944
  ` : text());
17390
17945
  switch (what) {
17391
17946
  case void 0: {
17392
17947
  const [body, card] = await Promise.all([asked("/v1/billing", { method: "GET" }), cardOnFile()]);
17393
- print4({ ...body, card }, () => describeBilling(body, card));
17948
+ print5({ ...body, card }, () => describeBilling(body, card));
17394
17949
  return;
17395
17950
  }
17396
17951
  case "invoices": {
@@ -17399,28 +17954,28 @@ async function billing(positionals, asJson, limit) {
17399
17954
  }
17400
17955
  case "compare": {
17401
17956
  const body = await asked("/v1/burst/replay", { method: "GET" });
17402
- print4(body, () => describePlanReplay(body));
17957
+ print5(body, () => describePlanReplay(body));
17403
17958
  return;
17404
17959
  }
17405
17960
  case "details": {
17406
17961
  const body = await asked("/v1/billing/details", { method: "GET" });
17407
- print4(body, () => describeDetails(body.details));
17962
+ print5(body, () => describeDetails(body.details));
17408
17963
  return;
17409
17964
  }
17410
17965
  case "prices": {
17411
17966
  const body = await asked("/v1/billing/plans", { method: "GET" });
17412
- print4(body, () => isTerminal(process.stdout) ? pricesForPeople(body) : describePrices(body));
17967
+ print5(body, () => isTerminal(process.stdout) ? pricesForPeople(body) : describePrices(body));
17413
17968
  return;
17414
17969
  }
17415
17970
  case "card": {
17416
17971
  if (amount === void 0) {
17417
17972
  const body2 = await asked("/v1/billing/card", { method: "GET" });
17418
- print4(body2, () => body2.card ? `${describeCard(body2.card)}
17973
+ print5(body2, () => body2.card ? `${describeCard(body2.card)}
17419
17974
  ` : "No card saved. agental billing card save prints the page to save one on, charged nothing.\n");
17420
17975
  return;
17421
17976
  }
17422
17977
  const body = await asked("/v1/billing/checkout", { method: "POST", body: JSON.stringify({ card: true }) });
17423
- print4(
17978
+ print5(
17424
17979
  body,
17425
17980
  () => body.url ? `Save a card for the free plan at:
17426
17981
  ${body.url}
@@ -17439,7 +17994,7 @@ Nothing is charged. Once it is saved, the account has its monthly free allowance
17439
17994
  const body = await asked("/v1/billing/checkout", { method: "POST", body: JSON.stringify({ topUp: dollars }) });
17440
17995
  const topUp = topUpByDollars(dollars);
17441
17996
  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:`;
17442
- print4(
17997
+ print5(
17443
17998
  body,
17444
17999
  () => body.url ? `${what2}
17445
18000
  ${body.url}
@@ -17457,13 +18012,13 @@ Nothing is charged until it is paid. agental billing shows it within a minute of
17457
18012
  );
17458
18013
  }
17459
18014
  const body = await asked("/v1/billing/auto-reload", { method: "PUT", body: JSON.stringify({ dollars: off ? null : dollars }) });
17460
- print4(body, () => `${describeAutoReload(body.autoReload)}
18015
+ print5(body, () => `${describeAutoReload(body.autoReload)}
17461
18016
  `);
17462
18017
  return;
17463
18018
  }
17464
18019
  case "email-copy": {
17465
18020
  const body = await asked("/v1/billing/email-copy", { method: "GET" });
17466
- print4(
18021
+ print5(
17467
18022
  body,
17468
18023
  () => 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.
17469
18024
  ` : 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.
@@ -17862,10 +18417,10 @@ async function showLimits(positionals, options) {
17862
18417
  `);
17863
18418
  return;
17864
18419
  }
17865
- const answer5 = body2 && typeof body2 === "object" ? body2 : {};
17866
- const spent = typeof answer5["spentMicros"] === "number" ? answer5["spentMicros"] : 0;
17867
- const budget = typeof answer5["budgetMicros"] === "number" ? answer5["budgetMicros"] : 0;
17868
- process.stdout.write(`Budget for burst fees: ${money(budget)} a month${answer5["budgetSet"] === true ? "" : " (the default)"}; ${money(spent)} spent this month.
18420
+ const answer6 = body2 && typeof body2 === "object" ? body2 : {};
18421
+ const spent = typeof answer6["spentMicros"] === "number" ? answer6["spentMicros"] : 0;
18422
+ const budget = typeof answer6["budgetMicros"] === "number" ? answer6["budgetMicros"] : 0;
18423
+ process.stdout.write(`Budget for burst fees: ${money(budget)} a month${answer6["budgetSet"] === true ? "" : " (the default)"}; ${money(spent)} spent this month.
17869
18424
  `);
17870
18425
  return;
17871
18426
  }
@@ -17895,22 +18450,22 @@ async function showLimits(positionals, options) {
17895
18450
  process.stdout.write(describeLimits(body, options.from === void 0 && options.to === void 0, options.to === void 0));
17896
18451
  }
17897
18452
  function describeLimits(body, today, endsNow) {
17898
- const answer5 = body && typeof body === "object" ? body : {};
17899
- const now = answer5["now"] && typeof answer5["now"] === "object" ? answer5["now"] : {};
18453
+ const answer6 = body && typeof body === "object" ? body : {};
18454
+ const now = answer6["now"] && typeof answer6["now"] === "object" ? answer6["now"] : {};
17900
18455
  const number = (from, name) => typeof from[name] === "number" ? from[name] : 0;
17901
18456
  const units = (mb) => {
17902
18457
  const value = mb / 2048;
17903
18458
  return (Number.isInteger(value) ? value : Math.round(value * 10) / 10).toLocaleString("en-US");
17904
18459
  };
17905
18460
  const clock = (iso) => {
17906
- const at4 = new Date(iso).toISOString();
17907
- 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`;
18461
+ const at5 = new Date(iso).toISOString();
18462
+ 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`;
17908
18463
  };
17909
- const range = today ? "today (UTC)" : `from ${String(answer5["from"] ?? "")} to ${String(answer5["to"] ?? "")}`;
18464
+ const range = today ? "today (UTC)" : `from ${String(answer6["from"] ?? "")} to ${String(answer6["to"] ?? "")}`;
17910
18465
  const lines = [
17911
- `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(answer5, "atRunningCountMs"))} ${range}`
18466
+ `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}`
17912
18467
  ];
17913
- const bursts = Array.isArray(answer5["bursts"]) ? answer5["bursts"] : [];
18468
+ const bursts = Array.isArray(answer6["bursts"]) ? answer6["bursts"] : [];
17914
18469
  const open = endsNow ? bursts.find((one) => one["endedAt"] === null && typeof one["startedAt"] === "string") : void 0;
17915
18470
  const over = number(now, "overMb") > 0;
17916
18471
  const nextStart = Array.isArray(now["nextStart"]) ? now["nextStart"] : [];
@@ -17926,7 +18481,7 @@ function describeLimits(body, today, endsNow) {
17926
18481
  const budgetMonth = now["budgetMonth"] && typeof now["budgetMonth"] === "object" ? now["budgetMonth"] : null;
17927
18482
  const since = typeof budgetMonth?.start === "string" && budgetMonth.start.slice(8, 10) !== "01" ? ` (since ${shortDayOf(budgetMonth.start)})` : "";
17928
18483
  lines.push(`fees: ${money(number(now, "spentMicros"))} this month${since} of a ${money(number(now, "budgetMicros"))} budget`);
17929
- const refused2 = answer5["refused"] && typeof answer5["refused"] === "object" ? answer5["refused"] : {};
18484
+ const refused2 = answer6["refused"] && typeof answer6["refused"] === "object" ? answer6["refused"] : {};
17930
18485
  const total = number(refused2, "total");
17931
18486
  const byReason = Array.isArray(refused2["byReason"]) ? refused2["byReason"] : [];
17932
18487
  lines.push(
@@ -18135,7 +18690,7 @@ function adminKeyHere() {
18135
18690
  return given;
18136
18691
  }
18137
18692
  try {
18138
- const saved = JSON.parse(readFileSync7(`${os7.homedir()}/.config/agental/admin-key.json`, "utf8"));
18693
+ const saved = JSON.parse(readFileSync8(`${os7.homedir()}/.config/agental/admin-key.json`, "utf8"));
18139
18694
  const forHere = typeof saved.apiUrl === "string" && saved.apiUrl.replace(/\/$/, "") === apiBase().replace(/\/$/, "");
18140
18695
  if (forHere && typeof saved.key === "string" && !(typeof saved.expiresAt === "string" && Date.parse(saved.expiresAt) <= Date.now())) {
18141
18696
  return saved.key;
@@ -18176,11 +18731,11 @@ function readSandboxes(body) {
18176
18731
  return body.sandboxes.filter((item) => Boolean(item) && typeof item === "object");
18177
18732
  }
18178
18733
  function readList(body, name) {
18179
- const list5 = body && typeof body === "object" ? body[name] : void 0;
18180
- if (!Array.isArray(list5)) {
18734
+ const list6 = body && typeof body === "object" ? body[name] : void 0;
18735
+ if (!Array.isArray(list6)) {
18181
18736
  throw new Error(`Metrics response was missing ${name}`);
18182
18737
  }
18183
- return list5.filter((item) => Boolean(item) && typeof item === "object");
18738
+ return list6.filter((item) => Boolean(item) && typeof item === "object");
18184
18739
  }
18185
18740
  function teamOptions(values) {
18186
18741
  return { json: values.json, revokeKeys: values["revoke-keys"], ...values.role === void 0 ? {} : { role: values.role } };
@@ -18276,6 +18831,8 @@ Usage
18276
18831
  agental network <sandbox-id> [--allow <address-or-name>[,<address-or-name>...] | --none] [--json]
18277
18832
  agental egress <sandbox-id> [box | residential <country> [sticky | rotating]] [--json]
18278
18833
  agental tailscale [status | connect --client-id <id> | disconnect [--yes]] [--json]
18834
+ agental subscriptions [list | sign-in <agent> | delete <agent> [--yes]] [--json]
18835
+ agental agents (--template <template> | --sandbox <sandbox-id>) [<agent> off|subscription|api_key|template] [--json]
18279
18836
  agental tailnet <sandbox-id> [join --tag <tag>... [--accept <range>]... [--exit-node <ip>] [--keep-address] [--node-name <name>] | off] [--json]
18280
18837
  agental spot <sandbox-id> [off] [--on-reclaim delete|stop] [--warn-at <chance>] [--json]
18281
18838
  agental templates [--json]