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

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.
package/dist/browser.js CHANGED
@@ -6,6 +6,7 @@ import { randomBytes } from "node:crypto";
6
6
  import { PROTOCOL_VERSION } from "./protocol.js";
7
7
  import { checkGpu, checkLifetime } from "./provider.js";
8
8
  import { errorOf, fail, ok } from "./result.js";
9
+ import { labelsDiffer } from "./create-requests.js";
9
10
  import { BROWSER_IMAGE } from "./descriptors/shared.js";
10
11
  /** A key's or a value's longest, in characters: what both vendors keep of a metadata entry. */
11
12
  const MAX_LABEL = 256;
@@ -58,18 +59,52 @@ export const carries = (held, labels) => typeof held === "object" && held !== nu
58
59
  /** The labels a vendor's metadata holds, its string entries only. */
59
60
  export const labelsOf = (held) => typeof held === "object" && held !== null ? Object.fromEntries(Object.entries(held).filter((entry) => typeof entry[1] === "string")) : {};
60
61
  /**
61
- * The label every create writes beside the spec's, a value of its own: a create whose reply is lost, or whose caller
62
- * cancels it, finds the browser it made by this label alone and releases it. The provider's own: check() refuses it in a
63
- * spec, and no list or attach shows it.
62
+ * The label every create writes beside the spec's, the name of its request (computerNameFor): a create retried, here or
63
+ * in another process, finds the browser the first made by this label (heldBrowser), and a create that made one finds
64
+ * the request's others by it (convergedBrowser). The provider's own: check() refuses it in a spec, and no list or
65
+ * attach shows it.
64
66
  */
65
67
  export const CREATE_LABEL = "agentrun.create";
66
- /** Labels without the provider's create label. */
68
+ /**
69
+ * The label each create's POST writes beside the create label, a random value of that POST's own (newAttempt): a create
70
+ * whose reply is lost, or whose caller cancels it, finds the browser its own POST made by this label alone and releases
71
+ * it, never another create's browser of the same request. The provider's own, as the create label is.
72
+ */
73
+ export const ATTEMPT_LABEL = "agentrun.attempt";
74
+ /** A create attempt's own value of ATTEMPT_LABEL. */
75
+ export const newAttempt = () => randomBytes(8).toString("hex");
76
+ /** Labels without the provider's own, the create and attempt labels. */
67
77
  export const withoutCreateLabel = (labels) => {
68
- const { [CREATE_LABEL]: _, ...rest } = labels;
78
+ const { [CREATE_LABEL]: _, [ATTEMPT_LABEL]: __, ...rest } = labels;
69
79
  return rest;
70
80
  };
71
- /** A create label's value: 16 hex digits, fresh per create. */
72
- export const createLabelValue = () => randomBytes(8).toString("hex");
81
+ /**
82
+ * The order a request's browsers are read in (heldBrowser, a create's converge): the oldest first, by the time the
83
+ * vendor made each, then by id. The same browsers give the same order in every process.
84
+ */
85
+ export const oldestBrowserFirst = (a, b) => String(a.createdAt ?? "").localeCompare(String(b.createdAt ?? "")) || a.id.localeCompare(b.id);
86
+ /**
87
+ * The browser a vendor holds for a create's request (provider.md, Idempotent create), among those its create label finds
88
+ * (found, each with its labels as list shows them): undefined when there is none, so create makes it, else the oldest
89
+ * (oldestBrowserFirst), with how its labels differ from the ones asked (labelsDiffer; empty when it is this spec's). A
90
+ * browser's own options are not read back from the vendor, so a create from another process compares the labels alone.
91
+ */
92
+ export function heldBrowser(asked, found) {
93
+ const first = [...found].sort(oldestBrowserFirst)[0];
94
+ return first === undefined ? undefined : { id: first.id, differ: labelsDiffer(asked, first.labels, "read back") };
95
+ }
96
+ /**
97
+ * Where a create that made a browser stands among its request's (provider.md, Idempotent create). Two creates of one
98
+ * request in two processes can both find no browser by the create label and both make one: CreateRequests holds within
99
+ * one provider alone. So after the vendor's answer the label is listed again (listed; mine, made just now, added when it
100
+ * is not listed yet): "mine" when mine is the oldest, so the create answers it; else the older, which the create
101
+ * answers in place of its own once it has released its own. Every process picks the same one from the same listing.
102
+ */
103
+ export function convergedBrowser(listed, mine) {
104
+ const holders = listed.some((one) => one.id === mine.id) ? [...listed] : [...listed, { ...mine, createdAt: mine.createdAt ?? new Date().toISOString() }];
105
+ const kept = holders.sort(oldestBrowserFirst)[0];
106
+ return kept.id === mine.id ? "mine" : kept;
107
+ }
73
108
  /**
74
109
  * Whether a create that threw may still have made a browser: anything but the vendor's own 4xx answer (a refusal, which
75
110
  * makes nothing). A request not answered, aborted, cut short, or answered 5xx or with a body that is no browser may
@@ -79,17 +114,20 @@ export function createUncertain(error) {
79
114
  const status = error?.status;
80
115
  return !(typeof status === "number" && status >= 400 && status < 500);
81
116
  }
82
- /** How long a lost create's browser is looked for, in all, and how often: a vendor may list it a moment late. */
117
+ /**
118
+ * How long a lost create's browser is looked for and released, in all, and how often: a vendor may list it a moment
119
+ * late. Also the default bound of every other release a create runs for itself (a provider's cleanupMs).
120
+ */
83
121
  export const RECOVER_MS = 30_000;
84
122
  const RECOVER_TRIES = 3;
85
123
  const RECOVER_GAP_MS = 2_000;
86
124
  /**
87
- * After a create whose outcome is unknown: the browsers carrying its create label, found under a signal of the
88
- * recovery's own (the caller's may be what ended the create), each released. The words say what became of them, for the
89
- * create's failure; they never carry a URL.
125
+ * After a create whose outcome is unknown: the browsers carrying its create label, found and released under a signal
126
+ * of the recovery's own, `ms` in all (the caller's may be what ended the create). The words say what became of them, for
127
+ * the create's failure; they never carry a URL.
90
128
  */
91
- export async function recoverCreate(what, find, release, sleep) {
92
- const signal = AbortSignal.timeout(RECOVER_MS);
129
+ export async function recoverCreate(what, find, release, sleep, ms = RECOVER_MS) {
130
+ const signal = AbortSignal.timeout(ms);
93
131
  let found = ok([]);
94
132
  for (let tries = 0; tries < RECOVER_TRIES; tries++) {
95
133
  if (tries > 0)
@@ -104,8 +142,13 @@ export async function recoverCreate(what, find, release, sleep) {
104
142
  return `no ${what} carries its create label, so none was made or the vendor does not list it yet; its labels let a sweep find it`;
105
143
  const words = [];
106
144
  for (const id of found.value) {
107
- const released = await release(id);
108
- words.push(released.ok ? `the ${what} it made (${id}) was released` : `the ${what} it made (${id}) was not released (${released.error.code}), and its labels let a sweep find it`);
145
+ const released = await release(id, signal);
146
+ if (released.ok)
147
+ words.push(`the ${what} it made (${id}) was released`);
148
+ else if (signal.aborted)
149
+ words.push(`the ${what} it made (${id}) may still be running: the search and its release did not finish within ${ms / 1000} s, and its labels let a sweep find it`);
150
+ else
151
+ words.push(`the ${what} it made (${id}) was not released (${released.error.code}), and its labels let a sweep find it`);
109
152
  }
110
153
  return words.join("; ");
111
154
  }
@@ -134,8 +177,12 @@ export function checkBrowser(spec, capabilities, vendor, minLifetimeMs = 1) {
134
177
  const problem = labelsProblem(labels);
135
178
  if (problem)
136
179
  refusals.push({ field: "labels", message: problem });
137
- else if (Object.hasOwn(labels, CREATE_LABEL))
138
- refusals.push({ field: "labels", message: `the label ${CREATE_LABEL} is the provider's own: each create writes it, so a lost create finds its browser` });
180
+ else {
181
+ for (const own of [CREATE_LABEL, ATTEMPT_LABEL]) {
182
+ if (Object.hasOwn(labels, own))
183
+ refusals.push({ field: "labels", message: `the label ${own} is the provider's own: each create writes it, so a retried or lost create finds its browser` });
184
+ }
185
+ }
139
186
  }
140
187
  // A browser declares no gpu: one asked is refused, in the words every provider shares.
141
188
  refusals.push(...checkGpu(given.gpu, capabilities));
@@ -177,6 +224,18 @@ export function browserClient(hello, alive) {
177
224
  * up to confirm.polls times. Done means the vendor says it no longer runs, not that the request was sent; a session the
178
225
  * vendor no longer knows ("gone") is released. A session still running is a failure carrying the request's own error.
179
226
  */
227
+ /**
228
+ * A release a create runs for itself (its caller gone, or its browser the newer of the request's two), under a signal of
229
+ * its own that ends after `ms`, never the caller's: one that does not finish by then is a timeout that says the browser
230
+ * may still be running.
231
+ */
232
+ export async function boundedRelease(what, id, ms, release) {
233
+ const signal = AbortSignal.timeout(ms);
234
+ const released = await release(signal);
235
+ if (released.ok || !signal.aborted)
236
+ return released;
237
+ return fail("timeout", `its release did not finish within ${ms / 1000} s, so the ${what} ${id} may still be running`);
238
+ }
180
239
  export async function releaseConfirmed(o) {
181
240
  let failure;
182
241
  for (let attempt = 0; attempt < 2; attempt++) {
@@ -22,6 +22,8 @@ export interface BrowserbaseSession {
22
22
  connectUrl?: string;
23
23
  userMetadata?: Record<string, unknown>;
24
24
  expiresAt?: string;
25
+ /** When Browserbase made the session. */
26
+ createdAt?: string;
25
27
  /** When the session started and ended, as Browserbase records them (no end while it runs). */
26
28
  startedAt?: string;
27
29
  endedAt?: string;
@@ -100,6 +102,12 @@ export interface BrowserbaseProviderOptions {
100
102
  fetch?: typeof fetch;
101
103
  confirm?: ReleaseConfirm;
102
104
  sleep?: (ms: number) => Promise<void>;
105
+ /**
106
+ * How long, in all, a cleanup a create runs for itself may take: the release of the browser its POST made once its
107
+ * caller is gone, or once another create of the request made one first, and the search and release after a lost
108
+ * reply. Default RECOVER_MS. The caller's signal never cuts it short.
109
+ */
110
+ cleanupMs?: number;
103
111
  }
104
112
  /**
105
113
  * A session's signed CDP URL as a driver dials it: on the gateway that fronts the sessions' sockets where a server is
@@ -114,7 +122,7 @@ export declare class BrowserbaseProvider implements ComputerProvider, BrowserCom
114
122
  readonly version: string;
115
123
  readonly profiles: BrowserProfiles;
116
124
  readonly downloads: BrowserDownloads;
117
- constructor({ apiKey, projectId, apiUrl, env, fetch: fetcher, confirm, sleep }: BrowserbaseProviderOptions);
125
+ constructor({ apiKey, projectId, apiUrl, env, fetch: fetcher, confirm, sleep, cleanupMs }: BrowserbaseProviderOptions);
118
126
  /**
119
127
  * A browser: Browserbase ends a session at its timeout (lifetime vendor), at most 6 h; it reaches the open web; each
120
128
  * session is its own VM. browser is what its sessions offer beyond the protocol. Its downloads are read through the
@@ -124,8 +132,11 @@ export declare class BrowserbaseProvider implements ComputerProvider, BrowserCom
124
132
  capabilities(): ComputerCapabilities;
125
133
  check(spec: ComputerSpec): Refusal[];
126
134
  /**
127
- * Makes a session at most once: with keepAlive, so a dropped CDP client never ends it, the lifetime as its timeout in
128
- * whole seconds, and the labels as its userMetadata. spec.browser is the session's own options, each refused by check()
135
+ * Makes a session once per request (provider.md, Idempotent create): with keepAlive, so a dropped CDP client never
136
+ * ends it, the lifetime as its timeout in whole seconds, and the labels as its userMetadata, with the request's name
137
+ * (computerNameFor) as its create label. A request whose session Browserbase still runs or starts answers that one,
138
+ * found by its create label; one whose session was released here is refused exists; a create of a request in flight
139
+ * here waits for the first (CreateRequests). spec.browser is the session's own options, each refused by check()
129
140
  * unless declared.
130
141
  */
131
142
  create(spec: ComputerSpec, context: CreateContext): Promise<Result<CreatedComputer>>;
@@ -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, 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";
@@ -52,6 +53,8 @@ const toMetadata = (labels = {}) => Object.fromEntries(Object.entries(labels).ma
52
53
  const metadataLabels = (held) => Object.fromEntries(Object.entries(labelsOf(held)).map(([key, value]) => [labelKey(key), value]));
53
54
  /** userMetadata as the labels list and attach show: without the provider's create label. */
54
55
  const fromMetadata = (held) => withoutCreateLabel(metadataLabels(held));
56
+ /** A session as its create label finds it: its id, when Browserbase made it, and its labels. */
57
+ const heldOf = (s) => ({ id: s.id, ...(s.createdAt ?? s.startedAt ? { createdAt: (s.createdAt ?? s.startedAt) } : {}), labels: fromMetadata(s.userMetadata) });
55
58
  /** Why labels cannot ride a Browserbase session's userMetadata, in words naming the label; undefined when they can. */
56
59
  export function browserbaseLabelsProblem(labels) {
57
60
  const problem = labelsProblem(labels);
@@ -212,7 +215,18 @@ export class BrowserbaseProvider {
212
215
  #urls;
213
216
  #confirm;
214
217
  #sleep;
215
- constructor({ apiKey, projectId, apiUrl, env = {}, fetch: fetcher, confirm = DEFAULT_CONFIRM, sleep = defaultSleep }) {
218
+ /** The bound of each cleanup a create runs for itself (cleanupMs). */
219
+ #cleanupMs;
220
+ /** Idempotent create's in-process half: one session per request id (provider.md). */
221
+ #requests = new CreateRequests();
222
+ /** The request's name of each session this provider made or found for a create, by id: its release ends the request. */
223
+ #requestOf = new Map();
224
+ /**
225
+ * The session each request's create answered, by the request's name, kept past its release: a request whose session
226
+ * ended on its own (its timeout, the vendor) is refused exists, as one released here is, never made again.
227
+ */
228
+ #madeFor = new Map();
229
+ constructor({ apiKey, projectId, apiUrl, env = {}, fetch: fetcher, confirm = DEFAULT_CONFIRM, sleep = defaultSleep, cleanupMs = RECOVER_MS }) {
216
230
  if (typeof apiKey !== "string" || apiKey === "")
217
231
  throw new Error("set options.apiKey to a Browserbase API key: the provider reads no environment");
218
232
  const gateway = env.BROWSERBASE_BASE_URL?.trim() || undefined;
@@ -224,6 +238,7 @@ export class BrowserbaseProvider {
224
238
  this.#urls = memoryUrls();
225
239
  this.#confirm = confirm;
226
240
  this.#sleep = sleep;
241
+ this.#cleanupMs = cleanupMs;
227
242
  this.#browser = {
228
243
  timeout: "wall-clock",
229
244
  stealth: true,
@@ -264,19 +279,47 @@ export class BrowserbaseProvider {
264
279
  return refusals;
265
280
  }
266
281
  /**
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()
282
+ * Makes a session once per request (provider.md, Idempotent create): with keepAlive, so a dropped CDP client never
283
+ * ends it, the lifetime as its timeout in whole seconds, and the labels as its userMetadata, with the request's name
284
+ * (computerNameFor) as its create label. A request whose session Browserbase still runs or starts answers that one,
285
+ * found by its create label; one whose session was released here is refused exists; a create of a request in flight
286
+ * here waits for the first (CreateRequests). spec.browser is the session's own options, each refused by check()
269
287
  * unless declared.
270
288
  */
271
289
  async create(spec, context) {
272
- const signal = context?.signal;
273
290
  const refusals = this.check(spec);
274
- if (refusals.length > 0)
275
- return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
291
+ return this.#requests.create(spec, context, {
292
+ refuse: fail,
293
+ ...(refusals.length > 0 ? { refused: refusals.map(({ field, message }) => `${field}: ${message}`).join("; ") } : {}),
294
+ make: async (request) => {
295
+ const made = await this.#createNamed(spec, request, context.signal);
296
+ if (made.ok)
297
+ this.#madeFor.set(request, made.value.id);
298
+ return made;
299
+ },
300
+ });
301
+ }
302
+ /** Everything create does under the request's name: the session Browserbase holds under it, or a new one. */
303
+ async #createNamed(spec, request, signal) {
276
304
  if (signal?.aborted)
277
305
  return fail("aborted", "create was aborted before Browserbase was called");
306
+ const held = await this.#sessions({ [CREATE_LABEL]: request }, signal);
307
+ if (!held.ok)
308
+ return held;
309
+ const found = heldBrowser(spec.labels ?? {}, held.value.map(heldOf));
310
+ if (found !== undefined) {
311
+ if (found.differ.length > 0)
312
+ return fail("exists", otherSpecWords(`${request} (session ${found.id})`, "was made", found.differ));
313
+ this.#requestOf.set(found.id, request);
314
+ return ok(refOf({ id: found.id }));
315
+ }
316
+ const ended = await this.#ended(spec, request, signal);
317
+ if (ended !== undefined)
318
+ return ended;
278
319
  const browser = spec.browser;
279
- const written = { [CREATE_LABEL]: createLabelValue(), ...spec.labels };
320
+ // The request's label, which a retry and a converge find it by, and this POST's own, which its recovery finds it by.
321
+ const attempt = { [ATTEMPT_LABEL]: newAttempt() };
322
+ const written = { [CREATE_LABEL]: request, ...attempt, ...spec.labels };
280
323
  // Browserbase solves CAPTCHAs unless told not to: a browser's options say so either way, the solver only with stealth.
281
324
  const browserSettings = {
282
325
  ...(browser?.viewport ? { viewport: { width: browser.viewport.width, height: browser.viewport.height } } : {}),
@@ -299,12 +342,21 @@ export class BrowserbaseProvider {
299
342
  const failed = vendorFailure("browserbase", NAME, "POST /v1/sessions", error);
300
343
  if (failed.ok || !createUncertain(error))
301
344
  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");
345
+ // The session may have been made though its answer never came: found by this POST's attempt label and
346
+ // released, and the request is ended, so it is never made again.
347
+ this.#requests.end(request);
348
+ return causedFail(failed.error.code, `${failed.error.message}; ${await this.#recover(attempt)}`, causeOf(failed), "browserbase");
304
349
  }
305
350
  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)}`);
351
+ this.#requests.end(request);
352
+ return vendorFail("browserbase", `Browserbase POST /v1/sessions answered with no session id, so there is no session to connect to; ${await this.#recover(attempt)}`);
307
353
  }
354
+ this.#requests.made(request);
355
+ // Another process's create of this request may have made one too (#converge): the older is answered.
356
+ const converged = await this.#converge(spec, request, made, signal);
357
+ if (converged !== undefined)
358
+ return converged;
359
+ this.#requestOf.set(made.id, request);
308
360
  const unusable = cdpUrlProblem(made.connectUrl, NAME, CDP_DOMAIN);
309
361
  if (unusable !== undefined) {
310
362
  // The session is made and billed (keepAlive, up to its timeout): released here, not left to a later sweep.
@@ -314,6 +366,64 @@ export class BrowserbaseProvider {
314
366
  this.#urls.set(made.id, made.connectUrl);
315
367
  return ok(refOf(made));
316
368
  }
369
+ /**
370
+ * The one session a request keeps (convergedBrowser): the request's create label listed again once Browserbase made
371
+ * mine. Undefined when mine is the oldest (or the listing fails: the create goes on with its own); an abort releases
372
+ * mine, never under the caller's signal, and the create is aborted. Else mine is
373
+ * released, never under the caller's signal, and the older answered: refused exists when it has ended by then, or when
374
+ * its labels are another spec's.
375
+ */
376
+ async #converge(spec, request, mine, signal) {
377
+ const listed = await this.#sessions({ [CREATE_LABEL]: request }, signal);
378
+ if (!listed.ok) {
379
+ if (listed.error.code !== "aborted" && !signal?.aborted)
380
+ return undefined;
381
+ // The caller is gone: the session this POST made is released, never under the caller's signal.
382
+ this.#requests.end(request);
383
+ const released = await boundedRelease("session", mine.id, this.#cleanupMs, (bound) => this.#releaseSession(mine.id, bound));
384
+ 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`}`);
385
+ }
386
+ const kept = convergedBrowser(listed.value.map(heldOf), heldOf(mine));
387
+ if (kept === "mine")
388
+ return undefined;
389
+ const released = await boundedRelease("session", mine.id, this.#cleanupMs, (bound) => this.#releaseSession(mine.id, bound));
390
+ if (!released.ok)
391
+ 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})`);
392
+ const alive = await this.#alive(kept.id, signal);
393
+ if (!alive.ok)
394
+ return alive;
395
+ if (!alive.value) {
396
+ this.#requests.end(request);
397
+ return fail("exists", endedWords(request));
398
+ }
399
+ const differ = labelsDiffer(spec.labels ?? {}, kept.labels, "read back");
400
+ if (differ.length > 0)
401
+ return fail("exists", otherSpecWords(`${request} (session ${kept.id})`, "was made", differ));
402
+ this.#requestOf.set(kept.id, request);
403
+ return ok(refOf({ id: kept.id }));
404
+ }
405
+ /**
406
+ * A request this provider answered a session for before, which its create label no longer finds: refused exists, the
407
+ * request ended, once Browserbase reads that session as ended too; one it still runs (a listing that left it out) is
408
+ * answered when its labels are this spec's. Undefined for a request with no session here yet.
409
+ */
410
+ async #ended(spec, request, signal) {
411
+ const before = this.#madeFor.get(request);
412
+ if (before === undefined)
413
+ return undefined;
414
+ const read = await this.#running(before, signal);
415
+ if (!read.ok && read.error.code !== "not_found" && read.error.code !== "gone")
416
+ return read;
417
+ if (!read.ok) {
418
+ this.#requests.end(request);
419
+ return fail("exists", endedWords(request));
420
+ }
421
+ const differ = labelsDiffer(spec.labels ?? {}, fromMetadata(read.value.userMetadata), "read back");
422
+ if (differ.length > 0)
423
+ return fail("exists", otherSpecWords(`${request} (session ${before})`, "was made", differ));
424
+ this.#requestOf.set(before, request);
425
+ return ok(refOf({ id: before }));
426
+ }
317
427
  /** A new context, a profile's pointer: one POST /v1/contexts, never retried. */
318
428
  async #createProfile({ signal } = {}) {
319
429
  try {
@@ -413,15 +523,16 @@ export class BrowserbaseProvider {
413
523
  }
414
524
  /**
415
525
  * 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.
526
+ * the attempt label its POST wrote (ATTEMPT_LABEL), through #sessions and its metadata-key mapping: another create's
527
+ * session, of this request or another, carries an attempt label of its own and is left alone, even one another
528
+ * instance has answered.
418
529
  */
419
530
  #recover(labels) {
420
531
  const find = async (signal) => {
421
532
  const found = await this.#sessions(labels, signal);
422
533
  return found.ok ? ok(found.value.map((s) => s.id)) : found;
423
534
  };
424
- return recoverCreate("session", find, (id) => this.release({ id, name: id }, "delete"), this.#sleep);
535
+ return recoverCreate("session", find, (id, signal) => this.release({ id, name: id }, "delete", { signal }), this.#sleep, this.#cleanupMs);
425
536
  }
426
537
  /**
427
538
  * Settings' test: one read of the project's running sessions (GET /v1/sessions?status=RUNNING), which makes nothing.
@@ -568,6 +679,17 @@ export class BrowserbaseProvider {
568
679
  const problem = idProblem(id, NAME);
569
680
  if (problem)
570
681
  return fail("invalid", problem);
682
+ // The request's session is ended here: a later create of it is refused exists, never made again.
683
+ const request = this.#requestOf.get(id);
684
+ if (request !== undefined)
685
+ this.#requests.end(request);
686
+ const released = await this.#releaseSession(id, signal);
687
+ if (released.ok)
688
+ this.#requestOf.delete(id);
689
+ return released;
690
+ }
691
+ /** Asks Browserbase to release the session and waits until it reads as ended; the request it was made for is not ended. */
692
+ async #releaseSession(id, signal) {
571
693
  const released = await releaseConfirmed({
572
694
  request: async () => {
573
695
  try {
Binary file
Binary file
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "0.1.0-beta.59",
2
+ "version": "0.1.0-beta.60",
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"];