agental 0.6.1 → 0.7.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 +105 -31
  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.1" : "dev";
49
+ var CLI_VERSION = true ? "0.7.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}`;
@@ -2322,8 +2322,10 @@ function needId(id, what) {
2322
2322
  }
2323
2323
 
2324
2324
  // ../src/cli-shell.ts
2325
+ import { createHash as createHash2, randomBytes as randomBytes4 } from "node:crypto";
2325
2326
  var TERMINAL_PROTOCOL = "agental.terminal.v1";
2326
2327
  var TICKET_PROTOCOL_PREFIX = "ticket.";
2328
+ var VERIFIER_PROTOCOL_PREFIX = "verifier.";
2327
2329
  var MAX_INPUT_BYTES = 64 * 1024;
2328
2330
  var LOST = 255;
2329
2331
  function clamp(value, fallback) {
@@ -2367,13 +2369,15 @@ async function shell(client, id, streams = process) {
2367
2369
  }
2368
2370
  const { stdin, stdout, stderr } = streams;
2369
2371
  const size = sizeOf(stdout);
2370
- const response = await client.request(`/v1/sandboxes/${encodeURIComponent(id)}/terminal`, { method: "POST", body: JSON.stringify(size) });
2372
+ const verifier = randomBytes4(32).toString("base64url");
2373
+ const challenge = createHash2("sha256").update(verifier).digest("base64url");
2374
+ const response = await client.request(`/v1/sandboxes/${encodeURIComponent(id)}/terminal`, { method: "POST", body: JSON.stringify({ ...size, challenge }) });
2371
2375
  const body = await response.json().catch(() => null);
2372
2376
  if (!response.ok || typeof body?.ticket !== "string") {
2373
2377
  const error2 = body?.error;
2374
2378
  throw new Error(error2 && typeof error2.code === "string" ? `${error2.code}: ${String(error2.message ?? "")}` : `The API answered the terminal with HTTP ${response.status}.`);
2375
2379
  }
2376
- const socket = new WebSocket(webSocketUrl(client.base, body.path), [TERMINAL_PROTOCOL, `${TICKET_PROTOCOL_PREFIX}${body.ticket}`]);
2380
+ const socket = new WebSocket(webSocketUrl(client.base, body.path), [TERMINAL_PROTOCOL, `${TICKET_PROTOCOL_PREFIX}${body.ticket}`, `${VERIFIER_PROTOCOL_PREFIX}${verifier}`]);
2377
2381
  socket.binaryType = "arraybuffer";
2378
2382
  let exit = null;
2379
2383
  let error = null;
@@ -2756,6 +2760,8 @@ async function main() {
2756
2760
  raw: { type: "boolean", default: false },
2757
2761
  subject: { type: "string" },
2758
2762
  from: { type: "string" },
2763
+ // agental headroom: where its range ends (--from is where it begins).
2764
+ to: { type: "string" },
2759
2765
  "from-name": { type: "string" },
2760
2766
  "reply-to": { type: "string" },
2761
2767
  box: { type: "string" },
@@ -2997,9 +3003,8 @@ async function main() {
2997
3003
  case "billing":
2998
3004
  await billing(positionals.slice(1), values.json);
2999
3005
  return;
3000
- case "burst":
3001
- case "tier":
3002
- await burst(positionals.slice(1), values.json);
3006
+ case "headroom":
3007
+ await headroom(positionals.slice(1), { json: values.json, from: values.from, to: values.to, step: values.step });
3003
3008
  return;
3004
3009
  case "account":
3005
3010
  await account2(positionals.slice(1), values.out);
@@ -3102,7 +3107,7 @@ function maxBurstFeeHeaders(given) {
3102
3107
  function sayBurstFee(response) {
3103
3108
  const micros = Number(response.headers.get("Agental-Burst-Fee") ?? "0");
3104
3109
  if (micros > 0) {
3105
- 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.
3110
+ 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.
3106
3111
  `);
3107
3112
  }
3108
3113
  }
@@ -4847,7 +4852,7 @@ function describePrices(body) {
4847
4852
  }
4848
4853
  if (body.burstFee) {
4849
4854
  out.push(
4850
- `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>.`
4855
+ `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>.`
4851
4856
  );
4852
4857
  }
4853
4858
  if (body.topUps?.length) {
@@ -4884,45 +4889,101 @@ function describePrices(body) {
4884
4889
  `;
4885
4890
  }
4886
4891
  var BURST_DOCS = "https://agental.io/docs/usage#bursts";
4887
- async function burst(positionals, asJson) {
4888
- let body;
4892
+ async function headroom(positionals, options) {
4889
4893
  if (positionals[0] === "budget") {
4890
4894
  const given = positionals[1];
4891
4895
  if (given === void 0 || positionals.length > 2) {
4892
- 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.");
4896
+ 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.");
4893
4897
  }
4894
4898
  const dollars = Number(given.replace(/^\$/, ""));
4895
4899
  if (given !== "default" && (!Number.isFinite(dollars) || dollars < 0)) {
4896
- throw new Error(`burst budget takes US dollars, as 20 or 0, or default. It was given ${given}.`);
4900
+ throw new Error(`headroom budget takes US dollars, as 20 or 0, or default. It was given ${given}.`);
4897
4901
  }
4898
- body = await asked("/v1/burst/budget", { method: "PUT", body: JSON.stringify({ budgetMicros: given === "default" ? null : Math.round(dollars * 1e6) }) });
4899
- } else if (positionals.length > 0) {
4900
- throw new Error(`burst takes nothing, or budget <dollars>: it is the account's. It was given ${positionals.join(" ")}.`);
4901
- } else {
4902
- body = await asked("/v1/burst", { method: "GET" });
4902
+ const body2 = await asked("/v1/headroom/budget", { method: "PUT", body: JSON.stringify({ budgetMicros: given === "default" ? null : Math.round(dollars * 1e6) }) });
4903
+ if (options.json) {
4904
+ process.stdout.write(`${JSON.stringify(body2, null, 2)}
4905
+ `);
4906
+ return;
4907
+ }
4908
+ const answer = body2 && typeof body2 === "object" ? body2 : {};
4909
+ const spent = typeof answer["spentMicros"] === "number" ? answer["spentMicros"] : 0;
4910
+ const budget = typeof answer["budgetMicros"] === "number" ? answer["budgetMicros"] : 0;
4911
+ process.stdout.write(`Budget for burst fees: ${money(budget)} a month${answer["budgetSet"] === true ? "" : " (the default)"}; ${money(spent)} spent this month.
4912
+ `);
4913
+ return;
4903
4914
  }
4904
- if (asJson) {
4915
+ if (positionals.length > 0) {
4916
+ throw new Error(`headroom takes nothing, or budget <dollars>: it is the account's. It was given ${positionals.join(" ")}.`);
4917
+ }
4918
+ if (options.step !== void 0 && !["10m", "hour", "day"].includes(options.step)) {
4919
+ throw new Error(`--step is 10m, hour or day. It was given ${options.step}.`);
4920
+ }
4921
+ const query = new URLSearchParams();
4922
+ for (const [name, value] of [["from", options.from], ["to", options.to], ["step", options.step]]) {
4923
+ if (value !== void 0) {
4924
+ query.set(name, name !== "step" && /^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}T00:00:00Z` : value);
4925
+ }
4926
+ }
4927
+ const asks = query.toString();
4928
+ const body = await asked(`/v1/headroom${asks === "" ? "" : `?${asks}`}`, { method: "GET" });
4929
+ if (options.json) {
4905
4930
  process.stdout.write(`${JSON.stringify(body, null, 2)}
4906
4931
  `);
4907
4932
  return;
4908
4933
  }
4934
+ process.stdout.write(describeHeadroom(body, options.from === void 0 && options.to === void 0, options.to === void 0));
4935
+ }
4936
+ function describeHeadroom(body, today, endsNow) {
4909
4937
  const answer = body && typeof body === "object" ? body : {};
4910
- const number = (name) => typeof answer[name] === "number" ? answer[name] : 0;
4938
+ const now = answer["now"] && typeof answer["now"] === "object" ? answer["now"] : {};
4939
+ const number = (from, name) => typeof from[name] === "number" ? from[name] : 0;
4911
4940
  const smalls = (mb) => {
4912
4941
  const value = mb / 4096;
4913
4942
  return (Number.isInteger(value) ? value : Math.round(value * 10) / 10).toLocaleString("en-US");
4914
4943
  };
4915
- const next = Array.isArray(answer["nextStart"]) ? answer["nextStart"] : [];
4916
- process.stdout.write(
4917
- [
4918
- `running: ${smalls(number("runningMb"))} of ${number("runningUnits").toLocaleString("en-US")} small sandboxes (a medium is 2, a large 4, a tiny half)`,
4919
- `free burst: ${number("freeBurstUnits").toLocaleString("en-US")} small at once; the meter reads ${smalls(number("meterMb"))} and falls by half every ${number("halfLifeMinutes")} minutes`,
4920
- `fees: ${money(number("spentMicros"))} this month of a ${money(number("budgetMicros"))} budget`,
4921
- `a start now: ${next.map((quote) => `${quote.size} ${quote.feeMicros > 0 ? money(quote.feeMicros) : "free"}`).join(", ")}`,
4922
- `${answer["enforced"] === true ? "" : "Measured, not charged or refused, as your account is held to no plan. "}How bursts work: ${BURST_DOCS}`,
4923
- ""
4924
- ].join("\n")
4944
+ const clock = (iso) => {
4945
+ const at4 = new Date(iso).toISOString();
4946
+ 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`;
4947
+ };
4948
+ const range = today ? "today (UTC)" : `from ${String(answer["from"] ?? "")} to ${String(answer["to"] ?? "")}`;
4949
+ const lines = [
4950
+ `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}`
4951
+ ];
4952
+ const bursts = Array.isArray(answer["bursts"]) ? answer["bursts"] : [];
4953
+ const open = endsNow ? bursts.find((one) => one["endedAt"] === null && typeof one["startedAt"] === "string") : void 0;
4954
+ const meterMb = number(now, "meterMb");
4955
+ const freeMb = number(now, "freeMb");
4956
+ const halfLife = number(now, "halfLifeMinutes");
4957
+ const over = number(now, "overMb") > 0;
4958
+ const freeAgain = !over || freeMb <= 0 || halfLife <= 0 ? null : Math.ceil(halfLife * Math.log2(meterMb / freeMb));
4959
+ const freeAgainWords = freeAgain === null ? "" : `; free again in ${freeAgain.toLocaleString("en-US")} min`;
4960
+ if (open && over) {
4961
+ lines.push(`burst: in a burst since ${clock(String(open["startedAt"]))}: every start pays a fee${freeAgainWords}`);
4962
+ } else if (over) {
4963
+ lines.push(`burst: over the free burst: every start pays a fee${freeAgainWords}`);
4964
+ } else {
4965
+ 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`);
4966
+ }
4967
+ lines.push(`fees: ${money(number(now, "spentMicros"))} this month of a ${money(number(now, "budgetMicros"))} budget`);
4968
+ const refused = answer["refused"] && typeof answer["refused"] === "object" ? answer["refused"] : {};
4969
+ const total = number(refused, "total");
4970
+ const byReason = Array.isArray(refused["byReason"]) ? refused["byReason"] : [];
4971
+ lines.push(
4972
+ `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(", ")}` : ""}`
4925
4973
  );
4974
+ lines.push(`${now["enforced"] === true ? "" : "Measured, not charged or refused, as your account is held to no plan. "}How bursts work: ${BURST_DOCS}`, "");
4975
+ return lines.join("\n");
4976
+ }
4977
+ var REASON_WORDS = {
4978
+ running_count: "at the running count",
4979
+ budget: "past the budget",
4980
+ fee_cap: "past --max-burst-fee",
4981
+ room: "no room on agental's servers",
4982
+ other: "other"
4983
+ };
4984
+ function duration(ms) {
4985
+ const minutes = Math.round(ms / 6e4);
4986
+ return minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h${minutes % 60 === 0 ? "" : ` ${minutes % 60} min`}`;
4926
4987
  }
4927
4988
  async function asked(path4, init) {
4928
4989
  const response = await request(path4, init);
@@ -5060,9 +5121,21 @@ function teamOptions(values) {
5060
5121
  function fail(status, body) {
5061
5122
  const message = isApiError(body) ? `${body.error.code}: ${body.error.message}` : bareStatus(status);
5062
5123
  process.stderr.write(`${message}
5063
- `);
5124
+ ${status === 429 || status === 409 ? refusedWords(body) : ""}`);
5064
5125
  process.exit(1);
5065
5126
  }
5127
+ function refusedWords(body) {
5128
+ if (!isApiError(body)) {
5129
+ return "";
5130
+ }
5131
+ const { refusedLastHour, headroomUrl } = body.error;
5132
+ if (typeof refusedLastHour !== "number" || typeof headroomUrl !== "string") {
5133
+ return "";
5134
+ }
5135
+ return `Refused this way in the last hour: ${refusedLastHour.toLocaleString("en-US")}.
5136
+ ${headroomUrl}
5137
+ `;
5138
+ }
5066
5139
  async function readBody(response) {
5067
5140
  try {
5068
5141
  return await response.json();
@@ -5175,7 +5248,8 @@ Usage
5175
5248
  agental key allow-from <key> (<address-or-range>... | --anywhere) [--json]
5176
5249
  agental key delete <key>
5177
5250
  agental billing [prices | card | top-up <dollars> | auto-reload <dollars | off>] [--json]
5178
- agental burst [budget <dollars> | budget default] [--json]
5251
+ agental headroom [--from <day or date-time>] [--to <day or date-time>] [--step 10m|hour|day] [--json]
5252
+ agental headroom budget <dollars> | budget default [--json]
5179
5253
  agental egress [budget <dollars> | budget default] [--json]
5180
5254
  agental egress use-case "<what your sandboxes will use it for>" [--json]
5181
5255
  agental account export [--out <file>]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agental",
3
- "version": "0.6.1",
3
+ "version": "0.7.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",