agental 0.47.0 → 0.50.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 +598 -143
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -3037,18 +3037,18 @@ var require_set = __commonJS({
3037
3037
  }
3038
3038
  static from(schema, iterable, ctx) {
3039
3039
  const { replacer } = ctx;
3040
- const set2 = new this(schema);
3040
+ const set3 = new this(schema);
3041
3041
  if (iterable && Symbol.iterator in Object(iterable))
3042
3042
  for (let value of iterable) {
3043
3043
  if (typeof replacer === "function")
3044
3044
  value = replacer.call(iterable, value, value);
3045
- set2.items.push(Pair.createPair(value, null, ctx));
3045
+ set3.items.push(Pair.createPair(value, null, ctx));
3046
3046
  }
3047
- return set2;
3047
+ return set3;
3048
3048
  }
3049
3049
  };
3050
3050
  YAMLSet.tag = "tag:yaml.org,2002:set";
3051
- var set = {
3051
+ var set2 = {
3052
3052
  collection: "map",
3053
3053
  identify: (value) => value instanceof Set,
3054
3054
  nodeClass: YAMLSet,
@@ -3067,7 +3067,7 @@ var require_set = __commonJS({
3067
3067
  }
3068
3068
  };
3069
3069
  exports.YAMLSet = YAMLSet;
3070
- exports.set = set;
3070
+ exports.set = set2;
3071
3071
  }
3072
3072
  });
3073
3073
 
@@ -3174,7 +3174,7 @@ var require_schema3 = __commonJS({
3174
3174
  var merge = require_merge();
3175
3175
  var omap = require_omap();
3176
3176
  var pairs = require_pairs();
3177
- var set = require_set();
3177
+ var set2 = require_set();
3178
3178
  var timestamp = require_timestamp();
3179
3179
  var schema = [
3180
3180
  map.map,
@@ -3194,7 +3194,7 @@ var require_schema3 = __commonJS({
3194
3194
  merge.merge,
3195
3195
  omap.omap,
3196
3196
  pairs.pairs,
3197
- set.set,
3197
+ set2.set,
3198
3198
  timestamp.intTime,
3199
3199
  timestamp.floatTime,
3200
3200
  timestamp.timestamp
@@ -3221,7 +3221,7 @@ var require_tags = __commonJS({
3221
3221
  var omap = require_omap();
3222
3222
  var pairs = require_pairs();
3223
3223
  var schema$2 = require_schema3();
3224
- var set = require_set();
3224
+ var set2 = require_set();
3225
3225
  var timestamp = require_timestamp();
3226
3226
  var schemas = /* @__PURE__ */ new Map([
3227
3227
  ["core", schema.schema],
@@ -3247,7 +3247,7 @@ var require_tags = __commonJS({
3247
3247
  omap: omap.omap,
3248
3248
  pairs: pairs.pairs,
3249
3249
  seq: seq.seq,
3250
- set: set.set,
3250
+ set: set2.set,
3251
3251
  timestamp: timestamp.timestamp
3252
3252
  };
3253
3253
  var coreKnownTags = {
@@ -3255,7 +3255,7 @@ var require_tags = __commonJS({
3255
3255
  "tag:yaml.org,2002:merge": merge.merge,
3256
3256
  "tag:yaml.org,2002:omap": omap.omap,
3257
3257
  "tag:yaml.org,2002:pairs": pairs.pairs,
3258
- "tag:yaml.org,2002:set": set.set,
3258
+ "tag:yaml.org,2002:set": set2.set,
3259
3259
  "tag:yaml.org,2002:timestamp": timestamp.timestamp
3260
3260
  };
3261
3261
  function getTags(customTags, schemaName, addMergeTag) {
@@ -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(list4, type) {
6367
- for (let i = 0; i < list4.length; ++i)
6368
- if (list4[i].type === type)
6366
+ function includesToken(list5, type) {
6367
+ for (let i = 0; i < list5.length; ++i)
6368
+ if (list5[i].type === type)
6369
6369
  return true;
6370
6370
  return false;
6371
6371
  }
6372
- function findNonEmptyIndex(list4) {
6373
- for (let i = 0; i < list4.length; ++i) {
6374
- switch (list4[i].type) {
6372
+ function findNonEmptyIndex(list5) {
6373
+ for (let i = 0; i < list5.length; ++i) {
6374
+ switch (list5[i].type) {
6375
6375
  case "space":
6376
6376
  case "comment":
6377
6377
  case "newline":
@@ -7411,7 +7411,7 @@ import { parseArgs } from "node:util";
7411
7411
 
7412
7412
  // ../src/cli-build.ts
7413
7413
  var PUBLISHED = true;
7414
- var CLI_VERSION = true ? "0.47.0" : "dev";
7414
+ var CLI_VERSION = true ? "0.50.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}`;
@@ -7912,6 +7912,8 @@ var KEY_ACTIONS = [
7912
7912
  "snapshot.write",
7913
7913
  "template.read",
7914
7914
  "template.write",
7915
+ "bucket.read",
7916
+ "bucket.write",
7915
7917
  "key.manage",
7916
7918
  "account.read",
7917
7919
  "account.admin",
@@ -7935,7 +7937,7 @@ var FULL_SANDBOX = [
7935
7937
  ];
7936
7938
  var PRESETS = {
7937
7939
  // Every read, apart from secrets and mail, which are the two an agent should be given by name.
7938
- "read-only": ["sandbox.read", "file.read", "job.read", "snapshot.read", "template.read", "account.read"],
7940
+ "read-only": ["sandbox.read", "file.read", "job.read", "snapshot.read", "template.read", "bucket.read", "account.read"],
7939
7941
  "full-sandbox": [...FULL_SANDBOX, "job.read", "job.write", "job.run"],
7940
7942
  // A CI system runs the jobs it is given and reads how they went; it does not make them.
7941
7943
  ci: [...FULL_SANDBOX, "sandbox.create", "sandbox.fork", "sandbox.resume", "sandbox.delete-own", "job.read", "job.run"],
@@ -7967,8 +7969,8 @@ function keyOf(body) {
7967
7969
  throw new Error("The answer was not an API key.");
7968
7970
  }
7969
7971
  const key2 = body;
7970
- const list4 = (value) => Array.isArray(value) ? value.map(String) : [];
7971
- return { ...key2, actions: list4(key2.actions), sandboxIds: list4(key2.sandboxIds), templateIds: list4(key2.templateIds), allowFrom: list4(key2.allowFrom) };
7972
+ const list5 = (value) => Array.isArray(value) ? value.map(String) : [];
7973
+ return { ...key2, actions: list5(key2.actions), sandboxIds: list5(key2.sandboxIds), templateIds: list5(key2.templateIds), allowFrom: list5(key2.allowFrom) };
7972
7974
  }
7973
7975
  function keysOf(body) {
7974
7976
  const listed2 = body?.apiKeys;
@@ -8301,7 +8303,7 @@ async function pushRequest(base, ask13) {
8301
8303
  async function listen() {
8302
8304
  let arrived = () => {
8303
8305
  };
8304
- let answer3 = () => {
8306
+ let answer4 = () => {
8305
8307
  };
8306
8308
  const next = new Promise((resolve) => arrived = resolve);
8307
8309
  let taken = false;
@@ -8316,7 +8318,7 @@ async function listen() {
8316
8318
  return;
8317
8319
  }
8318
8320
  taken = true;
8319
- answer3 = (to) => response.writeHead(302, { location: to, "cache-control": "no-store" }).end();
8321
+ answer4 = (to) => response.writeHead(302, { location: to, "cache-control": "no-store" }).end();
8320
8322
  arrived(url);
8321
8323
  });
8322
8324
  await new Promise((resolve, reject) => {
@@ -8324,7 +8326,7 @@ async function listen() {
8324
8326
  server2.listen(0, "127.0.0.1", resolve);
8325
8327
  });
8326
8328
  const { port } = server2.address();
8327
- return { server: server2, redirectUri: `http://127.0.0.1:${port}/callback`, next, answer: (to) => answer3(to) };
8329
+ return { server: server2, redirectUri: `http://127.0.0.1:${port}/callback`, next, answer: (to) => answer4(to) };
8328
8330
  }
8329
8331
  async function browserSignIn(base, term, organizationId) {
8330
8332
  const verifier = randomBytes2(32).toString("base64url");
@@ -8689,8 +8691,8 @@ function claudeDesktopHere(places, platform = process.platform, env = process.en
8689
8691
  function addToClaudeLink(url) {
8690
8692
  return `https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=${CONNECTOR_NAME}&connectorUrl=${encodeURIComponent(url)}`;
8691
8693
  }
8692
- function names(list4) {
8693
- return list4.length < 2 ? list4[0] ?? "" : `${list4.slice(0, -1).join(", ")} and ${list4.at(-1)}`;
8694
+ function names(list5) {
8695
+ return list5.length < 2 ? list5[0] ?? "" : `${list5.slice(0, -1).join(", ")} and ${list5.at(-1)}`;
8694
8696
  }
8695
8697
  async function ensureConnector(site2, places = placesFrom()) {
8696
8698
  const url = `${site2}/v1/mcp`;
@@ -8992,9 +8994,9 @@ async function api(base, key2, method, pathname, body, headers = {}) {
8992
8994
  }
8993
8995
  return { status: response.status, body: parsed && typeof parsed === "object" ? parsed : {} };
8994
8996
  }
8995
- function errorOf(answer3) {
8996
- const error = answer3.body["error"] && typeof answer3.body["error"] === "object" ? answer3.body["error"] : {};
8997
- return { code: String(error["code"] ?? `http_${answer3.status}`), message: String(error["message"] ?? `HTTP ${answer3.status}`) };
8997
+ function errorOf(answer4) {
8998
+ const error = answer4.body["error"] && typeof answer4.body["error"] === "object" ? answer4.body["error"] : {};
8999
+ return { code: String(error["code"] ?? `http_${answer4.status}`), message: String(error["message"] ?? `HTTP ${answer4.status}`) };
8998
9000
  }
8999
9001
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
9000
9002
  function real(file) {
@@ -9611,6 +9613,18 @@ var COMMANDS = [
9611
9613
  ["--json", "print as JSON"]
9612
9614
  ]
9613
9615
  },
9616
+ {
9617
+ name: "secret",
9618
+ summary: "Keep your organization's secrets, sealed on this machine before they are sent, and give them to templates and sandboxes.",
9619
+ examples: ["agental secret set GITHUB_TOKEN --host api.github.com,github.com", "agental secret use GITHUB_TOKEN --template default", "agental secret list"],
9620
+ flags: [
9621
+ ["--host <host>[,<host>...]", "set, seal: the hosts its value may go to, and no other"],
9622
+ ["--template <template>", "use, unuse: the template whose sandboxes see it"],
9623
+ ["--sandbox <sandbox-id>", "use, unuse: the one sandbox that sees it"],
9624
+ ["--yes", "delete: go on without asking"],
9625
+ ["--json", "print as JSON"]
9626
+ ]
9627
+ },
9614
9628
  { name: "jobs", summary: "List your jobs, or one sandbox's, or one template's." },
9615
9629
  {
9616
9630
  name: "job",
@@ -10471,12 +10485,12 @@ async function organizations(client) {
10471
10485
  const me = await ask5(client, "GET", "/v1/me");
10472
10486
  return { organizations: Array.isArray(listed2) ? listed2 : [], acting: String(me["activeOrganizationId"] ?? "") };
10473
10487
  }
10474
- function organizationNamed(list4, given) {
10475
- const byId = list4.find((organization) => organization.id === given);
10488
+ function organizationNamed(list5, given) {
10489
+ const byId = list5.find((organization) => organization.id === given);
10476
10490
  if (byId) {
10477
10491
  return byId;
10478
10492
  }
10479
- const byName = list4.filter((organization) => organization.name.toLowerCase() === given.toLowerCase());
10493
+ const byName = list5.filter((organization) => organization.name.toLowerCase() === given.toLowerCase());
10480
10494
  if (byName.length === 1 && byName[0]) {
10481
10495
  return byName[0];
10482
10496
  }
@@ -10489,14 +10503,14 @@ async function org(client, positionals, options, signInTo) {
10489
10503
  const [verb = "list", ...rest] = positionals;
10490
10504
  switch (verb) {
10491
10505
  case "list": {
10492
- const { organizations: list4, acting } = await organizations(client);
10506
+ const { organizations: list5, acting } = await organizations(client);
10493
10507
  if (options.json) {
10494
- print2(true, { organizations: list4.map((organization) => ({ ...organization, acting: organization.id === acting })) }, "");
10508
+ print2(true, { organizations: list5.map((organization) => ({ ...organization, acting: organization.id === acting })) }, "");
10495
10509
  return;
10496
10510
  }
10497
10511
  process.stdout.write(` ${[pad("ID", 22), pad("NAME", 24), "ROLE"].join(" ")}
10498
10512
  `);
10499
- for (const organization of list4) {
10513
+ for (const organization of list5) {
10500
10514
  const role = organization.personal ? "your own" : organization.role ?? "";
10501
10515
  process.stdout.write(`${organization.id === acting ? "*" : " "} ${[pad(organization.id, 22), pad(organization.name, 24), role].join(" ")}
10502
10516
  `);
@@ -10509,8 +10523,8 @@ async function org(client, positionals, options, signInTo) {
10509
10523
  if (!given) {
10510
10524
  throw new Error("org use takes the organization's id or name: agental org use Acme.");
10511
10525
  }
10512
- const { organizations: list4, acting } = await organizations(client);
10513
- const chosen = organizationNamed(list4, given);
10526
+ const { organizations: list5, acting } = await organizations(client);
10527
+ const chosen = organizationNamed(list5, given);
10514
10528
  if (chosen.id === acting) {
10515
10529
  process.stdout.write(`This command's key acts in ${chosen.name} already.
10516
10530
  `);
@@ -10540,15 +10554,15 @@ agental org use ${organization.id} signs this command in to it.
10540
10554
  }
10541
10555
  }
10542
10556
  async function actingTeam(client) {
10543
- const { organizations: list4, acting } = await organizations(client);
10544
- const team = list4.find((organization) => organization.id === acting);
10557
+ const { organizations: list5, acting } = await organizations(client);
10558
+ const team = list5.find((organization) => organization.id === acting);
10545
10559
  if (!team) {
10546
10560
  throw new Error("This command's key acts in no organization you are in. agental org use <organization> signs it in to one.");
10547
10561
  }
10548
10562
  return team;
10549
10563
  }
10550
- function memberNamed(list4, given) {
10551
- const found = list4.find((member) => member.userId === given || member.email?.toLowerCase() === given.toLowerCase());
10564
+ function memberNamed(list5, given) {
10565
+ const found = list5.find((member) => member.userId === given || member.email?.toLowerCase() === given.toLowerCase());
10552
10566
  if (!found) {
10553
10567
  throw new Error(`No member ${given} in this team. agental members lists them.`);
10554
10568
  }
@@ -10558,7 +10572,7 @@ async function members(client, positionals, options) {
10558
10572
  const [verb = "list", target] = positionals;
10559
10573
  const team = await actingTeam(client);
10560
10574
  const listed2 = await ask5(client, "GET", `/v1/organizations/${encodeURIComponent(team.id)}/members`);
10561
- const list4 = Array.isArray(listed2["members"]) ? listed2["members"] : [];
10575
+ const list5 = Array.isArray(listed2["members"]) ? listed2["members"] : [];
10562
10576
  switch (verb) {
10563
10577
  case "list": {
10564
10578
  if (options.json) {
@@ -10570,7 +10584,7 @@ async function members(client, positionals, options) {
10570
10584
  `);
10571
10585
  process.stdout.write(`${[pad("ID", 34), pad("EMAIL", 30), pad("ROLE", 8), "ADDED"].join(" ")}
10572
10586
  `);
10573
- for (const member of list4) {
10587
+ for (const member of list5) {
10574
10588
  process.stdout.write(`${[pad(member.userId, 34), pad(member.email ?? member.name ?? "", 30), pad(member.role, 8), member.addedAt.slice(0, 10)].join(" ")}
10575
10589
  `);
10576
10590
  }
@@ -10580,7 +10594,7 @@ async function members(client, positionals, options) {
10580
10594
  if (!target) {
10581
10595
  throw new Error("members remove takes the member's id or email: agental members remove cy@example.com.");
10582
10596
  }
10583
- const member = memberNamed(list4, target);
10597
+ const member = memberNamed(list5, target);
10584
10598
  const query = options.revokeKeys ? "?revokeKeys=true" : "";
10585
10599
  const removed = await ask5(client, "DELETE", `/v1/organizations/${encodeURIComponent(team.id)}/members/${encodeURIComponent(member.userId)}${query}`);
10586
10600
  const revoked = Number(removed["revokedKeys"] ?? 0);
@@ -10862,15 +10876,15 @@ function jobInputsOf(options) {
10862
10876
  return void 0;
10863
10877
  }
10864
10878
  const inputs = {};
10865
- const add = (given, secret) => {
10879
+ const add = (given, secret2) => {
10866
10880
  const [name, value] = pairOf(given);
10867
10881
  if (name === "") {
10868
- throw new Error(`${secret ? "--secret-input" : "--input"} is NAME=DEFAULT, or NAME for one a run must be given: ${given} has no name.`);
10882
+ throw new Error(`${secret2 ? "--secret-input" : "--input"} is NAME=DEFAULT, or NAME for one a run must be given: ${given} has no name.`);
10869
10883
  }
10870
10884
  if (Object.hasOwn(inputs, name)) {
10871
10885
  throw new Error(`The input ${name} is given twice.`);
10872
10886
  }
10873
- inputs[name] = secret ? { default: value, secret: true } : value;
10887
+ inputs[name] = secret2 ? { default: value, secret: true } : value;
10874
10888
  };
10875
10889
  for (const given of options.input ?? []) {
10876
10890
  add(given, false);
@@ -11321,11 +11335,11 @@ function signatureOf(trigger2) {
11321
11335
  }
11322
11336
  }
11323
11337
  var addressOf = (trigger2) => trigger2.url ?? "none: this API serves no addresses";
11324
- function printTrigger(trigger2, secret) {
11338
+ function printTrigger(trigger2, secret2) {
11325
11339
  const rows = [
11326
11340
  ["id", trigger2.id],
11327
11341
  ["address", addressOf(trigger2)],
11328
- ...secret === void 0 ? [] : [["secret", `${secret} (shown this once: keep it now)`]],
11342
+ ...secret2 === void 0 ? [] : [["secret", `${secret2} (shown this once: keep it now)`]],
11329
11343
  ["signature", signatureOf(trigger2)],
11330
11344
  ["respond", trigger2.respond === "wait" ? "wait: a call is held until the run ends, up to 60 s" : "accepted: a call is answered at once with its run's id"],
11331
11345
  ["rate", `${trigger2.ratePerMinute} calls a minute`],
@@ -12429,11 +12443,11 @@ async function offload(client, words2, options) {
12429
12443
  return;
12430
12444
  }
12431
12445
  const enabled = turn === void 0 ? (await ask8(client, "GET", "/v1/offload")).enabled : turn === "on";
12432
- const set = await ask8(client, "PUT", "/v1/offload", { enabled, ...overPercent === void 0 ? {} : { overPercent } });
12446
+ const set2 = await ask8(client, "PUT", "/v1/offload", { enabled, ...overPercent === void 0 ? {} : { overPercent } });
12433
12447
  if (options.json) {
12434
- printJson2(set);
12448
+ printJson2(set2);
12435
12449
  } else {
12436
- sayOffload(set);
12450
+ sayOffload(set2);
12437
12451
  }
12438
12452
  }
12439
12453
  async function coreDays(client, options) {
@@ -12791,9 +12805,9 @@ function describe4(webhook2) {
12791
12805
  ""
12792
12806
  ].join("\n");
12793
12807
  }
12794
- function saySecret(secret) {
12795
- if (secret) {
12796
- process.stdout.write(`secret: ${secret}
12808
+ function saySecret(secret2) {
12809
+ if (secret2) {
12810
+ process.stdout.write(`secret: ${secret2}
12797
12811
  `);
12798
12812
  process.stderr.write("The signing secret is shown this once. Keep it where your receiver checks the X-Agental-Signature of each post.\n");
12799
12813
  }
@@ -13220,16 +13234,16 @@ async function snapshot(client, positionals, options) {
13220
13234
  if (found.kept === STORAGE_ONLY) {
13221
13235
  process.stderr.write("Its server no longer holds it: it is fetched from storage first, which takes a few minutes.\n");
13222
13236
  }
13223
- const answer3 = await ask10(client, "POST", `/v1/sandboxes/${encodeURIComponent(found.sandboxId)}/restore`, {
13237
+ const answer4 = await ask10(client, "POST", `/v1/sandboxes/${encodeURIComponent(found.sandboxId)}/restore`, {
13224
13238
  headers: { "Idempotency-Key": options.idempotencyKey ?? `cli-${randomUUID2()}` },
13225
13239
  body: { snapshotId: found.id }
13226
13240
  });
13227
13241
  if (options.json) {
13228
- process.stdout.write(`${JSON.stringify(answer3, null, 2)}
13242
+ process.stdout.write(`${JSON.stringify(answer4, null, 2)}
13229
13243
  `);
13230
13244
  return;
13231
13245
  }
13232
- const read2 = answer3;
13246
+ const read2 = answer4;
13233
13247
  const discarded = Array.isArray(read2?.discarded) ? read2.discarded.map(String) : [];
13234
13248
  const status = typeof read2?.sandbox?.status === "string" ? `, and ${read2.sandbox.status}` : "";
13235
13249
  process.stdout.write(`${sandbox} is as it was at ${found.name}${status}.
@@ -13258,8 +13272,368 @@ async function snapshot(client, positionals, options) {
13258
13272
  }
13259
13273
  }
13260
13274
 
13275
+ // ../sdk/typescript/src/sealed.ts
13276
+ var SEALED_SUITE = "x25519-hkdf-sha256-aes256gcm";
13277
+ var ROOT_PUBLIC_KEYS = [];
13278
+ var KEM_ID = 32;
13279
+ var KDF_ID = 1;
13280
+ var AEAD_ID = 2;
13281
+ var INFO = "agental sealed secret v1";
13282
+ var AAD_LABEL = "agental sealed secret aad v1";
13283
+ var KEY_MESSAGE_LABEL = "agental sealing key v1";
13284
+ var SealingError = class extends Error {
13285
+ name = "SealingError";
13286
+ };
13287
+ async function seal(key2, secret2, roots = ROOT_PUBLIC_KEYS) {
13288
+ await verifySealingKey(key2, roots);
13289
+ const ephemeral = await subtle().generateKey({ name: "X25519" }, true, ["deriveBits"]);
13290
+ return sealWith(key2, secret2, ephemeral);
13291
+ }
13292
+ async function verifySealingKey(key2, roots = ROOT_PUBLIC_KEYS) {
13293
+ if (key2.suite !== SEALED_SUITE) throw new SealingError(`sealing key ${key2.kid} is for suite ${key2.suite}, not ${SEALED_SUITE}`);
13294
+ if ([key2.kid, key2.owner, key2.publicKey, key2.signature].some((field) => !field || /[\n\u0000]/.test(field))) {
13295
+ throw new SealingError(`sealing key ${key2.kid} has an empty field or one holding a newline`);
13296
+ }
13297
+ const publicKey2 = fromBase64url(key2.publicKey);
13298
+ if (publicKey2.length !== 32) throw new SealingError(`sealing key ${key2.kid} is not a 32-byte X25519 key`);
13299
+ if (key2.kid !== await sealingKeyId(publicKey2)) throw new SealingError(`sealing key ${key2.kid} does not have the id its public key gives`);
13300
+ if (roots.length === 0) throw new SealingError("no root key is known yet, so no sealing key can be trusted");
13301
+ const message = utf8(sealingKeyMessage(key2));
13302
+ const signature = fromBase64url(key2.signature);
13303
+ for (const root of roots) {
13304
+ let rootKey;
13305
+ try {
13306
+ rootKey = await subtle().importKey("raw", fromBase64url(root), { name: "Ed25519" }, false, ["verify"]);
13307
+ } catch {
13308
+ continue;
13309
+ }
13310
+ if (await subtle().verify({ name: "Ed25519" }, rootKey, signature, message)) return;
13311
+ }
13312
+ throw new SealingError(`sealing key ${key2.kid} is not signed by agental's root key`);
13313
+ }
13314
+ function sealingKeyMessage(key2) {
13315
+ return [KEY_MESSAGE_LABEL, key2.kid, key2.suite, key2.owner, key2.publicKey].join("\n");
13316
+ }
13317
+ async function sealingKeyId(publicKey2) {
13318
+ const digest = new Uint8Array(await subtle().digest("SHA-256", publicKey2));
13319
+ return `sk_${[...digest.subarray(0, 12)].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
13320
+ }
13321
+ function sealedAad(org2, name) {
13322
+ return utf8(`${AAD_LABEL}\0${org2}\0${name}`);
13323
+ }
13324
+ async function sealWith(key2, secret2, ephemeral) {
13325
+ checkSecret(key2, secret2);
13326
+ const recipient = await subtle().importKey("raw", fromBase64url(key2.publicKey), { name: "X25519" }, false, []);
13327
+ const dh = new Uint8Array(await subtle().deriveBits({ name: "X25519", public: recipient }, ephemeral.privateKey, 256));
13328
+ const enc = new Uint8Array(await subtle().exportKey("raw", ephemeral.publicKey));
13329
+ const sharedSecret = await kemSharedSecret(dh, enc, fromBase64url(key2.publicKey));
13330
+ const { aeadKey, baseNonce } = await keySchedule(sharedSecret, utf8(INFO));
13331
+ const plaintext = utf8(
13332
+ JSON.stringify({ value: secret2.value, hosts: secret2.hosts, org: secret2.org, name: secret2.name, sealedAt: secret2.sealedAt ?? (/* @__PURE__ */ new Date()).toISOString() })
13333
+ );
13334
+ const aes = await subtle().importKey("raw", aeadKey, { name: "AES-GCM" }, false, ["encrypt"]);
13335
+ const ct = new Uint8Array(
13336
+ await subtle().encrypt({ name: "AES-GCM", iv: baseNonce, additionalData: sealedAad(secret2.org, secret2.name) }, aes, plaintext)
13337
+ );
13338
+ return { v: 1, kid: key2.kid, suite: SEALED_SUITE, enc: toBase64url(enc), ct: toBase64url(ct) };
13339
+ }
13340
+ function checkSecret(key2, secret2) {
13341
+ if (key2.owner !== "agental" && key2.owner !== secret2.org) {
13342
+ throw new SealingError(`sealing key ${key2.kid} holds ${key2.owner}'s secrets, not ${secret2.org}'s`);
13343
+ }
13344
+ if (!secret2.org || !secret2.name) throw new SealingError("a secret needs its organization and its name");
13345
+ if (secret2.org.includes("\0") || secret2.name.includes("\0")) throw new SealingError("an organization or a name cannot hold a NUL");
13346
+ if (!Array.isArray(secret2.hosts) || secret2.hosts.length === 0) throw new SealingError("a secret needs at least one host it may be sent to");
13347
+ if (secret2.hosts.some((host) => typeof host !== "string" || host === "")) throw new SealingError("a host cannot be empty");
13348
+ if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(secret2.value)) {
13349
+ throw new SealingError("the value holds a broken character (a lone surrogate)");
13350
+ }
13351
+ }
13352
+ async function kemSharedSecret(dh, enc, recipientPublic) {
13353
+ const kemSuite = concat(utf8("KEM"), i2osp(KEM_ID, 2));
13354
+ const eaePrk = await labeledExtract(kemSuite, new Uint8Array(), "eae_prk", dh);
13355
+ return labeledExpand(kemSuite, eaePrk, "shared_secret", concat(enc, recipientPublic), 32);
13356
+ }
13357
+ async function keySchedule(sharedSecret, info) {
13358
+ const suite = concat(utf8("HPKE"), i2osp(KEM_ID, 2), i2osp(KDF_ID, 2), i2osp(AEAD_ID, 2));
13359
+ const pskIdHash = await labeledExtract(suite, new Uint8Array(), "psk_id_hash", new Uint8Array());
13360
+ const infoHash = await labeledExtract(suite, new Uint8Array(), "info_hash", info);
13361
+ const context = concat(new Uint8Array([0]), pskIdHash, infoHash);
13362
+ const secret2 = await labeledExtract(suite, sharedSecret, "secret", new Uint8Array());
13363
+ return {
13364
+ aeadKey: await labeledExpand(suite, secret2, "key", context, 32),
13365
+ baseNonce: await labeledExpand(suite, secret2, "base_nonce", context, 12)
13366
+ };
13367
+ }
13368
+ function labeledExtract(suite, salt, label, ikm) {
13369
+ return hkdfExtract(salt, concat(utf8("HPKE-v1"), suite, utf8(label), ikm));
13370
+ }
13371
+ function labeledExpand(suite, prk, label, info, length) {
13372
+ return hkdfExpand(prk, concat(i2osp(length, 2), utf8("HPKE-v1"), suite, utf8(label), info), length);
13373
+ }
13374
+ async function hkdfExtract(salt, ikm) {
13375
+ return hmac(salt.length > 0 ? salt : new Uint8Array(32), ikm);
13376
+ }
13377
+ async function hkdfExpand(prk, info, length) {
13378
+ const out = new Uint8Array(length);
13379
+ let block = new Uint8Array();
13380
+ for (let counter = 1, filled = 0; filled < length; counter++) {
13381
+ block = await hmac(prk, concat(block, info, new Uint8Array([counter])));
13382
+ out.set(block.subarray(0, Math.min(block.length, length - filled)), filled);
13383
+ filled += block.length;
13384
+ }
13385
+ return out;
13386
+ }
13387
+ async function hmac(key2, data) {
13388
+ const hmacKey = await subtle().importKey("raw", key2, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
13389
+ return new Uint8Array(await subtle().sign("HMAC", hmacKey, data));
13390
+ }
13391
+ function subtle() {
13392
+ const webCrypto = globalThis.crypto?.subtle;
13393
+ if (!webCrypto) throw new SealingError("this runtime has no WebCrypto, so it cannot seal");
13394
+ return webCrypto;
13395
+ }
13396
+ function i2osp(value, length) {
13397
+ const out = new Uint8Array(length);
13398
+ for (let i = length - 1, v = value; i >= 0; i--, v >>>= 8) out[i] = v & 255;
13399
+ return out;
13400
+ }
13401
+ function concat(...parts) {
13402
+ const out = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));
13403
+ let offset = 0;
13404
+ for (const part of parts) {
13405
+ out.set(part, offset);
13406
+ offset += part.length;
13407
+ }
13408
+ return out;
13409
+ }
13410
+ function utf8(text) {
13411
+ return new Uint8Array(new TextEncoder().encode(text));
13412
+ }
13413
+ function toBase64url(bytes4) {
13414
+ let binary = "";
13415
+ for (const byte of bytes4) binary += String.fromCharCode(byte);
13416
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
13417
+ }
13418
+ function fromBase64url(text) {
13419
+ if (!/^[A-Za-z0-9_-]*$/.test(text) || text.length % 4 === 1) throw new SealingError("not base64url");
13420
+ const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - text.length % 4) % 4));
13421
+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));
13422
+ }
13423
+
13424
+ // ../src/cli-secret.ts
13425
+ var ROOT_KEYS = ["jNdFf3FKdbFQ5J-1e_NE7ZzuaNPRdci-mzlGj384Rmw"];
13426
+ var USAGE8 = "secret takes list, get, set, seal, delete, use or unuse. agental secret --help shows each.";
13427
+ var NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
13428
+ var HOST = /^(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
13429
+ var SHORTEST_VALUE = 8;
13430
+ var MOST_HOSTS = 10;
13431
+ async function secret(client, positionals, options) {
13432
+ const [verb, ...args] = positionals;
13433
+ switch (verb) {
13434
+ case void 0:
13435
+ case "list":
13436
+ return list3(client, options);
13437
+ case "get":
13438
+ return get(client, nameOf2(args[0], "get"), options);
13439
+ case "set":
13440
+ return set(client, args[0], options);
13441
+ case "seal":
13442
+ return printSealed(client, args[0], options);
13443
+ case "delete":
13444
+ return remove2(client, nameOf2(args[0], "delete"), options);
13445
+ case "use":
13446
+ case "unuse":
13447
+ return use(client, verb === "use", nameOf2(args[0], verb), options);
13448
+ default:
13449
+ throw new Error(`agental secret ${verb} is not a command. ${USAGE8}`);
13450
+ }
13451
+ }
13452
+ async function list3(client, options) {
13453
+ const { secrets: secrets2 } = await answer2(client, "/v1/secrets", { method: "GET" });
13454
+ if (options.json) {
13455
+ process.stdout.write(`${JSON.stringify({ secrets: secrets2 }, null, 2)}
13456
+ `);
13457
+ return;
13458
+ }
13459
+ if (secrets2.length === 0) {
13460
+ process.stdout.write("No secrets. agental secret set <NAME> --host <host> keeps one.\n");
13461
+ return;
13462
+ }
13463
+ for (const s of secrets2) {
13464
+ process.stdout.write(`${s.name} ${s.hosts.join(",")} ${usedWords(s)}
13465
+ `);
13466
+ }
13467
+ }
13468
+ async function get(client, name, options) {
13469
+ const view = await answer2(client, `/v1/secrets/${encodeURIComponent(name)}`, { method: "GET" });
13470
+ if (options.json) {
13471
+ process.stdout.write(`${JSON.stringify(view, null, 2)}
13472
+ `);
13473
+ return;
13474
+ }
13475
+ process.stdout.write(
13476
+ `${view.name}
13477
+ goes to ${view.hosts.join(", ")}
13478
+ sealed to ${view.sealedTo.join(", ")}
13479
+ used by ${usedWords(view)}
13480
+ changed ${view.updatedAt}
13481
+ Its value is sealed, and nothing shows it: not the API, the console or this command.
13482
+ `
13483
+ );
13484
+ }
13485
+ async function set(client, given, options) {
13486
+ const { name, value, hosts } = await toSeal(client, given, options, "set");
13487
+ const { sealed, org: org2 } = await sealFor(client, name, value, hosts);
13488
+ const made = await client.request("/v1/secrets", { method: "POST", headers: JSON_HEADERS, body: JSON.stringify({ name, hosts, sealed }) });
13489
+ let view;
13490
+ if (made.ok) {
13491
+ view = await made.json();
13492
+ } else {
13493
+ const body = await made.json().catch(() => null);
13494
+ if (made.status !== 409 || codeOf(body) !== "secret_exists") {
13495
+ refused(client, made.status, body);
13496
+ }
13497
+ view = await answer2(client, `/v1/secrets/${encodeURIComponent(name)}`, { method: "PUT", headers: JSON_HEADERS, body: JSON.stringify({ hosts, sealed }) });
13498
+ }
13499
+ if (options.json) {
13500
+ process.stdout.write(`${JSON.stringify(view, null, 2)}
13501
+ `);
13502
+ return;
13503
+ }
13504
+ process.stdout.write(
13505
+ `Kept ${view.name} for the organization ${org2}, sealed here before it was sent; it goes only to ${view.hosts.join(", ")}. ${usedWords(view) === "nothing" ? `agental secret use ${view.name} --template <template> gives it to a template's sandboxes.` : `Used by ${usedWords(view)}.`}
13506
+ `
13507
+ );
13508
+ }
13509
+ async function printSealed(client, given, options) {
13510
+ const { name, value, hosts } = await toSeal(client, given, options, "seal");
13511
+ const { sealed, org: org2 } = await sealFor(client, name, value, hosts);
13512
+ process.stderr.write(`Sealed ${name} for the organization ${org2}.
13513
+ `);
13514
+ process.stdout.write(`${JSON.stringify(options.json ? { name, hosts, sealed } : sealed)}
13515
+ `);
13516
+ }
13517
+ async function remove2(client, name, options) {
13518
+ if (!options.yes && !await client.confirmed(`Delete the secret ${name}, and take it from every template and sandbox that uses it?`)) {
13519
+ throw new Error("Nothing was deleted. Give --yes to delete without asking.");
13520
+ }
13521
+ const { usedBy } = await answer2(client, `/v1/secrets/${encodeURIComponent(name)}`, { method: "DELETE" });
13522
+ if (options.json) {
13523
+ process.stdout.write(`${JSON.stringify({ deleted: name, usedBy }, null, 2)}
13524
+ `);
13525
+ return;
13526
+ }
13527
+ const from = usedBy.templates.length + usedBy.sandboxes.length;
13528
+ process.stdout.write(`Deleted ${name}${from > 0 ? `, and took it from ${usedWords({ usedBy })}` : ""}.
13529
+ `);
13530
+ }
13531
+ async function use(client, on, name, options) {
13532
+ if (options.template === void 0 === (options.sandbox === void 0)) {
13533
+ throw new Error(`secret ${on ? "use" : "unuse"} takes --template <template> or --sandbox <sandbox-id>, one of them.`);
13534
+ }
13535
+ const where = options.template !== void 0 ? { path: `/v1/templates/${encodeURIComponent(await client.templateId(options.template))}`, words: `the template ${options.template}` } : { path: `/v1/sandboxes/${encodeURIComponent(options.sandbox ?? "")}`, words: `the sandbox ${options.sandbox}` };
13536
+ const path6 = `${where.path}/secrets/${encodeURIComponent(name)}`;
13537
+ if (on) {
13538
+ const view = await answer2(client, path6, { method: "PUT" });
13539
+ process.stdout.write(options.json ? `${JSON.stringify(view, null, 2)}
13540
+ ` : `${where.words} uses ${name}: its commands see the variable, and its value goes only to ${view.hosts.join(", ")}.
13541
+ `);
13542
+ return;
13543
+ }
13544
+ const res = await client.request(path6, { method: "DELETE" });
13545
+ if (!res.ok) {
13546
+ refused(client, res.status, await res.json().catch(() => null));
13547
+ }
13548
+ process.stdout.write(options.json ? `${JSON.stringify({ unused: name }, null, 2)}
13549
+ ` : `${where.words} no longer uses ${name}.
13550
+ `);
13551
+ }
13552
+ async function toSeal(client, given, options, verb) {
13553
+ if (!given) {
13554
+ throw new Error(`secret ${verb} requires <NAME>, and --host: agental secret ${verb} GITHUB_TOKEN --host api.github.com`);
13555
+ }
13556
+ const at4 = given.indexOf("=");
13557
+ const name = nameOf2(at4 < 0 ? given : given.slice(0, at4), verb);
13558
+ const hosts = hostsOf(options.host, verb);
13559
+ const value = at4 < 0 ? await client.readValue(`${name}'s value (not shown): `) : given.slice(at4 + 1);
13560
+ if (value.length < SHORTEST_VALUE) {
13561
+ 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.`);
13562
+ }
13563
+ return { name, value, hosts };
13564
+ }
13565
+ async function sealFor(client, name, value, hosts) {
13566
+ const { keys } = await answer2(client, "/v1/secrets/key", { method: "GET" });
13567
+ const org2 = String((await answer2(client, "/v1/me", { method: "GET" })).activeOrganizationId ?? "");
13568
+ if (!org2) {
13569
+ throw new Error("The API did not say which organization this key acts in, so nothing could be sealed for it.");
13570
+ }
13571
+ const mine = keys.filter((key2) => key2.owner === "agental");
13572
+ if (mine.length === 0) {
13573
+ throw new Error("The API publishes no key of agental's boxes, so nothing was sealed or sent.");
13574
+ }
13575
+ for (const key2 of mine) {
13576
+ await verifySealingKey(key2, client.roots ?? ROOT_KEYS);
13577
+ }
13578
+ const sealed = await Promise.all(mine.map((key2) => seal(key2, { value, hosts, org: org2, name }, client.roots ?? ROOT_KEYS)));
13579
+ return { sealed, org: org2 };
13580
+ }
13581
+ function nameOf2(given, verb) {
13582
+ if (!given) {
13583
+ throw new Error(`secret ${verb} requires <NAME>`);
13584
+ }
13585
+ if (!NAME.test(given)) {
13586
+ throw new Error(`${given} is not a secret's name: letters, digits and _, not starting with a digit, up to 128.`);
13587
+ }
13588
+ return given;
13589
+ }
13590
+ function hostsOf(given, verb) {
13591
+ const hosts = (given ?? []).flatMap((h) => h.split(",")).map((h) => h.trim().toLowerCase()).filter((h) => h.length > 0);
13592
+ if (hosts.length === 0) {
13593
+ throw new Error(`secret ${verb} requires --host: the hosts its value may go to, as --host api.github.com`);
13594
+ }
13595
+ if (hosts.length > MOST_HOSTS) {
13596
+ throw new Error(`A secret goes to at most ${MOST_HOSTS} hosts, not ${hosts.length}.`);
13597
+ }
13598
+ for (const h of hosts) {
13599
+ if (!HOST.test(h)) {
13600
+ throw new Error(`${h} is not a host: a name such as api.github.com, or *.example.com.`);
13601
+ }
13602
+ }
13603
+ return [...new Set(hosts)];
13604
+ }
13605
+ function usedWords(view) {
13606
+ const t = view.usedBy.templates.length;
13607
+ const s = view.usedBy.sandboxes.length;
13608
+ if (t + s === 0) {
13609
+ return "nothing";
13610
+ }
13611
+ return [t > 0 ? `${t} template${t === 1 ? "" : "s"}` : "", s > 0 ? `${s} sandbox${s === 1 ? "" : "es"}` : ""].filter(Boolean).join(" and ");
13612
+ }
13613
+ function codeOf(body) {
13614
+ const error = body?.error;
13615
+ return typeof error?.code === "string" ? error.code : void 0;
13616
+ }
13617
+ var JSON_HEADERS = { "content-type": "application/json" };
13618
+ async function answer2(client, path6, init) {
13619
+ const res = await client.request(path6, init);
13620
+ const body = await res.json().catch(() => null);
13621
+ if (!res.ok) {
13622
+ refused(client, res.status, body);
13623
+ }
13624
+ return body;
13625
+ }
13626
+ function refused(client, status, body) {
13627
+ if (status === 403 && codeOf(body) === "key_reach_limited") {
13628
+ throw new Error(
13629
+ "This API key is held to some sandboxes or templates, and the account's secrets are the whole organization's: it cannot list, keep, change or give them. Use a key that reaches everything, or sign in with agental login."
13630
+ );
13631
+ }
13632
+ client.fail(status, body);
13633
+ }
13634
+
13261
13635
  // ../src/cli-sites.ts
13262
- var USAGE8 = "site takes a sandbox, or list, add, rm, stats or analytics, then the sandbox. agental site --help shows each.";
13636
+ var USAGE9 = "site takes a sandbox, or list, add, rm, stats or analytics, then the sandbox. agental site --help shows each.";
13263
13637
  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.";
13264
13638
  var REPORT_ROWS = 5;
13265
13639
  async function bodyOf2(response) {
@@ -13406,9 +13780,9 @@ async function organizationSwitch(client, words2, options) {
13406
13780
  const put2 = (body) => client.request("/v1/site-analytics", { method: "PUT", body: JSON.stringify(body) });
13407
13781
  let response = await put2({ enabled: turn === "on" });
13408
13782
  let answered = await bodyOf2(response);
13409
- const refused = answered?.error;
13410
- if (response.status === 409 && refused?.code === "notice_required") {
13411
- process.stderr.write(`${refused.message ?? ""}
13783
+ const refused2 = answered?.error;
13784
+ if (response.status === 409 && refused2?.code === "notice_required") {
13785
+ process.stderr.write(`${refused2.message ?? ""}
13412
13786
  `);
13413
13787
  if (!options.informed) {
13414
13788
  process.stderr.write("Nothing was changed. If your organization accepts this: agental site analytics org on --informed\n");
@@ -13448,13 +13822,13 @@ async function site(client, positionals, options) {
13448
13822
  const verb = positionals[0] === "list" || positionals[0] === "add" || positionals[0] === "rm" || positionals[0] === "stats" ? positionals[0] : null;
13449
13823
  const [sandbox, target, ...rest] = verb === null ? positionals : positionals.slice(1);
13450
13824
  if (sandbox === void 0) {
13451
- throw new Error(USAGE8);
13825
+ throw new Error(USAGE9);
13452
13826
  }
13453
13827
  switch (verb) {
13454
13828
  case null:
13455
13829
  case "list": {
13456
13830
  if (target !== void 0) {
13457
- throw new Error(USAGE8);
13831
+ throw new Error(USAGE9);
13458
13832
  }
13459
13833
  const sites = await sitesOf(client, sandbox);
13460
13834
  if (options.json) {
@@ -13474,7 +13848,7 @@ async function site(client, positionals, options) {
13474
13848
  }
13475
13849
  case "add": {
13476
13850
  if (rest.length > 0) {
13477
- throw new Error(USAGE8);
13851
+ throw new Error(USAGE9);
13478
13852
  }
13479
13853
  const port = portFrom(target);
13480
13854
  const made = routeOf(await ask11(client, "POST", `/v1/sandboxes/${encodeURIComponent(sandbox)}/host`, { port, title: `port-${port}`, public: true }));
@@ -13525,7 +13899,7 @@ async function site(client, positionals, options) {
13525
13899
  }
13526
13900
 
13527
13901
  // ../src/cli-claude.ts
13528
- var USAGE9 = "claude takes connect, show, update or disconnect. agental claude --help shows each.";
13902
+ var USAGE10 = "claude takes connect, show, update or disconnect. agental claude --help shows each.";
13529
13903
  var KEY_VARIABLE = "ANTHROPIC_ENVIRONMENT_KEY";
13530
13904
  var SECRET_VARIABLE = "ANTHROPIC_WEBHOOK_SIGNING_KEY";
13531
13905
  async function ask12(client, method, pathname, body) {
@@ -13610,10 +13984,10 @@ async function hidden(question) {
13610
13984
  const muted = lines;
13611
13985
  process.stderr.write(question);
13612
13986
  muted._writeToOutput = () => void 0;
13613
- lines.question("", (answer3) => {
13987
+ lines.question("", (answer4) => {
13614
13988
  lines.close();
13615
13989
  process.stderr.write("\n");
13616
- resolve(answer3.trim());
13990
+ resolve(answer4.trim());
13617
13991
  });
13618
13992
  });
13619
13993
  }
@@ -13640,7 +14014,7 @@ async function listClaude(client, asJson) {
13640
14014
  async function claude(client, positionals, options) {
13641
14015
  const [what, target, ...rest] = positionals;
13642
14016
  if (rest.length > 0) {
13643
- throw new Error(USAGE9);
14017
+ throw new Error(USAGE10);
13644
14018
  }
13645
14019
  switch (what) {
13646
14020
  case "connect": {
@@ -13708,7 +14082,7 @@ async function claude(client, positionals, options) {
13708
14082
  return;
13709
14083
  }
13710
14084
  default:
13711
- throw new Error(USAGE9);
14085
+ throw new Error(USAGE10);
13712
14086
  }
13713
14087
  }
13714
14088
  function needId2(id, what) {
@@ -13759,7 +14133,7 @@ function whyClosed(code, reason2, error) {
13759
14133
  return `The terminal was closed (${code})${said ? `: ${said}` : ""}.`;
13760
14134
  }
13761
14135
  }
13762
- async function answer2(response) {
14136
+ async function answer3(response) {
13763
14137
  const body = await response.json().catch(() => null);
13764
14138
  if (!response.ok) {
13765
14139
  const error = body?.error;
@@ -13768,7 +14142,7 @@ async function answer2(response) {
13768
14142
  return body;
13769
14143
  }
13770
14144
  async function keptShells2(client, id) {
13771
- const body = await answer2(await client.request(`/v1/sandboxes/${encodeURIComponent(id)}/terminals`, { method: "GET" }));
14145
+ const body = await answer3(await client.request(`/v1/sandboxes/${encodeURIComponent(id)}/terminals`, { method: "GET" }));
13772
14146
  if (!body || !Array.isArray(body.terminals)) {
13773
14147
  throw new Error("The list of kept shells was missing terminals.");
13774
14148
  }
@@ -13822,7 +14196,7 @@ async function listShells(client, id, json3, stdout) {
13822
14196
  }
13823
14197
  async function closeShell(client, id, given, stdout) {
13824
14198
  const found = await shellNamed(client, id, given, "--close");
13825
- await answer2(await client.request(`/v1/sandboxes/${encodeURIComponent(id)}/terminals/${encodeURIComponent(found.id)}`, { method: "DELETE" }));
14199
+ await answer3(await client.request(`/v1/sandboxes/${encodeURIComponent(id)}/terminals/${encodeURIComponent(found.id)}`, { method: "DELETE" }));
13826
14200
  stdout.write(`Closed ${found.n === null ? "shell" : `shell ${found.n}`} (${found.id}).
13827
14201
  `);
13828
14202
  }
@@ -14532,7 +14906,7 @@ async function main() {
14532
14906
  await create({ ...values, template: once(values.template, "--template") });
14533
14907
  return;
14534
14908
  case "list":
14535
- await list3(values.json, whereQuery(values.where ?? "", labelsFilter(values)), values.sort, values.limit, values.wide);
14909
+ await list4(values.json, whereQuery(values.where ?? "", labelsFilter(values)), values.sort, values.limit, values.wide);
14536
14910
  return;
14537
14911
  case "bulk-actions":
14538
14912
  await bulkActionsCommand(positionals.slice(1), values.json);
@@ -14568,7 +14942,7 @@ async function main() {
14568
14942
  await bulk("delete", whereQuery(values.where, labelsFilter(values)), {}, values.yes === true, values.json, values.confirm);
14569
14943
  return;
14570
14944
  }
14571
- await remove2(positionals[1], values["pause-jobs"] === true);
14945
+ await remove3(positionals[1], values["pause-jobs"] === true);
14572
14946
  return;
14573
14947
  case "start":
14574
14948
  if (values.where !== void 0) {
@@ -14615,31 +14989,31 @@ async function main() {
14615
14989
  await files({ request, fail }, positionals.slice(1), { json: values.json, recursive: values.recursive === true });
14616
14990
  return;
14617
14991
  case "desktop": {
14618
- const use = DESKTOP_USES.filter((name) => values[name] !== void 0);
14992
+ const use2 = DESKTOP_USES.filter((name) => values[name] !== void 0);
14619
14993
  const shotOptions = { crop: values.crop, scale: values.scale, quality: values.quality, cursor: values["no-cursor"] === true ? false : void 0 };
14620
14994
  const linkOptions = { expires: values.expires, keepStreams: values["keep-streams"] === true };
14621
14995
  const treeOptions = { window: values.window, query: values.query, limit: values.limit };
14622
14996
  const shaping = Object.values(shotOptions).some((value) => value !== void 0);
14623
14997
  const linking = linkOptions.expires !== void 0 || linkOptions.keepStreams;
14624
14998
  const narrowing = Object.values(treeOptions).some((value) => value !== void 0);
14625
- if (use.length === 0 && !shaping && !linking && !narrowing) {
14999
+ if (use2.length === 0 && !shaping && !linking && !narrowing) {
14626
15000
  await desktop(positionals[1], values.screen, values.off, values.status);
14627
- } else if (use.length !== 1 || values.screen !== void 0 || values.off || values.status) {
15001
+ } else if (use2.length !== 1 || values.screen !== void 0 || values.off || values.status) {
14628
15002
  throw new Error(
14629
- use.length === 0 ? "desktop takes --crop, --scale, --quality and --no-cursor with --screenshot, --window, --query and --limit with --tree, and --expires and --keep-streams with --link" : `desktop does one thing at a time: --${use[0]} goes with no other of its options`
15003
+ use2.length === 0 ? "desktop takes --crop, --scale, --quality and --no-cursor with --screenshot, --window, --query and --limit with --tree, and --expires and --keep-streams with --link" : `desktop does one thing at a time: --${use2[0]} goes with no other of its options`
14630
15004
  );
14631
- } else if (shaping && use[0] !== "screenshot" || linking && use[0] !== "link" || narrowing && use[0] !== "tree") {
15005
+ } else if (shaping && use2[0] !== "screenshot" || linking && use2[0] !== "link" || narrowing && use2[0] !== "tree") {
14632
15006
  throw new Error(shaping ? "--crop, --scale, --quality and --no-cursor go with --screenshot" : linking ? "--expires and --keep-streams go with --link" : "--window, --query and --limit go with --tree");
14633
- } else if (use[0] === "tree") {
15007
+ } else if (use2[0] === "tree") {
14634
15008
  await desktopTree(positionals[1], treeOptions, values.json);
14635
- } else if (use[0] === "screenshot") {
15009
+ } else if (use2[0] === "screenshot") {
14636
15010
  await screenshot(positionals[1], values.screenshot, shotOptions);
14637
- } else if (use[0] === "clipboard" || use[0] === "set-clipboard") {
15011
+ } else if (use2[0] === "clipboard" || use2[0] === "set-clipboard") {
14638
15012
  await clipboard(positionals[1], values["set-clipboard"]);
14639
- } else if (use[0] === "link" || use[0] === "links" || use[0] === "unlink") {
14640
- await desktopLinks(positionals[1], use[0], values[use[0]], linkOptions);
15013
+ } else if (use2[0] === "link" || use2[0] === "links" || use2[0] === "unlink") {
15014
+ await desktopLinks(positionals[1], use2[0], values[use2[0]], linkOptions);
14641
15015
  } else {
14642
- await useDesktop(positionals[1], use[0], String(values[use[0]]));
15016
+ await useDesktop(positionals[1], use2[0], String(values[use2[0]]));
14643
15017
  }
14644
15018
  return;
14645
15019
  }
@@ -14667,6 +15041,13 @@ async function main() {
14667
15041
  case "secrets":
14668
15042
  await secrets(positionals.slice(1), { ...values, template: once(values.template, "--template") });
14669
15043
  return;
15044
+ case "secret":
15045
+ await secret(
15046
+ { request, fail, confirmed, templateId: async (given) => (await templateNamed(given)).id, readValue: hiddenValue },
15047
+ positionals.slice(1),
15048
+ { json: values.json, ...values.host === void 0 ? {} : { host: values.host }, template: once(values.template, "--template"), sandbox: once(values.sandbox, "--sandbox"), yes: values.yes === true }
15049
+ );
15050
+ return;
14670
15051
  case "metrics":
14671
15052
  await metrics(positionals[1], values);
14672
15053
  return;
@@ -14801,6 +15182,9 @@ async function create(values) {
14801
15182
  const egressAsked = values.egress === void 0 ? void 0 : egressFrom(values.egress.split(":"), "--egress takes box, or residential:<country>, as residential:de or residential:us:rotating.");
14802
15183
  const sshKeys2 = values["ssh-key"] === void 0 ? void 0 : publicKeysFrom(values["ssh-key"]);
14803
15184
  const box = boxNamed(values.box);
15185
+ if (box !== void 0 && PUBLISHED) {
15186
+ throw new Error("--box is for whoever runs agental, from its repository.");
15187
+ }
14804
15188
  const templateId = values.template === void 0 ? void 0 : (await templateNamed(values.template)).id;
14805
15189
  const idempotencyKey = values["idempotency-key"] ?? `cli-${randomUUID3()}`;
14806
15190
  const response = await request("/v1/sandboxes", {
@@ -14863,12 +15247,12 @@ function regionsOption(given) {
14863
15247
  const named = listedIn([given]);
14864
15248
  return named.length === 1 ? { region: named[0] } : { regions: named };
14865
15249
  }
14866
- async function sshKeys(id, keyId, remove3, json3) {
15250
+ async function sshKeys(id, keyId, remove4, json3) {
14867
15251
  if (!id) {
14868
15252
  throw new Error("ssh-keys requires <sandbox-id>");
14869
15253
  }
14870
15254
  const path6 = `/v1/sandboxes/${encodeURIComponent(id)}/ssh/keys`;
14871
- if (remove3) {
15255
+ if (remove4) {
14872
15256
  if (!keyId) {
14873
15257
  throw new Error("ssh-keys --remove requires <key-id>, as ssh-keys lists it");
14874
15258
  }
@@ -14945,7 +15329,7 @@ async function regions(asJson) {
14945
15329
  }
14946
15330
  process.stdout.write("* where a sandbox is made when no region is named\n");
14947
15331
  }
14948
- async function list3(asJson, filter, sort, limit, wide = false) {
15332
+ async function list4(asJson, filter, sort, limit, wide = false) {
14949
15333
  const sandboxes2 = [];
14950
15334
  let cursor = null;
14951
15335
  do {
@@ -15071,6 +15455,52 @@ async function typedCount(count) {
15071
15455
  lines.close();
15072
15456
  }
15073
15457
  }
15458
+ async function hiddenValue(prompt) {
15459
+ if (!process.stdin.isTTY) {
15460
+ process.stderr.write(`${prompt.replace(/: $/, "")}: read from stdin
15461
+ `);
15462
+ const chunks = [];
15463
+ for await (const chunk of process.stdin) {
15464
+ chunks.push(chunk);
15465
+ }
15466
+ return Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/, "");
15467
+ }
15468
+ process.stderr.write(prompt);
15469
+ process.stdin.setEncoding("utf8");
15470
+ process.stdin.setRawMode(true);
15471
+ process.stdin.resume();
15472
+ try {
15473
+ let value = "";
15474
+ for await (const chunk of process.stdin) {
15475
+ const text = chunk;
15476
+ for (let i = 0; i < text.length; i++) {
15477
+ const ch = text[i] ?? "";
15478
+ if (ch === "\r" || ch === "\n") {
15479
+ if (text.slice(i + 1).replace(/^\n/, "").length > 0) {
15480
+ throw new Error("A value of more than one line was pasted: nothing was sealed or sent. Give such a value on stdin: agental secret set NAME --host \u2026 < file");
15481
+ }
15482
+ return value;
15483
+ }
15484
+ if (ch === "") {
15485
+ throw new Error("Nothing was sealed or sent.");
15486
+ }
15487
+ if (ch === "\x7F" || ch === "\b") {
15488
+ value = [...value].slice(0, -1).join("");
15489
+ continue;
15490
+ }
15491
+ if (ch < " " && ch !== " ") {
15492
+ throw new Error("A control or arrow key was typed in the value: nothing was sealed or sent.");
15493
+ }
15494
+ value += ch;
15495
+ }
15496
+ }
15497
+ return value;
15498
+ } finally {
15499
+ process.stdin.setRawMode(false);
15500
+ process.stdin.pause();
15501
+ process.stderr.write("\n");
15502
+ }
15503
+ }
15074
15504
  async function confirmed(question) {
15075
15505
  if (!process.stdin.isTTY) {
15076
15506
  return false;
@@ -15199,7 +15629,7 @@ async function exec(positionals) {
15199
15629
  }
15200
15630
  process.exitCode = typeof record["exitCode"] === "number" ? record["exitCode"] : 1;
15201
15631
  }
15202
- async function remove2(id, pauseJobs) {
15632
+ async function remove3(id, pauseJobs) {
15203
15633
  if (!id) {
15204
15634
  throw new Error("delete requires <sandbox-id>");
15205
15635
  }
@@ -15588,12 +16018,12 @@ async function desktopTree(id, options, json3) {
15588
16018
  ` : `${treeText(body)}
15589
16019
  `);
15590
16020
  }
15591
- async function desktopLinks(id, use, given, options) {
16021
+ async function desktopLinks(id, use2, given, options) {
15592
16022
  if (!id) {
15593
16023
  throw new Error("desktop requires <sandbox-id>");
15594
16024
  }
15595
16025
  const at4 = `/v1/sandboxes/${encodeURIComponent(id)}/desktop/links`;
15596
- if (use === "unlink") {
16026
+ if (use2 === "unlink") {
15597
16027
  const response2 = await request(`${at4}/${encodeURIComponent(String(given))}`, { method: "DELETE" });
15598
16028
  if (!response2.ok) {
15599
16029
  fail(response2.status, await readBody(response2));
@@ -15602,7 +16032,7 @@ async function desktopLinks(id, use, given, options) {
15602
16032
  `);
15603
16033
  return;
15604
16034
  }
15605
- if (use === "links") {
16035
+ if (use2 === "links") {
15606
16036
  const response2 = await request(at4, { method: "GET" });
15607
16037
  const body2 = await readBody(response2);
15608
16038
  if (!response2.ok) {
@@ -15640,38 +16070,38 @@ function numbers(text, least, most, signedFrom = most) {
15640
16070
  const whole = parts.every((part, index) => (index >= signedFrom ? /^-?\d+$/ : /^\d+$/).test(part));
15641
16071
  return whole && parts.length >= least && parts.length <= most ? parts.map(Number) : null;
15642
16072
  }
15643
- async function useDesktop(id, use, given) {
16073
+ async function useDesktop(id, use2, given) {
15644
16074
  if (!id) {
15645
16075
  throw new Error("desktop requires <sandbox-id>");
15646
16076
  }
15647
- const at4 = `/v1/sandboxes/${encodeURIComponent(id)}/desktop/${use}`;
16077
+ const at4 = `/v1/sandboxes/${encodeURIComponent(id)}/desktop/${use2}`;
15648
16078
  let body;
15649
- if (use === "click") {
16079
+ if (use2 === "click") {
15650
16080
  const [x, y, button, count, ...more] = given.split(",");
15651
16081
  const point = numbers(`${x ?? ""},${y ?? ""}`, 2, 2);
15652
16082
  if (!point || more.length > 0 || button !== void 0 && !["left", "middle", "right"].includes(button) || count !== void 0 && !/^[123]$/.test(count)) {
15653
16083
  throw new Error("--click is where to click, as x,y, with the button and how many times after it when they are not left and once: 640,400 or 640,400,right or 640,400,left,2");
15654
16084
  }
15655
16085
  body = { x: point[0], y: point[1], ...button ? { button } : {}, ...count ? { count: Number(count) } : {} };
15656
- } else if (use === "move") {
16086
+ } else if (use2 === "move") {
15657
16087
  const point = numbers(given, 2, 2);
15658
16088
  if (!point) {
15659
16089
  throw new Error("--move is where the pointer goes, as x,y: 640,400");
15660
16090
  }
15661
16091
  body = { x: point[0], y: point[1] };
15662
- } else if (use === "drag") {
16092
+ } else if (use2 === "drag") {
15663
16093
  const points = numbers(given, 4, 4);
15664
16094
  if (!points) {
15665
16095
  throw new Error("--drag is where the button goes down and where it comes up, as x,y,x,y: 10,20,300,400");
15666
16096
  }
15667
16097
  body = { from: { x: points[0], y: points[1] }, to: { x: points[2], y: points[3] } };
15668
- } else if (use === "scroll") {
16098
+ } else if (use2 === "scroll") {
15669
16099
  const turn = numbers(given, 3, 4, 2);
15670
16100
  if (!turn) {
15671
16101
  throw new Error("--scroll is where the pointer is and how many notches the wheel turns, down or with a minus up, as x,y,notches: 640,400,3. A fourth number turns it to the right, or with a minus to the left.");
15672
16102
  }
15673
16103
  body = { x: turn[0], y: turn[1], dy: turn[2], ...turn[3] !== void 0 ? { dx: turn[3] } : {} };
15674
- } else if (use === "type") {
16104
+ } else if (use2 === "type") {
15675
16105
  body = { text: given };
15676
16106
  } else {
15677
16107
  body = { keys: given };
@@ -15859,9 +16289,9 @@ async function egress(positionals, values) {
15859
16289
  card: "a card saved: agental billing card save",
15860
16290
  use_case: 'what your sandboxes will use it for: agental egress use-case "<what for>"'
15861
16291
  };
15862
- const refused = account3["refused"];
16292
+ const refused2 = account3["refused"];
15863
16293
  const lines = !account3["offered"] ? ["Residential egress is not offered here."] : [
15864
- `residential: ${account3["enabled"] ? "on for this account" : refused ? `refused: ${String(refused.reason ?? "")}` : "not yet"}`,
16294
+ `residential: ${account3["enabled"] ? "on for this account" : refused2 ? `refused: ${String(refused2.reason ?? "")}` : "not yet"}`,
15865
16295
  ...missing.map((need) => ` needs ${needs[need] ?? need}`),
15866
16296
  `price: ${money(number("microsPerGb"))} a GB, both directions counted`,
15867
16297
  `this month: ${money(number("spentMicros"))} of a ${money(number("budgetMicros"))} budget${account3["budgetSet"] ? "" : " (the default)"}`,
@@ -15993,15 +16423,15 @@ ${faint("The default is used when a sandbox is made without naming one. agental
15993
16423
  process.stdout.write("* used when a sandbox is made without naming one\n");
15994
16424
  }
15995
16425
  function showTemplate(each) {
15996
- const list4 = (items) => items && items.length > 0 ? items.join(", ") : "none";
16426
+ const list5 = (items) => items && items.length > 0 ? items.join(", ") : "none";
15997
16427
  return [
15998
16428
  `id: ${each.id}`,
15999
16429
  `name: ${each.name}${each.default ? " (default: used when a sandbox is made without naming one)" : ""}`,
16000
16430
  `start: ${startInWords(each.start)}`,
16001
- `variables: ${list4(each.variables)}`,
16431
+ `variables: ${list5(each.variables)}`,
16002
16432
  // Said only where some are. An API from before variables could be kept out of the sandbox says nothing of them.
16003
- ...each.hidden && each.hidden.length > 0 ? [`kept out: ${list4(each.hidden)}`] : [],
16004
- `files: ${list4(each.files)}`,
16433
+ ...each.hidden && each.hidden.length > 0 ? [`kept out: ${list5(each.hidden)}`] : [],
16434
+ `files: ${list5(each.files)}`,
16005
16435
  // An API from before templates held rules says nothing of one.
16006
16436
  ...each.network ? [`network: ${ruleInWords(each.network)}`] : [],
16007
16437
  // An API from before templates gave SSH says nothing of it.
@@ -16138,8 +16568,8 @@ ${mode === void 0 ? "" : "A sandbox on it takes this when it next starts, or now
16138
16568
  const found = await templateNamed(need(first, "<template>"));
16139
16569
  const path6 = `/v1/templates/${encodeURIComponent(found.id)}/egress`;
16140
16570
  const how = `template egress takes <template>, and then nothing, box, or residential <country> [sticky|rotating], as agental template egress ${first ?? ""} residential de.`;
16141
- const set = await call2(path6, rest.length === 0 ? { method: "GET" } : { method: "PUT", body: JSON.stringify(egressFrom(rest, how)) });
16142
- print4(set, `${found.name}: ${egressInWords(set)}${rest.length === 0 ? "" : ", for sandboxes made from it from now on"}
16571
+ const set2 = await call2(path6, rest.length === 0 ? { method: "GET" } : { method: "PUT", body: JSON.stringify(egressFrom(rest, how)) });
16572
+ print4(set2, `${found.name}: ${egressInWords(set2)}${rest.length === 0 ? "" : ", for sandboxes made from it from now on"}
16143
16573
  `);
16144
16574
  return;
16145
16575
  }
@@ -16421,8 +16851,8 @@ async function metrics(id, asked2) {
16421
16851
  if (!response.ok) {
16422
16852
  fail(response.status, body);
16423
16853
  }
16424
- const answer3 = body && typeof body === "object" ? body : {};
16425
- const fromTo = typeof answer3["since"] === "string" && typeof answer3["until"] === "string" ? ` from ${answer3["since"]} to ${answer3["until"]}` : "";
16854
+ const answer4 = body && typeof body === "object" ? body : {};
16855
+ const fromTo = typeof answer4["since"] === "string" && typeof answer4["until"] === "string" ? ` from ${answer4["since"]} to ${answer4["until"]}` : "";
16426
16856
  if (asked2.json) {
16427
16857
  process.stdout.write(`${JSON.stringify(body, null, 2)}
16428
16858
  `);
@@ -16447,7 +16877,7 @@ async function metrics(id, asked2) {
16447
16877
  ])
16448
16878
  );
16449
16879
  }
16450
- if (answer3["complete"] === false) {
16880
+ if (answer4["complete"] === false) {
16451
16881
  process.stderr.write(
16452
16882
  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.
16453
16883
  `
@@ -16490,8 +16920,8 @@ async function dataRetention(positionals, asJson) {
16490
16920
  `);
16491
16921
  return;
16492
16922
  }
16493
- const answer3 = body ?? {};
16494
- const days = answer3.keepDays ?? null;
16923
+ const answer4 = body ?? {};
16924
+ const days = answer4.keepDays ?? null;
16495
16925
  const kept2 = days === null ? "until their sandbox is deleted" : days === 1 ? "1 day" : `${days} days`;
16496
16926
  process.stdout.write(`${period === void 0 ? "" : "Saved. "}Command output, agent conversations and events are kept ${kept2}.
16497
16927
  `);
@@ -16499,7 +16929,7 @@ async function dataRetention(positionals, asJson) {
16499
16929
  process.stdout.write(`What is older is deleted within the hour, and cannot be brought back.
16500
16930
  `);
16501
16931
  }
16502
- const last = answer3.lastCleared;
16932
+ const last = answer4.lastCleared;
16503
16933
  if (period === void 0) {
16504
16934
  process.stdout.write(
16505
16935
  last ? `Last clean-up ${last.at}: ${last.commands} commands' output, ${last.conversations} conversations and ${last.events} events deleted.
@@ -16645,8 +17075,8 @@ async function telemetry(positionals, given, asJson) {
16645
17075
  `);
16646
17076
  return;
16647
17077
  }
16648
- const set = settingsIn(body);
16649
- process.stdout.write(set === null ? "No collector is set. agental telemetry set <endpoint> sets one.\n" : describeSettings(set));
17078
+ const set2 = settingsIn(body);
17079
+ process.stdout.write(set2 === null ? "No collector is set. agental telemetry set <endpoint> sets one.\n" : describeSettings(set2));
16650
17080
  return;
16651
17081
  }
16652
17082
  case "set": {
@@ -16667,8 +17097,8 @@ async function telemetry(positionals, given, asJson) {
16667
17097
  process.stdout.write(`${JSON.stringify({ ...saved, test: tested }, null, 2)}
16668
17098
  `);
16669
17099
  } else {
16670
- const set = settingsIn(saved);
16671
- process.stdout.write(set === null ? "" : describeSettings(set));
17100
+ const set2 = settingsIn(saved);
17101
+ process.stdout.write(set2 === null ? "" : describeSettings(set2));
16672
17102
  }
16673
17103
  sayTest(tested, "Saved. ");
16674
17104
  return;
@@ -17025,7 +17455,8 @@ function usedParts(body) {
17025
17455
  const parts = [
17026
17456
  ...(body.mailMicros ?? 0) > 0 ? [`${money(body.mailMicros ?? 0)} by email`] : [],
17027
17457
  ...(body.stoppedMicros ?? 0) > 0 ? [`${money(body.stoppedMicros ?? 0)} by stopped sandboxes`] : [],
17028
- ...(body.snapshotMicros ?? 0) > 0 ? [`${money(body.snapshotMicros ?? 0)} by snapshots past the free ones`] : []
17458
+ ...(body.snapshotMicros ?? 0) > 0 ? [`${money(body.snapshotMicros ?? 0)} by snapshots past the free ones`] : [],
17459
+ ...(body.bucketMicros ?? 0) > 0 ? [`${money(body.bucketMicros ?? 0)} by buckets`] : []
17029
17460
  ];
17030
17461
  return parts.length > 0 ? `, ${parts.join(" and ")} of it` : "";
17031
17462
  }
@@ -17181,10 +17612,10 @@ async function showLimits(positionals, options) {
17181
17612
  `);
17182
17613
  return;
17183
17614
  }
17184
- const answer3 = body2 && typeof body2 === "object" ? body2 : {};
17185
- const spent = typeof answer3["spentMicros"] === "number" ? answer3["spentMicros"] : 0;
17186
- const budget = typeof answer3["budgetMicros"] === "number" ? answer3["budgetMicros"] : 0;
17187
- process.stdout.write(`Budget for burst fees: ${money(budget)} a month${answer3["budgetSet"] === true ? "" : " (the default)"}; ${money(spent)} spent this month.
17615
+ const answer4 = body2 && typeof body2 === "object" ? body2 : {};
17616
+ const spent = typeof answer4["spentMicros"] === "number" ? answer4["spentMicros"] : 0;
17617
+ const budget = typeof answer4["budgetMicros"] === "number" ? answer4["budgetMicros"] : 0;
17618
+ process.stdout.write(`Budget for burst fees: ${money(budget)} a month${answer4["budgetSet"] === true ? "" : " (the default)"}; ${money(spent)} spent this month.
17188
17619
  `);
17189
17620
  return;
17190
17621
  }
@@ -17214,8 +17645,8 @@ async function showLimits(positionals, options) {
17214
17645
  process.stdout.write(describeLimits(body, options.from === void 0 && options.to === void 0, options.to === void 0));
17215
17646
  }
17216
17647
  function describeLimits(body, today, endsNow) {
17217
- const answer3 = body && typeof body === "object" ? body : {};
17218
- const now = answer3["now"] && typeof answer3["now"] === "object" ? answer3["now"] : {};
17648
+ const answer4 = body && typeof body === "object" ? body : {};
17649
+ const now = answer4["now"] && typeof answer4["now"] === "object" ? answer4["now"] : {};
17219
17650
  const number = (from, name) => typeof from[name] === "number" ? from[name] : 0;
17220
17651
  const units = (mb) => {
17221
17652
  const value = mb / 2048;
@@ -17225,11 +17656,11 @@ function describeLimits(body, today, endsNow) {
17225
17656
  const at4 = new Date(iso).toISOString();
17226
17657
  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`;
17227
17658
  };
17228
- const range = today ? "today (UTC)" : `from ${String(answer3["from"] ?? "")} to ${String(answer3["to"] ?? "")}`;
17659
+ const range = today ? "today (UTC)" : `from ${String(answer4["from"] ?? "")} to ${String(answer4["to"] ?? "")}`;
17229
17660
  const lines = [
17230
- `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(answer3, "atRunningCountMs"))} ${range}`
17661
+ `running: ${units(number(now, "runningMb"))} of ${number(now, "runningUnits").toLocaleString("en-US")} units (a tiny is 1, a small 2, a medium 4, a large 8); at the running count ${duration(number(answer4, "atRunningCountMs"))} ${range}`
17231
17662
  ];
17232
- const bursts = Array.isArray(answer3["bursts"]) ? answer3["bursts"] : [];
17663
+ const bursts = Array.isArray(answer4["bursts"]) ? answer4["bursts"] : [];
17233
17664
  const open = endsNow ? bursts.find((one) => one["endedAt"] === null && typeof one["startedAt"] === "string") : void 0;
17234
17665
  const over = number(now, "overMb") > 0;
17235
17666
  const nextStart = Array.isArray(now["nextStart"]) ? now["nextStart"] : [];
@@ -17245,9 +17676,9 @@ function describeLimits(body, today, endsNow) {
17245
17676
  const budgetMonth = now["budgetMonth"] && typeof now["budgetMonth"] === "object" ? now["budgetMonth"] : null;
17246
17677
  const since = typeof budgetMonth?.start === "string" && budgetMonth.start.slice(8, 10) !== "01" ? ` (since ${shortDayOf(budgetMonth.start)})` : "";
17247
17678
  lines.push(`fees: ${money(number(now, "spentMicros"))} this month${since} of a ${money(number(now, "budgetMicros"))} budget`);
17248
- const refused = answer3["refused"] && typeof answer3["refused"] === "object" ? answer3["refused"] : {};
17249
- const total = number(refused, "total");
17250
- const byReason = Array.isArray(refused["byReason"]) ? refused["byReason"] : [];
17679
+ const refused2 = answer4["refused"] && typeof answer4["refused"] === "object" ? answer4["refused"] : {};
17680
+ const total = number(refused2, "total");
17681
+ const byReason = Array.isArray(refused2["byReason"]) ? refused2["byReason"] : [];
17251
17682
  lines.push(
17252
17683
  `did not start: ${total.toLocaleString("en-US")} ${range}${byReason.length > 0 ? `: ${byReason.map((one) => `${one.count.toLocaleString("en-US")} ${REASON_WORDS[one.reason] ?? one.reason} (${one.code})`).join(", ")}` : ""}`
17253
17684
  );
@@ -17274,22 +17705,22 @@ async function asked(path6, init) {
17274
17705
  return body;
17275
17706
  }
17276
17707
  function settingsIn(body) {
17277
- const set = body && typeof body === "object" ? body["telemetry"] : void 0;
17278
- if (set === null) {
17708
+ const set2 = body && typeof body === "object" ? body["telemetry"] : void 0;
17709
+ if (set2 === null) {
17279
17710
  return null;
17280
17711
  }
17281
- if (!set || typeof set !== "object") {
17712
+ if (!set2 || typeof set2 !== "object") {
17282
17713
  throw new Error("Telemetry response was missing telemetry");
17283
17714
  }
17284
- return set;
17715
+ return set2;
17285
17716
  }
17286
- function describeSettings(set) {
17287
- const headers = Array.isArray(set["headers"]) ? set["headers"].map(String) : [];
17288
- const error = set["lastError"] && typeof set["lastError"] === "object" ? set["lastError"] : null;
17717
+ function describeSettings(set2) {
17718
+ const headers = Array.isArray(set2["headers"]) ? set2["headers"].map(String) : [];
17719
+ const error = set2["lastError"] && typeof set2["lastError"] === "object" ? set2["lastError"] : null;
17289
17720
  return [
17290
- String(set["endpoint"] ?? ""),
17721
+ String(set2["endpoint"] ?? ""),
17291
17722
  ` headers ${headers.length === 0 ? NO_FIGURE : headers.join(", ")}`,
17292
- ` last export ${typeof set["lastExportAt"] === "string" ? set["lastExportAt"] : NO_FIGURE}`,
17723
+ ` last export ${typeof set2["lastExportAt"] === "string" ? set2["lastExportAt"] : NO_FIGURE}`,
17293
17724
  ` last error ${error === null ? NO_FIGURE : `${String(error["message"] ?? "")}, at ${String(error["at"] ?? "")}`}`,
17294
17725
  ""
17295
17726
  ].join("\n");
@@ -17445,17 +17876,41 @@ async function request(pathname, init) {
17445
17876
  await new Promise((resolve) => setTimeout(resolve, seconds2 * 1e3));
17446
17877
  }
17447
17878
  }
17879
+ function adminKeyHere() {
17880
+ if (PUBLISHED) {
17881
+ return void 0;
17882
+ }
17883
+ const given = process.env["AGENTAL_ADMIN_KEY"]?.trim();
17884
+ if (given) {
17885
+ return given;
17886
+ }
17887
+ try {
17888
+ const saved = JSON.parse(readFileSync7(`${os7.homedir()}/.config/agental/admin-key.json`, "utf8"));
17889
+ const forHere = typeof saved.apiUrl === "string" && saved.apiUrl.replace(/\/$/, "") === apiBase().replace(/\/$/, "");
17890
+ if (forHere && typeof saved.key === "string" && !(typeof saved.expiresAt === "string" && Date.parse(saved.expiresAt) <= Date.now())) {
17891
+ return saved.key;
17892
+ }
17893
+ } catch {
17894
+ }
17895
+ return void 0;
17896
+ }
17448
17897
  async function requestOnce(pathname, init) {
17449
17898
  const base = apiBase();
17450
- const key2 = apiKey();
17899
+ const admin = adminKeyHere();
17900
+ const namesBox = new Headers(init.headers).has("x-agental-box");
17901
+ const key2 = admin && (pathname === "/v1/admin" || pathname.startsWith("/v1/admin/")) ? admin : apiKey();
17451
17902
  try {
17903
+ const sendsAdmin = admin !== void 0 && (key2 === admin || namesBox);
17452
17904
  return await fetch(`${base}${pathname}`, {
17453
17905
  ...init,
17906
+ // An admin key never follows a redirect: a custom header would go on to wherever it points.
17907
+ ...sendsAdmin ? { redirect: "error" } : {},
17454
17908
  headers: {
17455
17909
  Authorization: `Bearer ${key2}`,
17456
17910
  Accept: "application/json",
17457
17911
  "User-Agent": USER_AGENT,
17458
17912
  ...init.body ? { "Content-Type": "application/json" } : {},
17913
+ ...admin && namesBox ? { "X-Agental-Admin-Key": admin } : {},
17459
17914
  ...init.headers
17460
17915
  }
17461
17916
  });
@@ -17471,11 +17926,11 @@ function readSandboxes(body) {
17471
17926
  return body.sandboxes.filter((item) => Boolean(item) && typeof item === "object");
17472
17927
  }
17473
17928
  function readList(body, name) {
17474
- const list4 = body && typeof body === "object" ? body[name] : void 0;
17475
- if (!Array.isArray(list4)) {
17929
+ const list5 = body && typeof body === "object" ? body[name] : void 0;
17930
+ if (!Array.isArray(list5)) {
17476
17931
  throw new Error(`Metrics response was missing ${name}`);
17477
17932
  }
17478
- return list4.filter((item) => Boolean(item) && typeof item === "object");
17933
+ return list5.filter((item) => Boolean(item) && typeof item === "object");
17479
17934
  }
17480
17935
  function teamOptions(values) {
17481
17936
  return { json: values.json, revokeKeys: values["revoke-keys"], ...values.role === void 0 ? {} : { role: values.role } };