@parcha/agentrun-computer 0.1.0-beta.59 → 0.1.0-beta.61

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.
@@ -21,7 +21,8 @@
21
21
  import { readFileSync } from "node:fs";
22
22
  import { BROWSERBASE } from "./descriptors/browserbase.js";
23
23
  import { BROWSER_IMAGE } from "./descriptors/shared.js";
24
- import { cdpUrlProblem, browserClient, browserHello, BrowserVendorError, CREATE_LABEL, carries, causeOf, checkBrowser, createLabelValue, createUncertain, DEFAULT_CONFIRM, defaultSleep, idProblem, labelsOf, labelsProblem, limitedBytes, memoryUrls, pointerOk, queryable, recoverCreate, releaseConfirmed, restBytes, restCall, causedFail, vendorFailure, withoutCreateLabel, } from "./browser.js";
24
+ import { cdpUrlProblem, browserClient, browserHello, BrowserVendorError, CREATE_LABEL, carries, causeOf, checkBrowser, createUncertain, DEFAULT_CONFIRM, ATTEMPT_LABEL, convergedBrowser, heldBrowser, newAttempt, defaultSleep, idProblem, labelsOf, labelsProblem, limitedBytes, memoryUrls, pointerOk, queryable, RECOVER_MS, recoverCreate, leftToConverge, releaseConfirmed, boundedRelease, restBytes, restCall, causedFail, vendorFailure, withoutCreateLabel, } from "./browser.js";
25
+ import { CreateRequests, endedWords, labelsDiffer, otherSpecWords } from "./create-requests.js";
25
26
  import { httpsBase } from "./hosted/rest.js";
26
27
  import { runLifetimeMs, } from "./provider.js";
27
28
  import { failFor, ok, vendorFail } from "./result.js";
@@ -38,8 +39,16 @@ const CDP_DOMAIN = BROWSERBASE_CDP_DOMAIN;
38
39
  export const BROWSERBASE_MAX_LIFETIME_MS = 6 * 60 * 60_000;
39
40
  /** Browserbase's shortest session timeout: 60 s. */
40
41
  export const BROWSERBASE_MIN_LIFETIME_MS = 60_000;
41
- /** The statuses of a session that runs (PENDING bills once it starts); any other has ended. */
42
42
  const LIVE = new Set(["RUNNING", "PENDING"]);
43
+ /** Every status a session reads as, ended ones included: a request's whole record (#leftToConverge). */
44
+ const EVER = new Set([...LIVE, "COMPLETED", "ERROR", "TIMED_OUT"]);
45
+ /**
46
+ * The order #sessions asks for the statuses, a session's own: it is PENDING, then RUNNING, then ended, and never goes
47
+ * back. Each group is asked once the one before has answered, so a session that moves on while the read runs is found
48
+ * by a later group, never missed between two (asked side by side, a session could leave RUNNING after the COMPLETED
49
+ * answer and before the RUNNING one, and be in neither). The ended statuses are asked together: none moves to another.
50
+ */
51
+ const LIFECYCLE = [["PENDING"], ["RUNNING"], ["COMPLETED", "ERROR", "TIMED_OUT"]];
43
52
  /** A label key Browserbase's metadata can carry once its dots are underscores: letters, digits and dots, so the mapping is one to one. */
44
53
  const LABEL_KEY = /^[A-Za-z0-9.]+$/;
45
54
  /** The userMetadata key a label key is written under: each "." as "_", since Browserbase refuses a dot there. */
@@ -52,6 +61,8 @@ const toMetadata = (labels = {}) => Object.fromEntries(Object.entries(labels).ma
52
61
  const metadataLabels = (held) => Object.fromEntries(Object.entries(labelsOf(held)).map(([key, value]) => [labelKey(key), value]));
53
62
  /** userMetadata as the labels list and attach show: without the provider's create label. */
54
63
  const fromMetadata = (held) => withoutCreateLabel(metadataLabels(held));
64
+ /** A session as its create label finds it: its id, when Browserbase made it, and its labels. */
65
+ const heldOf = (s) => ({ id: s.id, ...(s.createdAt ?? s.startedAt ? { createdAt: (s.createdAt ?? s.startedAt) } : {}), labels: fromMetadata(s.userMetadata) });
55
66
  /** Why labels cannot ride a Browserbase session's userMetadata, in words naming the label; undefined when they can. */
56
67
  export function browserbaseLabelsProblem(labels) {
57
68
  const problem = labelsProblem(labels);
@@ -212,7 +223,18 @@ export class BrowserbaseProvider {
212
223
  #urls;
213
224
  #confirm;
214
225
  #sleep;
215
- constructor({ apiKey, projectId, apiUrl, env = {}, fetch: fetcher, confirm = DEFAULT_CONFIRM, sleep = defaultSleep }) {
226
+ /** The bound of each cleanup a create runs for itself (cleanupMs). */
227
+ #cleanupMs;
228
+ /** Idempotent create's in-process half: one session per request id (provider.md). */
229
+ #requests = new CreateRequests();
230
+ /** The request's name of each session this provider made or found for a create, by id: its release ends the request. */
231
+ #requestOf = new Map();
232
+ /**
233
+ * The session each request's create answered, by the request's name, kept past its release: a request whose session
234
+ * ended on its own (its timeout, the vendor) is refused exists, as one released here is, never made again.
235
+ */
236
+ #madeFor = new Map();
237
+ constructor({ apiKey, projectId, apiUrl, env = {}, fetch: fetcher, confirm = DEFAULT_CONFIRM, sleep = defaultSleep, cleanupMs = RECOVER_MS }) {
216
238
  if (typeof apiKey !== "string" || apiKey === "")
217
239
  throw new Error("set options.apiKey to a Browserbase API key: the provider reads no environment");
218
240
  const gateway = env.BROWSERBASE_BASE_URL?.trim() || undefined;
@@ -224,6 +246,7 @@ export class BrowserbaseProvider {
224
246
  this.#urls = memoryUrls();
225
247
  this.#confirm = confirm;
226
248
  this.#sleep = sleep;
249
+ this.#cleanupMs = cleanupMs;
227
250
  this.#browser = {
228
251
  timeout: "wall-clock",
229
252
  stealth: true,
@@ -264,19 +287,47 @@ export class BrowserbaseProvider {
264
287
  return refusals;
265
288
  }
266
289
  /**
267
- * Makes a session at most once: with keepAlive, so a dropped CDP client never ends it, the lifetime as its timeout in
268
- * whole seconds, and the labels as its userMetadata. spec.browser is the session's own options, each refused by check()
290
+ * Makes a session once per request (provider.md, Idempotent create): with keepAlive, so a dropped CDP client never
291
+ * ends it, the lifetime as its timeout in whole seconds, and the labels as its userMetadata, with the request's name
292
+ * (computerNameFor) as its create label. A request whose session Browserbase still runs or starts answers that one,
293
+ * found by its create label; one whose session was released here is refused exists; a create of a request in flight
294
+ * here waits for the first (CreateRequests). spec.browser is the session's own options, each refused by check()
269
295
  * unless declared.
270
296
  */
271
297
  async create(spec, context) {
272
- const signal = context?.signal;
273
298
  const refusals = this.check(spec);
274
- if (refusals.length > 0)
275
- return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
299
+ return this.#requests.create(spec, context, {
300
+ refuse: fail,
301
+ ...(refusals.length > 0 ? { refused: refusals.map(({ field, message }) => `${field}: ${message}`).join("; ") } : {}),
302
+ make: async (request) => {
303
+ const made = await this.#createNamed(spec, request, context.signal);
304
+ if (made.ok)
305
+ this.#madeFor.set(request, made.value.id);
306
+ return made;
307
+ },
308
+ });
309
+ }
310
+ /** Everything create does under the request's name: the session Browserbase holds under it, or a new one. */
311
+ async #createNamed(spec, request, signal) {
276
312
  if (signal?.aborted)
277
313
  return fail("aborted", "create was aborted before Browserbase was called");
314
+ const held = await this.#sessions({ [CREATE_LABEL]: request }, signal);
315
+ if (!held.ok)
316
+ return held;
317
+ const found = heldBrowser(spec.labels ?? {}, held.value.map(heldOf));
318
+ if (found !== undefined) {
319
+ if (found.differ.length > 0)
320
+ return fail("exists", otherSpecWords(`${request} (session ${found.id})`, "was made", found.differ));
321
+ this.#requestOf.set(found.id, request);
322
+ return ok(refOf({ id: found.id }));
323
+ }
324
+ const ended = await this.#ended(spec, request, signal);
325
+ if (ended !== undefined)
326
+ return ended;
278
327
  const browser = spec.browser;
279
- const written = { [CREATE_LABEL]: createLabelValue(), ...spec.labels };
328
+ // The request's label, which a retry and a converge find it by, and this POST's own, which its recovery finds it by.
329
+ const attempt = { [ATTEMPT_LABEL]: newAttempt() };
330
+ const written = { [CREATE_LABEL]: request, ...attempt, ...spec.labels };
280
331
  // Browserbase solves CAPTCHAs unless told not to: a browser's options say so either way, the solver only with stealth.
281
332
  const browserSettings = {
282
333
  ...(browser?.viewport ? { viewport: { width: browser.viewport.width, height: browser.viewport.height } } : {}),
@@ -299,21 +350,88 @@ export class BrowserbaseProvider {
299
350
  const failed = vendorFailure("browserbase", NAME, "POST /v1/sessions", error);
300
351
  if (failed.ok || !createUncertain(error))
301
352
  return failed;
302
- // The session may have been made though its answer never came: found by its create label, never made again.
303
- return causedFail(failed.error.code, `${failed.error.message}; ${await this.#recover(written)}`, causeOf(failed), "browserbase");
353
+ // The session may have been made though its answer never came: found by this POST's attempt label and
354
+ // released, and the request is ended, so it is never made again.
355
+ this.#requests.end(request);
356
+ return causedFail(failed.error.code, `${failed.error.message}; ${await this.#recover(attempt, request)}`, causeOf(failed), "browserbase");
304
357
  }
305
358
  if (idProblem(made?.id, NAME) !== undefined) {
306
- return vendorFail("browserbase", `Browserbase POST /v1/sessions answered with no session id, so there is no session to connect to; ${await this.#recover(written)}`);
359
+ this.#requests.end(request);
360
+ return vendorFail("browserbase", `Browserbase POST /v1/sessions answered with no session id, so there is no session to connect to; ${await this.#recover(attempt, request)}`);
307
361
  }
362
+ this.#requests.made(request);
363
+ // Another process's create of this request may have made one too (#converge): the older is answered.
364
+ const converged = await this.#converge(spec, request, made, signal);
365
+ if (converged !== undefined)
366
+ return converged;
367
+ this.#requestOf.set(made.id, request);
308
368
  const unusable = cdpUrlProblem(made.connectUrl, NAME, CDP_DOMAIN);
309
369
  if (unusable !== undefined) {
310
- // The session is made and billed (keepAlive, up to its timeout): released here, not left to a later sweep.
311
- const released = await this.release(refOf(made), "delete");
312
- return vendorFail("browserbase", `Browserbase POST /v1/sessions made a session with no CDP URL to hand over: ${unusable}; ${released.ok ? "the session was released" : `the session was not released (${released.error.code}), and its labels let a sweep find it`}`);
370
+ // The session is made and billed (keepAlive, up to its timeout): released here, under the cleanup's own bound.
371
+ const released = await boundedRelease("session", made.id, this.#cleanupMs, (bound) => this.release(refOf(made), "delete", { signal: bound }));
372
+ return vendorFail("browserbase", `Browserbase POST /v1/sessions made a session with no CDP URL to hand over: ${unusable}; ${released.ok ? "the session was released" : `the session was not released (${released.error.message}), and its labels let a sweep find it`}`);
313
373
  }
314
374
  this.#urls.set(made.id, made.connectUrl);
315
375
  return ok(refOf(made));
316
376
  }
377
+ /**
378
+ * The one session a request keeps (convergedBrowser): the request's create label listed again once Browserbase made
379
+ * mine. Undefined when mine is the oldest (or the listing fails: the create goes on with its own); an abort releases
380
+ * mine, never under the caller's signal, and the create is aborted. Else mine is
381
+ * released, never under the caller's signal, and the older answered: refused exists when it has ended by then, or when
382
+ * its labels are another spec's.
383
+ */
384
+ async #converge(spec, request, mine, signal) {
385
+ const listed = await this.#sessions({ [CREATE_LABEL]: request }, signal);
386
+ if (!listed.ok) {
387
+ if (listed.error.code !== "aborted" && !signal?.aborted)
388
+ return undefined;
389
+ // The caller is gone: the session this POST made is released, never under the caller's signal.
390
+ this.#requests.end(request);
391
+ const released = await boundedRelease("session", mine.id, this.#cleanupMs, (bound) => this.#releaseSession(mine.id, bound));
392
+ return fail("aborted", `create was aborted once Browserbase had made the session ${mine.id}; ${released.ok ? "the session was released" : `the session could not be released (${released.error.message}), and its labels let a sweep find it`}`);
393
+ }
394
+ const kept = convergedBrowser(listed.value.map(heldOf), heldOf(mine));
395
+ if (kept === "mine")
396
+ return undefined;
397
+ const released = await boundedRelease("session", mine.id, this.#cleanupMs, (bound) => this.#releaseSession(mine.id, bound));
398
+ if (!released.ok)
399
+ return fail(released.error.code, `${request} keeps the session ${kept.id}, the older of its two, and the session ${mine.id} made for it could not be released (${released.error.message})`);
400
+ const alive = await this.#alive(kept.id, signal);
401
+ if (!alive.ok)
402
+ return alive;
403
+ if (!alive.value) {
404
+ this.#requests.end(request);
405
+ return fail("exists", endedWords(request));
406
+ }
407
+ const differ = labelsDiffer(spec.labels ?? {}, kept.labels, "read back");
408
+ if (differ.length > 0)
409
+ return fail("exists", otherSpecWords(`${request} (session ${kept.id})`, "was made", differ));
410
+ this.#requestOf.set(kept.id, request);
411
+ return ok(refOf({ id: kept.id }));
412
+ }
413
+ /**
414
+ * A request this provider answered a session for before, which its create label no longer finds: refused exists, the
415
+ * request ended, once Browserbase reads that session as ended too; one it still runs (a listing that left it out) is
416
+ * answered when its labels are this spec's. Undefined for a request with no session here yet.
417
+ */
418
+ async #ended(spec, request, signal) {
419
+ const before = this.#madeFor.get(request);
420
+ if (before === undefined)
421
+ return undefined;
422
+ const read = await this.#running(before, signal);
423
+ if (!read.ok && read.error.code !== "not_found" && read.error.code !== "gone")
424
+ return read;
425
+ if (!read.ok) {
426
+ this.#requests.end(request);
427
+ return fail("exists", endedWords(request));
428
+ }
429
+ const differ = labelsDiffer(spec.labels ?? {}, fromMetadata(read.value.userMetadata), "read back");
430
+ if (differ.length > 0)
431
+ return fail("exists", otherSpecWords(`${request} (session ${before})`, "was made", differ));
432
+ this.#requestOf.set(before, request);
433
+ return ok(refOf({ id: before }));
434
+ }
317
435
  /** A new context, a profile's pointer: one POST /v1/contexts, never retried. */
318
436
  async #createProfile({ signal } = {}) {
319
437
  try {
@@ -413,15 +531,22 @@ export class BrowserbaseProvider {
413
531
  }
414
532
  /**
415
533
  * The sessions a lost create made, released: what recoverCreate says of them. They are found as list finds any, by
416
- * the labels the create wrote (its create label first, so the query names it, then the run's), through #sessions and
417
- * its metadata-key mapping: another session of the same run carries a create label of its own and is left alone.
534
+ * the attempt label its POST wrote (ATTEMPT_LABEL), through #sessions and its metadata-key mapping: another create's
535
+ * session, of this request or another, carries an attempt label of its own and is left alone, even one another
536
+ * instance has answered.
418
537
  */
419
- #recover(labels) {
538
+ #recover(labels, request) {
420
539
  const find = async (signal) => {
421
540
  const found = await this.#sessions(labels, signal);
422
541
  return found.ok ? ok(found.value.map((s) => s.id)) : found;
423
542
  };
424
- return recoverCreate("session", find, (id) => this.release({ id, name: id }, "delete"), this.#sleep);
543
+ const leave = (id, signal) => this.#leftToConverge(request, id, signal);
544
+ return recoverCreate("session", find, (id, signal) => this.release({ id, name: id }, "delete", { signal }), this.#sleep, this.#cleanupMs, leave);
545
+ }
546
+ /** Whether a lost create's session is left to another create of its request (leftToConverge); a listing that fails releases it. */
547
+ async #leftToConverge(request, id, signal) {
548
+ const made = await this.#sessions({ [CREATE_LABEL]: request }, signal, EVER);
549
+ return made.ok && leftToConverge(id, made.value.map((s) => ({ ...heldOf(s), live: LIVE.has(s.status) })));
425
550
  }
426
551
  /**
427
552
  * Settings' test: one read of the project's running sessions (GET /v1/sessions?status=RUNNING), which makes nothing.
@@ -456,7 +581,7 @@ export class BrowserbaseProvider {
456
581
  }
457
582
  if (found === undefined)
458
583
  return fail("not_found", `no Browserbase session has the id ${id}`);
459
- if (!LIVE.has(found.status ?? ""))
584
+ if (!LIVE.has(found.status))
460
585
  return fail("gone", `the Browserbase session ${id} has ended (${found.status ?? "no status"}): only a running session is attached or connected to`);
461
586
  return ok(found);
462
587
  }
@@ -492,9 +617,10 @@ export class BrowserbaseProvider {
492
617
  /**
493
618
  * The running and pending sessions with all of these labels. Browserbase is asked by status and by the first label a
494
619
  * query carries as it is; the match is the provider's own, so a lane that drops the query never hands back another's.
495
- * Both statuses must answer: a release trusts this list.
620
+ * Both statuses must answer: a release trusts this list. `statuses` widens it, to the ended ones too (EVER). The
621
+ * statuses are asked in a session's own order (LIFECYCLE), so every session there when the read starts is found.
496
622
  */
497
- async #sessions(labels, signal) {
623
+ async #sessions(labels, signal, statuses = LIVE) {
498
624
  const problem = browserbaseLabelsProblem(labels);
499
625
  if (problem)
500
626
  return fail("invalid", problem);
@@ -502,15 +628,23 @@ export class BrowserbaseProvider {
502
628
  return fail("invalid", "list and attach take at least one label: a Browserbase project holds sessions this provider did not make");
503
629
  const first = Object.entries(labels).find(queryable);
504
630
  const q = first === undefined ? undefined : `user_metadata['${metadataKey(first[0])}']:'${first[1]}'`;
505
- let pages;
631
+ const found = new Map();
506
632
  try {
507
- pages = await Promise.all(["RUNNING", "PENDING"].map((status) => this.#api.list({ status, ...(q === undefined ? {} : { q }) }, signal)));
633
+ for (const group of LIFECYCLE) {
634
+ const asked = group.filter((status) => statuses.has(status));
635
+ if (asked.length === 0)
636
+ continue;
637
+ const pages = await Promise.all(asked.map((status) => this.#api.list({ status, ...(q === undefined ? {} : { q }) }, signal)));
638
+ for (const s of pages.flat()) {
639
+ if (typeof s?.id === "string" && statuses.has(s.status) && carries(metadataLabels(s.userMetadata), labels) && !found.has(s.id))
640
+ found.set(s.id, s);
641
+ }
642
+ }
508
643
  }
509
644
  catch (error) {
510
645
  return vendorFailure("browserbase", NAME, "GET /v1/sessions", error);
511
646
  }
512
- const seen = new Set();
513
- return ok(pages.flat().filter((s) => typeof s?.id === "string" && LIVE.has(s.status ?? "") && carries(metadataLabels(s.userMetadata), labels) && !seen.has(s.id) && seen.add(s.id)));
647
+ return ok([...found.values()]);
514
648
  }
515
649
  async list(labels, { signal } = {}) {
516
650
  const found = await this.#sessions(labels, signal);
@@ -568,6 +702,17 @@ export class BrowserbaseProvider {
568
702
  const problem = idProblem(id, NAME);
569
703
  if (problem)
570
704
  return fail("invalid", problem);
705
+ // The request's session is ended here: a later create of it is refused exists, never made again.
706
+ const request = this.#requestOf.get(id);
707
+ if (request !== undefined)
708
+ this.#requests.end(request);
709
+ const released = await this.#releaseSession(id, signal);
710
+ if (released.ok)
711
+ this.#requestOf.delete(id);
712
+ return released;
713
+ }
714
+ /** Asks Browserbase to release the session and waits until it reads as ended; the request it was made for is not ended. */
715
+ async #releaseSession(id, signal) {
571
716
  const released = await releaseConfirmed({
572
717
  request: async () => {
573
718
  try {
Binary file
Binary file
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "0.1.0-beta.59",
2
+ "version": "0.1.0-beta.61",
3
3
  "source": "sha256:724f889fc95233b98e71e6ff4456498fb220f704db4ca2caed5772e3984ba4de"
4
4
  }
@@ -12,7 +12,11 @@ export declare const AGENT37_ENV: {
12
12
  readonly kind: "COMPUTER_AGENT37_KIND";
13
13
  /** apiKey, required: the workspace's API key. */
14
14
  readonly key: "COMPUTER_AGENT37_API_KEY";
15
- /** sshKey, required: the private SSH key registered on the workspace, its contents. */
15
+ /**
16
+ * sshKey, optional: the private half of an SSH key already registered on the workspace, its contents. Unset, the run
17
+ * makes a key of its own, kept in its process's memory, and registers it on the workspace (POST /v1/ssh-keys), where
18
+ * it stays: delete the agentrun-<hash> keys a run leaves (DELETE /v1/ssh-keys/{id}) before the workspace reaches 20.
19
+ */
16
20
  readonly sshKey: "COMPUTER_AGENT37_SSH_KEY";
17
21
  /** type: vm (default) or default. */
18
22
  readonly type: "COMPUTER_AGENT37_TYPE";
@@ -35,7 +39,11 @@ export declare const ENV: {
35
39
  readonly kind: "COMPUTER_AGENT37_KIND";
36
40
  /** apiKey, required: the workspace's API key. */
37
41
  readonly key: "COMPUTER_AGENT37_API_KEY";
38
- /** sshKey, required: the private SSH key registered on the workspace, its contents. */
42
+ /**
43
+ * sshKey, optional: the private half of an SSH key already registered on the workspace, its contents. Unset, the run
44
+ * makes a key of its own, kept in its process's memory, and registers it on the workspace (POST /v1/ssh-keys), where
45
+ * it stays: delete the agentrun-<hash> keys a run leaves (DELETE /v1/ssh-keys/{id}) before the workspace reaches 20.
46
+ */
39
47
  readonly sshKey: "COMPUTER_AGENT37_SSH_KEY";
40
48
  /** type: vm (default) or default. */
41
49
  readonly type: "COMPUTER_AGENT37_TYPE";
@@ -19,7 +19,11 @@ export const AGENT37_ENV = {
19
19
  kind: "COMPUTER_AGENT37_KIND",
20
20
  /** apiKey, required: the workspace's API key. */
21
21
  key: "COMPUTER_AGENT37_API_KEY",
22
- /** sshKey, required: the private SSH key registered on the workspace, its contents. */
22
+ /**
23
+ * sshKey, optional: the private half of an SSH key already registered on the workspace, its contents. Unset, the run
24
+ * makes a key of its own, kept in its process's memory, and registers it on the workspace (POST /v1/ssh-keys), where
25
+ * it stays: delete the agentrun-<hash> keys a run leaves (DELETE /v1/ssh-keys/{id}) before the workspace reaches 20.
26
+ */
23
27
  sshKey: "COMPUTER_AGENT37_SSH_KEY",
24
28
  /** type: vm (default) or default. */
25
29
  type: "COMPUTER_AGENT37_TYPE",
@@ -41,15 +45,12 @@ export const ENV = AGENT37_ENV;
41
45
  */
42
46
  export function settingsFromEnv(env = process.env) {
43
47
  const apiKey = requiredSecret(env, AGENT37_ENV.key, "an Agent37 API key");
44
- const sshKey = env[AGENT37_ENV.sshKey];
45
- if (sshKey === undefined || sshKey === "")
46
- throw new Error(`set ${AGENT37_ENV.sshKey} to the private SSH key registered on the Agent37 workspace (its contents, never a path)`);
47
48
  const lifetime = lifetimeFromEnv(env, AGENT37_ENV.maxLifetimeMs, "86400000");
48
- const set = setOptions(env, { type: AGENT37_ENV.type, region: AGENT37_ENV.region, apiUrl: AGENT37_ENV.apiUrl, daemonPath: AGENT37_ENV.daemon, daemonUser: AGENT37_ENV.user });
49
- return { apiKey, sshKey, ...set, ...kindFrom(env, AGENT37_ENV.kind), ...lifetime };
49
+ const set = setOptions(env, { sshKey: AGENT37_ENV.sshKey, type: AGENT37_ENV.type, region: AGENT37_ENV.region, apiUrl: AGENT37_ENV.apiUrl, daemonPath: AGENT37_ENV.daemon, daemonUser: AGENT37_ENV.user });
50
+ return { apiKey, ...set, ...kindFrom(env, AGENT37_ENV.kind), ...lifetime };
50
51
  }
51
52
  export const conformanceNotes = [
52
- "agent37: every computer is an instance (type vm by default), made with network deny-all, auto-sleep off and no public port, read back from Agent37 and probed from inside; the daemon is a child, started over SSH through the platform's sshd (port 22022; it and the platform's web terminal on 7681 are declared as the vendor's agent), and every command goes over that SSH as root. Agent37 never ends an instance on its own: lifetime janitor, capped at 30 minutes for the run. No stream() (a screen is streamed through agentrun), so screen.stream is skipped. Kind desktop (COMPUTER_AGENT37_KIND=desktop) starts from agentrun-box-<recipe hash>, our box image registered as a template of the key's workspace (prepareImage), with Xvfb on :0 started through the daemon as the tool user.",
53
+ "agent37: every computer is an instance (type vm by default), made with network deny-all, auto-sleep off and no public port, read back from Agent37 and probed from inside; the daemon is a child, started over SSH through the platform's sshd (port 22022; it and the platform's web terminal on 7681 are declared as the vendor's agent), and every command goes over that SSH as root. Agent37 never ends an instance on its own: lifetime janitor, capped at 30 minutes for the run. No stream() (a screen is streamed through agentrun), so screen.stream is skipped. Kind desktop (COMPUTER_AGENT37_KIND=desktop) starts from agentrun-box-<recipe hash>, our box image registered as a template of the key's workspace (prepareImage), with Xvfb on :0 started through the daemon as the tool user. With no COMPUTER_AGENT37_SSH_KEY, the run makes an ed25519 key for its process and registers it on the workspace (agentrun-<hash>) before its first instance; the key stays there, one more of the workspace's 20.",
53
54
  ];
54
55
  const agent37 = hostedModule({
55
56
  live: { name: AGENT37_ENV.live, what: "the Agent37 conformance module makes real instances, which bill until deleted", whose: "a key for an account you can bill" },
@@ -185,7 +185,10 @@ export const providerCases = [
185
185
  const made = t.ok(first, "create");
186
186
  t.deepEqual(refOf(t.ok(early, "the same create again while the first starts")), refOf(made), "the computer a create retried while it starts answers");
187
187
  t.deepEqual(refOf(t.ok(await t.attempt(spec, t.provider, requestId), "the same create again once it is up")), refOf(made), "the computer a create retried once it is up answers");
188
- t.equal(made.name, computerNameFor(requestId), "the computer's name, computer-<12 hex of sha256(request id)>");
188
+ // The request's name (computerNameFor) is the computer's, or begins it before a dash: a vendor whose name also
189
+ // carries what list reads (Orgo's deadline) puts that after it.
190
+ const request = computerNameFor(requestId);
191
+ t.assert(made.name === request || made.name.startsWith(`${request}-`), `the computer's name is ${request} (computer-<12 hex of sha256(request id)>), or begins with it and a dash: got ${made.name}`);
189
192
  t.deepEqual(await names(t, labels), [made.name], "the computers three creates of one request made");
190
193
  const other = t.refused(await t.attempt(t.spec({ labels: { ...labels, role: "other" } }), t.provider, requestId), "the same request id with other labels", ["exists"]);
191
194
  t.assert(other.message.includes(made.name), `the refusal names the request's computer ${made.name}: ${other.message}`);
@@ -44,6 +44,20 @@ export interface HostCommand {
44
44
  */
45
45
  readonly builds?: readonly string[];
46
46
  }
47
+ /**
48
+ * Where a provider keeps a secret it makes for itself (its descriptor's `secrets`): one value by each name, shared by
49
+ * every provider made on the same store, and by every process on it. A server's is sealed in its store.
50
+ */
51
+ export interface ProviderSecrets {
52
+ /** The value kept under `name`; undefined for none, and for one that does not open there. */
53
+ get(name: string): Promise<string | undefined>;
54
+ /**
55
+ * Keeps `value` under `name` unless a value is kept there already, and answers the one kept: of callers racing on one
56
+ * name, in this process or another on the same store, every one answers the same value. Undefined when none could be
57
+ * kept.
58
+ */
59
+ putIfAbsent(name: string, value: string): Promise<string | undefined>;
60
+ }
47
61
  /**
48
62
  * A provider, declared once. Every field is data but load(), which imports the provider module only when called:
49
63
  * reading a descriptor loads no provider and no vendor SDK.
@@ -124,10 +138,23 @@ export interface ProviderDescriptor<Module extends ProviderModule = ProviderModu
124
138
  readonly connect?: "dial" | "either";
125
139
  /** Its computers run on this machine's container engine: a server passes it its local host options (volume, host addresses). */
126
140
  readonly local?: boolean;
141
+ /**
142
+ * Its sandbox is the box a server gives a new agent that names no place and needs a shell (Docker's): one provider at
143
+ * most sets it. Where that box is not available, a server gives such an agent no other box in its place.
144
+ */
145
+ readonly defaultBox?: true;
127
146
  /** create() takes a ledger the server keeps for it, as `options[ledger.option]` (the phone harness's sessions). */
128
147
  readonly ledger?: {
129
148
  readonly option: string;
130
149
  };
150
+ /**
151
+ * create() takes the server's store of secrets the provider makes for itself (ProviderSecrets: Agent37's SSH key), as
152
+ * `options[secrets.option]`: one per server store, sealed at rest, never shown. Without one, a provider keeps what it
153
+ * makes for its process alone.
154
+ */
155
+ readonly secrets?: {
156
+ readonly option: string;
157
+ };
131
158
  /**
132
159
  * The server's own environment variables its provider reads on this machine, by name (Local Chrome's, where it finds
133
160
  * Chrome; a cloud browser's, the gateway a server reaches its API through): a server passes their values, and no other
@@ -95,6 +95,8 @@ export function descriptorProblems(value) {
95
95
  problems.push("connect is either exactly where a setting fills the connect option");
96
96
  if (d.ledger !== undefined && (typeof d.ledger?.option !== "string" || d.ledger.option === ""))
97
97
  problems.push("ledger names the option it fills");
98
+ if (d.secrets !== undefined && (typeof d.secrets?.option !== "string" || d.secrets.option === ""))
99
+ problems.push("secrets names the option it fills");
98
100
  if (d.imageEnv !== undefined && (typeof d.imageEnv !== "string" || !/^[A-Z][A-Z0-9_]*$/.test(d.imageEnv)))
99
101
  problems.push("imageEnv is an environment variable name (capital letters, digits and underscores)");
100
102
  if (d.hostEnv !== undefined && (!Array.isArray(d.hostEnv) || d.hostEnv.some((name) => typeof name !== "string" || name === "")))
@@ -10,8 +10,11 @@ export declare const AGENT37: {
10
10
  }, {
11
11
  readonly name: "AGENT37_SSH_KEY";
12
12
  readonly option: "sshKey";
13
- readonly required: true;
13
+ readonly required: false;
14
14
  }];
15
+ readonly secrets: {
16
+ readonly option: "secrets";
17
+ };
15
18
  readonly metered: true;
16
19
  readonly mounts: readonly ["archil"];
17
20
  readonly network: readonly ["none", "open", "allow"];
@@ -10,9 +10,12 @@ export const AGENT37 = defineProvider({
10
10
  label: "Agent37",
11
11
  keys: [
12
12
  { name: "AGENT37_API_KEY", option: "apiKey", required: true },
13
- // The private half of the SSH key registered on the workspace: every command reaches the machine over SSH.
14
- { name: "AGENT37_SSH_KEY", option: "sshKey", required: true },
13
+ // Every command reaches the machine over SSH. Optional: the private half of a key already on the workspace, used as
14
+ // given; unset, the provider makes its own and registers it with the API key (agent37.ts, kept in `secrets`).
15
+ { name: "AGENT37_SSH_KEY", option: "sshKey", required: false },
15
16
  ],
17
+ // The SSH key the provider makes for itself, kept in the server's sealed store: one per server.
18
+ secrets: { option: "secrets" },
16
19
  metered: true,
17
20
  mounts: ["archil"],
18
21
  // None: its programs run in a network of their own, their loopback alone (isolation.ts), and the instance is made
@@ -20,6 +20,7 @@ export declare const DOCKER: {
20
20
  }];
21
21
  readonly prepareImage: true;
22
22
  readonly local: true;
23
+ readonly defaultBox: true;
23
24
  readonly hostEnv: readonly string[];
24
25
  readonly load: () => Promise<typeof import("../docker.js")>;
25
26
  };
@@ -16,6 +16,8 @@ export const DOCKER = defineProvider({
16
16
  // No default image: the server makes one from the provider's recipe (prepareImage) before the first create.
17
17
  prepareImage: true,
18
18
  local: true,
19
+ // The box a new agent with no place gets, where this machine's Docker answers.
20
+ defaultBox: true,
19
21
  // What the docker CLI reads (env-names.ts DOCKER_ENV_NAMES): the server's own values of these, and no other.
20
22
  hostEnv: DOCKER_ENV_NAMES,
21
23
  load: () => import("../docker.js"),
@@ -36,6 +36,7 @@ export declare const DESCRIPTORS: readonly [{
36
36
  }];
37
37
  readonly prepareImage: true;
38
38
  readonly local: true;
39
+ readonly defaultBox: true;
39
40
  readonly hostEnv: readonly string[];
40
41
  readonly load: () => Promise<typeof import("../docker.js")>;
41
42
  }, {
@@ -188,8 +189,11 @@ export declare const DESCRIPTORS: readonly [{
188
189
  }, {
189
190
  readonly name: "AGENT37_SSH_KEY";
190
191
  readonly option: "sshKey";
191
- readonly required: true;
192
+ readonly required: false;
192
193
  }];
194
+ readonly secrets: {
195
+ readonly option: "secrets";
196
+ };
193
197
  readonly metered: true;
194
198
  readonly mounts: readonly ["archil"];
195
199
  readonly network: readonly ["none", "open", "allow"];
package/dist/host.d.ts CHANGED
@@ -266,13 +266,16 @@ export interface HostFacts {
266
266
  * value together, the adapter's at their longest. Past either, check() refuses, and so create, before any host call.
267
267
  * Absent: no bound. packed: the adapter packs the labels it gives create (packLabels, ./hosted/values.ts: one name to
268
268
  * list by, the map in parts of at most valueBytes each), unpacks those get and list answer, and asks list for that
269
- * name alone; the host stores and answers them as they are. count and bytes are then the packed labels'.
269
+ * name alone; the host stores and answers them as they are. count and bytes are then the packed labels'. unpacked:
270
+ * the host's machines may also carry their labels as given (made before it packed): one with no packed map reads as
271
+ * its stored labels, and a listing by name asks for the labels as given beside the packed name.
270
272
  */
271
273
  labels?: {
272
274
  count?: number;
273
275
  bytes?: number;
274
276
  packed?: {
275
277
  valueBytes?: number;
278
+ unpacked?: true;
276
279
  };
277
280
  };
278
281
  /**
@@ -184,7 +184,9 @@ export declare class HostedProvider implements ComputerProvider {
184
184
  /**
185
185
  * The host's listing by labels, bounded by ms: only the machines that carry every one of them, since a vendor's listing
186
186
  * may answer more (MachineHost.list). A packed host is asked for PACKED_NAME alone, the name's where one is asked, and
187
- * its machines' labels unpacked.
187
+ * its machines' labels unpacked. A listing by name on a host whose machines may also carry their labels as given
188
+ * (facts.labels.packed.unpacked) asks both ways, one after the other within ms together, and answers every machine
189
+ * either finds: across an upgrade one request can make one machine of each form, and convergence must see both.
188
190
  */
189
191
  export declare function listedBy(host: MachineHost, what: string, labels: Record<string, string>, ms: number, signal?: AbortSignal): Promise<Result<Machine[]>>;
190
192
  /**
@@ -1772,18 +1772,38 @@ function packedRoom(host) {
1772
1772
  const room = host.facts.labels;
1773
1773
  return room?.packed ? room : undefined;
1774
1774
  }
1775
- /** A machine as the host read it, with a packed host's labels unpacked: none where it holds no packed map (not the adapter's). */
1776
- const unpacked = (host, machine) => (packedRoom(host) === undefined ? machine : { ...machine, labels: unpackLabels(machine.labels) ?? {} });
1775
+ /**
1776
+ * A machine as the host read it, with a packed host's labels unpacked. One that holds no packed map has none (not the
1777
+ * adapter's), or its stored labels on a host whose machines may carry them as given (facts.labels.packed.unpacked).
1778
+ */
1779
+ function unpacked(host, machine) {
1780
+ const room = packedRoom(host);
1781
+ if (room === undefined)
1782
+ return machine;
1783
+ return { ...machine, labels: unpackLabels(machine.labels) ?? (room.packed?.unpacked ? machine.labels : {}) };
1784
+ }
1777
1785
  /**
1778
1786
  * The host's listing by labels, bounded by ms: only the machines that carry every one of them, since a vendor's listing
1779
1787
  * may answer more (MachineHost.list). A packed host is asked for PACKED_NAME alone, the name's where one is asked, and
1780
- * its machines' labels unpacked.
1788
+ * its machines' labels unpacked. A listing by name on a host whose machines may also carry their labels as given
1789
+ * (facts.labels.packed.unpacked) asks both ways, one after the other within ms together, and answers every machine
1790
+ * either finds: across an upgrade one request can make one machine of each form, and convergence must see both.
1781
1791
  */
1782
1792
  export async function listedBy(host, what, labels, ms, signal) {
1783
1793
  const name = labels[NAME_LABEL];
1784
- const asked = packedRoom(host) === undefined ? labels : name === undefined ? {} : { [PACKED_NAME]: name };
1785
- const listed = await hostCall(host, what, (ctx) => host.list(asked, ctx), ms, signal);
1786
- return listed.ok ? ok(listed.value.map((machine) => unpacked(host, machine)).filter((machine) => carries(machine, labels))) : listed;
1794
+ const room = packedRoom(host);
1795
+ const asks = room === undefined ? [labels] : name === undefined ? [{}] : room.packed?.unpacked ? [{ [PACKED_NAME]: name }, labels] : [{ [PACKED_NAME]: name }];
1796
+ const until = Date.now() + ms;
1797
+ const found = new Map();
1798
+ for (const asked of asks) {
1799
+ const listed = await hostCall(host, what, (ctx) => host.list(asked, ctx), Math.max(1, until - Date.now()), signal);
1800
+ if (!listed.ok)
1801
+ return listed;
1802
+ for (const machine of listed.value)
1803
+ if (!found.has(machine.id))
1804
+ found.set(machine.id, unpacked(host, machine));
1805
+ }
1806
+ return ok([...found.values()].filter((machine) => carries(machine, labels)));
1787
1807
  }
1788
1808
  /** Whether a machine carries every one of these labels. */
1789
1809
  const carries = (machine, labels) => Object.entries(labels).every(([key, value]) => machine.labels?.[key] === value);
@@ -75,11 +75,17 @@ export interface SshExecOptions {
75
75
  /** The login to machine id. */
76
76
  loginOf: (id: string) => SshLogin;
77
77
  tunnelOf: SshTunnelOf;
78
+ /**
79
+ * Until when (ms since the epoch) a login machine id's sshd refuses is tried again, every DENIED_RETRY_MS within the
80
+ * call's bound: a key the vendor is still handing its machines (Agent37's, minutes after its registration). Absent,
81
+ * or past: a refused login fails at once.
82
+ */
83
+ deniedUntil?: (id: string) => number;
78
84
  }
79
85
  /** MachineHost.exec over SSH: argv as the host's login, as channels on one connection per machine, shared by its execs. */
80
86
  export declare class SshExec {
81
87
  #private;
82
- constructor({ ssh2, loginOf, tunnelOf }: SshExecOptions);
88
+ constructor({ ssh2, loginOf, tunnelOf, deniedUntil }: SshExecOptions);
83
89
  /** Ends every connection to machine id, channels and all: the vendor calls it once the machine is deleted. */
84
90
  closeAll(id: string): void;
85
91
  /**