agental 0.31.0 → 0.33.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 +621 -338
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -126,17 +126,17 @@ var require_visit = __commonJS({
126
126
  visit.BREAK = BREAK;
127
127
  visit.SKIP = SKIP;
128
128
  visit.REMOVE = REMOVE;
129
- function visit_(key2, node, visitor, path5) {
130
- const ctrl = callVisitor(key2, node, visitor, path5);
129
+ function visit_(key2, node, visitor, path6) {
130
+ const ctrl = callVisitor(key2, node, visitor, path6);
131
131
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
132
- replaceNode(key2, path5, ctrl);
133
- return visit_(key2, ctrl, visitor, path5);
132
+ replaceNode(key2, path6, ctrl);
133
+ return visit_(key2, ctrl, visitor, path6);
134
134
  }
135
135
  if (typeof ctrl !== "symbol") {
136
136
  if (identity.isCollection(node)) {
137
- path5 = Object.freeze(path5.concat(node));
137
+ path6 = Object.freeze(path6.concat(node));
138
138
  for (let i = 0; i < node.items.length; ++i) {
139
- const ci2 = visit_(i, node.items[i], visitor, path5);
139
+ const ci2 = visit_(i, node.items[i], visitor, path6);
140
140
  if (typeof ci2 === "number")
141
141
  i = ci2 - 1;
142
142
  else if (ci2 === BREAK)
@@ -147,13 +147,13 @@ var require_visit = __commonJS({
147
147
  }
148
148
  }
149
149
  } else if (identity.isPair(node)) {
150
- path5 = Object.freeze(path5.concat(node));
151
- const ck = visit_("key", node.key, visitor, path5);
150
+ path6 = Object.freeze(path6.concat(node));
151
+ const ck = visit_("key", node.key, visitor, path6);
152
152
  if (ck === BREAK)
153
153
  return BREAK;
154
154
  else if (ck === REMOVE)
155
155
  node.key = null;
156
- const cv = visit_("value", node.value, visitor, path5);
156
+ const cv = visit_("value", node.value, visitor, path6);
157
157
  if (cv === BREAK)
158
158
  return BREAK;
159
159
  else if (cv === REMOVE)
@@ -174,17 +174,17 @@ var require_visit = __commonJS({
174
174
  visitAsync.BREAK = BREAK;
175
175
  visitAsync.SKIP = SKIP;
176
176
  visitAsync.REMOVE = REMOVE;
177
- async function visitAsync_(key2, node, visitor, path5) {
178
- const ctrl = await callVisitor(key2, node, visitor, path5);
177
+ async function visitAsync_(key2, node, visitor, path6) {
178
+ const ctrl = await callVisitor(key2, node, visitor, path6);
179
179
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
180
- replaceNode(key2, path5, ctrl);
181
- return visitAsync_(key2, ctrl, visitor, path5);
180
+ replaceNode(key2, path6, ctrl);
181
+ return visitAsync_(key2, ctrl, visitor, path6);
182
182
  }
183
183
  if (typeof ctrl !== "symbol") {
184
184
  if (identity.isCollection(node)) {
185
- path5 = Object.freeze(path5.concat(node));
185
+ path6 = Object.freeze(path6.concat(node));
186
186
  for (let i = 0; i < node.items.length; ++i) {
187
- const ci2 = await visitAsync_(i, node.items[i], visitor, path5);
187
+ const ci2 = await visitAsync_(i, node.items[i], visitor, path6);
188
188
  if (typeof ci2 === "number")
189
189
  i = ci2 - 1;
190
190
  else if (ci2 === BREAK)
@@ -195,13 +195,13 @@ var require_visit = __commonJS({
195
195
  }
196
196
  }
197
197
  } else if (identity.isPair(node)) {
198
- path5 = Object.freeze(path5.concat(node));
199
- const ck = await visitAsync_("key", node.key, visitor, path5);
198
+ path6 = Object.freeze(path6.concat(node));
199
+ const ck = await visitAsync_("key", node.key, visitor, path6);
200
200
  if (ck === BREAK)
201
201
  return BREAK;
202
202
  else if (ck === REMOVE)
203
203
  node.key = null;
204
- const cv = await visitAsync_("value", node.value, visitor, path5);
204
+ const cv = await visitAsync_("value", node.value, visitor, path6);
205
205
  if (cv === BREAK)
206
206
  return BREAK;
207
207
  else if (cv === REMOVE)
@@ -228,23 +228,23 @@ var require_visit = __commonJS({
228
228
  }
229
229
  return visitor;
230
230
  }
231
- function callVisitor(key2, node, visitor, path5) {
231
+ function callVisitor(key2, node, visitor, path6) {
232
232
  if (typeof visitor === "function")
233
- return visitor(key2, node, path5);
233
+ return visitor(key2, node, path6);
234
234
  if (identity.isMap(node))
235
- return visitor.Map?.(key2, node, path5);
235
+ return visitor.Map?.(key2, node, path6);
236
236
  if (identity.isSeq(node))
237
- return visitor.Seq?.(key2, node, path5);
237
+ return visitor.Seq?.(key2, node, path6);
238
238
  if (identity.isPair(node))
239
- return visitor.Pair?.(key2, node, path5);
239
+ return visitor.Pair?.(key2, node, path6);
240
240
  if (identity.isScalar(node))
241
- return visitor.Scalar?.(key2, node, path5);
241
+ return visitor.Scalar?.(key2, node, path6);
242
242
  if (identity.isAlias(node))
243
- return visitor.Alias?.(key2, node, path5);
243
+ return visitor.Alias?.(key2, node, path6);
244
244
  return void 0;
245
245
  }
246
- function replaceNode(key2, path5, node) {
247
- const parent = path5[path5.length - 1];
246
+ function replaceNode(key2, path6, node) {
247
+ const parent = path6[path6.length - 1];
248
248
  if (identity.isCollection(parent)) {
249
249
  parent.items[key2] = node;
250
250
  } else if (identity.isPair(parent)) {
@@ -856,10 +856,10 @@ var require_Collection = __commonJS({
856
856
  var createNode = require_createNode();
857
857
  var identity = require_identity();
858
858
  var Node = require_Node();
859
- function collectionFromPath(schema, path5, value) {
859
+ function collectionFromPath(schema, path6, value) {
860
860
  let v = value;
861
- for (let i = path5.length - 1; i >= 0; --i) {
862
- const k = path5[i];
861
+ for (let i = path6.length - 1; i >= 0; --i) {
862
+ const k = path6[i];
863
863
  if (typeof k === "number" && Number.isInteger(k) && k >= 0) {
864
864
  const a = [];
865
865
  a[k] = v;
@@ -878,7 +878,7 @@ var require_Collection = __commonJS({
878
878
  sourceObjects: /* @__PURE__ */ new Map()
879
879
  });
880
880
  }
881
- var isEmptyPath = (path5) => path5 == null || typeof path5 === "object" && !!path5[Symbol.iterator]().next().done;
881
+ var isEmptyPath = (path6) => path6 == null || typeof path6 === "object" && !!path6[Symbol.iterator]().next().done;
882
882
  var Collection = class extends Node.NodeBase {
883
883
  constructor(type, schema) {
884
884
  super(type);
@@ -908,11 +908,11 @@ var require_Collection = __commonJS({
908
908
  * be a Pair instance or a `{ key, value }` object, which may not have a key
909
909
  * that already exists in the map.
910
910
  */
911
- addIn(path5, value) {
912
- if (isEmptyPath(path5))
911
+ addIn(path6, value) {
912
+ if (isEmptyPath(path6))
913
913
  this.add(value);
914
914
  else {
915
- const [key2, ...rest] = path5;
915
+ const [key2, ...rest] = path6;
916
916
  const node = this.get(key2, true);
917
917
  if (identity.isCollection(node))
918
918
  node.addIn(rest, value);
@@ -926,8 +926,8 @@ var require_Collection = __commonJS({
926
926
  * Removes a value from the collection.
927
927
  * @returns `true` if the item was found and removed.
928
928
  */
929
- deleteIn(path5) {
930
- const [key2, ...rest] = path5;
929
+ deleteIn(path6) {
930
+ const [key2, ...rest] = path6;
931
931
  if (rest.length === 0)
932
932
  return this.delete(key2);
933
933
  const node = this.get(key2, true);
@@ -941,8 +941,8 @@ var require_Collection = __commonJS({
941
941
  * scalar values from their surrounding node; to disable set `keepScalar` to
942
942
  * `true` (collections are always returned intact).
943
943
  */
944
- getIn(path5, keepScalar) {
945
- const [key2, ...rest] = path5;
944
+ getIn(path6, keepScalar) {
945
+ const [key2, ...rest] = path6;
946
946
  const node = this.get(key2, true);
947
947
  if (rest.length === 0)
948
948
  return !keepScalar && identity.isScalar(node) ? node.value : node;
@@ -960,8 +960,8 @@ var require_Collection = __commonJS({
960
960
  /**
961
961
  * Checks if the collection includes a value with the key `key`.
962
962
  */
963
- hasIn(path5) {
964
- const [key2, ...rest] = path5;
963
+ hasIn(path6) {
964
+ const [key2, ...rest] = path6;
965
965
  if (rest.length === 0)
966
966
  return this.has(key2);
967
967
  const node = this.get(key2, true);
@@ -971,8 +971,8 @@ var require_Collection = __commonJS({
971
971
  * Sets a value in this collection. For `!!set`, `value` needs to be a
972
972
  * boolean to add/remove the item from the set.
973
973
  */
974
- setIn(path5, value) {
975
- const [key2, ...rest] = path5;
974
+ setIn(path6, value) {
975
+ const [key2, ...rest] = path6;
976
976
  if (rest.length === 0) {
977
977
  this.set(key2, value);
978
978
  } else {
@@ -3487,9 +3487,9 @@ var require_Document = __commonJS({
3487
3487
  this.contents.add(value);
3488
3488
  }
3489
3489
  /** Adds a value to the document. */
3490
- addIn(path5, value) {
3490
+ addIn(path6, value) {
3491
3491
  if (assertCollection(this.contents))
3492
- this.contents.addIn(path5, value);
3492
+ this.contents.addIn(path6, value);
3493
3493
  }
3494
3494
  /**
3495
3495
  * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
@@ -3564,14 +3564,14 @@ var require_Document = __commonJS({
3564
3564
  * Removes a value from the document.
3565
3565
  * @returns `true` if the item was found and removed.
3566
3566
  */
3567
- deleteIn(path5) {
3568
- if (Collection.isEmptyPath(path5)) {
3567
+ deleteIn(path6) {
3568
+ if (Collection.isEmptyPath(path6)) {
3569
3569
  if (this.contents == null)
3570
3570
  return false;
3571
3571
  this.contents = null;
3572
3572
  return true;
3573
3573
  }
3574
- return assertCollection(this.contents) ? this.contents.deleteIn(path5) : false;
3574
+ return assertCollection(this.contents) ? this.contents.deleteIn(path6) : false;
3575
3575
  }
3576
3576
  /**
3577
3577
  * Returns item at `key`, or `undefined` if not found. By default unwraps
@@ -3586,10 +3586,10 @@ var require_Document = __commonJS({
3586
3586
  * scalar values from their surrounding node; to disable set `keepScalar` to
3587
3587
  * `true` (collections are always returned intact).
3588
3588
  */
3589
- getIn(path5, keepScalar) {
3590
- if (Collection.isEmptyPath(path5))
3589
+ getIn(path6, keepScalar) {
3590
+ if (Collection.isEmptyPath(path6))
3591
3591
  return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents;
3592
- return identity.isCollection(this.contents) ? this.contents.getIn(path5, keepScalar) : void 0;
3592
+ return identity.isCollection(this.contents) ? this.contents.getIn(path6, keepScalar) : void 0;
3593
3593
  }
3594
3594
  /**
3595
3595
  * Checks if the document includes a value with the key `key`.
@@ -3600,10 +3600,10 @@ var require_Document = __commonJS({
3600
3600
  /**
3601
3601
  * Checks if the document includes a value at `path`.
3602
3602
  */
3603
- hasIn(path5) {
3604
- if (Collection.isEmptyPath(path5))
3603
+ hasIn(path6) {
3604
+ if (Collection.isEmptyPath(path6))
3605
3605
  return this.contents !== void 0;
3606
- return identity.isCollection(this.contents) ? this.contents.hasIn(path5) : false;
3606
+ return identity.isCollection(this.contents) ? this.contents.hasIn(path6) : false;
3607
3607
  }
3608
3608
  /**
3609
3609
  * Sets a value in this document. For `!!set`, `value` needs to be a
@@ -3620,13 +3620,13 @@ var require_Document = __commonJS({
3620
3620
  * Sets a value in this document. For `!!set`, `value` needs to be a
3621
3621
  * boolean to add/remove the item from the set.
3622
3622
  */
3623
- setIn(path5, value) {
3624
- if (Collection.isEmptyPath(path5)) {
3623
+ setIn(path6, value) {
3624
+ if (Collection.isEmptyPath(path6)) {
3625
3625
  this.contents = value;
3626
3626
  } else if (this.contents == null) {
3627
- this.contents = Collection.collectionFromPath(this.schema, Array.from(path5), value);
3627
+ this.contents = Collection.collectionFromPath(this.schema, Array.from(path6), value);
3628
3628
  } else if (assertCollection(this.contents)) {
3629
- this.contents.setIn(path5, value);
3629
+ this.contents.setIn(path6, value);
3630
3630
  }
3631
3631
  }
3632
3632
  /**
@@ -5587,9 +5587,9 @@ var require_cst_visit = __commonJS({
5587
5587
  visit.BREAK = BREAK;
5588
5588
  visit.SKIP = SKIP;
5589
5589
  visit.REMOVE = REMOVE;
5590
- visit.itemAtPath = (cst, path5) => {
5590
+ visit.itemAtPath = (cst, path6) => {
5591
5591
  let item = cst;
5592
- for (const [field, index] of path5) {
5592
+ for (const [field, index] of path6) {
5593
5593
  const tok = item?.[field];
5594
5594
  if (tok && "items" in tok) {
5595
5595
  item = tok.items[index];
@@ -5598,23 +5598,23 @@ var require_cst_visit = __commonJS({
5598
5598
  }
5599
5599
  return item;
5600
5600
  };
5601
- visit.parentCollection = (cst, path5) => {
5602
- const parent = visit.itemAtPath(cst, path5.slice(0, -1));
5603
- const field = path5[path5.length - 1][0];
5601
+ visit.parentCollection = (cst, path6) => {
5602
+ const parent = visit.itemAtPath(cst, path6.slice(0, -1));
5603
+ const field = path6[path6.length - 1][0];
5604
5604
  const coll = parent?.[field];
5605
5605
  if (coll && "items" in coll)
5606
5606
  return coll;
5607
5607
  throw new Error("Parent collection not found");
5608
5608
  };
5609
- function _visit(path5, item, visitor) {
5610
- let ctrl = visitor(item, path5);
5609
+ function _visit(path6, item, visitor) {
5610
+ let ctrl = visitor(item, path6);
5611
5611
  if (typeof ctrl === "symbol")
5612
5612
  return ctrl;
5613
5613
  for (const field of ["key", "value"]) {
5614
5614
  const token = item[field];
5615
5615
  if (token && "items" in token) {
5616
5616
  for (let i = 0; i < token.items.length; ++i) {
5617
- const ci2 = _visit(Object.freeze(path5.concat([[field, i]])), token.items[i], visitor);
5617
+ const ci2 = _visit(Object.freeze(path6.concat([[field, i]])), token.items[i], visitor);
5618
5618
  if (typeof ci2 === "number")
5619
5619
  i = ci2 - 1;
5620
5620
  else if (ci2 === BREAK)
@@ -5625,10 +5625,10 @@ var require_cst_visit = __commonJS({
5625
5625
  }
5626
5626
  }
5627
5627
  if (typeof ctrl === "function" && field === "key")
5628
- ctrl = ctrl(item, path5);
5628
+ ctrl = ctrl(item, path6);
5629
5629
  }
5630
5630
  }
5631
- return typeof ctrl === "function" ? ctrl(item, path5) : ctrl;
5631
+ return typeof ctrl === "function" ? ctrl(item, path6) : ctrl;
5632
5632
  }
5633
5633
  exports.visit = visit;
5634
5634
  }
@@ -5641,7 +5641,7 @@ var require_cst = __commonJS({
5641
5641
  var cstScalar = require_cst_scalar();
5642
5642
  var cstStringify = require_cst_stringify();
5643
5643
  var cstVisit = require_cst_visit();
5644
- var BOM = "\uFEFF";
5644
+ var BOM2 = "\uFEFF";
5645
5645
  var DOCUMENT = "";
5646
5646
  var FLOW_END = "";
5647
5647
  var SCALAR = "";
@@ -5649,7 +5649,7 @@ var require_cst = __commonJS({
5649
5649
  var isScalar = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar");
5650
5650
  function prettyToken(token) {
5651
5651
  switch (token) {
5652
- case BOM:
5652
+ case BOM2:
5653
5653
  return "<BOM>";
5654
5654
  case DOCUMENT:
5655
5655
  return "<DOC>";
@@ -5663,7 +5663,7 @@ var require_cst = __commonJS({
5663
5663
  }
5664
5664
  function tokenType(source) {
5665
5665
  switch (source) {
5666
- case BOM:
5666
+ case BOM2:
5667
5667
  return "byte-order-mark";
5668
5668
  case DOCUMENT:
5669
5669
  return "doc-mode";
@@ -5725,7 +5725,7 @@ var require_cst = __commonJS({
5725
5725
  exports.setScalarValue = cstScalar.setScalarValue;
5726
5726
  exports.stringify = cstStringify.stringify;
5727
5727
  exports.visit = cstVisit.visit;
5728
- exports.BOM = BOM;
5728
+ exports.BOM = BOM2;
5729
5729
  exports.DOCUMENT = DOCUMENT;
5730
5730
  exports.FLOW_END = FLOW_END;
5731
5731
  exports.SCALAR = SCALAR;
@@ -7404,14 +7404,14 @@ var init_cli_operator = __esm({
7404
7404
 
7405
7405
  // ../src/cli.ts
7406
7406
  import { randomUUID as randomUUID2 } from "node:crypto";
7407
- import { readFileSync as readFileSync6, writeFileSync as writeFileSync4 } from "node:fs";
7408
- import os6 from "node:os";
7407
+ import { readFileSync as readFileSync7, writeFileSync as writeFileSync5 } from "node:fs";
7408
+ import os7 from "node:os";
7409
7409
  import { readFile as readFile2 } from "node:fs/promises";
7410
7410
  import { parseArgs } from "node:util";
7411
7411
 
7412
7412
  // ../src/cli-build.ts
7413
7413
  var PUBLISHED = true;
7414
- var CLI_VERSION = true ? "0.31.0" : "dev";
7414
+ var CLI_VERSION = true ? "0.33.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}`;
@@ -7803,27 +7803,27 @@ ${USAGE2}`);
7803
7803
  return;
7804
7804
  }
7805
7805
  case "cat": {
7806
- const path5 = need(first, "a path");
7807
- const body = await ask2(client, "GET", `${base}/files?path=${encodeURIComponent(path5)}&encoding=base64`);
7806
+ const path6 = need(first, "a path");
7807
+ const body = await ask2(client, "GET", `${base}/files?path=${encodeURIComponent(path6)}&encoding=base64`);
7808
7808
  process.stdout.write(Buffer.from(String(body["base64"] ?? ""), "base64"));
7809
7809
  return;
7810
7810
  }
7811
7811
  case "put": {
7812
7812
  const local = need(first, "a local file and a path in the sandbox");
7813
- const path5 = need(second, "a path in the sandbox");
7813
+ const path6 = need(second, "a path in the sandbox");
7814
7814
  const bytes3 = await readFile(local);
7815
7815
  if (bytes3.length > LIMIT) {
7816
7816
  throw new Error(`${local} is ${size(bytes3.length)}, over the 10 MB files put sends. agental scp copies bigger ones.`);
7817
7817
  }
7818
- const body = await ask2(client, "PUT", `${base}/files`, { path: path5, base64: bytes3.toString("base64") });
7818
+ const body = await ask2(client, "PUT", `${base}/files`, { path: path6, base64: bytes3.toString("base64") });
7819
7819
  process.stdout.write(options.json ? `${JSON.stringify(body, null, 2)}
7820
7820
  ` : `${String(body["path"])}: ${size(Number(body["bytes"]))}
7821
7821
  `);
7822
7822
  return;
7823
7823
  }
7824
7824
  case "get": {
7825
- const path5 = need(first, "a path");
7826
- const response = await client.request(`${base}/artifacts?path=${encodeURIComponent(path5)}`, { method: "GET", headers: { Accept: "application/octet-stream" } });
7825
+ const path6 = need(first, "a path");
7826
+ const response = await client.request(`${base}/artifacts?path=${encodeURIComponent(path6)}`, { method: "GET", headers: { Accept: "application/octet-stream" } });
7827
7827
  if (!response.ok) {
7828
7828
  client.fail(response.status, await readObject2(response));
7829
7829
  }
@@ -7852,8 +7852,8 @@ ${USAGE2}`);
7852
7852
  return;
7853
7853
  }
7854
7854
  case "rm": {
7855
- const path5 = need(first, "a path");
7856
- await ask2(client, "DELETE", `${base}/files?path=${encodeURIComponent(path5)}${options.recursive ? "&recursive=true" : ""}`);
7855
+ const path6 = need(first, "a path");
7856
+ await ask2(client, "DELETE", `${base}/files?path=${encodeURIComponent(path6)}${options.recursive ? "&recursive=true" : ""}`);
7857
7857
  return;
7858
7858
  }
7859
7859
  case "link": {
@@ -8519,19 +8519,205 @@ async function readAll(stream) {
8519
8519
  }
8520
8520
 
8521
8521
  // ../src/cli-onboard.ts
8522
- import { execFile, spawnSync as spawnSync3 } from "node:child_process";
8522
+ import { execFile as execFile2, spawnSync as spawnSync3 } from "node:child_process";
8523
8523
  import { randomUUID, randomBytes as randomBytes3 } from "node:crypto";
8524
- import { existsSync as existsSync2, readFileSync as readFileSync3, realpathSync, statSync } from "node:fs";
8525
- import os4 from "node:os";
8526
- import path3 from "node:path";
8524
+ import { existsSync as existsSync3, readFileSync as readFileSync4, realpathSync as realpathSync2, statSync as statSync2 } from "node:fs";
8525
+ import os5 from "node:os";
8526
+ import path4 from "node:path";
8527
8527
  import { createInterface } from "node:readline/promises";
8528
8528
 
8529
+ // ../src/cli-mcp.ts
8530
+ import { execFile } from "node:child_process";
8531
+ import { chmodSync as chmodSync2, existsSync, readFileSync as readFileSync2, realpathSync, renameSync as renameSync2, rmSync as rmSync2, statSync, writeFileSync as writeFileSync2 } from "node:fs";
8532
+ import os3 from "node:os";
8533
+ import path2 from "node:path";
8534
+ var CONNECTOR_NAME = "agental";
8535
+ function placesFrom(env = process.env) {
8536
+ const home = env["HOME"] || os3.homedir();
8537
+ return {
8538
+ home,
8539
+ config: env["XDG_CONFIG_HOME"]?.trim() || path2.join(home, ".config"),
8540
+ claudeDir: env["CLAUDE_CONFIG_DIR"]?.trim() || path2.join(home, ".claude"),
8541
+ codexDir: env["CODEX_HOME"]?.trim() || path2.join(home, ".codex")
8542
+ };
8543
+ }
8544
+ var SIGN_IN = {
8545
+ "Claude Code": "/mcp, then agental, then Authenticate",
8546
+ Codex: "codex mcp login agental",
8547
+ Cursor: "Settings \u203A MCP, turn agental on, then log in",
8548
+ Windsurf: "its MCP servers list, then agental",
8549
+ "Gemini CLI": "/mcp auth agental",
8550
+ opencode: "opencode mcp auth agental"
8551
+ };
8552
+ var JSON_AGENTS = [
8553
+ { agent: "Cursor", folder: (p) => path2.join(p.home, ".cursor"), file: "mcp.json", key: "mcpServers", entry: (url) => ({ url }) },
8554
+ { agent: "Windsurf", folder: (p) => path2.join(p.home, ".codeium", "windsurf"), file: "mcp_config.json", key: "mcpServers", entry: (url) => ({ serverUrl: url }) },
8555
+ { agent: "Gemini CLI", folder: (p) => path2.join(p.home, ".gemini"), file: "settings.json", key: "mcpServers", entry: (url) => ({ httpUrl: url }) },
8556
+ { agent: "opencode", folder: (p) => path2.join(p.config, "opencode"), file: "opencode.json", other: "opencode.jsonc", key: "mcp", entry: (url) => ({ type: "remote", url }) }
8557
+ ];
8558
+ function replaceFile(file, text) {
8559
+ const target = existsSync(file) ? realpathSync(file) : file;
8560
+ const mode = existsSync(target) ? statSync(target).mode & 511 : 420;
8561
+ const next = `${target}.agental-${process.pid}`;
8562
+ try {
8563
+ writeFileSync2(next, text, { mode });
8564
+ chmodSync2(next, mode);
8565
+ renameSync2(next, target);
8566
+ } catch (error) {
8567
+ rmSync2(next, { force: true });
8568
+ throw error;
8569
+ }
8570
+ }
8571
+ var BOM = "\uFEFF";
8572
+ function addToJson(agent, places, url) {
8573
+ const folder = agent.folder(places);
8574
+ if (!existsSync(folder)) {
8575
+ return null;
8576
+ }
8577
+ const file = path2.join(folder, agent.file);
8578
+ const lines = JSON.stringify({ [agent.key]: { [CONNECTOR_NAME]: agent.entry(url) } });
8579
+ if (agent.other && existsSync(path2.join(folder, agent.other))) {
8580
+ return { agent: agent.agent, did: "left", why: `its settings are in ${path2.join(folder, agent.other)}, which this does not change: add ${lines}` };
8581
+ }
8582
+ let settings = {};
8583
+ let bom = "";
8584
+ if (existsSync(file)) {
8585
+ try {
8586
+ const text = readFileSync2(file, "utf8");
8587
+ bom = text.startsWith(BOM) ? BOM : "";
8588
+ const read2 = JSON.parse(text.slice(bom.length));
8589
+ if (!read2 || typeof read2 !== "object" || Array.isArray(read2)) {
8590
+ throw new Error("not an object");
8591
+ }
8592
+ settings = read2;
8593
+ } catch {
8594
+ return { agent: agent.agent, did: "left", why: `${file} is not plain JSON, so it was left as it is: add ${lines}` };
8595
+ }
8596
+ }
8597
+ const servers = settings[agent.key] ?? {};
8598
+ if (typeof servers !== "object" || servers === null || Array.isArray(servers)) {
8599
+ return { agent: agent.agent, did: "left", why: `${agent.key} in ${file} is not a list of servers, so it was left as it is: add ${lines}` };
8600
+ }
8601
+ if (CONNECTOR_NAME in servers) {
8602
+ return { agent: agent.agent, did: "already" };
8603
+ }
8604
+ settings[agent.key] = { ...servers, [CONNECTOR_NAME]: agent.entry(url) };
8605
+ replaceFile(file, `${bom}${JSON.stringify(settings, null, 2)}
8606
+ `);
8607
+ return { agent: agent.agent, did: "added" };
8608
+ }
8609
+ function codexHas(text) {
8610
+ const has = /^\s*\[\s*mcp_servers\s*\.\s*["']?agental["']?\s*[\].]/m.test(text) || /^\s*mcp_servers\s*\.\s*["']?agental["']?\s*[.=]/m.test(text) || /^\s*\[\s*mcp_servers\s*\]/m.test(text) && /^\s*["']?agental["']?\s*[.=]/m.test(text);
8611
+ if (has) {
8612
+ return "agental";
8613
+ }
8614
+ return /^\s*mcp_servers\s*=/m.test(text) ? "inline" : null;
8615
+ }
8616
+ function addToCodex(places, url) {
8617
+ if (!existsSync(places.codexDir)) {
8618
+ return null;
8619
+ }
8620
+ const file = path2.join(places.codexDir, "config.toml");
8621
+ const text = existsSync(file) ? readFileSync2(file, "utf8") : "";
8622
+ const has = codexHas(text);
8623
+ if (has === "agental") {
8624
+ return { agent: "Codex", did: "already" };
8625
+ }
8626
+ if (has === "inline") {
8627
+ return { agent: "Codex", did: "left", why: `${file} lists its servers inline, so it was left as it is: add agental = { url = "${url}" } to them` };
8628
+ }
8629
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
8630
+ const lead = text === "" ? "" : text.endsWith("\n") ? eol : eol + eol;
8631
+ replaceFile(file, `${text}${lead}[mcp_servers.${CONNECTOR_NAME}]${eol}url = "${url}"${eol}`);
8632
+ return { agent: "Codex", did: "added" };
8633
+ }
8634
+ function run(command2, args, cwd) {
8635
+ return new Promise((resolve) => {
8636
+ execFile(command2, args, { encoding: "utf8", timeout: 6e4, cwd, shell: process.platform === "win32" }, (error, stdout, stderr) => {
8637
+ const out = `${stdout}${stderr}`.trim();
8638
+ const missing = error?.code === "ENOENT" || process.platform === "win32" && /is not recognized as an internal or external command/i.test(out);
8639
+ resolve({ ok: !error, out, missing });
8640
+ });
8641
+ });
8642
+ }
8643
+ async function addToClaudeCode(places, url) {
8644
+ if (!existsSync(places.claudeDir)) {
8645
+ return null;
8646
+ }
8647
+ const add = `claude mcp add --transport http --scope user ${CONNECTOR_NAME} ${url}`;
8648
+ const found = await run("claude", ["mcp", "get", CONNECTOR_NAME], places.home);
8649
+ if (found.missing) {
8650
+ return { agent: "Claude Code", did: "left", why: `the claude command is not on the PATH: run ${add}` };
8651
+ }
8652
+ if (found.ok) {
8653
+ return { agent: "Claude Code", did: "already" };
8654
+ }
8655
+ const added = await run("claude", ["mcp", "add", "--transport", "http", "--scope", "user", CONNECTOR_NAME, url], places.home);
8656
+ if (!added.ok) {
8657
+ const last = added.out.split("\n").filter((line) => line.trim()).pop() ?? "it failed";
8658
+ return { agent: "Claude Code", did: "left", why: `claude mcp add failed (${last.slice(0, 160)}): run ${add}` };
8659
+ }
8660
+ return { agent: "Claude Code", did: "added" };
8661
+ }
8662
+ async function step(agent, add) {
8663
+ try {
8664
+ return await add();
8665
+ } catch (error) {
8666
+ return { agent, did: "left", why: `it could not be added (${error instanceof Error ? error.message : String(error)})` };
8667
+ }
8668
+ }
8669
+ async function addConnector(url, places = placesFrom()) {
8670
+ const outcomes = [await step("Claude Code", () => addToClaudeCode(places, url)), await step("Codex", () => addToCodex(places, url))];
8671
+ for (const agent of JSON_AGENTS) {
8672
+ outcomes.push(await step(agent.agent, () => addToJson(agent, places, url)));
8673
+ }
8674
+ return outcomes.filter((outcome) => outcome !== null);
8675
+ }
8676
+ function claudeDesktopHere(places, platform = process.platform, env = process.env) {
8677
+ const folder = platform === "darwin" ? path2.join(places.home, "Library", "Application Support", "Claude") : platform === "win32" ? path2.join(env["APPDATA"] ?? path2.join(places.home, "AppData", "Roaming"), "Claude") : path2.join(places.config, "Claude");
8678
+ return existsSync(folder);
8679
+ }
8680
+ function addToClaudeLink(url) {
8681
+ return `https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=${CONNECTOR_NAME}&connectorUrl=${encodeURIComponent(url)}`;
8682
+ }
8683
+ function names(list3) {
8684
+ return list3.length < 2 ? list3[0] ?? "" : `${list3.slice(0, -1).join(", ")} and ${list3.at(-1)}`;
8685
+ }
8686
+ async function ensureConnector(site2, places = placesFrom()) {
8687
+ const url = `${site2}/v1/mcp`;
8688
+ const outcomes = await addConnector(url, places);
8689
+ const lines = [];
8690
+ const added = outcomes.filter((outcome) => outcome.did === "added").map((outcome) => outcome.agent);
8691
+ const already = outcomes.filter((outcome) => outcome.did === "already").map((outcome) => outcome.agent);
8692
+ if (added.length > 0) {
8693
+ lines.push(done(`connector added to ${names(added)} ${dim("\xB7 sign in once from each:")}`));
8694
+ for (const agent of added) {
8695
+ lines.push(` ${dim(`${agent}:`)} ${SIGN_IN[agent] ?? ""}`);
8696
+ }
8697
+ }
8698
+ if (already.length > 0) {
8699
+ lines.push(done(`connector already in ${names(already)}`));
8700
+ }
8701
+ for (const outcome of outcomes) {
8702
+ if (outcome.did === "left") {
8703
+ lines.push(`${bold("!")} connector not added to ${outcome.agent}: ${outcome.why}`);
8704
+ }
8705
+ }
8706
+ if (claudeDesktopHere(places)) {
8707
+ lines.push(`${dim("Claude Desktop adds connectors in its own window:")} ${addToClaudeLink(url)}`);
8708
+ }
8709
+ if (outcomes.length === 0) {
8710
+ lines.push(`${dim("no coding agent found here to add the connector to \xB7 any MCP client takes")} ${url}`);
8711
+ }
8712
+ return lines;
8713
+ }
8714
+
8529
8715
  // ../src/cli-ssh.ts
8530
8716
  import { spawn as spawn2, spawnSync as spawnSync2 } from "node:child_process";
8531
- import { existsSync, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
8717
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "node:fs";
8532
8718
  import net from "node:net";
8533
- import os3 from "node:os";
8534
- import path2 from "node:path";
8719
+ import os4 from "node:os";
8720
+ import path3 from "node:path";
8535
8721
  var Refused2 = class extends Error {
8536
8722
  constructor(code, said) {
8537
8723
  super(`${code}: ${said}`);
@@ -8550,22 +8736,22 @@ var TRIES_IN_A_ROW = 3;
8550
8736
  var TAKES_A_VALUE = new Set("BbcDEeFIiJLlmOoPpQRSWw".split("").map((letter) => `-${letter}`));
8551
8737
  var TMUX = "tmux new-session -A -s agental";
8552
8738
  function keyPath() {
8553
- return process.env["AGENTAL_SSH_KEY"] || path2.join(os3.homedir(), ".ssh", "agental_ed25519");
8739
+ return process.env["AGENTAL_SSH_KEY"] || path3.join(os4.homedir(), ".ssh", "agental_ed25519");
8554
8740
  }
8555
8741
  function knownHostsPath() {
8556
- return process.env["AGENTAL_SSH_KNOWN_HOSTS"] || path2.join(os3.homedir(), ".ssh", "agental_known_hosts");
8742
+ return process.env["AGENTAL_SSH_KNOWN_HOSTS"] || path3.join(os4.homedir(), ".ssh", "agental_known_hosts");
8557
8743
  }
8558
8744
  function publicKey() {
8559
8745
  const key2 = keyPath();
8560
- if (!existsSync(key2)) {
8561
- mkdirSync2(path2.dirname(key2), { recursive: true, mode: 448 });
8746
+ if (!existsSync2(key2)) {
8747
+ mkdirSync2(path3.dirname(key2), { recursive: true, mode: 448 });
8562
8748
  const made = spawnSync2("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", "agental", "-f", key2], { stdio: ["ignore", "ignore", "inherit"] });
8563
8749
  if (made.error || made.status !== 0) {
8564
8750
  throw new Error(`No key pair at ${key2}, and ssh-keygen could not make one${made.error ? `: ${made.error.message}` : "."}`);
8565
8751
  }
8566
8752
  }
8567
8753
  try {
8568
- return readFileSync2(`${key2}.pub`, "utf8").trim();
8754
+ return readFileSync3(`${key2}.pub`, "utf8").trim();
8569
8755
  } catch {
8570
8756
  throw new Error(`${key2}.pub could not be read. It is the public half of the key the CLI logs in with.`);
8571
8757
  }
@@ -8614,14 +8800,14 @@ async function letIn(client, sandboxId) {
8614
8800
  }
8615
8801
  function pin(sandboxId, hostKey) {
8616
8802
  const file = knownHostsPath();
8617
- mkdirSync2(path2.dirname(file), { recursive: true, mode: 448 });
8803
+ mkdirSync2(path3.dirname(file), { recursive: true, mode: 448 });
8618
8804
  let lines = [];
8619
8805
  try {
8620
- lines = readFileSync2(file, "utf8").split("\n").filter((line) => line.trim() !== "" && !line.startsWith(`${sandboxId} `));
8806
+ lines = readFileSync3(file, "utf8").split("\n").filter((line) => line.trim() !== "" && !line.startsWith(`${sandboxId} `));
8621
8807
  } catch {
8622
8808
  }
8623
8809
  lines.push(`${sandboxId} ${hostKey}`);
8624
- writeFileSync2(file, `${lines.join("\n")}
8810
+ writeFileSync3(file, `${lines.join("\n")}
8625
8811
  `, { mode: 384 });
8626
8812
  }
8627
8813
  function kept(sandboxId, user, given) {
@@ -8639,7 +8825,7 @@ function kept(sandboxId, user, given) {
8639
8825
  function flags(sandboxId, access, given) {
8640
8826
  return [["HostName", access.host], ["Port", String(access.port)], ...kept(sandboxId, access.user, given)].flatMap(([name, value]) => ["-o", `${name}=${value}`]);
8641
8827
  }
8642
- async function run(program, args) {
8828
+ async function run2(program, args) {
8643
8829
  const child = spawn2(program, args, { stdio: "inherit" });
8644
8830
  return await new Promise((resolve, reject) => {
8645
8831
  child.on("error", (error) => reject(new Error(`${program} could not be run: ${error.message}`)));
@@ -8674,7 +8860,7 @@ async function ssh(client, args) {
8674
8860
  await letIn(client, sandboxId);
8675
8861
  for (let soon2 = 0; ; ) {
8676
8862
  const began = Date.now();
8677
- const code = await run("ssh", [...flags(sandboxId, access, passed), ...tmux ? ["-t"] : [], sandboxId, ...passed, ...tmux ? [TMUX] : []]);
8863
+ const code = await run2("ssh", [...flags(sandboxId, access, passed), ...tmux ? ["-t"] : [], sandboxId, ...passed, ...tmux ? [TMUX] : []]);
8678
8864
  if (tmux && code === 127) {
8679
8865
  process.stderr.write("tmux is not in this sandbox. Install it there, with apt-get update && apt-get install -y tmux, or leave --tmux out.\n");
8680
8866
  }
@@ -8712,7 +8898,7 @@ async function scp(client, args) {
8712
8898
  }
8713
8899
  const access = await reach(client, sandboxId);
8714
8900
  await letIn(client, sandboxId);
8715
- process.exitCode = await run("scp", [...flags(sandboxId, access, args), ...args]);
8901
+ process.exitCode = await run2("scp", [...flags(sandboxId, access, args), ...args]);
8716
8902
  }
8717
8903
  function quoted(argument) {
8718
8904
  return `'${argument.replaceAll("'", `'\\''`)}'`;
@@ -8785,14 +8971,14 @@ function errorOf(answer3) {
8785
8971
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
8786
8972
  function real(file) {
8787
8973
  try {
8788
- return realpathSync(file);
8974
+ return realpathSync2(file);
8789
8975
  } catch {
8790
8976
  return file;
8791
8977
  }
8792
8978
  }
8793
8979
  function runnable(file) {
8794
8980
  try {
8795
- const stat = statSync(file);
8981
+ const stat = statSync2(file);
8796
8982
  return stat.isFile() && (stat.mode & 73) !== 0;
8797
8983
  } catch {
8798
8984
  return false;
@@ -8801,12 +8987,12 @@ function runnable(file) {
8801
8987
  function installedCommand() {
8802
8988
  const self = real(process.argv[1] ?? "");
8803
8989
  const name = process.platform === "win32" ? "agental.cmd" : "agental";
8804
- for (const dir of (process.env["PATH"] ?? "").split(path3.delimiter)) {
8805
- if (!dir || dir.includes(`${path3.sep}_npx${path3.sep}`)) {
8990
+ for (const dir of (process.env["PATH"] ?? "").split(path4.delimiter)) {
8991
+ if (!dir || dir.includes(`${path4.sep}_npx${path4.sep}`)) {
8806
8992
  continue;
8807
8993
  }
8808
- const file = path3.join(dir, name);
8809
- if (runnable(file) && !real(file).includes(`${path3.sep}_npx${path3.sep}`)) {
8994
+ const file = path4.join(dir, name);
8995
+ if (runnable(file) && !real(file).includes(`${path4.sep}_npx${path4.sep}`)) {
8810
8996
  return { file, self: real(file) === self };
8811
8997
  }
8812
8998
  }
@@ -8814,7 +9000,7 @@ function installedCommand() {
8814
9000
  }
8815
9001
  function versionOf(file) {
8816
9002
  return new Promise((resolve) => {
8817
- execFile(file, ["--version"], { encoding: "utf8", timeout: 1e4 }, (error, stdout) => {
9003
+ execFile2(file, ["--version"], { encoding: "utf8", timeout: 1e4 }, (error, stdout) => {
8818
9004
  resolve(error ? null : /^agental (\S+)$/m.exec(String(stdout).trim())?.[1] ?? null);
8819
9005
  });
8820
9006
  });
@@ -8831,7 +9017,7 @@ function older(version, than) {
8831
9017
  }
8832
9018
  function npm(args) {
8833
9019
  return new Promise((resolve) => {
8834
- execFile(process.platform === "win32" ? "npm.cmd" : "npm", args, { encoding: "utf8", timeout: 5 * 6e4, shell: process.platform === "win32" }, (error, stdout, stderr) => {
9020
+ execFile2(process.platform === "win32" ? "npm.cmd" : "npm", args, { encoding: "utf8", timeout: 5 * 6e4, shell: process.platform === "win32" }, (error, stdout, stderr) => {
8835
9021
  resolve({ ok: !error, out: `${stdout}${stderr}`.trim() });
8836
9022
  });
8837
9023
  });
@@ -8864,8 +9050,8 @@ async function ensureCommand(options) {
8864
9050
  return `${bold("!")} agental was not installed${permission ? ", as npm's global folder needs more rights than you have" : ""}. Run ${bold(permission ? `sudo ${INSTALL}` : INSTALL)} to install it.`;
8865
9051
  }
8866
9052
  const prefix = (await npm(["prefix", "-g"])).out.split("\n").pop()?.trim() ?? "";
8867
- const bin = process.platform === "win32" ? prefix : path3.join(prefix, "bin");
8868
- const onPath = (process.env["PATH"] ?? "").split(path3.delimiter).some((dir) => real(dir) === real(bin));
9053
+ const bin = process.platform === "win32" ? prefix : path4.join(prefix, "bin");
9054
+ const onPath = (process.env["PATH"] ?? "").split(path4.delimiter).some((dir) => real(dir) === real(bin));
8869
9055
  return done(`agental ${CLI_VERSION} ${found ? "updated" : "installed"} ${dim("\xB7 try")} agental list`) + (onPath ? "" : `
8870
9056
  ${dim("npm put it in")} ${bin}${dim(", which is not on your PATH: add it, as")} export PATH="${bin}:$PATH"`);
8871
9057
  }
@@ -8893,13 +9079,13 @@ var AGENT_HOMES = [
8893
9079
  ];
8894
9080
  var AGENT_CONFIGS = ["opencode", "amp", "goose"];
8895
9081
  function codingAgentHere(env = process.env) {
8896
- const home = env["HOME"] || os4.homedir();
8897
- const config = env["XDG_CONFIG_HOME"]?.trim() || path3.join(home, ".config");
9082
+ const home = env["HOME"] || os5.homedir();
9083
+ const config = env["XDG_CONFIG_HOME"]?.trim() || path4.join(home, ".config");
8898
9084
  return [
8899
- ...AGENT_HOMES.map((folder) => path3.join(home, folder)),
8900
- ...AGENT_CONFIGS.map((folder) => path3.join(config, folder)),
9085
+ ...AGENT_HOMES.map((folder) => path4.join(home, folder)),
9086
+ ...AGENT_CONFIGS.map((folder) => path4.join(config, folder)),
8901
9087
  ...[env["CLAUDE_CONFIG_DIR"], env["CODEX_HOME"]].filter((folder) => Boolean(folder?.trim()))
8902
- ].some((folder) => existsSync2(folder));
9088
+ ].some((folder) => existsSync3(folder));
8903
9089
  }
8904
9090
  async function ensureSkills(options, site2) {
8905
9091
  if (!options.installSkills) {
@@ -8910,7 +9096,7 @@ async function ensureSkills(options, site2) {
8910
9096
  }
8911
9097
  const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => !/^npm_(config_package|config_call|command|execpath|lifecycle_)/i.test(name)));
8912
9098
  const ran = await new Promise((resolve) => {
8913
- execFile(
9099
+ execFile2(
8914
9100
  process.platform === "win32" ? "npx.cmd" : "npx",
8915
9101
  ["--yes", `--package=${SKILLS_CLI}`, "--", "skills", "add", site2, "-g", "-y"],
8916
9102
  { encoding: "utf8", timeout: 5 * 6e4, shell: process.platform === "win32", env },
@@ -9044,14 +9230,14 @@ async function hourly(base, key2, size2) {
9044
9230
  return typeof micros === "number" ? micros : null;
9045
9231
  }
9046
9232
  var perHour = (micros) => `$${(micros / 1e6).toFixed(micros < 1e5 ? 4 : 3)} an hour`;
9047
- function completionStep(shell2 = process.env["SHELL"], home = os4.homedir()) {
9048
- const name = path3.basename(shell2 ?? "");
9233
+ function completionStep(shell2 = process.env["SHELL"], home = os5.homedir()) {
9234
+ const name = path4.basename(shell2 ?? "");
9049
9235
  const config = name === "zsh" ? ".zshrc" : name === "bash" ? ".bashrc" : name === "fish" ? ".config/fish/config.fish" : null;
9050
9236
  if (config === null) {
9051
9237
  return null;
9052
9238
  }
9053
9239
  try {
9054
- if (readFileSync3(path3.join(home, config), "utf8").includes("agental completion")) {
9240
+ if (readFileSync4(path4.join(home, config), "utf8").includes("agental completion")) {
9055
9241
  return null;
9056
9242
  }
9057
9243
  } catch {
@@ -9092,7 +9278,7 @@ async function onboard(base, options) {
9092
9278
  term.say(` ${dim("signed in as")} ${bold(describe2(account3))} ${dim(`\xB7 with the key ${credentials.keyName ?? "pasted in"} \xB7 not you?`)} agental logout`);
9093
9279
  }
9094
9280
  const site2 = new URL(base).origin;
9095
- const installs = (async () => [await ensureCommand(options), await ensureSkills(options, site2)])();
9281
+ const installs = (async () => [await ensureCommand(options), await ensureSkills(options, site2), ...options.installConnector ? await ensureConnector(site2) : []])();
9096
9282
  const report = async () => {
9097
9283
  for (const line of await installs) {
9098
9284
  if (line) {
@@ -9171,9 +9357,9 @@ async function onboard(base, options) {
9171
9357
 
9172
9358
  // ../src/cli-completion.ts
9173
9359
  import { createHash as createHash2 } from "node:crypto";
9174
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "node:fs";
9175
- import os5 from "node:os";
9176
- import path4 from "node:path";
9360
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync4 } from "node:fs";
9361
+ import os6 from "node:os";
9362
+ import path5 from "node:path";
9177
9363
 
9178
9364
  // ../src/cli-help.ts
9179
9365
  function isTerminal(stream) {
@@ -9202,6 +9388,9 @@ var COMMANDS = [
9202
9388
  [" --ttl <time>", "stop it after this long, as 30m or 2h"],
9203
9389
  [" --allow <addresses>", "reach only these addresses, comma-separated"],
9204
9390
  [" --egress <egress>", "box, or residential:<country>[:sticky|rotating]"],
9391
+ [" --spot", "half the price, in spare room taken back when needed"],
9392
+ [" --on-reclaim <what>", "with --spot: stop (default), delete or upgrade"],
9393
+ [" --warn-at <chance>", "with --spot: warn at this chance, as 0.5 or 50%"],
9205
9394
  [" --ssh-key <key or file>", "let this key in over SSH (may be given again)"],
9206
9395
  [" --tag <tag>", "label it (may be given again)"],
9207
9396
  [" --meta <key>=<value>", "attach data to it (may be given again)"],
@@ -9324,6 +9513,11 @@ var COMMANDS = [
9324
9513
  { name: "regions", summary: "List where sandboxes run, and how much room each has now." },
9325
9514
  { name: "network", summary: "Say what a sandbox may reach outside itself.", examples: ["agental network sbx_2a9a47e50daec64a --allow github.com,registry.npmjs.org", "agental network sbx_2a9a47e50daec64a --none"] },
9326
9515
  { name: "egress", summary: "Say where a sandbox's web traffic leaves from, or read your residential egress.", examples: ["agental egress sbx_2a9a47e50daec64a residential de"] },
9516
+ {
9517
+ name: "spot",
9518
+ summary: "Read a spot sandbox's chance of being stopped, change what a reclaim does to it, or make it normal.",
9519
+ examples: ["agental spot sbx_2a9a47e50daec64a", "agental spot sbx_2a9a47e50daec64a --on-reclaim upgrade --warn-at 30%", "agental spot sbx_2a9a47e50daec64a normal"]
9520
+ },
9327
9521
  { name: "templates", summary: "List your templates: what new sandboxes start from." },
9328
9522
  {
9329
9523
  name: "template",
@@ -9519,7 +9713,7 @@ var MAP = [
9519
9713
  [
9520
9714
  ["start, stop, delete", "one sandbox, or every one --where finds"],
9521
9715
  ["recover, auto-stop", "get a stuck one going, say when one stops"],
9522
- ["resize", "a larger size, now or at its next start"],
9716
+ ["resize, spot", "a larger size; a spot one's chance of being stopped"],
9523
9717
  ["job", "run a command on a timer"],
9524
9718
  ["secret", "values and files kept out of the sandbox"],
9525
9719
  ["site", "share a port on a public link"],
@@ -9558,13 +9752,13 @@ var MAP = [
9558
9752
  ];
9559
9753
  var DOCS = "https://agental.io/docs/cli";
9560
9754
  function shortHelp() {
9561
- const width = Math.max(...MAP.flatMap(([, rows]) => rows.map(([names]) => names.length))) + 3;
9755
+ const width = Math.max(...MAP.flatMap(([, rows]) => rows.map(([names2]) => names2.length))) + 3;
9562
9756
  const lines = [`${strong("agental")} \xB7 Linux sandboxes for your agents`, "", `${strong("Usage")} agental <command> [flags]`];
9563
9757
  for (const [group, rows] of MAP) {
9564
9758
  lines.push("", strong(group));
9565
- for (const [names, what] of rows) {
9566
- const painted = names.split(", ").map((name) => command(name)).join(", ");
9567
- lines.push(` ${painted}${" ".repeat(width - names.length)}${what}`);
9759
+ for (const [names2, what] of rows) {
9760
+ const painted = names2.split(", ").map((name) => command(name)).join(", ");
9761
+ lines.push(` ${painted}${" ".repeat(width - names2.length)}${what}`);
9568
9762
  }
9569
9763
  }
9570
9764
  lines.push("", faint("Each thing takes list, show, add or create, update and delete, as agental key list."));
@@ -9969,10 +10163,10 @@ async function jobs(api2) {
9969
10163
  }
9970
10164
  var KEPT_MS = 3e4;
9971
10165
  async function cached(what, as, ask10) {
9972
- const folder = path4.join(process.env["XDG_CACHE_HOME"] || path4.join(os5.homedir(), ".cache"), "agental");
9973
- const file = path4.join(folder, `complete-${what}-${createHash2("sha256").update(as).digest("hex").slice(0, 16)}.json`);
10166
+ const folder = path5.join(process.env["XDG_CACHE_HOME"] || path5.join(os6.homedir(), ".cache"), "agental");
10167
+ const file = path5.join(folder, `complete-${what}-${createHash2("sha256").update(as).digest("hex").slice(0, 16)}.json`);
9974
10168
  try {
9975
- const kept2 = JSON.parse(readFileSync4(file, "utf8"));
10169
+ const kept2 = JSON.parse(readFileSync5(file, "utf8"));
9976
10170
  if (Date.now() - kept2.at < KEPT_MS) {
9977
10171
  return kept2.body;
9978
10172
  }
@@ -9986,7 +10180,7 @@ async function cached(what, as, ask10) {
9986
10180
  }
9987
10181
  try {
9988
10182
  mkdirSync3(folder, { recursive: true, mode: 448 });
9989
- writeFileSync3(file, JSON.stringify({ at: Date.now(), body }), { mode: 384 });
10183
+ writeFileSync4(file, JSON.stringify({ at: Date.now(), body }), { mode: 384 });
9990
10184
  } catch {
9991
10185
  }
9992
10186
  return body;
@@ -10293,7 +10487,7 @@ async function invite(client, positionals, options) {
10293
10487
 
10294
10488
  // ../src/cli-jobs.ts
10295
10489
  var import_yaml = __toESM(require_dist(), 1);
10296
- import { readFileSync as readFileSync5 } from "node:fs";
10490
+ import { readFileSync as readFileSync6 } from "node:fs";
10297
10491
  var USAGE4 = "job takes add, list, get, update, delete, pause, resume, run, again, runs, logs, keep, apply, trigger or calls. agental job --help shows each.";
10298
10492
  var OVERLAPS = ["skip", "replace", "parallel"];
10299
10493
  var ALERTS = ["email", "webhook", "both", "none"];
@@ -10437,40 +10631,40 @@ function nextOf(job2, terse) {
10437
10631
  }
10438
10632
  return job2.every === null && job2.cron === null ? "when asked" : "never";
10439
10633
  }
10440
- function lastOf(run2) {
10441
- if (run2 === null) {
10634
+ function lastOf(run3) {
10635
+ if (run3 === null) {
10442
10636
  return "none yet";
10443
10637
  }
10444
- const code = run2.exitCode === null ? "" : ` (exit ${run2.exitCode})`;
10445
- return `${run2.outcome}${code} ${past(run2.dueAt)}`;
10638
+ const code = run3.exitCode === null ? "" : ` (exit ${run3.exitCode})`;
10639
+ return `${run3.outcome}${code} ${past(run3.dueAt)}`;
10446
10640
  }
10447
- function tookOf(run2) {
10448
- if (run2.startedAt === null || run2.finishedAt === null) {
10641
+ function tookOf(run3) {
10642
+ if (run3.startedAt === null || run3.finishedAt === null) {
10449
10643
  return "-";
10450
10644
  }
10451
- const seconds2 = Math.max(0, Math.round((Date.parse(run2.finishedAt) - Date.parse(run2.startedAt)) / 1e3));
10645
+ const seconds2 = Math.max(0, Math.round((Date.parse(run3.finishedAt) - Date.parse(run3.startedAt)) / 1e3));
10452
10646
  return seconds2 < 60 ? `${seconds2}s` : seconds2 < 3600 ? `${Math.floor(seconds2 / 60)}m${String(seconds2 % 60).padStart(2, "0")}s` : `${Math.floor(seconds2 / 3600)}h${String(Math.floor(seconds2 % 3600 / 60)).padStart(2, "0")}m`;
10453
10647
  }
10454
- function sandboxDoneOf(run2) {
10455
- if (run2.fresh === true) {
10456
- if (run2.sandboxKept === true) {
10648
+ function sandboxDoneOf(run3) {
10649
+ if (run3.fresh === true) {
10650
+ if (run3.sandboxKept === true) {
10457
10651
  return "fresh, kept by you";
10458
10652
  }
10459
- if (run2.deletedSandbox) {
10653
+ if (run3.deletedSandbox) {
10460
10654
  return "fresh, deleted";
10461
10655
  }
10462
- if (run2.keepUntil) {
10463
- return `fresh, kept until ${soon(run2.keepUntil)}`;
10656
+ if (run3.keepUntil) {
10657
+ return `fresh, kept until ${soon(run3.keepUntil)}`;
10464
10658
  }
10465
- return run2.sandboxId === null ? "fresh, not made" : "fresh";
10659
+ return run3.sandboxId === null ? "fresh, not made" : "fresh";
10466
10660
  }
10467
- if (run2.deletedSandbox) {
10468
- return run2.startedSandbox ? "started, deleted" : "deleted";
10661
+ if (run3.deletedSandbox) {
10662
+ return run3.startedSandbox ? "started, deleted" : "deleted";
10469
10663
  }
10470
- if (!run2.startedSandbox) {
10664
+ if (!run3.startedSandbox) {
10471
10665
  return "-";
10472
10666
  }
10473
- return run2.stoppedSandbox === null ? "started, left running" : `started, stopped (${run2.stoppedSandbox})`;
10667
+ return run3.stoppedSandbox === null ? "started, left running" : `started, stopped (${run3.stoppedSandbox})`;
10474
10668
  }
10475
10669
  var BY = { timer: "timer", run_now: "by hand", api: "api", http: "http", event: "event" };
10476
10670
  function commandLine(words2) {
@@ -10721,33 +10915,33 @@ async function listJobs(client, options) {
10721
10915
  }
10722
10916
  table2([["NAME", "SANDBOX", "WHEN", "NEXT", "LAST RUN"], ...jobs2.map((job2) => [job2.name, sandboxOf(job2), whenOf(job2), nextOf(job2, true), lastOf(job2.lastRun)])], 2);
10723
10917
  }
10724
- function writeOutput(run2) {
10725
- if (run2.stdout) {
10726
- process.stdout.write(run2.stdout);
10918
+ function writeOutput(run3) {
10919
+ if (run3.stdout) {
10920
+ process.stdout.write(run3.stdout);
10727
10921
  }
10728
- if (run2.stderr) {
10729
- process.stderr.write(run2.stderr);
10922
+ if (run3.stderr) {
10923
+ process.stderr.write(run3.stderr);
10730
10924
  }
10731
- if ((run2.stdout ?? null) === null && (run2.stderr ?? null) === null) {
10732
- const said = run2.outputHidden === true ? "Its output needs a key that may run commands in its sandbox (exec)." : run2.commandId === null ? "It ran no command." : "Its output is no longer kept.";
10733
- process.stderr.write(`Run ${run2.id} ${run2.outcome}${why(run2)}. ${said}
10925
+ if ((run3.stdout ?? null) === null && (run3.stderr ?? null) === null) {
10926
+ const said = run3.outputHidden === true ? "Its output needs a key that may run commands in its sandbox (exec)." : run3.commandId === null ? "It ran no command." : "Its output is no longer kept.";
10927
+ process.stderr.write(`Run ${run3.id} ${run3.outcome}${why(run3)}. ${said}
10734
10928
  `);
10735
10929
  }
10736
10930
  }
10737
- function writeNotes(run2, name) {
10738
- const cut = [run2.stdoutCut === true ? "stdout" : null, run2.stderrCut === true ? "stderr" : null].filter((each) => each !== null);
10931
+ function writeNotes(run3, name) {
10932
+ const cut = [run3.stdoutCut === true ? "stdout" : null, run3.stderrCut === true ? "stderr" : null].filter((each) => each !== null);
10739
10933
  if (cut.length > 0) {
10740
10934
  process.stderr.write(faint(`Only the end of its ${cut.join(" and ")} was kept.
10741
10935
  `, process.stderr));
10742
10936
  }
10743
- if (run2.fresh === true && run2.keepUntil && run2.sandboxKept !== true && run2.sandboxId !== null) {
10744
- process.stderr.write(`Its sandbox ${run2.sandboxId} is kept, stopped, until ${at2(run2.keepUntil)}, then deleted. agental job keep ${name} ${run2.id} keeps it for good.
10937
+ if (run3.fresh === true && run3.keepUntil && run3.sandboxKept !== true && run3.sandboxId !== null) {
10938
+ process.stderr.write(`Its sandbox ${run3.sandboxId} is kept, stopped, until ${at2(run3.keepUntil)}, then deleted. agental job keep ${name} ${run3.id} keeps it for good.
10745
10939
  `);
10746
10940
  }
10747
10941
  }
10748
- var why = (run2) => run2.reason ? `: ${run2.reason.replace(/\.$/, "")}` : "";
10749
- function exitOf(run2) {
10750
- return run2.exitCode ?? (run2.outcome === "succeeded" ? 0 : 1);
10942
+ var why = (run3) => run3.reason ? `: ${run3.reason.replace(/\.$/, "")}` : "";
10943
+ function exitOf(run3) {
10944
+ return run3.exitCode ?? (run3.outcome === "succeeded" ? 0 : 1);
10751
10945
  }
10752
10946
  async function job(client, positionals, command2, options) {
10753
10947
  const [what, name, ...rest] = positionals;
@@ -10818,10 +11012,10 @@ async function job(client, positionals, command2, options) {
10818
11012
  if (name === void 0) {
10819
11013
  throw new Error(`job ${what} needs the job, by its name or id: agental job ${what} <job>`);
10820
11014
  }
10821
- const path5 = jobPath(name);
11015
+ const path6 = jobPath(name);
10822
11016
  switch (what) {
10823
11017
  case "get":
10824
- print3(await ask6(client, "GET", path5), options.json);
11018
+ print3(await ask6(client, "GET", path6), options.json);
10825
11019
  return;
10826
11020
  case "update": {
10827
11021
  const changes = { ...fieldsOf(options), ...options.name === void 0 ? {} : { name: options.name }, ...command2 !== null && command2.length > 0 ? { command: commandLine(command2) } : {} };
@@ -10830,43 +11024,43 @@ async function job(client, positionals, command2, options) {
10830
11024
  "job update needs something to change: --sandbox, --template (and --size), --keep-failed-for, --every, --cron, --at, --tz, --timeout, --overlap, --if-stopped, --keep-memory, --delete-after or --disk-only, --retries, --alerts, --max-monthly-spend, --input or --secret-input, --after-job, --on-mail or --no-events, --name for a new name, or a new command after --."
10831
11025
  );
10832
11026
  }
10833
- print3(await ask6(client, "PATCH", path5, changes), options.json);
11027
+ print3(await ask6(client, "PATCH", path6, changes), options.json);
10834
11028
  return;
10835
11029
  }
10836
11030
  case "delete":
10837
- await ask6(client, "DELETE", path5);
11031
+ await ask6(client, "DELETE", path6);
10838
11032
  process.stdout.write(`Deleted job ${name}, with its runs.
10839
11033
  `);
10840
11034
  return;
10841
11035
  case "pause":
10842
11036
  case "resume":
10843
- print3(await ask6(client, "PATCH", path5, { enabled: what === "resume" }), options.json);
11037
+ print3(await ask6(client, "PATCH", path6, { enabled: what === "resume" }), options.json);
10844
11038
  return;
10845
11039
  case "runs": {
10846
11040
  const limit = options.limit === void 0 ? "" : `?limit=${encodeURIComponent(options.limit)}`;
10847
- const retries = options.json ? 0 : (await ask6(client, "GET", path5))?.retries ?? 0;
10848
- const runs = (await ask6(client, "GET", `${path5}/runs${limit}`))?.runs ?? [];
11041
+ const retries = options.json ? 0 : (await ask6(client, "GET", path6))?.retries ?? 0;
11042
+ const runs = (await ask6(client, "GET", `${path6}/runs${limit}`))?.runs ?? [];
10849
11043
  if (options.json) {
10850
11044
  json(runs);
10851
11045
  } else if (runs.length === 0) {
10852
11046
  process.stdout.write(`No runs yet. agental job run ${name} runs it now.
10853
11047
  `);
10854
11048
  } else {
10855
- const tries = retries > 0 || runs.some((run2) => (run2.attempt ?? 1) > 1);
10856
- const outcomeOf = (run2) => tries && run2.failedForGood === true ? `${run2.outcome}, for good` : run2.outcome;
10857
- const tryOf = (run2) => `${run2.attempt ?? 1} of ${Math.max(retries + 1, run2.attempt ?? 1)}`;
11049
+ const tries = retries > 0 || runs.some((run3) => (run3.attempt ?? 1) > 1);
11050
+ const outcomeOf = (run3) => tries && run3.failedForGood === true ? `${run3.outcome}, for good` : run3.outcome;
11051
+ const tryOf = (run3) => `${run3.attempt ?? 1} of ${Math.max(retries + 1, run3.attempt ?? 1)}`;
10858
11052
  table2([
10859
11053
  ["RUN", "DUE", ...tries ? ["TRY"] : [], "OUTCOME", "EXIT", "TOOK", "SANDBOX", "BY", "WHY"],
10860
- ...runs.map((run2) => [
10861
- run2.id,
10862
- past(run2.dueAt),
10863
- ...tries ? [tryOf(run2)] : [],
10864
- outcomeOf(run2),
10865
- run2.exitCode === null ? "-" : String(run2.exitCode),
10866
- tookOf(run2),
10867
- sandboxDoneOf(run2),
10868
- BY[run2.startedBy] ?? run2.startedBy,
10869
- run2.reason ?? ""
11054
+ ...runs.map((run3) => [
11055
+ run3.id,
11056
+ past(run3.dueAt),
11057
+ ...tries ? [tryOf(run3)] : [],
11058
+ outcomeOf(run3),
11059
+ run3.exitCode === null ? "-" : String(run3.exitCode),
11060
+ tookOf(run3),
11061
+ sandboxDoneOf(run3),
11062
+ BY[run3.startedBy] ?? run3.startedBy,
11063
+ run3.reason ?? ""
10870
11064
  ])
10871
11065
  ]);
10872
11066
  }
@@ -10875,23 +11069,23 @@ async function job(client, positionals, command2, options) {
10875
11069
  case "logs": {
10876
11070
  let runId = rest[0];
10877
11071
  if (runId === void 0) {
10878
- const latest = (await ask6(client, "GET", `${path5}/runs?limit=1`))?.runs?.[0];
11072
+ const latest = (await ask6(client, "GET", `${path6}/runs?limit=1`))?.runs?.[0];
10879
11073
  if (latest === void 0) {
10880
11074
  throw new Error(`Job ${name} has not run yet. agental job run ${name} runs it now.`);
10881
11075
  }
10882
11076
  runId = latest.id;
10883
11077
  }
10884
- const run2 = await ask6(client, "GET", `${path5}/runs/${encodeURIComponent(runId)}`);
11078
+ const run3 = await ask6(client, "GET", `${path6}/runs/${encodeURIComponent(runId)}`);
10885
11079
  if (options.json) {
10886
- json(run2);
11080
+ json(run3);
10887
11081
  return;
10888
11082
  }
10889
- writeOutput(run2);
10890
- if (run2.outcome === "running") {
10891
- process.stderr.write(faint(`Run ${run2.id} is still running: this is its output so far.
11083
+ writeOutput(run3);
11084
+ if (run3.outcome === "running") {
11085
+ process.stderr.write(faint(`Run ${run3.id} is still running: this is its output so far.
10892
11086
  `, process.stderr));
10893
11087
  }
10894
- writeNotes(run2, name);
11088
+ writeNotes(run3, name);
10895
11089
  return;
10896
11090
  }
10897
11091
  case "keep": {
@@ -10899,11 +11093,11 @@ async function job(client, positionals, command2, options) {
10899
11093
  if (runId === void 0) {
10900
11094
  throw new Error(`job keep needs the run whose fresh sandbox to keep: agental job keep ${name} <run-id>, as job runs ${name} lists them.`);
10901
11095
  }
10902
- const run2 = await ask6(client, "POST", `${path5}/runs/${encodeURIComponent(runId)}/keep-sandbox`);
11096
+ const run3 = await ask6(client, "POST", `${path6}/runs/${encodeURIComponent(runId)}/keep-sandbox`);
10903
11097
  if (options.json) {
10904
- json(run2);
11098
+ json(run3);
10905
11099
  } else {
10906
- process.stdout.write(`Kept ${run2.sandboxId ?? "the sandbox"} of run ${run2.id}: it is an ordinary sandbox now, out of the job, and is deleted only by you.
11100
+ process.stdout.write(`Kept ${run3.sandboxId ?? "the sandbox"} of run ${run3.id}: it is an ordinary sandbox now, out of the job, and is deleted only by you.
10907
11101
  `);
10908
11102
  }
10909
11103
  return;
@@ -10911,7 +11105,7 @@ async function job(client, positionals, command2, options) {
10911
11105
  case "run": {
10912
11106
  const inputs = runInputsOf(options);
10913
11107
  const query = options.wait ? `?wait=${waitSecondsOf(options)}` : "";
10914
- await follow(client, name, path5, await answer(client, "POST", `${path5}/run${query}`, inputs === void 0 ? void 0 : { inputs }), options);
11108
+ await follow(client, name, path6, await answer(client, "POST", `${path6}/run${query}`, inputs === void 0 ? void 0 : { inputs }), options);
10915
11109
  return;
10916
11110
  }
10917
11111
  case "again": {
@@ -10920,47 +11114,47 @@ async function job(client, positionals, command2, options) {
10920
11114
  throw new Error(`job again needs the run whose inputs to run it with again: agental job again ${name} <run-id>, as job runs ${name} lists them.`);
10921
11115
  }
10922
11116
  const query = options.wait ? `?wait=${waitSecondsOf(options)}` : "";
10923
- await follow(client, name, path5, await answer(client, "POST", `${path5}/runs/${encodeURIComponent(runId)}/again${query}`), options);
11117
+ await follow(client, name, path6, await answer(client, "POST", `${path6}/runs/${encodeURIComponent(runId)}/again${query}`), options);
10924
11118
  return;
10925
11119
  }
10926
11120
  }
10927
11121
  }
10928
- async function follow(client, name, path5, made, options) {
10929
- let run2 = made.body;
11122
+ async function follow(client, name, path6, made, options) {
11123
+ let run3 = made.body;
10930
11124
  if (!options.wait) {
10931
11125
  if (options.json) {
10932
- json(run2);
11126
+ json(run3);
10933
11127
  } else {
10934
- process.stdout.write(run2.outcome === "running" ? `Run ${run2.id} started. agental job logs ${name} ${run2.id} prints its output.
10935
- ` : `Run ${run2.id} ${run2.outcome}${run2.reason ? `: ${run2.reason}` : ""}
11128
+ process.stdout.write(run3.outcome === "running" ? `Run ${run3.id} started. agental job logs ${name} ${run3.id} prints its output.
11129
+ ` : `Run ${run3.id} ${run3.outcome}${run3.reason ? `: ${run3.reason}` : ""}
10936
11130
  `);
10937
11131
  }
10938
11132
  return;
10939
11133
  }
10940
11134
  if (made.status !== 200) {
10941
- if (!options.json && run2.outcome === "running") {
10942
- process.stderr.write(faint(`Run ${run2.id} is still running; waiting for it to end.
11135
+ if (!options.json && run3.outcome === "running") {
11136
+ process.stderr.write(faint(`Run ${run3.id} is still running; waiting for it to end.
10943
11137
  `, process.stderr));
10944
11138
  }
10945
11139
  for (; ; ) {
10946
- run2 = await ask6(client, "GET", `${path5}/runs/${encodeURIComponent(run2.id)}`);
10947
- if (run2.outcome !== "running") {
11140
+ run3 = await ask6(client, "GET", `${path6}/runs/${encodeURIComponent(run3.id)}`);
11141
+ if (run3.outcome !== "running") {
10948
11142
  break;
10949
11143
  }
10950
11144
  await new Promise((resolve) => setTimeout(resolve, POLL_MS));
10951
11145
  }
10952
11146
  }
10953
11147
  if (options.json) {
10954
- json(run2);
11148
+ json(run3);
10955
11149
  } else {
10956
- writeOutput(run2);
10957
- if (run2.outcome !== "succeeded" && (run2.stdout != null || run2.stderr != null)) {
10958
- process.stderr.write(`Run ${run2.id} ${run2.outcome}${run2.exitCode === null ? "" : ` (exit ${run2.exitCode})`}${why(run2)}.
11150
+ writeOutput(run3);
11151
+ if (run3.outcome !== "succeeded" && (run3.stdout != null || run3.stderr != null)) {
11152
+ process.stderr.write(`Run ${run3.id} ${run3.outcome}${run3.exitCode === null ? "" : ` (exit ${run3.exitCode})`}${why(run3)}.
10959
11153
  `);
10960
11154
  }
10961
- writeNotes(run2, name);
11155
+ writeNotes(run3, name);
10962
11156
  }
10963
- process.exitCode = exitOf(run2);
11157
+ process.exitCode = exitOf(run3);
10964
11158
  }
10965
11159
  var SIGNATURES = ["bearer", "github", "stripe", "hmac-sha256"];
10966
11160
  var RESPONDS = ["accepted", "wait"];
@@ -11048,8 +11242,8 @@ async function trigger(client, verb, rest, options) {
11048
11242
  if ((options.respond !== void 0 || options.rate !== void 0) && verb !== "add" && verb !== "update") {
11049
11243
  throw new Error("--respond and --rate go with job trigger add or update.");
11050
11244
  }
11051
- const path5 = `${jobPath(name)}/triggers`;
11052
- const one = (id) => `${path5}/${encodeURIComponent(id)}`;
11245
+ const path6 = `${jobPath(name)}/triggers`;
11246
+ const one = (id) => `${path6}/${encodeURIComponent(id)}`;
11053
11247
  switch (verb) {
11054
11248
  case "add": {
11055
11249
  if (options.signature !== void 0 && !SIGNATURES.includes(options.signature)) {
@@ -11063,12 +11257,12 @@ async function trigger(client, verb, rest, options) {
11063
11257
  throw new Error("--header names the header an hmac-sha256 signature is sent in, and goes with --signature hmac-sha256: GitHub's and Stripe's have their own.");
11064
11258
  }
11065
11259
  const body = { ...options.signature === void 0 ? {} : { signature: options.signature }, ...header === void 0 ? {} : { header }, ...triggerFieldsOf(options) };
11066
- printSecret(await ask6(client, "POST", path5, body), options);
11260
+ printSecret(await ask6(client, "POST", path6, body), options);
11067
11261
  return;
11068
11262
  }
11069
11263
  case "list":
11070
11264
  case "url": {
11071
- const triggers = (await ask6(client, "GET", path5))?.triggers ?? [];
11265
+ const triggers = (await ask6(client, "GET", path6))?.triggers ?? [];
11072
11266
  const chosen = triggerId === void 0 ? triggers : triggers.filter((each) => each.id === triggerId);
11073
11267
  if (triggerId !== void 0 && chosen.length === 0) {
11074
11268
  throw new Error(`Job ${name} has no trigger ${triggerId}. agental job trigger list ${name} lists its triggers.`);
@@ -11178,17 +11372,17 @@ function byEvents(jobs2) {
11178
11372
  const named = new Map(jobs2.map((each) => [each.name, each]));
11179
11373
  const done2 = /* @__PURE__ */ new Set();
11180
11374
  const ordered2 = [];
11181
- const visit = (each, path5) => {
11182
- if (done2.has(each.name) || path5.has(each.name)) {
11375
+ const visit = (each, path6) => {
11376
+ if (done2.has(each.name) || path6.has(each.name)) {
11183
11377
  return;
11184
11378
  }
11185
- path5.add(each.name);
11379
+ path6.add(each.name);
11186
11380
  const events = Array.isArray(each.body["events"]) ? each.body["events"] : [];
11187
11381
  for (const event of events) {
11188
11382
  const job2 = event !== null && typeof event === "object" ? event["job"] : void 0;
11189
11383
  const before = typeof job2 === "string" ? named.get(job2) : void 0;
11190
11384
  if (before !== void 0) {
11191
- visit(before, path5);
11385
+ visit(before, path6);
11192
11386
  }
11193
11387
  }
11194
11388
  done2.add(each.name);
@@ -11202,7 +11396,7 @@ function byEvents(jobs2) {
11202
11396
  function fileJobsOf(file) {
11203
11397
  let text;
11204
11398
  try {
11205
- text = readFileSync5(file === "-" ? 0 : file, "utf8");
11399
+ text = readFileSync6(file === "-" ? 0 : file, "utf8");
11206
11400
  } catch (error) {
11207
11401
  throw new Error(`Could not read ${file}: ${error instanceof Error ? error.message : String(error)}`);
11208
11402
  }
@@ -11217,8 +11411,8 @@ function fileJobsOf(file) {
11217
11411
  throw new Error(`${file} has no jobs: list. It is a map whose jobs: lists each job, with its name, command, and sandbox or template.`);
11218
11412
  }
11219
11413
  const jobs2 = listed.map((item, index) => fileJobOf(item, index));
11220
- const names = jobs2.map((each) => each.name);
11221
- const twice = names.filter((each, index) => names.indexOf(each) !== index);
11414
+ const names2 = jobs2.map((each) => each.name);
11415
+ const twice = names2.filter((each, index) => names2.indexOf(each) !== index);
11222
11416
  if (twice.length > 0) {
11223
11417
  throw new Error(`${file} lists ${[...new Set(twice)].join(", ")} more than once: each job is listed once, by its name.`);
11224
11418
  }
@@ -11241,9 +11435,9 @@ async function apply(client, file, options) {
11241
11435
  };
11242
11436
  if (options["dry-run"]) {
11243
11437
  const there = (await ask6(client, "GET", "/v1/jobs"))?.jobs ?? [];
11244
- const names = new Set(there.map((each) => each.name));
11438
+ const names2 = new Set(there.map((each) => each.name));
11245
11439
  for (const each of jobs2) {
11246
- say(names.has(each.name) ? "would_put" : "would_make", each.name);
11440
+ say(names2.has(each.name) ? "would_put" : "would_make", each.name);
11247
11441
  }
11248
11442
  if (options.prune) {
11249
11443
  const orgs = new Set(there.filter((one) => named.has(one.name)).map(orgOf));
@@ -11307,7 +11501,9 @@ var LIFECYCLE_EVENTS = [
11307
11501
  "sandbox.deleted",
11308
11502
  "sandbox.auto_stop_set",
11309
11503
  "sandbox.labels_changed",
11310
- "sandbox.low_cpu"
11504
+ "sandbox.low_cpu",
11505
+ "sandbox.upgraded",
11506
+ "sandbox.reclaim_chance"
11311
11507
  ];
11312
11508
  var WEBHOOK_EVENTS = [...LIFECYCLE_EVENTS, "prompt.created"];
11313
11509
  var EMAIL_EVENTS = ["email.received", "email.delivered", "email.bounced"];
@@ -11941,15 +12137,15 @@ function clamp(value, fallback) {
11941
12137
  function sizeOf(stdout) {
11942
12138
  return stdout.isTTY ? { cols: clamp(stdout.columns, 80), rows: clamp(stdout.rows, 24) } : { cols: 80, rows: 24 };
11943
12139
  }
11944
- function webSocketUrl(base, path5) {
11945
- if (typeof path5 !== "string" || !path5.startsWith("/") || path5.startsWith("//") || /[\\\s]/.test(path5)) {
12140
+ function webSocketUrl(base, path6) {
12141
+ if (typeof path6 !== "string" || !path6.startsWith("/") || path6.startsWith("//") || /[\\\s]/.test(path6)) {
11946
12142
  throw new Error("The API gave the terminal a path that is not one on its own address.");
11947
12143
  }
11948
12144
  const url = new URL(base);
11949
12145
  if (url.protocol !== "https:" && url.protocol !== "http:") {
11950
12146
  throw new Error(`A terminal is opened on an http: or https: API, not ${url.protocol}`);
11951
12147
  }
11952
- return `${url.protocol === "https:" ? "wss:" : "ws:"}//${url.host}${url.pathname.replace(/\/+$/, "")}${path5}`;
12148
+ return `${url.protocol === "https:" ? "wss:" : "ws:"}//${url.host}${url.pathname.replace(/\/+$/, "")}${path6}`;
11953
12149
  }
11954
12150
  function whyClosed(code, reason, error) {
11955
12151
  const said = error?.message || reason;
@@ -12262,6 +12458,18 @@ var MACHINE_SIZES = {
12262
12458
  large: { vcpu: 8, memoryMb: 16384, diskGb: 160 }
12263
12459
  };
12264
12460
  var MACHINE_SIZE_NAMES = ["tiny", "small", "medium", "large"];
12461
+ var LIST_PRICE_MICROS_PER_HOUR = {
12462
+ tiny: 13500,
12463
+ small: 27e3,
12464
+ medium: 54e3,
12465
+ large: 108e3
12466
+ };
12467
+ var SPOT_PRICE_MICROS_PER_HOUR = {
12468
+ tiny: LIST_PRICE_MICROS_PER_HOUR.tiny / 2,
12469
+ small: LIST_PRICE_MICROS_PER_HOUR.small / 2,
12470
+ medium: LIST_PRICE_MICROS_PER_HOUR.medium / 2,
12471
+ large: LIST_PRICE_MICROS_PER_HOUR.large / 2
12472
+ };
12265
12473
  var HOURS_PER_MONTH = 730;
12266
12474
  var STOPPED_MICROS_PER_GB_MONTH = 5e4;
12267
12475
  var BYTES_PER_GB = 1e9;
@@ -12332,14 +12540,15 @@ var METRICS_STEP_SECONDS = 60;
12332
12540
 
12333
12541
  // ../src/plans.ts
12334
12542
  var MICROS_PER_DOLLAR = 1e6;
12335
- function plan(id, dollarsPerMonth, sizes, runningUnits, freeBurstUnits) {
12336
- return { id, dollarsPerMonth, includedMicros: dollarsPerMonth * MICROS_PER_DOLLAR, sizes, runningUnits, freeBurstUnits };
12543
+ var FREE_STARTS_PER_RUNNING = 3;
12544
+ function plan(id, dollarsPerMonth, sizes, runningUnits) {
12545
+ return { id, dollarsPerMonth, includedMicros: dollarsPerMonth * MICROS_PER_DOLLAR, sizes, runningUnits, freeBurstUnits: runningUnits * FREE_STARTS_PER_RUNNING };
12337
12546
  }
12338
- var FREE_PLAN = plan("free", 0, ["tiny", "small"], 20, 20);
12547
+ var FREE_PLAN = plan("free", 0, ["tiny", "small"], 40);
12339
12548
  var PAID_PLANS = [
12340
- plan("plan100", 100, ["tiny", "small", "medium"], 100, 100),
12341
- plan("plan500", 500, MACHINE_SIZE_NAMES, 600, 200),
12342
- plan("plan2000", 2e3, MACHINE_SIZE_NAMES, 2e3, 400)
12549
+ plan("plan100", 100, ["tiny", "small", "medium"], 200),
12550
+ plan("plan500", 500, MACHINE_SIZE_NAMES, 1200),
12551
+ plan("plan2000", 2e3, MACHINE_SIZE_NAMES, 4e3)
12343
12552
  ];
12344
12553
  var PLANS = [FREE_PLAN, ...PAID_PLANS];
12345
12554
  var PLAN_NAMES = { free: "Free", plan100: "Fleet", plan500: "Platform", plan2000: "Scale" };
@@ -12468,18 +12677,19 @@ var SSH_COMMANDS = {
12468
12677
  };
12469
12678
  async function setUp(args) {
12470
12679
  const [command2, ...rest] = args;
12471
- const onboarding = command2 === void 0 || command2 === "sh" || command2 === "--no-skills" || command2 === "--no-install" || command2 === "--json";
12680
+ const onboarding = command2 === void 0 || command2 === "sh" || command2 === "--no-skills" || command2 === "--no-install" || command2 === "--no-mcp" || command2 === "--json";
12472
12681
  if (onboarding) {
12473
12682
  const flags2 = command2 === "sh" ? rest : args;
12474
- const unknown = flags2.filter((flag) => !["--json", "--no-skills", "--no-install"].includes(flag));
12683
+ const unknown = flags2.filter((flag) => !["--json", "--no-skills", "--no-install", "--no-mcp"].includes(flag));
12475
12684
  if (unknown.length > 0) {
12476
- throw new Error(`${command2 === "sh" ? "sh" : "agental"} takes --json, --no-skills and --no-install, not ${unknown.join(" ")}`);
12685
+ throw new Error(`${command2 === "sh" ? "sh" : "agental"} takes --json, --no-skills, --no-install and --no-mcp, not ${unknown.join(" ")}`);
12477
12686
  }
12478
12687
  await onboard(apiBase(), {
12479
12688
  sandbox: command2 === "sh",
12480
12689
  json: flags2.includes("--json"),
12481
12690
  installCommand: !flags2.includes("--no-install"),
12482
- installSkills: !flags2.includes("--no-skills")
12691
+ installSkills: !flags2.includes("--no-skills"),
12692
+ installConnector: !flags2.includes("--no-mcp")
12483
12693
  });
12484
12694
  return true;
12485
12695
  }
@@ -12695,6 +12905,10 @@ async function main() {
12695
12905
  ttl: { type: "string" },
12696
12906
  // agental create: what its time limit does when it runs out, delete or stop.
12697
12907
  "on-timeout": { type: "string" },
12908
+ // agental create and agental spot: a spot sandbox, what is done when its room is taken back, and the chance it is warned at.
12909
+ spot: { type: "boolean", default: false },
12910
+ "on-reclaim": { type: "string" },
12911
+ "warn-at": { type: "string" },
12698
12912
  "max-burst-fee": { type: "string" },
12699
12913
  in: { type: "string" },
12700
12914
  never: { type: "boolean", default: false },
@@ -12878,6 +13092,9 @@ async function main() {
12878
13092
  case "egress":
12879
13093
  await egress(positionals.slice(1), values);
12880
13094
  return;
13095
+ case "spot":
13096
+ await spot(positionals.slice(1), values);
13097
+ return;
12881
13098
  case "templates":
12882
13099
  await listTemplates(values.json);
12883
13100
  return;
@@ -12990,6 +13207,10 @@ async function create(values) {
12990
13207
  if (values.size !== void 0 && !isMachineSize(values.size)) {
12991
13208
  throw new Error("--size must be tiny, small, medium or large");
12992
13209
  }
13210
+ if (!values.spot && (values["on-reclaim"] !== void 0 || values["warn-at"] !== void 0)) {
13211
+ throw new Error("--on-reclaim and --warn-at are for a spot sandbox: add --spot.");
13212
+ }
13213
+ const spotAsked = values.spot ? spotSettingsFrom(values) : void 0;
12993
13214
  if (values.outbound !== void 0) {
12994
13215
  throw new Error(
12995
13216
  "--outbound is gone: a sandbox's rule comes from its template. Set it with agental template network <template> open|blocked|allowlist <address>..., and make the sandbox with --template <template>. --allow gives it addresses of its own on top."
@@ -13013,6 +13234,7 @@ async function create(values) {
13013
13234
  ...egressAsked ? { egress: egressAsked } : {},
13014
13235
  ...ttlSeconds === void 0 ? {} : { ttlSeconds },
13015
13236
  ...onTimeout === void 0 ? {} : { onTimeout: onTimeout.replaceAll("-", "_") },
13237
+ ...spotAsked === void 0 ? {} : { spot: spotAsked },
13016
13238
  ...sshKeys2 === void 0 ? {} : { sshKeys: sshKeys2 },
13017
13239
  ...given
13018
13240
  })
@@ -13048,7 +13270,7 @@ function maxBurstFeeHeaders(given) {
13048
13270
  function sayBurstFee(response) {
13049
13271
  const micros = Number(response.headers.get("Agental-Burst-Fee") ?? "0");
13050
13272
  if (micros > 0) {
13051
- 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.
13273
+ process.stderr.write(`This start cost a burst fee of ${money(micros)}: the account started more than its plan's free starts in the last 15 minutes. Starts are free again within 15 minutes; agental headroom says the minute.
13052
13274
  `);
13053
13275
  }
13054
13276
  }
@@ -13063,17 +13285,17 @@ async function sshKeys(id, keyId, remove3, json2) {
13063
13285
  if (!id) {
13064
13286
  throw new Error("ssh-keys requires <sandbox-id>");
13065
13287
  }
13066
- const path5 = `/v1/sandboxes/${encodeURIComponent(id)}/ssh/keys`;
13288
+ const path6 = `/v1/sandboxes/${encodeURIComponent(id)}/ssh/keys`;
13067
13289
  if (remove3) {
13068
13290
  if (!keyId) {
13069
13291
  throw new Error("ssh-keys --remove requires <key-id>, as ssh-keys lists it");
13070
13292
  }
13071
- await call2(`${path5}/${encodeURIComponent(keyId)}`, { method: "DELETE" });
13293
+ await call2(`${path6}/${encodeURIComponent(keyId)}`, { method: "DELETE" });
13072
13294
  process.stdout.write(`${keyId} may log in to ${id} no longer.
13073
13295
  `);
13074
13296
  return;
13075
13297
  }
13076
- const body = await call2(path5, { method: "GET" });
13298
+ const body = await call2(path6, { method: "GET" });
13077
13299
  const keys = body?.keys ?? [];
13078
13300
  if (json2) {
13079
13301
  process.stdout.write(`${JSON.stringify(keys, null, 2)}
@@ -13087,10 +13309,10 @@ function publicKeysFrom(given) {
13087
13309
  if (SSH_PUBLIC_KEY.test(each.trim())) {
13088
13310
  return [each.trim()];
13089
13311
  }
13090
- const file = each.startsWith("~/") ? `${os6.homedir()}${each.slice(1)}` : each;
13312
+ const file = each.startsWith("~/") ? `${os7.homedir()}${each.slice(1)}` : each;
13091
13313
  let text;
13092
13314
  try {
13093
- text = readFileSync6(file, "utf8");
13315
+ text = readFileSync7(file, "utf8");
13094
13316
  } catch {
13095
13317
  throw new Error(`${each} is neither a public key nor a file that can be read. Give a key line, as ssh-ed25519 AAAA... you@laptop, or its file, as ~/.ssh/id_ed25519.pub.`);
13096
13318
  }
@@ -13176,9 +13398,9 @@ async function list2(asJson, filter, sort, limit, wide = false) {
13176
13398
  process.stdout.write(filter.size > 0 ? "No sandboxes match.\n" : "No sandboxes.\n");
13177
13399
  return;
13178
13400
  }
13179
- const names = sandboxes2.some((sandbox) => typeof sandbox["templateId"] === "string") ? await templateNames() : /* @__PURE__ */ new Map();
13401
+ const names2 = sandboxes2.some((sandbox) => typeof sandbox["templateId"] === "string") ? await templateNames() : /* @__PURE__ */ new Map();
13180
13402
  if (isTerminal(process.stdout) && !wide) {
13181
- process.stdout.write(sandboxesForPeople(sandboxes2, names, sort !== void 0));
13403
+ process.stdout.write(sandboxesForPeople(sandboxes2, names2, sort !== void 0));
13182
13404
  return;
13183
13405
  }
13184
13406
  const tagged = sandboxes2.some((sandbox) => Array.isArray(sandbox["tags"]));
@@ -13195,7 +13417,7 @@ async function list2(asJson, filter, sort, limit, wide = false) {
13195
13417
  pad2(typeof sandbox["pendingSize"] === "string" ? `${String(sandbox["size"] ?? "")}>${sandbox["pendingSize"]}` : String(sandbox["size"] ?? "")),
13196
13418
  pad2(String(sandbox["status"] ?? "")),
13197
13419
  sandbox["vmIsolation"] === true ? "yes" : "no ",
13198
- pad2(templateId === null ? "-" : names.get(templateId) ?? templateId),
13420
+ pad2(templateId === null ? "-" : names2.get(templateId) ?? templateId),
13199
13421
  // An API from before sandboxes said their rule says nothing, and nothing is shown for it.
13200
13422
  (tagged ? pad2 : (word) => word)(rule && typeof rule === "object" ? String(rule["outbound"] ?? "") : ""),
13201
13423
  ...tagged ? [Array.isArray(sandbox["tags"]) && sandbox["tags"].length > 0 ? sandbox["tags"].join(",") : "-"] : []
@@ -13292,8 +13514,8 @@ async function bulk(action, filter, options, yes2, asJson, confirm) {
13292
13514
  `);
13293
13515
  const pausing = read2.jobsPaused ?? 0;
13294
13516
  if (pausing > 0) {
13295
- const names = read2.jobsPausedNames ?? [];
13296
- process.stderr.write(`It pauses ${pausing} ${pausing === 1 ? "job" : "jobs"} that run in them: ${names.join(", ")}${pausing > names.length ? `, and ${pausing - names.length} more` : ""}.
13517
+ const names2 = read2.jobsPausedNames ?? [];
13518
+ process.stderr.write(`It pauses ${pausing} ${pausing === 1 ? "job" : "jobs"} that run in them: ${names2.join(", ")}${pausing > names2.length ? `, and ${pausing - names2.length} more` : ""}.
13297
13519
  `);
13298
13520
  }
13299
13521
  let count = null;
@@ -13339,11 +13561,11 @@ async function bulk(action, filter, options, yes2, asJson, confirm) {
13339
13561
  }
13340
13562
  async function bulkActionsCommand(positionals, asJson) {
13341
13563
  const [verb, id] = positionals;
13342
- const path5 = verb === void 0 || verb === "list" ? "/v1/bulk-actions" : verb === "show" && id ? `/v1/bulk-actions/${encodeURIComponent(id)}` : verb === "cancel" && id ? `/v1/bulk-actions/${encodeURIComponent(id)}/cancel` : null;
13343
- if (path5 === null) {
13564
+ const path6 = verb === void 0 || verb === "list" ? "/v1/bulk-actions" : verb === "show" && id ? `/v1/bulk-actions/${encodeURIComponent(id)}` : verb === "cancel" && id ? `/v1/bulk-actions/${encodeURIComponent(id)}/cancel` : null;
13565
+ if (path6 === null) {
13344
13566
  throw new Error("bulk-actions takes list, show <id> or cancel <id>");
13345
13567
  }
13346
- const response = await request(path5, { method: verb === "cancel" ? "POST" : "GET" });
13568
+ const response = await request(path6, { method: verb === "cancel" ? "POST" : "GET" });
13347
13569
  const body = await readBody(response);
13348
13570
  if (!response.ok) {
13349
13571
  fail(response.status, body);
@@ -13470,8 +13692,8 @@ async function resize(id, size2, now, cancel, maxBurstFee, asJson) {
13470
13692
  throw new Error("--max-burst-fee goes with --now: it caps what the restart's start pays in burst fees");
13471
13693
  }
13472
13694
  const headers = maxBurstFeeHeaders(maxBurstFee);
13473
- const path5 = `/v1/sandboxes/${encodeURIComponent(id)}`;
13474
- const before = await call2(path5, { method: "GET" });
13695
+ const path6 = `/v1/sandboxes/${encodeURIComponent(id)}`;
13696
+ const before = await call2(path6, { method: "GET" });
13475
13697
  const name = before.name || id;
13476
13698
  const print4 = (sandbox, line) => process.stdout.write(asJson ? `${JSON.stringify(sandbox, null, 2)}
13477
13699
  ` : `${line}
@@ -13487,11 +13709,11 @@ async function resize(id, size2, now, cancel, maxBurstFee, asJson) {
13487
13709
  process.stderr.write(`Restarting ${name} as a ${to}: every process in it ends, as on a stop. Its files stay.
13488
13710
  `);
13489
13711
  }
13490
- const response = await request(`${path5}/resize`, { method: "POST", headers: restart ? headers : {}, body: JSON.stringify({ size: to, ...restart ? { restart: true } : {} }) });
13712
+ const response = await request(`${path6}/resize`, { method: "POST", headers: restart ? headers : {}, body: JSON.stringify({ size: to, ...restart ? { restart: true } : {} }) });
13491
13713
  const body = await readBody(response);
13492
13714
  if (!response.ok) {
13493
13715
  if (cancel && response.status === 409 && isApiError(body) && body.error.code === "size_smaller") {
13494
- const read2 = await call2(path5, { method: "GET" });
13716
+ const read2 = await call2(path6, { method: "GET" });
13495
13717
  print4(read2, `${read2.name || id} is already a ${read2.size}; nothing was waiting.`);
13496
13718
  return;
13497
13719
  }
@@ -13644,18 +13866,18 @@ async function autoStop(id, inText, at4, never, asJson) {
13644
13866
  if ([inText !== void 0, at4 !== void 0, never].filter(Boolean).length > 1) {
13645
13867
  throw new Error("--in, --at and --never say different things: give one.");
13646
13868
  }
13647
- const path5 = `/v1/sandboxes/${encodeURIComponent(id)}/auto-stop`;
13869
+ const path6 = `/v1/sandboxes/${encodeURIComponent(id)}/auto-stop`;
13648
13870
  let body;
13649
13871
  if (never) {
13650
- body = await call2(path5, { method: "DELETE" });
13872
+ body = await call2(path6, { method: "DELETE" });
13651
13873
  } else if (inText === void 0 && at4 === void 0) {
13652
- body = await call2(path5, { method: "GET" });
13874
+ body = await call2(path6, { method: "GET" });
13653
13875
  } else {
13654
13876
  const inSeconds = inText === void 0 ? void 0 : seconds(inText);
13655
13877
  if (inSeconds === null) {
13656
13878
  throw new Error("--in is a time from now, such as 30m, 2h or 1d");
13657
13879
  }
13658
- body = await call2(path5, { method: "PUT", body: JSON.stringify(inSeconds === void 0 ? { at: at4 } : { inSeconds }) });
13880
+ body = await call2(path6, { method: "PUT", body: JSON.stringify(inSeconds === void 0 ? { at: at4 } : { inSeconds }) });
13659
13881
  }
13660
13882
  if (asJson) {
13661
13883
  process.stdout.write(`${JSON.stringify(body, null, 2)}
@@ -13711,7 +13933,7 @@ async function screenshot(id, file, options) {
13711
13933
  fail(response.status, await readBody(response));
13712
13934
  }
13713
13935
  const picture = Buffer.from(await response.arrayBuffer());
13714
- writeFileSync4(file, picture);
13936
+ writeFileSync5(file, picture);
13715
13937
  const size2 = pictureSize(picture);
13716
13938
  process.stderr.write(`A picture of the screen of ${id} is in ${file}: ${size2 ? `${size2.width} by ${size2.height}, ` : ""}${picture.length} bytes.
13717
13939
  `);
@@ -13746,7 +13968,7 @@ async function clipboard(id, text) {
13746
13968
  process.stdout.write(String(body.text ?? ""));
13747
13969
  return;
13748
13970
  }
13749
- const given = text === "-" ? readFileSync6(0, "utf8") : text;
13971
+ const given = text === "-" ? readFileSync7(0, "utf8") : text;
13750
13972
  const response = await request(at4, { method: "PUT", body: JSON.stringify({ text: given }) });
13751
13973
  if (!response.ok) {
13752
13974
  fail(response.status, await readBody(response));
@@ -13920,10 +14142,10 @@ async function labels(what, holder, positionals, asJson) {
13920
14142
  throw new Error(`${command2} requires <${holder}>: ${usage}`);
13921
14143
  }
13922
14144
  const id = holder === "template" ? (await templateNamed(named)).id : named;
13923
- const path5 = `/v1/${holder === "template" ? "templates" : "sandboxes"}/${encodeURIComponent(id)}`;
14145
+ const path6 = `/v1/${holder === "template" ? "templates" : "sandboxes"}/${encodeURIComponent(id)}`;
13924
14146
  let body;
13925
14147
  if (action === void 0) {
13926
- body = await call2(path5, { method: "GET" });
14148
+ body = await call2(path6, { method: "GET" });
13927
14149
  } else if (what === "tags" && (action === "add" || action === "rm")) {
13928
14150
  const tags = listedIn(words2).map((tag) => tag.toLowerCase());
13929
14151
  if (tags.length === 0) {
@@ -13934,14 +14156,14 @@ async function labels(what, holder, positionals, asJson) {
13934
14156
  throw new Error(`A tag is lowercase letters, digits and hyphens, 1 to 63 characters, not starting or ending with a hyphen, not ${JSON.stringify(bad2)}.`);
13935
14157
  }
13936
14158
  for (const tag of tags) {
13937
- body = await call2(`${path5}/tags/${encodeURIComponent(tag)}`, { method: action === "add" ? "PUT" : "DELETE" });
14159
+ body = await call2(`${path6}/tags/${encodeURIComponent(tag)}`, { method: action === "add" ? "PUT" : "DELETE" });
13938
14160
  }
13939
14161
  } else if (what === "meta" && (action === "set" || action === "unset")) {
13940
14162
  if (words2.length === 0) {
13941
14163
  throw new Error(`${command2} ${action} requires ${action === "set" ? "<key>=<value>" : "<key>"}...`);
13942
14164
  }
13943
14165
  const metadata = action === "set" ? metadataGiven(words2) : Object.fromEntries(words2.map((key2) => [key2, null]));
13944
- body = await call2(path5, { method: "PATCH", body: JSON.stringify({ metadata }) });
14166
+ body = await call2(path6, { method: "PATCH", body: JSON.stringify({ metadata }) });
13945
14167
  } else {
13946
14168
  throw new Error(`${command2} takes ${usage}`);
13947
14169
  }
@@ -13968,9 +14190,9 @@ async function network(positionals, values) {
13968
14190
  if (values.allow !== void 0 && values.none) {
13969
14191
  throw new Error("--allow and --none say two things: give one.");
13970
14192
  }
13971
- const path5 = `/v1/sandboxes/${encodeURIComponent(id)}/network`;
14193
+ const path6 = `/v1/sandboxes/${encodeURIComponent(id)}/network`;
13972
14194
  const allow = values.none ? [] : values.allow === void 0 ? void 0 : listedIn(values.allow);
13973
- const body = await call2(path5, allow === void 0 ? { method: "GET" } : { method: "PUT", body: JSON.stringify({ allow }) });
14195
+ const body = await call2(path6, allow === void 0 ? { method: "GET" } : { method: "PUT", body: JSON.stringify({ allow }) });
13974
14196
  if (values.json) {
13975
14197
  process.stdout.write(`${JSON.stringify(body, null, 2)}
13976
14198
  `);
@@ -14046,12 +14268,55 @@ async function egress(positionals, values) {
14046
14268
  `);
14047
14269
  return;
14048
14270
  }
14049
- const path5 = `/v1/sandboxes/${encodeURIComponent(first)}/egress`;
14271
+ const path6 = `/v1/sandboxes/${encodeURIComponent(first)}/egress`;
14050
14272
  const how = `egress takes <sandbox-id>, and then nothing, box, or residential <country> [sticky|rotating], as agental egress ${first} residential de.`;
14051
- const body = await call2(path5, rest.length === 0 ? { method: "GET" } : { method: "PUT", body: JSON.stringify(egressFrom(rest, how)) });
14273
+ const body = await call2(path6, rest.length === 0 ? { method: "GET" } : { method: "PUT", body: JSON.stringify(egressFrom(rest, how)) });
14052
14274
  print4(body, `${first}: ${egressInWords(body)}
14053
14275
  `);
14054
14276
  }
14277
+ function spotSettingsFrom(values) {
14278
+ const onReclaim = values["on-reclaim"];
14279
+ if (onReclaim !== void 0 && onReclaim !== "delete" && onReclaim !== "stop" && onReclaim !== "upgrade") {
14280
+ throw new Error("--on-reclaim is delete, stop or upgrade: what is done to a spot sandbox when its room is taken back.");
14281
+ }
14282
+ const given = values["warn-at"];
14283
+ const percent = given?.endsWith("%") ? Number(given.slice(0, -1)) / 100 : Number(given);
14284
+ if (given !== void 0 && (!/^(\d+(\.\d+)?|\.\d+)%?$/.test(given) || percent > 1)) {
14285
+ throw new Error(`--warn-at is the chance of being stopped at which sandbox.reclaim_chance is sent, from 0 to 1 or 0% to 100%, as 0.5 or 50%. It was given ${given}.`);
14286
+ }
14287
+ return { ...onReclaim === void 0 ? {} : { onReclaim }, ...given === void 0 ? {} : { warnAt: percent } };
14288
+ }
14289
+ function spotInWords(sandbox) {
14290
+ const spot2 = sandbox?.["spot"];
14291
+ if (!spot2) {
14292
+ return "a normal sandbox, at the list price";
14293
+ }
14294
+ const done2 = {
14295
+ delete: "deleted when its room is taken back",
14296
+ stop: "stopped when its room is taken back, its disk kept",
14297
+ upgrade: "made normal at the list price when its room is taken back, or stopped where that frees nothing"
14298
+ };
14299
+ const chance = typeof spot2.reclaimChance === "number" ? `${Math.round(spot2.reclaimChance * 100)}% chance of being stopped in the next minute` : "no chance worked out while it is not running";
14300
+ const warnAt = typeof spot2.warnAt === "number" ? `, warned at ${Math.round(spot2.warnAt * 100)}%` : "";
14301
+ return `spot, ${done2[String(spot2.onReclaim)] ?? String(spot2.onReclaim)}; ${chance}${warnAt}`;
14302
+ }
14303
+ async function spot(positionals, values) {
14304
+ const [id, word, ...rest] = positionals;
14305
+ const how = "spot takes <sandbox-id>, and then nothing, normal, or --on-reclaim delete|stop|upgrade and --warn-at <chance>, as agental spot sbx_2a9a47e50daec64a --on-reclaim upgrade.";
14306
+ if (id === void 0 || rest.length > 0 || word !== void 0 && word !== "normal") {
14307
+ throw new Error(how);
14308
+ }
14309
+ const settings = spotSettingsFrom(values);
14310
+ if (word === "normal" && Object.keys(settings).length > 0) {
14311
+ throw new Error(how);
14312
+ }
14313
+ const path6 = `/v1/sandboxes/${encodeURIComponent(id)}`;
14314
+ const change = word === "normal" ? { spot: null } : Object.keys(settings).length > 0 ? { spot: settings } : null;
14315
+ const body = await call2(path6, change === null ? { method: "GET" } : { method: "PATCH", body: JSON.stringify(change) });
14316
+ process.stdout.write(values.json ? `${JSON.stringify(body?.["spot"] ?? null, null, 2)}
14317
+ ` : `${id}: ${spotInWords(body)}
14318
+ `);
14319
+ }
14055
14320
  function templateSshInWords(ssh2) {
14056
14321
  const keys = ssh2.keys.length === 1 ? "1 key" : `${ssh2.keys.length} keys`;
14057
14322
  return `${ssh2.enabled ? "on" : "off"} as a sandbox is made, ${keys} let in`;
@@ -14202,7 +14467,7 @@ async function template(positionals, values) {
14202
14467
  }
14203
14468
  case "start": {
14204
14469
  const found = await templateNamed(need(first, "<template>"));
14205
- const path5 = `/v1/templates/${encodeURIComponent(found.id)}/start`;
14470
+ const path6 = `/v1/templates/${encodeURIComponent(found.id)}/start`;
14206
14471
  if (values.snapshot !== void 0 && values["new-machine"]) {
14207
14472
  throw new Error("--snapshot and --new-machine say two things: give one.");
14208
14473
  }
@@ -14212,12 +14477,12 @@ async function template(positionals, values) {
14212
14477
  const ttlSeconds = ttlOption(values.ttl);
14213
14478
  let start;
14214
14479
  if (values.size === void 0 && values.snapshot === void 0 && !values["new-machine"] && ttlSeconds === void 0) {
14215
- start = await call2(path5, { method: "GET" });
14480
+ start = await call2(path6, { method: "GET" });
14216
14481
  } else {
14217
- const current = await call2(path5, { method: "GET" });
14482
+ const current = await call2(path6, { method: "GET" });
14218
14483
  const snapshotId = values["new-machine"] ? null : values.snapshot ?? current?.snapshotId ?? null;
14219
14484
  const ttl = ttlSeconds === void 0 ? current?.ttlSeconds ?? null : ttlSeconds;
14220
- start = await call2(path5, { method: "PUT", body: JSON.stringify({ size: values.size ?? current?.size, snapshotId, ttlSeconds: ttl }) });
14485
+ start = await call2(path6, { method: "PUT", body: JSON.stringify({ size: values.size ?? current?.size, snapshotId, ttlSeconds: ttl }) });
14221
14486
  }
14222
14487
  print4(start, `start: ${startInWords(start)}
14223
14488
  `);
@@ -14225,11 +14490,11 @@ async function template(positionals, values) {
14225
14490
  }
14226
14491
  case "network": {
14227
14492
  const found = await templateNamed(need(first, "<template>"));
14228
- const path5 = `/v1/templates/${encodeURIComponent(found.id)}/network`;
14493
+ const path6 = `/v1/templates/${encodeURIComponent(found.id)}/network`;
14229
14494
  const [mode, ...addresses] = rest;
14230
14495
  let rule;
14231
14496
  if (mode === void 0) {
14232
- rule = await call2(path5, { method: "GET" });
14497
+ rule = await call2(path6, { method: "GET" });
14233
14498
  } else {
14234
14499
  if (!OUTBOUND_MODES.some((known) => known === mode)) {
14235
14500
  throw new Error("template network requires <template>, and then nothing, open, blocked, or allowlist <address>...");
@@ -14241,7 +14506,7 @@ async function template(positionals, values) {
14241
14506
  if (mode === "allowlist" && listed.length === 0) {
14242
14507
  throw new Error(`allowlist needs at least one address, as agental template network ${first ?? ""} allowlist 203.0.113.7 198.51.100.0/24`);
14243
14508
  }
14244
- rule = await call2(path5, { method: "PUT", body: JSON.stringify(mode === "allowlist" ? { outbound: mode, allow: listed } : { outbound: mode }) });
14509
+ rule = await call2(path6, { method: "PUT", body: JSON.stringify(mode === "allowlist" ? { outbound: mode, allow: listed } : { outbound: mode }) });
14245
14510
  }
14246
14511
  print4(
14247
14512
  rule,
@@ -14252,37 +14517,37 @@ ${mode === void 0 ? "" : "A sandbox on it takes this when it next starts, or now
14252
14517
  }
14253
14518
  case "egress": {
14254
14519
  const found = await templateNamed(need(first, "<template>"));
14255
- const path5 = `/v1/templates/${encodeURIComponent(found.id)}/egress`;
14520
+ const path6 = `/v1/templates/${encodeURIComponent(found.id)}/egress`;
14256
14521
  const how = `template egress takes <template>, and then nothing, box, or residential <country> [sticky|rotating], as agental template egress ${first ?? ""} residential de.`;
14257
- const set = await call2(path5, rest.length === 0 ? { method: "GET" } : { method: "PUT", body: JSON.stringify(egressFrom(rest, how)) });
14522
+ const set = await call2(path6, rest.length === 0 ? { method: "GET" } : { method: "PUT", body: JSON.stringify(egressFrom(rest, how)) });
14258
14523
  print4(set, `${found.name}: ${egressInWords(set)}${rest.length === 0 ? "" : ", for sandboxes made from it from now on"}
14259
14524
  `);
14260
14525
  return;
14261
14526
  }
14262
14527
  case "ssh": {
14263
14528
  const found = await templateNamed(need(first, "<template>"));
14264
- const path5 = `/v1/templates/${encodeURIComponent(found.id)}/ssh`;
14529
+ const path6 = `/v1/templates/${encodeURIComponent(found.id)}/ssh`;
14265
14530
  const [turn] = rest;
14266
14531
  if (turn !== void 0 && turn !== "on" && turn !== "off") {
14267
14532
  throw new Error("template ssh requires <template>, and then nothing, on or off");
14268
14533
  }
14269
- const ssh2 = await call2(path5, { method: turn === "on" ? "PUT" : turn === "off" ? "DELETE" : "GET" });
14534
+ const ssh2 = await call2(path6, { method: turn === "on" ? "PUT" : turn === "off" ? "DELETE" : "GET" });
14270
14535
  print4(ssh2, `${found.name}: SSH ${templateSshInWords(ssh2)}
14271
14536
  `);
14272
14537
  return;
14273
14538
  }
14274
14539
  case "ssh-keys": {
14275
14540
  const found = await templateNamed(need(first, "<template>"));
14276
- const path5 = `/v1/templates/${encodeURIComponent(found.id)}/ssh/keys`;
14541
+ const path6 = `/v1/templates/${encodeURIComponent(found.id)}/ssh/keys`;
14277
14542
  if (values.remove) {
14278
14543
  const keyId = need(rest[0], "<template> --remove <key-id>");
14279
- await call2(`${path5}/${encodeURIComponent(keyId)}`, { method: "DELETE" });
14544
+ await call2(`${path6}/${encodeURIComponent(keyId)}`, { method: "DELETE" });
14280
14545
  process.stdout.write(`${keyId} is let in to no sandbox made from ${found.name} from now on. The sandboxes made already keep it.
14281
14546
  `);
14282
14547
  return;
14283
14548
  }
14284
14549
  for (const publicKey2 of publicKeysFrom(rest)) {
14285
- await call2(path5, { method: "POST", body: JSON.stringify({ publicKey: publicKey2 }) });
14550
+ await call2(path6, { method: "POST", body: JSON.stringify({ publicKey: publicKey2 }) });
14286
14551
  }
14287
14552
  const ssh2 = await call2(`/v1/templates/${encodeURIComponent(found.id)}/ssh`, { method: "GET" });
14288
14553
  if (values.json) {
@@ -14344,8 +14609,8 @@ up to date: ${body["upToDate"] === true ? "yes" : "no: it takes the template whe
14344
14609
  function keptOutInWords(variable) {
14345
14610
  return [`${variable.name} is kept out of the sandbox, and its value is never given back.`, `stand-in: ${variable.standIn}`, `hosts: ${variable.hosts.join(", ")}`, ""].join("\n");
14346
14611
  }
14347
- async function keptOutNow(path5) {
14348
- const response = await request(path5, { method: "GET" });
14612
+ async function keptOutNow(path6) {
14613
+ const response = await request(path6, { method: "GET" });
14349
14614
  const body = await readBody(response);
14350
14615
  if (response.status === 404) {
14351
14616
  return false;
@@ -14370,30 +14635,30 @@ async function secrets(positionals, values) {
14370
14635
  base = `/v1/sandboxes/${encodeURIComponent(sandboxId)}/secrets`;
14371
14636
  }
14372
14637
  const [action, ...args] = words2;
14373
- const fileQuery = (path5) => {
14374
- if (!path5) {
14638
+ const fileQuery = (path6) => {
14639
+ if (!path6) {
14375
14640
  throw new Error(`secrets ${action ?? ""} requires <path>`);
14376
14641
  }
14377
- return `${base}/files?path=${encodeURIComponent(path5)}`;
14642
+ return `${base}/files?path=${encodeURIComponent(path6)}`;
14378
14643
  };
14379
14644
  switch (action) {
14380
14645
  case void 0: {
14381
14646
  const listed = await call2(`${base}/variables`, { method: "GET" });
14382
- const names = listed.names;
14647
+ const names2 = listed.names;
14383
14648
  const hidden2 = listed.hidden ?? [];
14384
14649
  const paths = (await call2(`${base}/files`, { method: "GET" })).paths;
14385
14650
  if (values.json) {
14386
- process.stdout.write(`${JSON.stringify({ variables: names, hidden: hidden2, files: paths }, null, 2)}
14651
+ process.stdout.write(`${JSON.stringify({ variables: names2, hidden: hidden2, files: paths }, null, 2)}
14387
14652
  `);
14388
14653
  return;
14389
14654
  }
14390
- if (names.length === 0 && paths.length === 0) {
14655
+ if (names2.length === 0 && paths.length === 0) {
14391
14656
  process.stdout.write("No secrets.\n");
14392
14657
  return;
14393
14658
  }
14394
14659
  process.stdout.write(
14395
- [...names.map((name) => `variable ${name}${hidden2.includes(name) ? " kept out of the sandbox" : ""}
14396
- `), ...paths.map((path5) => `file ${path5}
14660
+ [...names2.map((name) => `variable ${name}${hidden2.includes(name) ? " kept out of the sandbox" : ""}
14661
+ `), ...paths.map((path6) => `file ${path6}
14397
14662
  `)].join("")
14398
14663
  );
14399
14664
  return;
@@ -14431,11 +14696,11 @@ async function secrets(positionals, values) {
14431
14696
  }
14432
14697
  return [arg.slice(0, at4), arg.slice(at4 + 1)];
14433
14698
  });
14434
- const path5 = (name) => `${base}/variables/${encodeURIComponent(name)}`;
14699
+ const path6 = (name) => `${base}/variables/${encodeURIComponent(name)}`;
14435
14700
  if (hosts === void 0 && !values.plain) {
14436
14701
  const byTemplate = sandboxId === void 0 ? [] : (await call2(`/v1/sandboxes/${encodeURIComponent(sandboxId)}/template`, { method: "GET" }))?.hidden ?? [];
14437
14702
  for (const [name] of pairs) {
14438
- if (await keptOutNow(path5(name))) {
14703
+ if (await keptOutNow(path6(name))) {
14439
14704
  throw new Error(
14440
14705
  `${name} is kept out of the sandbox. Set without --host it would be plain, and its commands would read its value. Give its hosts again with --host to keep it out, or --plain for its commands to read it. Nothing was set.`
14441
14706
  );
@@ -14448,7 +14713,7 @@ async function secrets(positionals, values) {
14448
14713
  }
14449
14714
  }
14450
14715
  for (const [name, value] of pairs) {
14451
- const body = await call2(path5(name), { method: "PUT", body: JSON.stringify(hosts === void 0 ? { value } : { value, hosts }) });
14716
+ const body = await call2(path6(name), { method: "PUT", body: JSON.stringify(hosts === void 0 ? { value } : { value, hosts }) });
14452
14717
  process.stdout.write(
14453
14718
  body.hidden === true ? `set ${name}, kept out of the sandbox: its commands see ${body.standIn}, and its value is sent only to ${body.hosts.join(", ")}
14454
14719
  ` : `set ${name}
@@ -14490,12 +14755,12 @@ async function secrets(positionals, values) {
14490
14755
  return;
14491
14756
  }
14492
14757
  case "put-file": {
14493
- const [path5, local] = args;
14494
- if (!path5 || local === void 0 === (values.text === void 0)) {
14758
+ const [path6, local] = args;
14759
+ if (!path6 || local === void 0 === (values.text === void 0)) {
14495
14760
  throw new Error("secrets put-file requires <path>, and then a local file to read it from or --text with what it holds");
14496
14761
  }
14497
14762
  const text = values.text ?? await readFile2(local ?? "", "utf8");
14498
- const body = await call2(`${base}/files`, { method: "PUT", body: JSON.stringify({ path: path5, text }) });
14763
+ const body = await call2(`${base}/files`, { method: "PUT", body: JSON.stringify({ path: path6, text }) });
14499
14764
  process.stdout.write(`put ${body.path}
14500
14765
  `);
14501
14766
  return;
@@ -14530,9 +14795,9 @@ async function metrics(id, asked2) {
14530
14795
  query.set(name, value);
14531
14796
  }
14532
14797
  }
14533
- const path5 = asked2.running ? "/v1/metrics/running" : id === void 0 ? "/v1/metrics" : `/v1/sandboxes/${encodeURIComponent(id)}/metrics`;
14798
+ const path6 = asked2.running ? "/v1/metrics/running" : id === void 0 ? "/v1/metrics" : `/v1/sandboxes/${encodeURIComponent(id)}/metrics`;
14534
14799
  const search = query.toString();
14535
- const response = await request(search === "" ? path5 : `${path5}?${search}`, { method: "GET" });
14800
+ const response = await request(search === "" ? path6 : `${path6}?${search}`, { method: "GET" });
14536
14801
  const body = await readBody(response);
14537
14802
  if (!response.ok) {
14538
14803
  fail(response.status, body);
@@ -14581,7 +14846,7 @@ async function account2(positionals, out) {
14581
14846
  process.stdout.write(text);
14582
14847
  return;
14583
14848
  }
14584
- writeFileSync4(out, text, { mode: 384 });
14849
+ writeFileSync5(out, text, { mode: 384 });
14585
14850
  process.stdout.write(`Written to ${out}.
14586
14851
  `);
14587
14852
  }
@@ -14660,9 +14925,9 @@ async function ci(positionals, options) {
14660
14925
  if (repo === void 0 || !/^[^/\s]+\/[^/\s]+$/.test(repo)) {
14661
14926
  throw new Error(`ci ${what} needs the repository, as agental ci ${what} acme/app`);
14662
14927
  }
14663
- const path5 = `/v1/runs-on/repositories/${repo.split("/").map(encodeURIComponent).join("/")}`;
14928
+ const path6 = `/v1/runs-on/repositories/${repo.split("/").map(encodeURIComponent).join("/")}`;
14664
14929
  if (what === "reset") {
14665
- const response = await request(path5, { method: "DELETE" });
14930
+ const response = await request(path6, { method: "DELETE" });
14666
14931
  if (!response.ok) {
14667
14932
  fail(response.status, await readBody(response));
14668
14933
  }
@@ -14684,7 +14949,7 @@ async function ci(positionals, options) {
14684
14949
  if (options.template !== void 0) {
14685
14950
  templateId = options.template === "default" ? null : (await templateNamed(options.template)).id;
14686
14951
  }
14687
- const saved = await asked(path5, { method: "PUT", body: JSON.stringify({ poolMax, templateId }) });
14952
+ const saved = await asked(path6, { method: "PUT", body: JSON.stringify({ poolMax, templateId }) });
14688
14953
  if (options.json) {
14689
14954
  process.stdout.write(`${JSON.stringify(saved, null, 2)}
14690
14955
  `);
@@ -14907,7 +15172,7 @@ function describeBilling(body, card = null) {
14907
15172
  lines.push(["Card", describeCard(card)]);
14908
15173
  }
14909
15174
  if (free.cardSaved && !free.paid) {
14910
- lines.push(["At once", `${free.unpaidUnits} small sandboxes until you buy a top-up, then ${(body.plan.runningUnits ?? 20).toLocaleString("en-US")}. A tiny counts half.`]);
15175
+ lines.push(["At once", `${free.unpaidUnits} units until you buy a top-up, then ${(body.plan.runningUnits ?? 40).toLocaleString("en-US")}. A tiny sandbox is 1 unit, a small 2.`]);
14911
15176
  }
14912
15177
  lines.push(["Used", `${money(body.usedMicros)} this month at list price${usedParts(body)}`]);
14913
15178
  const allowance = free.allowanceMicros ?? 0;
@@ -15102,7 +15367,7 @@ function pricesForPeople(body) {
15102
15367
  section(
15103
15368
  "Plans",
15104
15369
  [
15105
- ["", "A MONTH", "CREDITS BACK", "RUN AT ONCE", "START FREE", "SIZES"],
15370
+ ["", "A MONTH", "CREDITS BACK", "RUN AT ONCE", "FREE STARTS, 15 MIN", "SIZES"],
15106
15371
  ...body.tiers.map((tier) => [
15107
15372
  (tier.id ? PLAN_NAMES[tier.id] : void 0) ?? (tier.dollarsPerMonth === 0 ? "Free" : `$${tier.dollarsPerMonth.toLocaleString("en-US")}`),
15108
15373
  wholeMoney(tier.dollarsPerMonth * 1e6),
@@ -15113,8 +15378,8 @@ function pricesForPeople(body) {
15113
15378
  ])
15114
15379
  ],
15115
15380
  [
15116
- ...body.free ? [`Free needs a card saved, charged nothing; it runs ${body.free.unpaidUnits} at once until your first top-up.`] : [],
15117
- ...body.tiers.some((tier) => tier.runningUnits !== void 0) ? ["Counted in small sandboxes: a medium is 2, a large 4, a tiny half."] : []
15381
+ ...body.free ? [`Free needs a card saved, charged nothing; it runs ${body.free.unpaidUnits} units at once until your first top-up.`] : [],
15382
+ ...body.tiers.some((tier) => tier.runningUnits !== void 0) ? ["Counted in units: a tiny sandbox is 1, a small 2, a medium 4, a large 8."] : []
15118
15383
  ]
15119
15384
  );
15120
15385
  }
@@ -15164,23 +15429,23 @@ function describePrices(body) {
15164
15429
  out.push(withSizes ? "Plans, a month, and the sizes each makes" : "Plans, a month");
15165
15430
  for (const tier of body.tiers) {
15166
15431
  const sizes = tier.sizes === void 0 ? "" : tier.sizes.length === body.plans.length ? "every size" : tier.sizes.join(", ");
15167
- const speed = tier.runningUnits !== void 0 && tier.freeBurstUnits !== void 0 ? `${tier.runningUnits.toLocaleString("en-US")} running, ${tier.freeBurstUnits.toLocaleString("en-US")} start free` : tier.burst ? `${(tier.burst.perQuarterMb / 1024).toLocaleString("en-US")} GiB per 15 minutes` : typeof tier.sandboxesAtOnce === "number" ? `${tier.sandboxesAtOnce.toLocaleString("en-US")} sandboxes at once` : "";
15432
+ const speed = tier.runningUnits !== void 0 && tier.freeBurstUnits !== void 0 ? `${tier.runningUnits.toLocaleString("en-US")} running, ${tier.freeBurstUnits.toLocaleString("en-US")} free starts` : tier.burst ? `${(tier.burst.perQuarterMb / 1024).toLocaleString("en-US")} GiB per 15 minutes` : typeof tier.sandboxesAtOnce === "number" ? `${tier.sandboxesAtOnce.toLocaleString("en-US")} sandboxes at once` : "";
15168
15433
  const price = tier.dollarsPerMonth === 0 ? "Free" : `$${tier.dollarsPerMonth.toLocaleString("en-US")}`;
15169
15434
  const included = tier.dollarsPerMonth === 0 ? body.free ? `${wholeOrCents(body.free.allowanceMicros)} free, then as you go` : "pay as you go" : `${wholeMoney(tier.includedMicros)} of credits`;
15170
15435
  out.push(` ${price.padEnd(8)}${included.padEnd(28)}${speed.padEnd(34)}${sizes}`.trimEnd());
15171
15436
  }
15172
15437
  if (body.free) {
15173
15438
  out.push(
15174
- ` Free needs a card saved, charged nothing. Each month's first ${wholeOrCents(body.free.allowanceMicros)} of use is free: 185 hours of a small sandbox, 370 of a tiny one, or 11,100 CI minutes on small. It runs ${body.free.unpaidUnits} small sandboxes at once until you buy a top-up.`
15439
+ ` Free needs a card saved, charged nothing. Each month's first ${wholeOrCents(body.free.allowanceMicros)} of use is free: 185 hours of a small sandbox, 370 of a tiny one, or 11,100 CI minutes on small. It runs ${body.free.unpaidUnits} units at once until you buy a top-up.`
15175
15440
  );
15176
15441
  }
15177
15442
  if (body.tiers.some((tier) => tier.runningUnits !== void 0)) {
15178
- out.push(" Counted in small sandboxes: a medium is 2, a large 4, a tiny half.");
15443
+ out.push(" Counted in units: a tiny sandbox is 1, a small 2, a medium 4, a large 8. Free starts are in any 15 minutes.");
15179
15444
  }
15180
15445
  }
15181
15446
  if (body.burstFee) {
15182
15447
  out.push(
15183
- `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>.`
15448
+ `A start past your free starts in any ${body.burstFee.windowMinutes} minutes costs one hour of its price: $${body.burstFee.feeMicrosPerUnit / 1e6} a unit, $0.027 a small, $0.108 a large. At most ${wholeMoney(body.burstFee.defaultBudgetMicros)} a month unless you set another budget: agental headroom budget <dollars>.`
15184
15449
  );
15185
15450
  }
15186
15451
  if (body.topUps?.length) {
@@ -15267,8 +15532,8 @@ function describeHeadroom(body, today, endsNow) {
15267
15532
  const answer3 = body && typeof body === "object" ? body : {};
15268
15533
  const now = answer3["now"] && typeof answer3["now"] === "object" ? answer3["now"] : {};
15269
15534
  const number = (from, name) => typeof from[name] === "number" ? from[name] : 0;
15270
- const smalls = (mb) => {
15271
- const value = mb / 4096;
15535
+ const units = (mb) => {
15536
+ const value = mb / 2048;
15272
15537
  return (Number.isInteger(value) ? value : Math.round(value * 10) / 10).toLocaleString("en-US");
15273
15538
  };
15274
15539
  const clock = (iso) => {
@@ -15277,22 +15542,20 @@ function describeHeadroom(body, today, endsNow) {
15277
15542
  };
15278
15543
  const range = today ? "today (UTC)" : `from ${String(answer3["from"] ?? "")} to ${String(answer3["to"] ?? "")}`;
15279
15544
  const lines = [
15280
- `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(answer3, "atRunningCountMs"))} ${range}`
15545
+ `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}`
15281
15546
  ];
15282
15547
  const bursts = Array.isArray(answer3["bursts"]) ? answer3["bursts"] : [];
15283
15548
  const open = endsNow ? bursts.find((one) => one["endedAt"] === null && typeof one["startedAt"] === "string") : void 0;
15284
- const meterMb = number(now, "meterMb");
15285
- const freeMb = number(now, "freeMb");
15286
- const halfLife = number(now, "halfLifeMinutes");
15287
15549
  const over = number(now, "overMb") > 0;
15288
- const freeAgain = !over || freeMb <= 0 || halfLife <= 0 ? null : Math.ceil(halfLife * Math.log2(meterMb / freeMb));
15289
- const freeAgainWords = freeAgain === null ? "" : `; free again in ${freeAgain.toLocaleString("en-US")} min`;
15550
+ const nextStart = Array.isArray(now["nextStart"]) ? now["nextStart"] : [];
15551
+ const wait = typeof nextStart[0]?.["freeInSeconds"] === "number" ? nextStart[0]["freeInSeconds"] : null;
15552
+ const freeAgainWords = !over || wait === null || wait <= 0 ? "" : `; free at ${clock(new Date(Math.ceil((Date.now() + wait * 1e3) / 6e4) * 6e4).toISOString())}`;
15290
15553
  if (open && over) {
15291
- lines.push(`burst: in a burst since ${clock(String(open["startedAt"]))}: every start pays a fee${freeAgainWords}`);
15554
+ lines.push(`free starts: over since ${clock(String(open["startedAt"]))}: every start pays a fee${freeAgainWords}`);
15292
15555
  } else if (over) {
15293
- lines.push(`burst: over the free burst: every start pays a fee${freeAgainWords}`);
15556
+ lines.push(`free starts: over: every start pays a fee${freeAgainWords}`);
15294
15557
  } else {
15295
- 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`);
15558
+ lines.push(`free starts: ${units(number(now, "meterMb"))} of ${number(now, "freeBurstUnits").toLocaleString("en-US")} units used in the last 15 min`);
15296
15559
  }
15297
15560
  lines.push(`fees: ${money(number(now, "spentMicros"))} this month of a ${money(number(now, "budgetMicros"))} budget`);
15298
15561
  const refused = answer3["refused"] && typeof answer3["refused"] === "object" ? answer3["refused"] : {};
@@ -15315,8 +15578,8 @@ function duration(ms) {
15315
15578
  const minutes = Math.round(ms / 6e4);
15316
15579
  return minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h${minutes % 60 === 0 ? "" : ` ${minutes % 60} min`}`;
15317
15580
  }
15318
- async function asked(path5, init) {
15319
- const response = await request(path5, init);
15581
+ async function asked(path6, init) {
15582
+ const response = await request(path6, init);
15320
15583
  const body = await readBody(response);
15321
15584
  if (!response.ok) {
15322
15585
  fail(response.status, body);
@@ -15395,7 +15658,7 @@ function table3(rows) {
15395
15658
  `).join("");
15396
15659
  }
15397
15660
  var ACTIVE = /* @__PURE__ */ new Set(["running", "starting", "stopping", "restoring", "creating"]);
15398
- function sandboxesForPeople(sandboxes2, names, sorted) {
15661
+ function sandboxesForPeople(sandboxes2, names2, sorted) {
15399
15662
  const text = (value) => typeof value === "string" ? value : "";
15400
15663
  const changed = (sandbox) => Date.parse(text(sandbox["stoppedAt"]) || text(sandbox["updatedAt"]) || text(sandbox["createdAt"])) || 0;
15401
15664
  const shown = sorted ? sandboxes2 : [...sandboxes2].sort((a, b) => Number(ACTIVE.has(text(b["status"]))) - Number(ACTIVE.has(text(a["status"]))) || changed(b) - changed(a));
@@ -15407,6 +15670,14 @@ function sandboxesForPeople(sandboxes2, names, sorted) {
15407
15670
  const showVm = differs((sandbox) => String(sandbox["vmIsolation"] === true));
15408
15671
  const showOutbound = differs(outbound);
15409
15672
  const showTags = shown.some((sandbox) => Array.isArray(sandbox["tags"]) && sandbox["tags"].length > 0);
15673
+ const showSpot = shown.some((sandbox) => sandbox["spot"] !== null && typeof sandbox["spot"] === "object");
15674
+ const spotWord = (sandbox) => {
15675
+ const spot2 = sandbox["spot"];
15676
+ if (!spot2) {
15677
+ return "-";
15678
+ }
15679
+ return typeof spot2.reclaimChance === "number" ? `spot ${Math.round(spot2.reclaimChance * 100)}%` : "spot";
15680
+ };
15410
15681
  const status = (sandbox) => {
15411
15682
  const word = text(sandbox["status"]) || "unknown";
15412
15683
  const stops = word === "running" ? until(text(sandbox["autoStopAt"])) : null;
@@ -15414,7 +15685,7 @@ function sandboxesForPeople(sandboxes2, names, sorted) {
15414
15685
  return stops ? `running, stops ${stops}` : stopped ? `stopped ${stopped}` : word;
15415
15686
  };
15416
15687
  const rows = [
15417
- ["", "ID", "NAME", "SIZE", "TEMPLATE", "STATUS", ...showVm ? ["VM"] : [], ...showOutbound ? ["OUTBOUND"] : [], ...showTags ? ["TAGS"] : []],
15688
+ ["", "ID", "NAME", "SIZE", "TEMPLATE", "STATUS", ...showSpot ? ["SPOT"] : [], ...showVm ? ["VM"] : [], ...showOutbound ? ["OUTBOUND"] : [], ...showTags ? ["TAGS"] : []],
15418
15689
  ...shown.map((sandbox) => {
15419
15690
  const templateId = text(sandbox["templateId"]);
15420
15691
  return [
@@ -15422,8 +15693,9 @@ function sandboxesForPeople(sandboxes2, names, sorted) {
15422
15693
  text(sandbox["id"]),
15423
15694
  text(sandbox["name"]),
15424
15695
  sizeOf2(sandbox),
15425
- templateId ? names.get(templateId) ?? templateId : "-",
15696
+ templateId ? names2.get(templateId) ?? templateId : "-",
15426
15697
  status(sandbox),
15698
+ ...showSpot ? [spotWord(sandbox)] : [],
15427
15699
  ...showVm ? [sandbox["vmIsolation"] === true ? "yes" : "no"] : [],
15428
15700
  ...showOutbound ? [outbound(sandbox)] : [],
15429
15701
  ...showTags ? [Array.isArray(sandbox["tags"]) ? sandbox["tags"].join(",") : ""] : []
@@ -15552,8 +15824,8 @@ async function helpText() {
15552
15824
  return `agental \u2014 Linux sandboxes for your agents
15553
15825
 
15554
15826
  Setting up
15555
- agental [--json] [--no-install] [--no-skills]
15556
- agental sh [--json] [--no-install] [--no-skills]
15827
+ agental [--json] [--no-install] [--no-skills] [--no-mcp]
15828
+ agental sh [--json] [--no-install] [--no-skills] [--no-mcp]
15557
15829
  agental login [--key]
15558
15830
  agental logout
15559
15831
  agental whoami [--json]
@@ -15562,6 +15834,7 @@ Setting up
15562
15834
 
15563
15835
  Usage
15564
15836
  agental create [--name <name>] [--template <template>] [--size tiny|small|medium|large] [--region <region>[,<region>...]] [--ttl <time> | --ttl default] [--on-timeout delete|stop|stop-with-memory] [--idempotency-key <key>]
15837
+ [--spot [--on-reclaim delete|stop|upgrade] [--warn-at <chance>]]
15565
15838
  ${operator ? "[--box <name-or-id>] " : ""}[--allow <address>[,<address>...]] [--egress box | residential:<country>[:sticky|rotating]] [--max-burst-fee <dollars>]
15566
15839
  [--ssh-key <public-key-or-file>]... [--tag <tag>[,<tag>...]]... [--meta <key>=<value>]...
15567
15840
  agental summary [--where '<words>'] [--tag <tag>[,<tag>...]]... [--meta <key>=<value>]... [--facets <field>[,<field>...]] [--json]
@@ -15587,6 +15860,7 @@ Usage
15587
15860
  agental auto-stop <sandbox-id> [--in <time> | --at <date-time> | --never] [--json]
15588
15861
  agental network <sandbox-id> [--allow <address>[,<address>...] | --none] [--json]
15589
15862
  agental egress <sandbox-id> [box | residential <country> [sticky | rotating]] [--json]
15863
+ agental spot <sandbox-id> [normal] [--on-reclaim delete|stop|upgrade] [--warn-at <chance>] [--json]
15590
15864
  agental templates [--json]
15591
15865
  agental template create <name> [--tag <tag>[,<tag>...]]... [--meta <key>=<value>]...
15592
15866
  agental template show <template> [--json]
@@ -15705,12 +15979,13 @@ ${FILES_USAGE.map((line) => ` ${line}`).join("\n")}
15705
15979
  agental browser <sandbox-id> [--headless | --headed] [--off] [--status]
15706
15980
  ${operator ? operator.OPERATOR_USAGE : ""}
15707
15981
  With no command, as npx agental@latest runs it, agental signs in the first time on a computer,
15708
- installs itself with npm where it stays on the PATH, and installs the agent skills for the coding
15709
- agents it finds here. sh does the same, then makes a sandbox on your default template and opens a
15982
+ installs itself with npm where it stays on the PATH, installs the agent skills for the coding
15983
+ agents it finds here, and adds agental's MCP server to them (Claude Code, Codex, Cursor, Windsurf,
15984
+ Gemini CLI and opencode), which each signs in to through the browser the first time. sh does the same, then makes a sandbox on your default template and opens a
15710
15985
  shell in it over SSH. Run with no terminal, as an agent runs it, sh prints the commands to use the
15711
15986
  sandbox with instead, and --json prints the sandbox as JSON. At your plan's limit it makes none:
15712
15987
  in a terminal it offers to open your newest running sandbox instead, and otherwise lists them.
15713
- --no-install leaves the command as it is, and --no-skills the skills.
15988
+ --no-install leaves the command as it is, --no-skills the skills, and --no-mcp the agents' MCP servers.
15714
15989
  login signs in through the browser: the page asks you to allow this computer, and the command is
15715
15990
  given an API key of its own, named CLI on <this computer>, which is in the console under API keys.
15716
15991
  --key reads a key from standard input instead, for a computer with no browser.
@@ -15742,6 +16017,14 @@ start carries on where it was (after the account's first top-up: before it, refu
15742
16017
  memory_needs_top_up); agental stop always keeps the disk. auto-stop
15743
16018
  says when a running sandbox is to be stopped, with --in or --at moves that stop, later or sooner,
15744
16019
  for the run under way, and with --never takes its time limit away, for this run and the next.
16020
+ create --spot makes a spot sandbox: half the list price, in room on our servers nobody else is
16021
+ paying for, taken back when a normal sandbox needs it. --on-reclaim says what is then done to it:
16022
+ stop (the default) stops it and keeps its disk, never its memory; delete deletes it; upgrade
16023
+ makes it a normal sandbox at the list price and keeps it running, where that frees what was
16024
+ needed, and stops it otherwise. It is not counted in the plan's running count, and comes with
16025
+ the account's first top-up. agental spot shows its chance of being stopped in the next minute, a
16026
+ hint and not a promise, and with --warn-at sets the chance at which sandbox.reclaim_chance is sent
16027
+ (0.5 when left out); agental spot <sandbox-id> normal makes it a normal sandbox from then on.
15745
16028
  ${operator ? operator.OPERATOR_HELP : ""}template network says what a sandbox on a template may reach outside itself, and with open,
15746
16029
  blocked or allowlist sets it: everything, nothing, or only the addresses that follow, which are
15747
16030
  IPv4 addresses and ranges such as 203.0.113.7 and 198.51.100.0/24. The rule that is given takes
@@ -15936,7 +16219,7 @@ first $5 of use free, 185 small hours or 11,100 CI minutes, and pays for the res
15936
16219
  credits; it makes tiny and small sandboxes. prices lists the plans with the sizes each
15937
16220
  makes, the top-ups with their bonus and the hourly price of each size. card names the card the account
15938
16221
  pays with, and card save prints the address of a page to save one for the free plan: nothing is charged, and once it is saved the account
15939
- has the monthly allowance, once a card. Until it buys a top-up it runs 2 small sandboxes at once, then 20.
16222
+ has the monthly allowance, once a card. Until it buys a top-up it runs 4 units at once (2 small sandboxes), then 40.
15940
16223
  top-up <dollars> starts buying credits for
15941
16224
  any whole number of dollars from 15 to 100,000, and prints the address of the page to pay on.
15942
16225
  From $200 a top-up adds a bonus, 2% there and growing to 25% at $10,000: $500 adds $537.