@parcha/agentrun-computer 0.1.0-beta.58 → 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.
Files changed (143) hide show
  1. package/README.md +285 -81
  2. package/box/Dockerfile +4 -3
  3. package/box/install.sh +57 -11
  4. package/dist/agent37.d.ts +11 -4
  5. package/dist/agent37.js +217 -19
  6. package/dist/attach.d.ts +24 -4
  7. package/dist/attach.js +50 -19
  8. package/dist/boxd.js +22 -9
  9. package/dist/browser.d.ts +56 -11
  10. package/dist/browser.js +76 -17
  11. package/dist/browserbase.d.ts +20 -5
  12. package/dist/browserbase.js +186 -21
  13. package/dist/child-env.d.ts +11 -0
  14. package/dist/child-env.js +22 -0
  15. package/dist/chrome.d.ts +5 -2
  16. package/dist/chrome.js +5 -2
  17. package/dist/cloudflare.d.ts +2 -0
  18. package/dist/cloudflare.js +5 -3
  19. package/dist/computerd-linux-amd64 +0 -0
  20. package/dist/computerd-linux-arm64 +0 -0
  21. package/dist/computerd.json +1 -1
  22. package/dist/conformance/agent37.d.ts +20 -40
  23. package/dist/conformance/agent37.js +31 -118
  24. package/dist/conformance/archil.d.ts +13 -3
  25. package/dist/conformance/archil.js +22 -17
  26. package/dist/conformance/boxd.d.ts +8 -31
  27. package/dist/conformance/boxd.js +19 -74
  28. package/dist/conformance/browserbase.d.ts +3 -6
  29. package/dist/conformance/browserbase.js +6 -17
  30. package/dist/conformance/cases/health.js +6 -3
  31. package/dist/conformance/cases/provider.js +4 -1
  32. package/dist/conformance/cli.d.ts +3 -1
  33. package/dist/conformance/cli.js +69 -9
  34. package/dist/conformance/cloudflare.d.ts +3 -6
  35. package/dist/conformance/cloudflare.js +7 -15
  36. package/dist/conformance/daytona.d.ts +6 -20
  37. package/dist/conformance/daytona.js +22 -57
  38. package/dist/conformance/dial-only.d.ts +4 -3
  39. package/dist/conformance/dial-only.js +3 -3
  40. package/dist/conformance/docker.d.ts +4 -5
  41. package/dist/conformance/docker.js +8 -14
  42. package/dist/conformance/e2b.d.ts +10 -36
  43. package/dist/conformance/e2b.js +27 -84
  44. package/dist/conformance/fly.d.ts +3 -6
  45. package/dist/conformance/fly.js +2 -6
  46. package/dist/conformance/groundbox.d.ts +7 -23
  47. package/dist/conformance/groundbox.js +16 -56
  48. package/dist/conformance/index.d.ts +1 -0
  49. package/dist/conformance/index.js +1 -0
  50. package/dist/conformance/kernel.d.ts +3 -6
  51. package/dist/conformance/kernel.js +5 -15
  52. package/dist/conformance/kind.d.ts +0 -6
  53. package/dist/conformance/kind.js +0 -4
  54. package/dist/conformance/local-chrome.d.ts +5 -7
  55. package/dist/conformance/local-chrome.js +7 -11
  56. package/dist/conformance/modal.d.ts +10 -38
  57. package/dist/conformance/modal.js +27 -74
  58. package/dist/conformance/module-kit.d.ts +87 -0
  59. package/dist/conformance/module-kit.js +88 -0
  60. package/dist/conformance/morph.d.ts +7 -23
  61. package/dist/conformance/morph.js +20 -66
  62. package/dist/conformance/orgo.d.ts +5 -10
  63. package/dist/conformance/orgo.js +15 -27
  64. package/dist/conformance/phone-harness.d.ts +3 -5
  65. package/dist/conformance/phone-harness.js +3 -11
  66. package/dist/conformance/runner.d.ts +13 -3
  67. package/dist/conformance/runner.js +32 -11
  68. package/dist/conformance/smolcloud.d.ts +7 -23
  69. package/dist/conformance/smolcloud.js +16 -49
  70. package/dist/conformance/sweep.d.ts +10 -5
  71. package/dist/conformance/sweep.js +91 -38
  72. package/dist/conformance/tti.d.ts +69 -0
  73. package/dist/conformance/tti.js +205 -0
  74. package/dist/conformance/types.d.ts +9 -2
  75. package/dist/daytona.js +60 -20
  76. package/dist/descriptor.d.ts +37 -0
  77. package/dist/descriptor.js +9 -0
  78. package/dist/descriptors/agent37.d.ts +4 -1
  79. package/dist/descriptors/agent37.js +5 -2
  80. package/dist/descriptors/browserbase.d.ts +3 -0
  81. package/dist/descriptors/browserbase.js +4 -0
  82. package/dist/descriptors/docker.d.ts +2 -0
  83. package/dist/descriptors/docker.js +5 -0
  84. package/dist/descriptors/env-names.d.ts +32 -0
  85. package/dist/descriptors/env-names.js +60 -0
  86. package/dist/descriptors/index.d.ts +14 -3
  87. package/dist/descriptors/kernel.d.ts +3 -0
  88. package/dist/descriptors/kernel.js +2 -0
  89. package/dist/descriptors/local-chrome.d.ts +1 -1
  90. package/dist/descriptors/local-chrome.js +5 -3
  91. package/dist/descriptors/phone-harness.d.ts +1 -1
  92. package/dist/descriptors/phone-harness.js +4 -2
  93. package/dist/docker/egress.d.ts +7 -0
  94. package/dist/docker/egress.js +8 -0
  95. package/dist/docker/image.d.ts +5 -1
  96. package/dist/docker/image.js +12 -8
  97. package/dist/docker.d.ts +52 -13
  98. package/dist/docker.js +166 -92
  99. package/dist/drift.js +6 -6
  100. package/dist/e2b.d.ts +2 -2
  101. package/dist/e2b.js +2 -3
  102. package/dist/groundbox.js +6 -6
  103. package/dist/host.d.ts +23 -0
  104. package/dist/hosted/download.d.ts +23 -0
  105. package/dist/hosted/download.js +144 -0
  106. package/dist/hosted/process.d.ts +5 -0
  107. package/dist/hosted/process.js +20 -0
  108. package/dist/hosted/provider.js +120 -48
  109. package/dist/hosted/rest.d.ts +19 -8
  110. package/dist/hosted/rest.js +47 -14
  111. package/dist/hosted/scripts.d.ts +10 -0
  112. package/dist/hosted/scripts.js +23 -2
  113. package/dist/hosted/ssh-exec.d.ts +7 -1
  114. package/dist/hosted/ssh-exec.js +19 -14
  115. package/dist/hosted/ssh-key.d.ts +18 -0
  116. package/dist/hosted/ssh-key.js +36 -0
  117. package/dist/index.d.ts +5 -3
  118. package/dist/index.js +4 -2
  119. package/dist/janitor.d.ts +7 -1
  120. package/dist/janitor.js +2 -2
  121. package/dist/kernel.d.ts +14 -4
  122. package/dist/kernel.js +141 -18
  123. package/dist/local-chrome.d.ts +12 -3
  124. package/dist/local-chrome.js +108 -10
  125. package/dist/local-supervisor.js +1 -0
  126. package/dist/modal.d.ts +6 -5
  127. package/dist/modal.js +7 -7
  128. package/dist/morph.js +5 -8
  129. package/dist/orgo-channel.d.ts +3 -2
  130. package/dist/orgo-channel.js +3 -3
  131. package/dist/orgo-desktop.js +2 -4
  132. package/dist/orgo.d.ts +6 -0
  133. package/dist/orgo.js +158 -15
  134. package/dist/phone-harness.d.ts +7 -5
  135. package/dist/phone-harness.js +60 -61
  136. package/dist/protocol.d.ts +10 -0
  137. package/dist/protocol.js +17 -0
  138. package/dist/provider.d.ts +6 -2
  139. package/dist/screen-watch.d.ts +6 -1
  140. package/dist/screen-watch.js +166 -12
  141. package/dist/vendor-sdk.d.ts +9 -0
  142. package/dist/vendor-sdk.js +26 -0
  143. package/package.json +8 -1
@@ -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);
@@ -144,10 +147,50 @@ export function browserbaseRest({ apiKey, apiUrl = BROWSERBASE_API_URL, projectI
144
147
  /** Rows per downloads page, and the most pages a list reads before it fails rather than run on. */
145
148
  const DOWNLOADS_PAGE = 100;
146
149
  const MAX_PAGES = 100;
147
- /** How long after a saving session ends Browserbase may still be writing its context back. */
148
- export const BROWSERBASE_PROFILE_SETTLE_MS = 5_000;
149
150
  /** The directory Browserbase syncs a session's downloads from: a driver sets the download behaviour into it. */
150
151
  export const BROWSERBASE_DOWNLOADS_PATH = "downloads";
152
+ /**
153
+ * A session's signed CDP URL as a driver dials it: on the gateway that fronts the sessions' sockets where a server is
154
+ * behind one (BROWSERBASE_CONNECT_BASE_URL), its path under the gateway's and the signing query kept; else as Browserbase
155
+ * gave it. Only a URL on Browserbase's own domain moves, and a gateway that is no URL moves none.
156
+ */
157
+ export function throughGateway(connectUrl, connectBase) {
158
+ if (!connectBase)
159
+ return connectUrl;
160
+ try {
161
+ const target = new URL(connectBase);
162
+ const url = new URL(connectUrl);
163
+ const host = url.hostname.toLowerCase();
164
+ if (host !== CDP_DOMAIN && !host.endsWith(`.${CDP_DOMAIN}`))
165
+ return connectUrl;
166
+ url.protocol = target.protocol;
167
+ url.host = target.host;
168
+ url.pathname = target.pathname.replace(/\/$/, "") + url.pathname;
169
+ return url.toString();
170
+ }
171
+ catch {
172
+ return connectUrl;
173
+ }
174
+ }
175
+ /**
176
+ * The gateway that fronts the sessions' sockets (BROWSERBASE_CONNECT_BASE_URL), held to wss: or https: as httpsBase holds
177
+ * an API URL, since every session's signed CDP URL rides it; throws in words on another, loopback included. One that is
178
+ * no URL is not echoed: it may carry the gateway's own token.
179
+ */
180
+ function connectBaseOf(url) {
181
+ if (url === undefined)
182
+ return undefined;
183
+ let parsed;
184
+ try {
185
+ parsed = new URL(url);
186
+ }
187
+ catch {
188
+ throw new Error("BROWSERBASE_CONNECT_BASE_URL is not a URL");
189
+ }
190
+ if (parsed.protocol !== "wss:" && parsed.protocol !== "https:")
191
+ throw new Error(`BROWSERBASE_CONNECT_BASE_URL must be wss or https, so a session's signed URL never crosses in the clear: ${parsed.protocol}`);
192
+ return url;
193
+ }
151
194
  const refOf = (s) => ({ id: s.id, name: s.id });
152
195
  const deadlineOf = (s) => {
153
196
  const at = typeof s.expiresAt === "string" ? new Date(s.expiresAt) : undefined;
@@ -159,32 +202,47 @@ export class BrowserbaseProvider {
159
202
  version = VERSION;
160
203
  /**
161
204
  * A session ends at its timeout, a wall clock; it may be stealth (Verified, with the CAPTCHA solver); it opens a
162
- * context as a profile (written back about 5 s after a saving session ends) and keeps what is saved into downloads/.
163
- * capabilities().browser gives it.
205
+ * context as a profile (written back within its descriptor's settle window after a saving session ends) and keeps
206
+ * what is saved into downloads/. capabilities().browser gives it.
164
207
  */
165
208
  #browser;
166
209
  profiles;
167
210
  downloads;
168
211
  #api;
169
212
  #projectId;
213
+ /** The gateway that fronts the sessions' sockets (BROWSERBASE_CONNECT_BASE_URL), where a server is behind one. */
214
+ #connectBase;
170
215
  #urls;
171
216
  #confirm;
172
217
  #sleep;
173
- 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 }) {
174
230
  if (typeof apiKey !== "string" || apiKey === "")
175
231
  throw new Error("set options.apiKey to a Browserbase API key: the provider reads no environment");
176
232
  const gateway = env.BROWSERBASE_BASE_URL?.trim() || undefined;
177
- const behindGateway = Boolean(gateway || env.BROWSERBASE_CONNECT_BASE_URL?.trim());
233
+ this.#connectBase = connectBaseOf(env.BROWSERBASE_CONNECT_BASE_URL?.trim() || undefined);
234
+ const behindGateway = Boolean(gateway || this.#connectBase);
178
235
  this.#projectId = behindGateway ? undefined : projectId || undefined;
179
236
  const base = apiUrl || gateway;
180
237
  this.#api = browserbaseRest({ apiKey, ...(base ? { apiUrl: base } : {}), ...(this.#projectId ? { projectId: this.#projectId } : {}), ...(fetcher ? { fetch: fetcher } : {}) });
181
238
  this.#urls = memoryUrls();
182
239
  this.#confirm = confirm;
183
240
  this.#sleep = sleep;
241
+ this.#cleanupMs = cleanupMs;
184
242
  this.#browser = {
185
243
  timeout: "wall-clock",
186
244
  stealth: true,
187
- profiles: { settleMs: BROWSERBASE_PROFILE_SETTLE_MS },
245
+ profiles: { settleMs: BROWSERBASE.profiles.settleMs },
188
246
  downloads: { path: BROWSERBASE_DOWNLOADS_PATH },
189
247
  };
190
248
  this.profiles = { create: (context) => this.#createProfile(context), remove: (pointer, context) => this.#removeProfile(pointer, context) };
@@ -221,19 +279,47 @@ export class BrowserbaseProvider {
221
279
  return refusals;
222
280
  }
223
281
  /**
224
- * Makes a session at most once: with keepAlive, so a dropped CDP client never ends it, the lifetime as its timeout in
225
- * 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()
226
287
  * unless declared.
227
288
  */
228
289
  async create(spec, context) {
229
- const signal = context?.signal;
230
290
  const refusals = this.check(spec);
231
- if (refusals.length > 0)
232
- 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) {
233
304
  if (signal?.aborted)
234
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;
235
319
  const browser = spec.browser;
236
- 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 };
237
323
  // Browserbase solves CAPTCHAs unless told not to: a browser's options say so either way, the solver only with stealth.
238
324
  const browserSettings = {
239
325
  ...(browser?.viewport ? { viewport: { width: browser.viewport.width, height: browser.viewport.height } } : {}),
@@ -256,12 +342,21 @@ export class BrowserbaseProvider {
256
342
  const failed = vendorFailure("browserbase", NAME, "POST /v1/sessions", error);
257
343
  if (failed.ok || !createUncertain(error))
258
344
  return failed;
259
- // The session may have been made though its answer never came: found by its create label, never made again.
260
- 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");
261
349
  }
262
350
  if (idProblem(made?.id, NAME) !== undefined) {
263
- 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)}`);
264
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);
265
360
  const unusable = cdpUrlProblem(made.connectUrl, NAME, CDP_DOMAIN);
266
361
  if (unusable !== undefined) {
267
362
  // The session is made and billed (keepAlive, up to its timeout): released here, not left to a later sweep.
@@ -271,6 +366,64 @@ export class BrowserbaseProvider {
271
366
  this.#urls.set(made.id, made.connectUrl);
272
367
  return ok(refOf(made));
273
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
+ }
274
427
  /** A new context, a profile's pointer: one POST /v1/contexts, never retried. */
275
428
  async #createProfile({ signal } = {}) {
276
429
  try {
@@ -370,15 +523,16 @@ export class BrowserbaseProvider {
370
523
  }
371
524
  /**
372
525
  * The sessions a lost create made, released: what recoverCreate says of them. They are found as list finds any, by
373
- * the labels the create wrote (its create label first, so the query names it, then the run's), through #sessions and
374
- * 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.
375
529
  */
376
530
  #recover(labels) {
377
531
  const find = async (signal) => {
378
532
  const found = await this.#sessions(labels, signal);
379
533
  return found.ok ? ok(found.value.map((s) => s.id)) : found;
380
534
  };
381
- 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);
382
536
  }
383
537
  /**
384
538
  * Settings' test: one read of the project's running sessions (GET /v1/sessions?status=RUNNING), which makes nothing.
@@ -515,7 +669,7 @@ export class BrowserbaseProvider {
515
669
  this.#urls.set(id, url);
516
670
  const hello = browserHello(VERSION, this.capabilities().groups);
517
671
  const client = browserClient(hello, (signal) => this.#alive(id, signal));
518
- return ok({ client, hello, cdp: { url }, close: async () => client.close() });
672
+ return ok({ client, hello, cdp: { url: throughGateway(url, this.#connectBase) }, close: async () => client.close() });
519
673
  }
520
674
  /** Asks Browserbase to release the session and waits until it reads as ended; one already ended or unknown is released. */
521
675
  async release(ref, how, { signal } = {}) {
@@ -525,6 +679,17 @@ export class BrowserbaseProvider {
525
679
  const problem = idProblem(id, NAME);
526
680
  if (problem)
527
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) {
528
693
  const released = await releaseConfirmed({
529
694
  request: async () => {
530
695
  try {
@@ -0,0 +1,11 @@
1
+ export { ADB_ENV_NAMES, BASE_ENV_NAMES, CHROME_ENV_NAMES, DOCKER_ENV_NAMES } from "./descriptors/env-names.js";
2
+ /** The environment variables a host passes, by name; a name with no value is unset. */
3
+ export type HostEnv = Readonly<Record<string, string | undefined>>;
4
+ /** `env`'s values of `names` that are set, and nothing else: a child's whole environment. */
5
+ export declare function childEnv(env: HostEnv, names: readonly string[]): Record<string, string>;
6
+ /** A docker CLI child's environment: DOCKER_ENV_NAMES of `env`. */
7
+ export declare const dockerEnv: (env?: HostEnv) => Record<string, string>;
8
+ /** A Chrome child's (and the local browser's supervisor's) environment: CHROME_ENV_NAMES of `env`. */
9
+ export declare const chromeEnv: (env?: HostEnv) => Record<string, string>;
10
+ /** An adb child's (and the adb server's it starts) environment: ADB_ENV_NAMES of `env`. */
11
+ export declare const adbEnv: (env?: HostEnv) => Record<string, string>;
@@ -0,0 +1,22 @@
1
+ // The environment a child this package starts holds: the names that child reads, of the environment its host passes
2
+ // (the provider's `env` option), and nothing else, so a key the host holds never reaches a child that has no use for it.
3
+ // The package itself reads no environment: with no `env`, a child starts with none. The lists of names are
4
+ // descriptors/env-names.ts', where the descriptors' hostEnv reads them too.
5
+ import { ADB_ENV_NAMES, CHROME_ENV_NAMES, DOCKER_ENV_NAMES } from "./descriptors/env-names.js";
6
+ export { ADB_ENV_NAMES, BASE_ENV_NAMES, CHROME_ENV_NAMES, DOCKER_ENV_NAMES } from "./descriptors/env-names.js";
7
+ /** `env`'s values of `names` that are set, and nothing else: a child's whole environment. */
8
+ export function childEnv(env, names) {
9
+ const out = {};
10
+ for (const name of names) {
11
+ const value = env[name];
12
+ if (typeof value === "string")
13
+ out[name] = value;
14
+ }
15
+ return out;
16
+ }
17
+ /** A docker CLI child's environment: DOCKER_ENV_NAMES of `env`. */
18
+ export const dockerEnv = (env = {}) => childEnv(env, DOCKER_ENV_NAMES);
19
+ /** A Chrome child's (and the local browser's supervisor's) environment: CHROME_ENV_NAMES of `env`. */
20
+ export const chromeEnv = (env = {}) => childEnv(env, CHROME_ENV_NAMES);
21
+ /** An adb child's (and the adb server's it starts) environment: ADB_ENV_NAMES of `env`. */
22
+ export const adbEnv = (env = {}) => childEnv(env, ADB_ENV_NAMES);
package/dist/chrome.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type HostEnv } from "./child-env.js";
1
2
  import { type Result } from "./result.js";
2
3
  /** The environment names a Chrome is found by: PI_BROWSER_CHROME, then the common CHROME_PATH. */
3
4
  export declare const CHROME_ENV: readonly ["PI_BROWSER_CHROME", "CHROME_PATH"];
@@ -64,9 +65,11 @@ export declare const CHECK_MS = 30000;
64
65
  * Whether the Chrome at `path` starts here with its sandbox on: an executable file, a user that is not root, and one
65
66
  * headless start on a blank page (`--dump-dom about:blank`) in a profile of its own that goes with it, with a proxy no
66
67
  * name or address reaches, so nothing leaves the machine. ok with the resolved path; refused in words that never offer
67
- * to turn the sandbox off. From #1718's checkChrome. `uid`: the user this process runs as (a test's seam).
68
+ * to turn the sandbox off. From #1718's checkChrome. `uid`: the user this process runs as (a test's seam). `env`: the
69
+ * host's environment, of which Chrome holds the names it reads (CHROME_ENV_NAMES) and nothing else; without it, none.
68
70
  */
69
- export declare function checkChrome(path: string, { uid, timeoutMs }?: {
71
+ export declare function checkChrome(path: string, { uid, timeoutMs, env }?: {
70
72
  uid?: number;
71
73
  timeoutMs?: number;
74
+ env?: HostEnv;
72
75
  }): Promise<Result<string>>;
package/dist/chrome.js CHANGED
@@ -7,6 +7,7 @@ import { constants, existsSync, readFileSync } from "node:fs";
7
7
  import { access, mkdtemp, readFile, readlink, rm, stat } from "node:fs/promises";
8
8
  import { tmpdir } from "node:os";
9
9
  import { basename, delimiter, dirname, join, resolve } from "node:path";
10
+ import { chromeEnv } from "./child-env.js";
10
11
  import { fail, ok } from "./result.js";
11
12
  /** The names a Chrome or Chromium goes by on a Linux PATH. */
12
13
  const LINUX_NAMES = ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"];
@@ -178,9 +179,10 @@ export const CHECK_MS = 30_000;
178
179
  * Whether the Chrome at `path` starts here with its sandbox on: an executable file, a user that is not root, and one
179
180
  * headless start on a blank page (`--dump-dom about:blank`) in a profile of its own that goes with it, with a proxy no
180
181
  * name or address reaches, so nothing leaves the machine. ok with the resolved path; refused in words that never offer
181
- * to turn the sandbox off. From #1718's checkChrome. `uid`: the user this process runs as (a test's seam).
182
+ * to turn the sandbox off. From #1718's checkChrome. `uid`: the user this process runs as (a test's seam). `env`: the
183
+ * host's environment, of which Chrome holds the names it reads (CHROME_ENV_NAMES) and nothing else; without it, none.
182
184
  */
183
- export async function checkChrome(path, { uid = process.getuid?.(), timeoutMs = CHECK_MS } = {}) {
185
+ export async function checkChrome(path, { uid = process.getuid?.(), timeoutMs = CHECK_MS, env } = {}) {
184
186
  const at = resolve(path);
185
187
  const runs = (await stat(at).then((info) => info.isFile(), () => false)) && (await access(at, constants.X_OK).then(() => true, () => false));
186
188
  if (!runs)
@@ -194,6 +196,7 @@ export async function checkChrome(path, { uid = process.getuid?.(), timeoutMs =
194
196
  const said = await new Promise((done) => {
195
197
  const child = spawn(at, ["--headless=new", `--user-data-dir=${profile}`, "--no-first-run", "--proxy-server=http://agentrun-check.invalid:9", "--host-resolver-rules=MAP * ~NOTFOUND", "--dump-dom", "about:blank"], {
196
198
  stdio: ["ignore", "ignore", "pipe"],
199
+ env: chromeEnv(env),
197
200
  timeout: timeoutMs,
198
201
  killSignal: "SIGKILL",
199
202
  });
@@ -9,6 +9,8 @@ export interface CloudflareProviderOptions extends Omit<HostedOptions, "desktop"
9
9
  relayToken: string;
10
10
  /** The fetch every call goes through; default the global one. */
11
11
  fetch?: typeof fetch;
12
+ /** For tests: the pause before a request is tried again, given its ms and the call's signal. Default a timer. */
13
+ pause?: (ms: number, signal?: AbortSignal) => Promise<void>;
12
14
  /** The longest lifetime check takes, in ms: at most 24 h, the janitor's cap, which is the default. */
13
15
  maxLifetimeMs?: number;
14
16
  timeouts?: Partial<HostedTimeouts>;
@@ -77,7 +77,7 @@ class CloudflareHost {
77
77
  vendor: CLOUDFLARE.id,
78
78
  fetch: options.fetch,
79
79
  timeoutMs: 30_000,
80
- retry: { attempts: 4, baseMs: 1_000 },
80
+ retry: { attempts: 4, baseMs: 1_000, ...(options.pause ? { pause: options.pause } : {}) },
81
81
  // The relay's refusals are { error } in words.
82
82
  explain: ({ status, bytes, what }) => {
83
83
  const said = jsonOf(bytes)?.error;
@@ -161,7 +161,7 @@ export const conformance = () => import("./conformance/cloudflare.js");
161
161
  export class CloudflareProvider extends HostedProvider {
162
162
  #relay;
163
163
  constructor(options) {
164
- const { relayUrl, relayToken, fetch: fetcher = globalThis.fetch, timeouts = {}, ...rest } = options ?? {};
164
+ const { relayUrl, relayToken, fetch: fetcher = globalThis.fetch, pause, timeouts = {}, ...rest } = options ?? {};
165
165
  if (typeof relayToken !== "string" || relayToken === "")
166
166
  throw new Error("options.relayToken, the relay's RELAY_TOKEN, is required: the provider reads no environment, so the caller passes it");
167
167
  if (typeof relayUrl !== "string" || relayUrl === "")
@@ -169,7 +169,9 @@ export class CloudflareProvider extends HostedProvider {
169
169
  const base = httpsBase(relayUrl, "the Cloudflare relay URL");
170
170
  if (typeof fetcher !== "function")
171
171
  throw new Error("options.fetch must be a function, as the global fetch is");
172
- const host = new CloudflareHost({ relayUrl: base, relayToken, fetch: fetcher });
172
+ if (pause !== undefined && typeof pause !== "function")
173
+ throw new Error("options.pause must be a function");
174
+ const host = new CloudflareHost({ relayUrl: base, relayToken, fetch: fetcher, ...(pause ? { pause } : {}) });
173
175
  super(host, { ...rest, timeouts: { ...CLOUDFLARE_TIMEOUTS, ...timeouts } });
174
176
  this.#relay = host;
175
177
  }
Binary file
Binary file
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "0.1.0-beta.58",
2
+ "version": "0.1.0-beta.60",
3
3
  "source": "sha256:724f889fc95233b98e71e6ff4456498fb220f704db4ca2caed5772e3984ba4de"
4
4
  }
@@ -1,11 +1,9 @@
1
1
  import { type Agent37Options, type Agent37Provider } from "../agent37.js";
2
- import type { MachineHost } from "../host.js";
3
- import type { MountKind } from "../mount.js";
4
- import { type ArchilRunFolderOptions } from "./archil.js";
5
- import type { RunFolder } from "./types.js";
2
+ import { type ArchilMountOptions } from "./archil.js";
3
+ import { type Env, type HostedModuleOptions } from "./module-kit.js";
4
+ export { CONFORMANCE_MAX_LIFETIME_MS } from "./module-kit.js";
6
5
  /** The Archil disk's settings for the mount cases, by name (COMPUTER_ARCHIL_*: all five, or none). */
7
6
  export { ARCHIL_ENV } from "./archil.js";
8
- /** The environment this module reads, by name, each for the option its comment names, the live switch and the run's template. */
9
7
  export declare const AGENT37_ENV: {
10
8
  readonly live: "AGENTRUN_COMPUTER_LIVE_AGENT37";
11
9
  /** The template every computer of the run starts from; default agent37-base, or the box template for kind desktop. */
@@ -14,7 +12,11 @@ export declare const AGENT37_ENV: {
14
12
  readonly kind: "COMPUTER_AGENT37_KIND";
15
13
  /** apiKey, required: the workspace's API key. */
16
14
  readonly key: "COMPUTER_AGENT37_API_KEY";
17
- /** 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
+ */
18
20
  readonly sshKey: "COMPUTER_AGENT37_SSH_KEY";
19
21
  /** type: vm (default) or default. */
20
22
  readonly type: "COMPUTER_AGENT37_TYPE";
@@ -29,7 +31,6 @@ export declare const AGENT37_ENV: {
29
31
  /** daemonUser: uid:gid the daemon runs as; default 2510:2510. */
30
32
  readonly user: "COMPUTER_AGENT37_USER";
31
33
  };
32
- /** The names this module reads, under the conformance modules' common name (ConformanceModule.ENV). */
33
34
  export declare const ENV: {
34
35
  readonly live: "AGENTRUN_COMPUTER_LIVE_AGENT37";
35
36
  /** The template every computer of the run starts from; default agent37-base, or the box template for kind desktop. */
@@ -38,7 +39,11 @@ export declare const ENV: {
38
39
  readonly kind: "COMPUTER_AGENT37_KIND";
39
40
  /** apiKey, required: the workspace's API key. */
40
41
  readonly key: "COMPUTER_AGENT37_API_KEY";
41
- /** 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
+ */
42
47
  readonly sshKey: "COMPUTER_AGENT37_SSH_KEY";
43
48
  /** type: vm (default) or default. */
44
49
  readonly type: "COMPUTER_AGENT37_TYPE";
@@ -57,21 +62,15 @@ export declare const ENV: {
57
62
  export type Agent37Settings = Omit<Agent37Options, "ssh2" | "fetch" | "WebSocket" | "timeouts" | "probeTargets" | "proxyDomain">;
58
63
  /**
59
64
  * The provider's options this module reads from env, each only when its name is set; throws in words without a key,
60
- * or on a value it cannot read, never echoing a key. create() checks the rest.
65
+ * or on a value it cannot read, never echoing a key.
61
66
  */
62
- export declare function settingsFromEnv(env?: Record<string, string | undefined>): Agent37Settings;
63
- /** The longest lifetime a computer of a run may ask for: init ends it at its deadline, the sweep deletes it. */
64
- export declare const CONFORMANCE_MAX_LIFETIME_MS: number;
65
- /** For the run's report: what this configuration means for the suite. */
67
+ export declare function settingsFromEnv(env?: Env): Agent37Settings;
66
68
  export declare const conformanceNotes: string[];
67
- export interface Agent37ModuleOptions extends Pick<Agent37Options, "ssh2" | "fetch" | "WebSocket" | "daemonPath" | "timeouts" | "onNote"> {
68
- /** Where the settings are read; default process.env. */
69
- env?: Record<string, string | undefined>;
70
- /** Builds this package's daemon for linux/amd64 stamped with version, and gives its path; default go build. */
71
- buildDaemon?: (version: string) => Promise<string>;
72
- /** For mountFor("archil"): the disk's object API, or the SDK's Archil client, in place of the host's disk package. */
73
- archil?: Pick<ArchilRunFolderOptions, "objects" | "Archil" | "baseUrl">;
69
+ export interface Agent37ModuleOptions extends HostedModuleOptions, Pick<Agent37Options, "ssh2" | "fetch" | "WebSocket" | "daemonPath" | "timeouts" | "onNote">, ArchilMountOptions {
74
70
  }
71
+ export declare const createProvider: (options?: Agent37ModuleOptions | undefined) => Promise<Agent37Provider>, createDriftedProvider: (options?: Agent37ModuleOptions | undefined) => Promise<Agent37Provider>, createHost: (options?: Agent37ModuleOptions | undefined) => Promise<import("../host.js").MachineHost>, sweepScope: (options?: {
72
+ env?: Env;
73
+ }) => string;
75
74
  /**
76
75
  * The template every computer of the run starts from: COMPUTER_AGENT37_TEMPLATE, else agent37-base, else for kind
77
76
  * desktop the box template, which the run's provider registers in the key's workspace first (prepareImage, live).
@@ -79,23 +78,4 @@ export interface Agent37ModuleOptions extends Pick<Agent37Options, "ssh2" | "fet
79
78
  export declare function conformanceImage(options?: Agent37ModuleOptions, { signal }?: {
80
79
  signal?: AbortSignal;
81
80
  }): Promise<string>;
82
- /** The provider the CLI runs; throws in words without the live switch, or when a setting is missing or wrong. */
83
- export declare function createProvider(options?: Agent37ModuleOptions): Promise<Agent37Provider>;
84
- /** The same provider uploading a daemon that reports version <version>-drift, for the drift.version case. */
85
- export declare function createDriftedProvider(options?: Agent37ModuleOptions): Promise<Agent37Provider>;
86
- /**
87
- * A run folder for an Archil mount, and none for any other kind (an Agent37 computer takes no bind): a fresh folder on
88
- * the disk the COMPUTER_ARCHIL_* names name (archilSettings), none when they name none. Reaching it is a call to
89
- * Archil, so it needs the live switch.
90
- */
91
- export declare function mountFor(kind: MountKind, { env, archil }?: Agent37ModuleOptions): Promise<RunFolder | undefined>;
92
- /**
93
- * The Agent37 host the live sweep (sweep.ts) lists and deletes through, from the same settings; it needs no live
94
- * switch, since the sweep makes nothing, and it calls nothing until the sweep does.
95
- */
96
- export declare function createHost(options?: Pick<Agent37ModuleOptions, "env" | "ssh2" | "fetch" | "WebSocket">): Promise<MachineHost>;
97
- /**
98
- * Where the host lists, in words: one key is one workspace, and one listing covers all of it, every region and type
99
- * (docs: instances/list). The key is named by its sha256 prefix alone, so a before file of another key is refused.
100
- */
101
- export declare function sweepScope({ env }?: Pick<Agent37ModuleOptions, "env">): string;
81
+ export declare const mountFor: (kind: import("../mount.js").MountKind, options?: ArchilMountOptions) => Promise<import("./types.js").RunFolder | undefined>;