agental 0.6.2 → 0.9.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 +345 -38
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -46,7 +46,7 @@ import { parseArgs } from "node:util";
46
46
 
47
47
  // ../src/cli-build.ts
48
48
  var PUBLISHED = true;
49
- var CLI_VERSION = true ? "0.6.2" : "dev";
49
+ var CLI_VERSION = true ? "0.9.0" : "dev";
50
50
  var DEFAULT_API_URL = true ? "https://agental.io" : "http://127.0.0.1:8741";
51
51
  var PACKAGE_NAME = "agental";
52
52
  var USER_AGENT = `agental-cli/${CLI_VERSION}`;
@@ -763,10 +763,10 @@ async function whoIs(base, key2) {
763
763
  throw error;
764
764
  }
765
765
  }
766
- async function pushRequest(base, ask7) {
766
+ async function pushRequest(base, ask8) {
767
767
  let made;
768
768
  try {
769
- made = await call(base, "POST", "/v1/cli-sign-ins", ask7);
769
+ made = await call(base, "POST", "/v1/cli-sign-ins", ask8);
770
770
  } catch (error) {
771
771
  if (error instanceof Refused && (error.status === 401 || error.status === 404)) {
772
772
  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.`);
@@ -2077,7 +2077,16 @@ var WEBHOOK_EVENTS = [...LIFECYCLE_EVENTS, "prompt.created"];
2077
2077
  var EMAIL_EVENTS = ["email.received", "email.delivered", "email.bounced"];
2078
2078
  var MEMBER_EVENTS = ["member.invited", "member.joined", "member.removed", "member.role_changed", "key.revoked"];
2079
2079
  var TEMPLATE_EVENTS = ["template.created", "template.updated", "template.secrets_changed", "template.labels_changed", "template.deleted"];
2080
- var WEBHOOK_KINDS = [...WEBHOOK_EVENTS, ...EMAIL_EVENTS, ...MEMBER_EVENTS, ...TEMPLATE_EVENTS];
2080
+ var HEADROOM_EVENTS = [
2081
+ "headroom.burst_started",
2082
+ "headroom.burst_ended",
2083
+ "headroom.refused",
2084
+ "headroom.running_count_reached",
2085
+ "headroom.budget_threshold",
2086
+ "headroom.budget_reached"
2087
+ ];
2088
+ var WEBHOOK_KINDS = [...WEBHOOK_EVENTS, ...EMAIL_EVENTS, ...MEMBER_EVENTS, ...TEMPLATE_EVENTS, ...HEADROOM_EVENTS];
2089
+ var WEBHOOK_GROUPS = [...new Set(WEBHOOK_KINDS.map((kind) => kind.slice(0, kind.indexOf("."))))];
2081
2090
  var WEBHOOK_RETRY_AFTER_MS = [6e4, 5 * 6e4, 15 * 6e4, 60 * 6e4, 3 * 36e5, 6 * 36e5, 12 * 36e5];
2082
2091
 
2083
2092
  // ../src/cli-webhooks.ts
@@ -2176,14 +2185,16 @@ function eventsFrom(options, needed) {
2176
2185
  }
2177
2186
  if (options.events === void 0) {
2178
2187
  if (needed) {
2179
- throw new Error(`Say what to send: --events with kinds such as sandbox.stopped,sandbox.error, or --all. The kinds are ${WEBHOOK_KINDS.join(", ")}.`);
2188
+ 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.`);
2180
2189
  }
2181
2190
  return void 0;
2182
2191
  }
2183
2192
  const kinds = options.events.split(",").map((kind) => kind.trim()).filter(Boolean);
2184
- const unknown = kinds.filter((kind) => !WEBHOOK_KINDS.includes(kind));
2193
+ const unknown = kinds.filter((kind) => !WEBHOOK_KINDS.includes(kind) && !(kind.endsWith(".*") && WEBHOOK_GROUPS.includes(kind.slice(0, -2))));
2185
2194
  if (kinds.length === 0 || unknown.length > 0) {
2186
- throw new Error(`${unknown.length > 0 ? `No event is called ${unknown.join(", ")}. ` : "--events names no kind. "}The kinds are ${WEBHOOK_KINDS.join(", ")}, or --all for every event.`);
2195
+ throw new Error(
2196
+ `${unknown.length > 0 ? `No event is called ${unknown.join(", ")}. ` : "--events names no kind. "}The kinds are ${WEBHOOK_KINDS.join(", ")}; a group of them is ${WEBHOOK_GROUPS.map((group) => `${group}.*`).join(", ")}; or --all for every event.`
2197
+ );
2187
2198
  }
2188
2199
  return kinds;
2189
2200
  }
@@ -2321,6 +2332,200 @@ function needId(id, what) {
2321
2332
  return id;
2322
2333
  }
2323
2334
 
2335
+ // ../src/cli-claude.ts
2336
+ var USAGE5 = "claude takes connect, show, update or disconnect. agental help shows each.";
2337
+ var KEY_VARIABLE = "ANTHROPIC_ENVIRONMENT_KEY";
2338
+ var SECRET_VARIABLE = "ANTHROPIC_WEBHOOK_SIGNING_KEY";
2339
+ async function ask7(client, method, pathname, body) {
2340
+ const response = await client.request(pathname, { method, ...body === void 0 ? {} : { body: JSON.stringify(body) } });
2341
+ let answered = null;
2342
+ if (response.status !== 204) {
2343
+ try {
2344
+ answered = await response.json();
2345
+ } catch {
2346
+ answered = null;
2347
+ }
2348
+ }
2349
+ if (!response.ok) {
2350
+ client.fail(response.status, answered);
2351
+ }
2352
+ return answered;
2353
+ }
2354
+ function connectionOf(body) {
2355
+ const connection = body?.connection ?? body;
2356
+ if (!connection || typeof connection !== "object" || typeof connection.id !== "string") {
2357
+ throw new Error("The answer was not a Claude connection.");
2358
+ }
2359
+ return connection;
2360
+ }
2361
+ function describe4(connection) {
2362
+ return [
2363
+ `id: ${connection.id}`,
2364
+ `environment: ${connection.environmentId}`,
2365
+ `template: ${connection.templateId ?? "the account's default"}`,
2366
+ `keeps a sleeping session's sandbox for ${connection.keepDays} day${connection.keepDays === 1 ? "" : "s"}`,
2367
+ `webhook: ${connection.webhookUrl}`,
2368
+ ` ${connection.hasWebhookSecret ? "its signing secret is kept" : "no signing secret: sessions are found by a pass every minute, so a first turn waits up to a minute"}`,
2369
+ ""
2370
+ ].join("\n");
2371
+ }
2372
+ function keepDaysOf(options) {
2373
+ const given = options["keep-days"];
2374
+ if (given === void 0) {
2375
+ return void 0;
2376
+ }
2377
+ const days = Number(given);
2378
+ if (!Number.isInteger(days) || days < 1) {
2379
+ throw new Error("--keep-days takes a whole number of days, as --keep-days 7");
2380
+ }
2381
+ return days;
2382
+ }
2383
+ async function templateOf(client, options) {
2384
+ if (options.template === void 0) {
2385
+ return void 0;
2386
+ }
2387
+ return options.template === "default" ? null : await client.templateId(options.template);
2388
+ }
2389
+ async function secretFrom(variable, what, required) {
2390
+ const fromEnvironment = process.env[variable]?.trim();
2391
+ if (fromEnvironment) {
2392
+ return fromEnvironment;
2393
+ }
2394
+ if (!process.stdin.isTTY) {
2395
+ if (!required) {
2396
+ return void 0;
2397
+ }
2398
+ const chunks = [];
2399
+ for await (const chunk of process.stdin) {
2400
+ chunks.push(Buffer.from(chunk));
2401
+ }
2402
+ const piped = Buffer.concat(chunks).toString("utf8").trim();
2403
+ if (!piped) {
2404
+ throw new Error(`Give the ${what} in ${variable}, or pipe it in. It is never taken on the command line.`);
2405
+ }
2406
+ return piped;
2407
+ }
2408
+ const typed = await hidden(`${what} (not shown${required ? "" : "; Enter for none"}): `);
2409
+ if (!typed && required) {
2410
+ throw new Error(`The ${what} is needed.`);
2411
+ }
2412
+ return typed || void 0;
2413
+ }
2414
+ async function hidden(question) {
2415
+ const { createInterface: createInterface2 } = await import("node:readline");
2416
+ return await new Promise((resolve) => {
2417
+ const lines = createInterface2({ input: process.stdin, output: process.stderr, terminal: true });
2418
+ const muted = lines;
2419
+ process.stderr.write(question);
2420
+ muted._writeToOutput = () => void 0;
2421
+ lines.question("", (answer) => {
2422
+ lines.close();
2423
+ process.stderr.write("\n");
2424
+ resolve(answer.trim());
2425
+ });
2426
+ });
2427
+ }
2428
+ async function listClaude(client, asJson) {
2429
+ const body = await ask7(client, "GET", "/v1/claude/connections");
2430
+ if (asJson) {
2431
+ process.stdout.write(`${JSON.stringify(body, null, 2)}
2432
+ `);
2433
+ return;
2434
+ }
2435
+ const connections = (Array.isArray(body?.data) ? body.data : []).map(connectionOf);
2436
+ if (connections.length === 0) {
2437
+ process.stdout.write("No Claude environments are connected. agental claude connect <environment-id> connects one.\n");
2438
+ return;
2439
+ }
2440
+ const pad3 = (value, width) => value.padEnd(width, " ");
2441
+ process.stdout.write(`${[pad3("ID", 22), pad3("ENVIRONMENT", 30), pad3("TEMPLATE", 22), pad3("KEEPS", 8), "WEBHOOK"].join(" ")}
2442
+ `);
2443
+ for (const one of connections) {
2444
+ process.stdout.write(`${[pad3(one.id, 22), pad3(one.environmentId, 30), pad3(one.templateId ?? "default", 22), pad3(`${one.keepDays}d`, 8), one.hasWebhookSecret ? "signed" : "none"].join(" ")}
2445
+ `);
2446
+ }
2447
+ }
2448
+ async function claude(client, positionals, options) {
2449
+ const [what, target, ...rest] = positionals;
2450
+ if (rest.length > 0) {
2451
+ throw new Error(USAGE5);
2452
+ }
2453
+ switch (what) {
2454
+ case "connect": {
2455
+ if (target === void 0) {
2456
+ throw new Error("claude connect needs the environment's id from the Claude Console, as agental claude connect env_01...");
2457
+ }
2458
+ const templateId = await templateOf(client, options);
2459
+ const keepDays = keepDaysOf(options);
2460
+ const environmentKey = await secretFrom(KEY_VARIABLE, "environment key", true);
2461
+ const webhookSecret = await secretFrom(SECRET_VARIABLE, "webhook signing secret", false);
2462
+ const made = connectionOf(
2463
+ await ask7(client, "POST", "/v1/claude/connections", {
2464
+ environmentId: target,
2465
+ environmentKey,
2466
+ ...webhookSecret !== void 0 ? { webhookSecret } : {},
2467
+ ...templateId !== void 0 ? { templateId } : {},
2468
+ ...keepDays !== void 0 ? { keepDays } : {}
2469
+ })
2470
+ );
2471
+ if (options.json) {
2472
+ process.stdout.write(`${JSON.stringify(made, null, 2)}
2473
+ `);
2474
+ return;
2475
+ }
2476
+ process.stdout.write(describe4(made));
2477
+ process.stderr.write(
2478
+ made.hasWebhookSecret ? `In the Claude Console, set ${made.webhookUrl} as a webhook for session.status_run_started.
2479
+ ` : `For a turn to start at once, add ${made.webhookUrl} as a webhook for session.status_run_started in the Claude Console, then: ${SECRET_VARIABLE}=whsec_... agental claude update ${made.id} --webhook-secret
2480
+ `
2481
+ );
2482
+ return;
2483
+ }
2484
+ case "show": {
2485
+ const found = connectionOf(await ask7(client, "GET", `/v1/claude/connections/${encodeURIComponent(needId2(target, "show"))}`));
2486
+ process.stdout.write(options.json ? `${JSON.stringify(found, null, 2)}
2487
+ ` : describe4(found));
2488
+ return;
2489
+ }
2490
+ case "update": {
2491
+ const id = needId2(target, "update");
2492
+ if (options["webhook-secret"] && options["no-webhook-secret"]) {
2493
+ throw new Error("--webhook-secret and --no-webhook-secret say two things: give one.");
2494
+ }
2495
+ const templateId = await templateOf(client, options);
2496
+ const keepDays = keepDaysOf(options);
2497
+ const environmentKey = options["new-key"] ? await secretFrom(KEY_VARIABLE, "new environment key", true) : void 0;
2498
+ const webhookSecret = options["webhook-secret"] ? await secretFrom(SECRET_VARIABLE, "new webhook signing secret", true) : options["no-webhook-secret"] ? null : void 0;
2499
+ const patch = {
2500
+ ...environmentKey !== void 0 ? { environmentKey } : {},
2501
+ ...webhookSecret !== void 0 ? { webhookSecret } : {},
2502
+ ...templateId !== void 0 ? { templateId } : {},
2503
+ ...keepDays !== void 0 ? { keepDays } : {}
2504
+ };
2505
+ if (Object.keys(patch).length === 0) {
2506
+ throw new Error("claude update changes --template, --keep-days, --new-key, --webhook-secret or --no-webhook-secret, and was given none of them.");
2507
+ }
2508
+ const updated = connectionOf(await ask7(client, "PATCH", `/v1/claude/connections/${encodeURIComponent(id)}`, patch));
2509
+ process.stdout.write(options.json ? `${JSON.stringify(updated, null, 2)}
2510
+ ` : describe4(updated));
2511
+ return;
2512
+ }
2513
+ case "disconnect": {
2514
+ await ask7(client, "DELETE", `/v1/claude/connections/${encodeURIComponent(needId2(target, "disconnect"))}`);
2515
+ 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");
2516
+ return;
2517
+ }
2518
+ default:
2519
+ throw new Error(USAGE5);
2520
+ }
2521
+ }
2522
+ function needId2(id, what) {
2523
+ if (id === void 0) {
2524
+ throw new Error(`claude ${what} needs the connection's id, as agental claude lists them.`);
2525
+ }
2526
+ return id;
2527
+ }
2528
+
2324
2529
  // ../src/cli-shell.ts
2325
2530
  import { createHash as createHash2, randomBytes as randomBytes4 } from "node:crypto";
2326
2531
  var TERMINAL_PROTOCOL = "agental.terminal.v1";
@@ -2760,6 +2965,8 @@ async function main() {
2760
2965
  raw: { type: "boolean", default: false },
2761
2966
  subject: { type: "string" },
2762
2967
  from: { type: "string" },
2968
+ // agental headroom: where its range ends (--from is where it begins).
2969
+ to: { type: "string" },
2763
2970
  "from-name": { type: "string" },
2764
2971
  "reply-to": { type: "string" },
2765
2972
  box: { type: "string" },
@@ -2820,6 +3027,11 @@ async function main() {
2820
3027
  all: { type: "boolean", default: false },
2821
3028
  description: { type: "string" },
2822
3029
  url: { type: "string" },
3030
+ // agental claude: a connection's days, and which of its secrets to read anew.
3031
+ "keep-days": { type: "string" },
3032
+ "new-key": { type: "boolean", default: false },
3033
+ "webhook-secret": { type: "boolean", default: false },
3034
+ "no-webhook-secret": { type: "boolean", default: false },
2823
3035
  preset: { type: "string" },
2824
3036
  actions: { type: "string" },
2825
3037
  sandbox: { type: "string", multiple: true },
@@ -2983,6 +3195,15 @@ async function main() {
2983
3195
  case "webhook":
2984
3196
  await webhook({ request, fail }, positionals.slice(1), values);
2985
3197
  return;
3198
+ case "claude": {
3199
+ const client = { request, fail, templateId: async (word) => (await templateNamed(word)).id };
3200
+ if (positionals.length === 1) {
3201
+ await listClaude(client, values.json);
3202
+ } else {
3203
+ await claude(client, positionals.slice(1), { ...values, template: once(values.template, "--template") });
3204
+ }
3205
+ return;
3206
+ }
2986
3207
  case "keys":
2987
3208
  await listKeys({ request, fail }, values.json);
2988
3209
  return;
@@ -3001,9 +3222,8 @@ async function main() {
3001
3222
  case "billing":
3002
3223
  await billing(positionals.slice(1), values.json);
3003
3224
  return;
3004
- case "burst":
3005
- case "tier":
3006
- await burst(positionals.slice(1), values.json);
3225
+ case "headroom":
3226
+ await headroom(positionals.slice(1), { json: values.json, from: values.from, to: values.to, step: values.step });
3007
3227
  return;
3008
3228
  case "account":
3009
3229
  await account2(positionals.slice(1), values.out);
@@ -3106,7 +3326,7 @@ function maxBurstFeeHeaders(given) {
3106
3326
  function sayBurstFee(response) {
3107
3327
  const micros = Number(response.headers.get("Agental-Burst-Fee") ?? "0");
3108
3328
  if (micros > 0) {
3109
- process.stderr.write(`This start cost a burst fee of ${money(micros)}, as the account started sandboxes faster than its plan's free burst. agental burst says where it stands.
3329
+ process.stderr.write(`This start cost a burst fee of ${money(micros)}, as the account started sandboxes faster than its plan's free burst. agental headroom says where it stands.
3110
3330
  `);
3111
3331
  }
3112
3332
  }
@@ -4300,10 +4520,10 @@ async function secrets(positionals, values) {
4300
4520
  case void 0: {
4301
4521
  const listed = await call2(`${base}/variables`, { method: "GET" });
4302
4522
  const names = listed.names;
4303
- const hidden = listed.hidden ?? [];
4523
+ const hidden2 = listed.hidden ?? [];
4304
4524
  const paths = (await call2(`${base}/files`, { method: "GET" })).paths;
4305
4525
  if (values.json) {
4306
- process.stdout.write(`${JSON.stringify({ variables: names, hidden, files: paths }, null, 2)}
4526
+ process.stdout.write(`${JSON.stringify({ variables: names, hidden: hidden2, files: paths }, null, 2)}
4307
4527
  `);
4308
4528
  return;
4309
4529
  }
@@ -4312,7 +4532,7 @@ async function secrets(positionals, values) {
4312
4532
  return;
4313
4533
  }
4314
4534
  process.stdout.write(
4315
- [...names.map((name) => `variable ${name}${hidden.includes(name) ? " kept out of the sandbox" : ""}
4535
+ [...names.map((name) => `variable ${name}${hidden2.includes(name) ? " kept out of the sandbox" : ""}
4316
4536
  `), ...paths.map((path4) => `file ${path4}
4317
4537
  `)].join("")
4318
4538
  );
@@ -4851,7 +5071,7 @@ function describePrices(body) {
4851
5071
  }
4852
5072
  if (body.burstFee) {
4853
5073
  out.push(
4854
- `Starting faster than the free burst costs a fee: $0.027 for each small sandbox past it, $0.108 for a large, never more than one more hour of what you start. What was started falls by half every ${body.burstFee.halfLifeMinutes} minutes. At most ${wholeMoney(body.burstFee.defaultBudgetMicros)} a month unless you set another budget: agental burst budget <dollars>.`
5074
+ `Starting faster than the free burst costs a fee: $0.027 for each small sandbox past it, $0.108 for a large, never more than one more hour of what you start. What was started falls by half every ${body.burstFee.halfLifeMinutes} minutes. At most ${wholeMoney(body.burstFee.defaultBudgetMicros)} a month unless you set another budget: agental headroom budget <dollars>.`
4855
5075
  );
4856
5076
  }
4857
5077
  if (body.topUps?.length) {
@@ -4888,45 +5108,101 @@ function describePrices(body) {
4888
5108
  `;
4889
5109
  }
4890
5110
  var BURST_DOCS = "https://agental.io/docs/usage#bursts";
4891
- async function burst(positionals, asJson) {
4892
- let body;
5111
+ async function headroom(positionals, options) {
4893
5112
  if (positionals[0] === "budget") {
4894
5113
  const given = positionals[1];
4895
5114
  if (given === void 0 || positionals.length > 2) {
4896
- throw new Error("burst budget takes the most to spend on burst fees in a month, in US dollars, as agental burst budget 20, or default.");
5115
+ throw new Error("headroom budget takes the most to spend on burst fees in a month, in US dollars, as agental headroom budget 20, or default.");
4897
5116
  }
4898
5117
  const dollars = Number(given.replace(/^\$/, ""));
4899
5118
  if (given !== "default" && (!Number.isFinite(dollars) || dollars < 0)) {
4900
- throw new Error(`burst budget takes US dollars, as 20 or 0, or default. It was given ${given}.`);
5119
+ throw new Error(`headroom budget takes US dollars, as 20 or 0, or default. It was given ${given}.`);
4901
5120
  }
4902
- body = await asked("/v1/burst/budget", { method: "PUT", body: JSON.stringify({ budgetMicros: given === "default" ? null : Math.round(dollars * 1e6) }) });
4903
- } else if (positionals.length > 0) {
4904
- throw new Error(`burst takes nothing, or budget <dollars>: it is the account's. It was given ${positionals.join(" ")}.`);
4905
- } else {
4906
- body = await asked("/v1/burst", { method: "GET" });
5121
+ const body2 = await asked("/v1/headroom/budget", { method: "PUT", body: JSON.stringify({ budgetMicros: given === "default" ? null : Math.round(dollars * 1e6) }) });
5122
+ if (options.json) {
5123
+ process.stdout.write(`${JSON.stringify(body2, null, 2)}
5124
+ `);
5125
+ return;
5126
+ }
5127
+ const answer = body2 && typeof body2 === "object" ? body2 : {};
5128
+ const spent = typeof answer["spentMicros"] === "number" ? answer["spentMicros"] : 0;
5129
+ const budget = typeof answer["budgetMicros"] === "number" ? answer["budgetMicros"] : 0;
5130
+ process.stdout.write(`Budget for burst fees: ${money(budget)} a month${answer["budgetSet"] === true ? "" : " (the default)"}; ${money(spent)} spent this month.
5131
+ `);
5132
+ return;
4907
5133
  }
4908
- if (asJson) {
5134
+ if (positionals.length > 0) {
5135
+ throw new Error(`headroom takes nothing, or budget <dollars>: it is the account's. It was given ${positionals.join(" ")}.`);
5136
+ }
5137
+ if (options.step !== void 0 && !["10m", "hour", "day"].includes(options.step)) {
5138
+ throw new Error(`--step is 10m, hour or day. It was given ${options.step}.`);
5139
+ }
5140
+ const query = new URLSearchParams();
5141
+ for (const [name, value] of [["from", options.from], ["to", options.to], ["step", options.step]]) {
5142
+ if (value !== void 0) {
5143
+ query.set(name, name !== "step" && /^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}T00:00:00Z` : value);
5144
+ }
5145
+ }
5146
+ const asks = query.toString();
5147
+ const body = await asked(`/v1/headroom${asks === "" ? "" : `?${asks}`}`, { method: "GET" });
5148
+ if (options.json) {
4909
5149
  process.stdout.write(`${JSON.stringify(body, null, 2)}
4910
5150
  `);
4911
5151
  return;
4912
5152
  }
5153
+ process.stdout.write(describeHeadroom(body, options.from === void 0 && options.to === void 0, options.to === void 0));
5154
+ }
5155
+ function describeHeadroom(body, today, endsNow) {
4913
5156
  const answer = body && typeof body === "object" ? body : {};
4914
- const number = (name) => typeof answer[name] === "number" ? answer[name] : 0;
5157
+ const now = answer["now"] && typeof answer["now"] === "object" ? answer["now"] : {};
5158
+ const number = (from, name) => typeof from[name] === "number" ? from[name] : 0;
4915
5159
  const smalls = (mb) => {
4916
5160
  const value = mb / 4096;
4917
5161
  return (Number.isInteger(value) ? value : Math.round(value * 10) / 10).toLocaleString("en-US");
4918
5162
  };
4919
- const next = Array.isArray(answer["nextStart"]) ? answer["nextStart"] : [];
4920
- process.stdout.write(
4921
- [
4922
- `running: ${smalls(number("runningMb"))} of ${number("runningUnits").toLocaleString("en-US")} small sandboxes (a medium is 2, a large 4, a tiny half)`,
4923
- `free burst: ${number("freeBurstUnits").toLocaleString("en-US")} small at once; the meter reads ${smalls(number("meterMb"))} and falls by half every ${number("halfLifeMinutes")} minutes`,
4924
- `fees: ${money(number("spentMicros"))} this month of a ${money(number("budgetMicros"))} budget`,
4925
- `a start now: ${next.map((quote) => `${quote.size} ${quote.feeMicros > 0 ? money(quote.feeMicros) : "free"}`).join(", ")}`,
4926
- `${answer["enforced"] === true ? "" : "Measured, not charged or refused, as your account is held to no plan. "}How bursts work: ${BURST_DOCS}`,
4927
- ""
4928
- ].join("\n")
5163
+ const clock = (iso) => {
5164
+ const at4 = new Date(iso).toISOString();
5165
+ 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`;
5166
+ };
5167
+ const range = today ? "today (UTC)" : `from ${String(answer["from"] ?? "")} to ${String(answer["to"] ?? "")}`;
5168
+ const lines = [
5169
+ `running: ${smalls(number(now, "runningMb"))} of ${number(now, "runningUnits").toLocaleString("en-US")} small sandboxes (a medium is 2, a large 4, a tiny half); at the running count ${duration(number(answer, "atRunningCountMs"))} ${range}`
5170
+ ];
5171
+ const bursts = Array.isArray(answer["bursts"]) ? answer["bursts"] : [];
5172
+ const open = endsNow ? bursts.find((one) => one["endedAt"] === null && typeof one["startedAt"] === "string") : void 0;
5173
+ const meterMb = number(now, "meterMb");
5174
+ const freeMb = number(now, "freeMb");
5175
+ const halfLife = number(now, "halfLifeMinutes");
5176
+ const over = number(now, "overMb") > 0;
5177
+ const freeAgain = !over || freeMb <= 0 || halfLife <= 0 ? null : Math.ceil(halfLife * Math.log2(meterMb / freeMb));
5178
+ const freeAgainWords = freeAgain === null ? "" : `; free again in ${freeAgain.toLocaleString("en-US")} min`;
5179
+ if (open && over) {
5180
+ lines.push(`burst: in a burst since ${clock(String(open["startedAt"]))}: every start pays a fee${freeAgainWords}`);
5181
+ } else if (over) {
5182
+ lines.push(`burst: over the free burst: every start pays a fee${freeAgainWords}`);
5183
+ } else {
5184
+ lines.push(`burst: free burst ${smalls(number(now, "freeNowMb"))} of ${number(now, "freeBurstUnits").toLocaleString("en-US")} small free now; the meter falls by half every ${halfLife} minutes`);
5185
+ }
5186
+ lines.push(`fees: ${money(number(now, "spentMicros"))} this month of a ${money(number(now, "budgetMicros"))} budget`);
5187
+ const refused = answer["refused"] && typeof answer["refused"] === "object" ? answer["refused"] : {};
5188
+ const total = number(refused, "total");
5189
+ const byReason = Array.isArray(refused["byReason"]) ? refused["byReason"] : [];
5190
+ lines.push(
5191
+ `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(", ")}` : ""}`
4929
5192
  );
5193
+ lines.push(`${now["enforced"] === true ? "" : "Measured, not charged or refused, as your account is held to no plan. "}How bursts work: ${BURST_DOCS}`, "");
5194
+ return lines.join("\n");
5195
+ }
5196
+ var REASON_WORDS = {
5197
+ running_count: "at the running count",
5198
+ budget: "past the budget",
5199
+ fee_cap: "past --max-burst-fee",
5200
+ room: "no room on agental's servers",
5201
+ other: "other"
5202
+ };
5203
+ function duration(ms) {
5204
+ const minutes = Math.round(ms / 6e4);
5205
+ return minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h${minutes % 60 === 0 ? "" : ` ${minutes % 60} min`}`;
4930
5206
  }
4931
5207
  async function asked(path4, init) {
4932
5208
  const response = await request(path4, init);
@@ -5064,9 +5340,21 @@ function teamOptions(values) {
5064
5340
  function fail(status, body) {
5065
5341
  const message = isApiError(body) ? `${body.error.code}: ${body.error.message}` : bareStatus(status);
5066
5342
  process.stderr.write(`${message}
5067
- `);
5343
+ ${status === 429 || status === 409 ? refusedWords(body) : ""}`);
5068
5344
  process.exit(1);
5069
5345
  }
5346
+ function refusedWords(body) {
5347
+ if (!isApiError(body)) {
5348
+ return "";
5349
+ }
5350
+ const { refusedLastHour, headroomUrl } = body.error;
5351
+ if (typeof refusedLastHour !== "number" || typeof headroomUrl !== "string") {
5352
+ return "";
5353
+ }
5354
+ return `Refused this way in the last hour: ${refusedLastHour.toLocaleString("en-US")}.
5355
+ ${headroomUrl}
5356
+ `;
5357
+ }
5070
5358
  async function readBody(response) {
5071
5359
  try {
5072
5360
  return await response.json();
@@ -5165,6 +5453,11 @@ Usage
5165
5453
  agental webhook update <webhook-id> [--url <url>] [--events <kind>[,<kind>...] | --all] [--description <text>] [--json]
5166
5454
  agental webhook rotate <webhook-id> [--json]
5167
5455
  agental webhook delete <webhook-id>
5456
+ agental claude [--json]
5457
+ agental claude connect <environment-id> [--template <template>|default] [--keep-days <n>] [--json]
5458
+ agental claude show <connection-id> [--json]
5459
+ agental claude update <connection-id> [--template <template>|default] [--keep-days <n>] [--new-key] [--webhook-secret | --no-webhook-secret] [--json]
5460
+ agental claude disconnect <connection-id>
5168
5461
  agental org [list] [--json]
5169
5462
  agental org use <organization>
5170
5463
  agental org create <name> [--json]
@@ -5179,7 +5472,8 @@ Usage
5179
5472
  agental key allow-from <key> (<address-or-range>... | --anywhere) [--json]
5180
5473
  agental key delete <key>
5181
5474
  agental billing [prices | card | top-up <dollars> | auto-reload <dollars | off>] [--json]
5182
- agental burst [budget <dollars> | budget default] [--json]
5475
+ agental headroom [--from <day or date-time>] [--to <day or date-time>] [--step 10m|hour|day] [--json]
5476
+ agental headroom budget <dollars> | budget default [--json]
5183
5477
  agental egress [budget <dollars> | budget default] [--json]
5184
5478
  agental egress use-case "<what your sandboxes will use it for>" [--json]
5185
5479
  agental account export [--out <file>]
@@ -5312,6 +5606,10 @@ webhooks lists the addresses your account's events are posted to, with what each
5312
5606
  how its last post went. webhook add makes one: it posts to <url>, which has to be on the public
5313
5607
  internet, the kinds --events names, such as sandbox.stopped,sandbox.error, or every kind with
5314
5608
  --all, those added later included. The kinds are ${WEBHOOK_KINDS.join(", ")}.
5609
+ A group by its name and .*, as headroom.* or sandbox.*, is every kind of the group, and any
5610
+ added to it later; quote it, as --events 'headroom.*,sandbox.error', so the shell leaves it be.
5611
+ headroom.* are the organization's, about no sandbox: a burst begun and ended, starts refused,
5612
+ the running count met, and the burst budget at 80% and reached.
5315
5613
  It prints the webhook's signing secret, the one time it is given: each post carries
5316
5614
  X-Agental-Signature, the HMAC-SHA256 of its body under that secret. show says what one is sent,
5317
5615
  how its last post went, and each event it did not take at the first try, with the answer to
@@ -5320,6 +5618,15 @@ every try. A post that is not answered with a 2xx is made again after 1, 5 and 1
5320
5618
  its kinds or its description, and keeps what it is not given. rotate gives it a new secret,
5321
5619
  and the old one stops working at once. delete removes it, the events still owed to it, and its
5322
5620
  tries.
5621
+ claude lists the Claude Managed Agents environments connected to this account: each session of a
5622
+ connected self-hosted environment runs its tool calls in a sandbox of your own, made on the
5623
+ connection's template, stopped between turns and deleted once it has slept --keep-days (7). claude
5624
+ connect takes the environment's id from the Claude Console; its key is read from
5625
+ ANTHROPIC_ENVIRONMENT_KEY, from what is piped in, or asked for without being shown, never from the
5626
+ command line, and the webhook's signing secret likewise from ANTHROPIC_WEBHOOK_SIGNING_KEY. It
5627
+ prints the address to give the Claude Console as the webhook for session.status_run_started. update
5628
+ --new-key and --webhook-secret read a new one the same way; --no-webhook-secret forgets it.
5629
+ disconnect forgets the key and claims no more of its work.
5323
5630
  org lists the organizations you are in, your own and your teams, and marks the one this command
5324
5631
  acts in. A key acts in the organization it was made in, for good, so org use signs in again in
5325
5632
  the browser for a key made in the one given, by its id or name, and deletes the key the command
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agental",
3
- "version": "0.6.2",
3
+ "version": "0.9.0",
4
4
  "description": "The agental command: Linux sandboxes for your agents, from the terminal. npx agental@latest signs you in and installs the agent skills.",
5
5
  "license": "MIT",
6
6
  "author": "VERTIXER LTD",