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

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 (131) hide show
  1. package/README.md +187 -62
  2. package/box/Dockerfile +4 -3
  3. package/box/install.sh +57 -11
  4. package/dist/agent37.js +6 -9
  5. package/dist/attach.d.ts +24 -4
  6. package/dist/attach.js +50 -19
  7. package/dist/boxd.js +22 -9
  8. package/dist/browserbase.d.ts +6 -2
  9. package/dist/browserbase.js +50 -7
  10. package/dist/child-env.d.ts +11 -0
  11. package/dist/child-env.js +22 -0
  12. package/dist/chrome.d.ts +5 -2
  13. package/dist/chrome.js +5 -2
  14. package/dist/cloudflare.d.ts +2 -0
  15. package/dist/cloudflare.js +5 -3
  16. package/dist/computerd-linux-amd64 +0 -0
  17. package/dist/computerd-linux-arm64 +0 -0
  18. package/dist/computerd.json +1 -1
  19. package/dist/conformance/agent37.d.ts +10 -38
  20. package/dist/conformance/agent37.js +25 -113
  21. package/dist/conformance/archil.d.ts +13 -3
  22. package/dist/conformance/archil.js +22 -17
  23. package/dist/conformance/boxd.d.ts +8 -31
  24. package/dist/conformance/boxd.js +19 -74
  25. package/dist/conformance/browserbase.d.ts +3 -6
  26. package/dist/conformance/browserbase.js +6 -17
  27. package/dist/conformance/cases/health.js +6 -3
  28. package/dist/conformance/cli.d.ts +3 -1
  29. package/dist/conformance/cli.js +69 -9
  30. package/dist/conformance/cloudflare.d.ts +3 -6
  31. package/dist/conformance/cloudflare.js +7 -15
  32. package/dist/conformance/daytona.d.ts +6 -20
  33. package/dist/conformance/daytona.js +22 -57
  34. package/dist/conformance/dial-only.d.ts +4 -3
  35. package/dist/conformance/dial-only.js +3 -3
  36. package/dist/conformance/docker.d.ts +4 -5
  37. package/dist/conformance/docker.js +8 -14
  38. package/dist/conformance/e2b.d.ts +10 -36
  39. package/dist/conformance/e2b.js +27 -84
  40. package/dist/conformance/fly.d.ts +3 -6
  41. package/dist/conformance/fly.js +2 -6
  42. package/dist/conformance/groundbox.d.ts +7 -23
  43. package/dist/conformance/groundbox.js +16 -56
  44. package/dist/conformance/index.d.ts +1 -0
  45. package/dist/conformance/index.js +1 -0
  46. package/dist/conformance/kernel.d.ts +3 -6
  47. package/dist/conformance/kernel.js +5 -15
  48. package/dist/conformance/kind.d.ts +0 -6
  49. package/dist/conformance/kind.js +0 -4
  50. package/dist/conformance/local-chrome.d.ts +5 -7
  51. package/dist/conformance/local-chrome.js +7 -11
  52. package/dist/conformance/modal.d.ts +10 -38
  53. package/dist/conformance/modal.js +27 -74
  54. package/dist/conformance/module-kit.d.ts +87 -0
  55. package/dist/conformance/module-kit.js +88 -0
  56. package/dist/conformance/morph.d.ts +7 -23
  57. package/dist/conformance/morph.js +20 -66
  58. package/dist/conformance/orgo.d.ts +5 -10
  59. package/dist/conformance/orgo.js +15 -27
  60. package/dist/conformance/phone-harness.d.ts +3 -5
  61. package/dist/conformance/phone-harness.js +3 -11
  62. package/dist/conformance/runner.d.ts +13 -3
  63. package/dist/conformance/runner.js +32 -11
  64. package/dist/conformance/smolcloud.d.ts +7 -23
  65. package/dist/conformance/smolcloud.js +16 -49
  66. package/dist/conformance/sweep.d.ts +10 -5
  67. package/dist/conformance/sweep.js +91 -38
  68. package/dist/conformance/tti.d.ts +69 -0
  69. package/dist/conformance/tti.js +205 -0
  70. package/dist/conformance/types.d.ts +9 -2
  71. package/dist/daytona.js +60 -20
  72. package/dist/descriptor.d.ts +10 -0
  73. package/dist/descriptor.js +7 -0
  74. package/dist/descriptors/browserbase.d.ts +3 -0
  75. package/dist/descriptors/browserbase.js +4 -0
  76. package/dist/descriptors/docker.d.ts +1 -0
  77. package/dist/descriptors/docker.js +3 -0
  78. package/dist/descriptors/env-names.d.ts +32 -0
  79. package/dist/descriptors/env-names.js +60 -0
  80. package/dist/descriptors/index.d.ts +9 -2
  81. package/dist/descriptors/kernel.d.ts +3 -0
  82. package/dist/descriptors/kernel.js +2 -0
  83. package/dist/descriptors/local-chrome.d.ts +1 -1
  84. package/dist/descriptors/local-chrome.js +5 -3
  85. package/dist/descriptors/phone-harness.d.ts +1 -1
  86. package/dist/descriptors/phone-harness.js +4 -2
  87. package/dist/docker/egress.d.ts +7 -0
  88. package/dist/docker/egress.js +8 -0
  89. package/dist/docker/image.d.ts +5 -1
  90. package/dist/docker/image.js +12 -8
  91. package/dist/docker.d.ts +63 -15
  92. package/dist/docker.js +181 -98
  93. package/dist/drift.js +6 -6
  94. package/dist/e2b.d.ts +2 -2
  95. package/dist/e2b.js +2 -3
  96. package/dist/groundbox.js +6 -6
  97. package/dist/host.d.ts +23 -0
  98. package/dist/hosted/download.d.ts +23 -0
  99. package/dist/hosted/download.js +144 -0
  100. package/dist/hosted/process.d.ts +5 -0
  101. package/dist/hosted/process.js +20 -0
  102. package/dist/hosted/provider.js +120 -48
  103. package/dist/hosted/rest.d.ts +19 -8
  104. package/dist/hosted/rest.js +47 -14
  105. package/dist/hosted/scripts.d.ts +10 -0
  106. package/dist/hosted/scripts.js +23 -2
  107. package/dist/index.d.ts +3 -1
  108. package/dist/index.js +3 -1
  109. package/dist/janitor.d.ts +7 -1
  110. package/dist/janitor.js +2 -2
  111. package/dist/kernel.js +1 -1
  112. package/dist/local-chrome.d.ts +5 -2
  113. package/dist/local-chrome.js +4 -2
  114. package/dist/local-supervisor.js +1 -0
  115. package/dist/modal.d.ts +6 -5
  116. package/dist/modal.js +7 -7
  117. package/dist/morph.js +5 -8
  118. package/dist/orgo-channel.d.ts +3 -2
  119. package/dist/orgo-channel.js +3 -3
  120. package/dist/orgo-desktop.js +2 -4
  121. package/dist/orgo.js +2 -4
  122. package/dist/phone-harness.d.ts +7 -5
  123. package/dist/phone-harness.js +60 -61
  124. package/dist/protocol.d.ts +10 -0
  125. package/dist/protocol.js +17 -0
  126. package/dist/provider.d.ts +6 -2
  127. package/dist/screen-watch.d.ts +6 -1
  128. package/dist/screen-watch.js +166 -12
  129. package/dist/vendor-sdk.d.ts +9 -0
  130. package/dist/vendor-sdk.js +26 -0
  131. package/package.json +8 -1
@@ -12,16 +12,18 @@ import { execFile } from "node:child_process";
12
12
  import { createHash, randomBytes } from "node:crypto";
13
13
  import { readFileSync } from "node:fs";
14
14
  import { readFile } from "node:fs/promises";
15
+ import { STATUS_CODES } from "node:http";
15
16
  import { createConnection } from "node:net";
16
17
  import { basename, isAbsolute } from "node:path";
17
18
  import { fileURLToPath } from "node:url";
19
+ import { adbEnv } from "./child-env.js";
18
20
  import { DaemonClient } from "./client.js";
19
21
  import { CreateRequests, endedWords, labelsDiffer, otherSpecWords } from "./create-requests.js";
20
22
  import { PHONE_GROUPS, PHONE_HARNESS } from "./descriptors/phone-harness.js";
21
- import { httpsBase } from "./hosted/rest.js";
22
- import { PROTOCOL_VERSION } from "./protocol.js";
23
+ import { httpsBase, rest } from "./hosted/rest.js";
24
+ import { helloProblem } from "./protocol.js";
23
25
  import { checkGpu, checkTenure, runLifetimeMs, } from "./provider.js";
24
- import { failFor, ok, vendorFail } from "./result.js";
26
+ import { failAs, failFor, ok, vendorFail } from "./result.js";
25
27
  import { daemonWatch, redactWords } from "./screen-watch.js";
26
28
  import { listTested } from "./test-connection.js";
27
29
  /** This module's failures: one with code vendor names the phone harness. */
@@ -128,23 +130,22 @@ async function ledgerSafe(fn) {
128
130
  }
129
131
  /** The adb server's port when none is given: adb's own default. */
130
132
  export const ADB_SERVER_PORT = 5037;
131
- /** The environment variables adb reads to find its server or its device: every one is dropped from a spawned adb's. */
132
- const ADB_ENV = /^(ADB_|ANDROID_ADB_|ANDROID_SERIAL$)/;
133
133
  /**
134
134
  * The adb CLI (Android platform-tools) at path, by execFile, never a shell, and the adb server it starts, on the
135
135
  * loopback at port (adb's own default), spoken to by its socket protocol.
136
136
  *
137
- * env is the environment a spawned adb starts from, with every adb variable dropped from it (ADB_SERVER_SOCKET,
138
- * ANDROID_ADB_SERVER_SOCKET, ANDROID_ADB_SERVER_ADDRESS, ANDROID_SERIAL, ...), so nothing in it points the CLI at
139
- * another server than its socket requests reach. The library reads no environment of its own: a caller passes it (the
140
- * conformance module passes process.env). Without env, a spawned adb inherits the process's environment as it is.
137
+ * env is the environment the host passes: a spawned adb, and the adb server it starts, hold its ADB_ENV_NAMES alone
138
+ * (adbEnv), never a key, and none of the variables that point adb at another server or device (ADB_SERVER_SOCKET,
139
+ * ANDROID_ADB_SERVER_ADDRESS, ANDROID_SERIAL, ...) than its socket requests reach. The library reads no environment of
140
+ * its own: the provider passes its env, the conformance module process.env. Without env, adb starts with none, and a
141
+ * bare "adb" is found only on the default path: pass env, or adb's absolute path.
141
142
  */
142
143
  export function adbCli(path = "adb", { port = ADB_SERVER_PORT, env } = {}) {
143
144
  // Every spawned adb names the server the socket requests go to: without -P it would take its own default, 5037 or
144
145
  // ANDROID_ADB_SERVER_PORT, and start or ask another server.
145
- const spawnEnv = env === undefined ? undefined : Object.fromEntries(Object.entries(env).filter(([name, value]) => value !== undefined && !ADB_ENV.test(name)));
146
+ const spawnEnv = adbEnv(env);
146
147
  const run = (args, { timeoutMs, signal, input }) => new Promise((resolve) => {
147
- const child = execFile(path, ["-P", String(port), ...args], { encoding: "buffer", ...(spawnEnv ? { env: spawnEnv } : {}), timeout: timeoutMs, killSignal: "SIGKILL", maxBuffer: 64 * 1024 * 1024, ...(signal ? { signal } : {}) }, (error, stdout, stderr) => {
148
+ const child = execFile(path, ["-P", String(port), ...args], { encoding: "buffer", env: spawnEnv, timeout: timeoutMs, killSignal: "SIGKILL", maxBuffer: 64 * 1024 * 1024, ...(signal ? { signal } : {}) }, (error, stdout, stderr) => {
148
149
  const code = error?.code;
149
150
  if (code === "ENOENT") {
150
151
  return resolve(fail("not_found", `the phone provider needs adb (Android platform-tools) on this machine: ${path} is not there; install platform-tools or give the provider's adb option`));
@@ -319,6 +320,7 @@ export async function create(options) {
319
320
  /** The conformance CLI's module for the phone harness. */
320
321
  export const conformance = () => import("./conformance/phone-harness.js");
321
322
  const show = (value) => JSON.stringify(value) ?? String(value);
323
+ const decoder = new TextDecoder();
322
324
  /** One argument for the phone's sh: single-quoted. */
323
325
  const quote = (text) => `'${text.replaceAll("'", "'\\''")}'`;
324
326
  /** An Android package id: dotted Java names. */
@@ -333,6 +335,8 @@ export class PhoneHarnessProvider {
333
335
  #apiKey;
334
336
  #baseUrl;
335
337
  #fetch;
338
+ /** The API's client (hosted/rest.ts); a call with headers of its own (a create's Idempotency-Key) gets one of its own. */
339
+ #rest;
336
340
  #adb;
337
341
  #ledger;
338
342
  /** Each create in flight, and the names of the phones this provider ended (create-requests.ts). Past this process, the
@@ -378,7 +382,7 @@ export class PhoneHarnessProvider {
378
382
  throw new Error(`platform ${show(platform)} is not one of android, ios`);
379
383
  this.#apiKey = apiKey;
380
384
  this.#baseUrl = httpsBase(options.baseUrl ?? PHONE_HARNESS_URL, "the phone harness URL");
381
- this.#fetch = options.fetch ?? globalThis.fetch;
385
+ this.#fetch = options.fetch;
382
386
  const adb = options.adb;
383
387
  if (adb !== undefined && typeof adb !== "string" && !(typeof adb?.run === "function" && typeof adb?.server === "function" && typeof adb?.open === "function")) {
384
388
  throw new Error("options.adb is the adb CLI's path, or a transport with run(), server() and open()");
@@ -388,7 +392,7 @@ export class PhoneHarnessProvider {
388
392
  if (!Array.isArray(apks) || !apks.every(pinned))
389
393
  throw new Error(`options.apks ${show(options.apks)} is not a list of { path, sha256 }: an APK file's absolute path and its sha256, 64 lowercase hex digits`);
390
394
  this.#apks = apks.map(({ path, sha256 }) => ({ path, sha256 }));
391
- this.#adb = adb === undefined || typeof adb === "string" ? adbCli(adb ?? "adb") : adb;
395
+ this.#adb = adb === undefined || typeof adb === "string" ? adbCli(adb ?? "adb", { env: options.env ?? {} }) : adb;
392
396
  this.#ledger = guardedLedger(options.ledger ?? memoryLedger());
393
397
  this.#maxLifetimeMs = options.maxLifetimeMs ?? DEFAULT_MAX_LIFETIME_MS;
394
398
  if (!(Number.isSafeInteger(this.#maxLifetimeMs) && this.#maxLifetimeMs > 0))
@@ -402,6 +406,7 @@ export class PhoneHarnessProvider {
402
406
  throw new Error(`requestMs ${show(options.requestMs)} is not a whole number of milliseconds above 0`);
403
407
  this.#timeout = options.timeout ?? ((ms) => AbortSignal.timeout(ms));
404
408
  this.#daemonVersion = options.daemonVersion ?? VERSION;
409
+ this.#rest = this.#client();
405
410
  }
406
411
  capabilities() {
407
412
  return {
@@ -438,45 +443,38 @@ export class PhoneHarnessProvider {
438
443
  #clean(text) {
439
444
  return text.replaceAll(this.#apiKey, "[the key]");
440
445
  }
446
+ /** The API's client, with headers of one call's own beside the key. */
447
+ #client(headers = {}) {
448
+ return rest({
449
+ base: this.#baseUrl,
450
+ headers: () => ({ Authorization: `Bearer ${this.#apiKey}`, Accept: "application/json", ...headers }),
451
+ vendor: this.id,
452
+ ...(this.#fetch ? { fetch: this.#fetch } : {}),
453
+ timeoutMs: this.#requestMs,
454
+ timeout: this.#timeout,
455
+ });
456
+ }
441
457
  /**
442
458
  * One request, bounded by ms (default requestMs) and by the caller's signal. A failure is `uncertain` when the
443
459
  * service may have acted on the request all the same: no answer (lost, or cut off by its bound), or a 5xx other than
444
- * phones_busy, the service's own word that nothing was made.
460
+ * phones_busy, the service's own word that nothing was made. A redirect is refused unfollowed, and is uncertain too:
461
+ * its answer is never read, and a 303 after a create is the usual answer to a POST.
445
462
  */
446
- async #api(method, path, { body, headers = {}, signal, ms = this.#requestMs } = {}) {
447
- const bound = this.#timeout(Math.max(1, Math.ceil(ms)));
448
- const either = signal ? AbortSignal.any([signal, bound]) : bound;
449
- const cut = (error) => {
450
- if (signal?.aborted)
451
- return fail("aborted", `${method} ${path} was aborted`);
452
- if (bound.aborted)
453
- return { ...fail("timeout", `${method} ${path}: the phone harness did not answer within ${Math.round(ms / 100) / 10} s`), uncertain: true };
454
- return { ...fail("unreachable", `${method} ${path}: the phone harness could not be reached: ${this.#clean(error?.message ?? String(error))}`), uncertain: true };
455
- };
456
- let response;
457
- try {
458
- response = await this.#fetch(`${this.#baseUrl}${path}`, {
459
- method,
460
- headers: { Authorization: `Bearer ${this.#apiKey}`, Accept: "application/json", ...(body === undefined ? {} : { "Content-Type": "application/json" }), ...headers },
461
- ...(body === undefined ? {} : { body: JSON.stringify(body) }),
462
- // Never followed: the key's header would go on to wherever a redirect points, as rest.ts's client refuses too.
463
- redirect: "error",
464
- signal: either,
465
- });
466
- }
467
- catch (error) {
468
- return cut(error);
469
- }
470
- let text;
471
- try {
472
- text = await response.text();
473
- }
474
- catch (error) {
475
- // The answer's body stalled or broke: as a lost answer when it was cut off, else no words.
476
- if (signal?.aborted || bound.aborted)
477
- return cut(error);
478
- text = "";
463
+ async #api(method, path, { body, headers, signal, ms = this.#requestMs } = {}) {
464
+ const api = headers === undefined ? this.#rest : this.#client(headers);
465
+ // Every answer is a value here, read below in the service's own words: what the client fails is no answer at all,
466
+ // or a redirect it would not follow.
467
+ const got = await api.call(method, api.url(path), { ...(body === undefined ? {} : { json: body }), timeoutMs: Math.max(1, Math.ceil(ms)), accept: () => true }, signal);
468
+ if (!got.ok) {
469
+ const words = this.#clean(got.error.message);
470
+ if (got.error.code === "aborted")
471
+ return failAs(got.error, words);
472
+ // A redirect keeps the client's code and words: the API answered, though the answer is unknown.
473
+ const code = got.error.redirect ? got.error.code : got.error.code === "timeout" ? "timeout" : "unreachable";
474
+ return { ...failAs(got.error, words, code), uncertain: true };
479
475
  }
476
+ const { status } = got.value;
477
+ const text = decoder.decode(got.value.bytes);
480
478
  let json;
481
479
  try {
482
480
  json = text === "" ? undefined : JSON.parse(text);
@@ -484,26 +482,26 @@ export class PhoneHarnessProvider {
484
482
  catch {
485
483
  json = undefined;
486
484
  }
487
- if (response.ok)
488
- return ok({ status: response.status, json });
485
+ if (status >= 200 && status < 300)
486
+ return ok({ status, json });
489
487
  const answer = (typeof json === "object" && json !== null ? json : {});
490
- const said = this.#clean(answer.error ?? (text.slice(0, 200) || response.statusText || "no words"));
488
+ const said = this.#clean(answer.error ?? (text.slice(0, 200) || STATUS_CODES[status] || "no words"));
491
489
  const where = `${method} ${path}`;
492
- if (response.status === 401)
490
+ if (status === 401)
493
491
  return fail("denied", `${where}: the phone harness refused the API key (401): ${said}`);
494
- if (response.status === 403)
492
+ if (status === 403)
495
493
  return fail("denied", `${where}: ${said} (403)`);
496
494
  if (answer.code === "phones_busy") {
497
- const retry = answer.retry_after_seconds ?? Number(response.headers.get("retry-after"));
498
- return fail("limit", `${where}: ${said}${Number.isFinite(retry) && retry > 0 ? `; try again in ${retry} s` : ""} (phones_busy)`);
495
+ const retry = answer.retry_after_seconds;
496
+ return fail("limit", `${where}: ${said}${typeof retry === "number" && Number.isFinite(retry) && retry > 0 ? `; try again in ${retry} s` : ""} (phones_busy)`);
499
497
  }
500
498
  if (answer.code === "session_limit")
501
499
  return fail("limit", `${where}: ${said} (session_limit)`);
502
- if (response.status === 404)
500
+ if (status === 404)
503
501
  return fail("not_found", `${where}: ${said} (404)`);
504
- const failed = vendorFail("phone-harness", `${where}: ${said} (${response.status}${answer.code ? `, ${answer.code}` : ""})`);
502
+ const failed = vendorFail("phone-harness", `${where}: ${said} (${status}${answer.code ? `, ${answer.code}` : ""})`);
505
503
  // A 5xx is no refusal: a gateway may answer it for a request the service went on to act on.
506
- return response.status >= 500 ? { ...failed, uncertain: true } : failed;
504
+ return status >= 500 ? { ...failed, uncertain: true } : failed;
507
505
  }
508
506
  async #session(id, signal, ms) {
509
507
  const got = await this.#api("GET", `/sessions/${encodeURIComponent(id)}`, { ...(signal ? { signal } : {}), ...(ms === undefined ? {} : { ms }) });
@@ -694,8 +692,8 @@ export class PhoneHarnessProvider {
694
692
  const posted = await this.#api("POST", "/sessions", { body, headers: { "Idempotency-Key": requestKey }, ...(signal ? { signal } : {}) });
695
693
  const cancelled = !posted.ok && posted.error.code === "aborted";
696
694
  let first = posted.ok ? sessionOf(posted.value.json, "POST /sessions") : undefined;
697
- // Only a refusal (a 4xx, or phones_busy) says nothing was made. No answer, a cancel, a 5xx, or a 2xx with no
698
- // session in it leaves the request uncertain: the service may have made the phone.
695
+ // Only a refusal (a 4xx, or phones_busy) says nothing was made. No answer, a cancel, a 5xx, a redirect, or a 2xx
696
+ // with no session in it leaves the request uncertain: the service may have made the phone.
699
697
  const uncertain = posted.ok ? !first?.ok : posted.uncertain === true || cancelled;
700
698
  if (uncertain) {
701
699
  // Ask by its key, never POST again, before the key is forgotten. The ask is create's own, not under the
@@ -1071,8 +1069,9 @@ export class PhoneHarnessProvider {
1071
1069
  const { hello } = daemon.value;
1072
1070
  if (hello.version !== this.#daemonVersion)
1073
1071
  return letGo(fail("refused", `hello: the daemon reports version ${hello.version}, expected ${this.#daemonVersion}`));
1074
- if (hello.protocol !== PROTOCOL_VERSION)
1075
- return letGo(fail("refused", `hello: phoned speaks protocol ${hello.protocol}, and this provider ${PROTOCOL_VERSION}`));
1072
+ const problem = helloProblem(hello.protocol, "provider");
1073
+ if (problem)
1074
+ return letGo(fail("refused", `hello: phoned ${problem}`));
1076
1075
  const client = new PhoneClient(daemon.value.client, release);
1077
1076
  return ok({ client, hello, close: () => client.closed() });
1078
1077
  }
@@ -45,6 +45,16 @@ export declare const PROVIDER_GROUPS: readonly Group[];
45
45
  * Go constant (methods.ProtocolVersion) holds the same value, and a test keeps them equal.
46
46
  */
47
47
  export declare const PROTOCOL_VERSION = "0.2";
48
+ /**
49
+ * Why a hello's protocol version does not work with this one, or undefined. A "<major>.<minor>" with this major works
50
+ * from 0.2 on, whatever its minor: a minor step only adds, and hello's groups and features say what the other side has.
51
+ * 0.1 is refused, as 0.2 removed its apps.ui_tree for ui. Another major, a version in another shape, and a hello that
52
+ * names none are refused. Every place that reads a hello asks this one check, but the conformance suite: it certifies a
53
+ * provider at exactly PROTOCOL_VERSION (health.declared). The words, after whoever answered:
54
+ * "speaks protocol <its>, and this <side> <ours>", `side` naming the reader (server, provider), and <its> "none" for a
55
+ * hello that names none.
56
+ */
57
+ export declare function helloProblem(protocol: unknown, side: string): string | undefined;
48
58
  export interface HelloParams {
49
59
  /** Who is asking, for the daemon's log: a name and version. */
50
60
  client: string;
package/dist/protocol.js CHANGED
@@ -33,6 +33,23 @@ export const PROVIDER_GROUPS = ["cdp", "stream", "downloads"];
33
33
  * Go constant (methods.ProtocolVersion) holds the same value, and a test keeps them equal.
34
34
  */
35
35
  export const PROTOCOL_VERSION = "0.2";
36
+ /**
37
+ * Why a hello's protocol version does not work with this one, or undefined. A "<major>.<minor>" with this major works
38
+ * from 0.2 on, whatever its minor: a minor step only adds, and hello's groups and features say what the other side has.
39
+ * 0.1 is refused, as 0.2 removed its apps.ui_tree for ui. Another major, a version in another shape, and a hello that
40
+ * names none are refused. Every place that reads a hello asks this one check, but the conformance suite: it certifies a
41
+ * provider at exactly PROTOCOL_VERSION (health.declared). The words, after whoever answered:
42
+ * "speaks protocol <its>, and this <side> <ours>", `side` naming the reader (server, provider), and <its> "none" for a
43
+ * hello that names none.
44
+ */
45
+ export function helloProblem(protocol, side) {
46
+ // The oldest minor of this major that works: the last that broke the wire. A new major starts it again at 0.
47
+ const oldestMinor = 2;
48
+ const parts = typeof protocol === "string" ? /^(\d+)\.(\d+)$/.exec(protocol) : null;
49
+ if (parts !== null && parts[1] === PROTOCOL_VERSION.split(".")[0] && Number(parts[2]) >= oldestMinor)
50
+ return undefined;
51
+ return `speaks protocol ${protocol === undefined || protocol === null ? "none" : String(protocol)}, and this ${side} ${PROTOCOL_VERSION}`;
52
+ }
36
53
  /**
37
54
  * The features a computer may list in hello.features, and what each one means. The names say what, never which OS:
38
55
  * a driver on any OS lists the same names, and says in the off reason what its OS is missing.
@@ -455,13 +455,17 @@ export interface ComputerProvider {
455
455
  watch?(ref: ComputerRef, handlers: ScreenWatchHandlers, options?: WatchOptions): Promise<Result<ScreenWatch>>;
456
456
  /**
457
457
  * Removes what this provider's computers left behind outside the computers themselves (Docker: an egress proxy and its
458
- * volume whose computer is gone or whose deadline has passed), with all of these labels, and returns what it removed,
459
- * by name. Optional; the janitor's sweep calls it after the computers, which release their own parts.
458
+ * volume whose computer is not there), with all of these labels, and returns what it removed, by name. Optional; the
459
+ * janitor's sweep calls it after the computers, which release their own parts. With `mine`, only a leftover whose
460
+ * labels (the computer's spec labels it carries) `mine` answers true for is removed: a host shared by several callers
461
+ * has each remove its own alone. `mine` is asked before the provider reads the leftover's computer, so a caller whose
462
+ * answer says no create of its own is under way makes that read the last word.
460
463
  */
461
464
  sweepLeftovers?(context: {
462
465
  labels: Record<string, string>;
463
466
  now: Date;
464
467
  signal?: AbortSignal;
468
+ mine?: (labels: Record<string, string>) => boolean | Promise<boolean>;
465
469
  }): Promise<Result<string[]>>;
466
470
  /**
467
471
  * One account-level read with the provider's keys (a list by label, the vendor's whoami) that never creates a
@@ -58,9 +58,14 @@ export interface ScreenWatch {
58
58
  /** Ends the watch: no frame and no ended() after it, and its connection is let go. Idempotent. */
59
59
  close(): Promise<void>;
60
60
  }
61
+ /** The characters redactWords' four scans read in its last call, for tests: a few per character. */
62
+ export declare let redactWordsReads: number;
61
63
  /**
62
64
  * Words with no URL and no secret: a URL of any scheme, a login, a bearer, a secret-named parameter, a key- or
63
- * token-shaped value and an endpoint (a host or an IPv4 address with a port) are taken out.
65
+ * token-shaped value and an endpoint (a host or an IPv4 address with a port) are taken out. The URL, the login, the
66
+ * parameter and the endpoint with a DNS name are scans that read each character a few times: as regexes with no
67
+ * anchored start they read to the end of a long word run from every character in it. The JWT starts only at the first
68
+ * eyJ of its run, for the same reason.
64
69
  */
65
70
  export declare function redactWords(words: string): string;
66
71
  /** The code a watch ends with for an error the computer gave. */
@@ -31,26 +31,180 @@ export class ScreenWatchError extends Error {
31
31
  const MAX_FRAME_BYTES = 64 << 20;
32
32
  /** The most input calls a watch has in flight at once: one more is refused as limit, never queued. */
33
33
  const MAX_INPUTS_IN_FLIGHT = 8;
34
+ /** The characters of each part of a URL, a login, a secret-named parameter and an endpoint, one character at a time. */
35
+ const URL_SCHEME = /[A-Za-z0-9+.-]/;
36
+ const URL_REST = /[^\s"'<>]/;
37
+ const LOGIN_USER = /[\w.+-]/;
38
+ const LOGIN_PASSWORD = /[^\s@/'"]/;
39
+ const LOGIN_HOST = /[\w.-]/;
40
+ const PARAM_NAME = /[\w-]/;
41
+ const PARAM_VALUE = /[^\s&"';,]/;
42
+ const PARAM_SECRET = /token|password|passwd|secret|key|jwt|auth|code|signingKey|credential/i;
43
+ const ENDPOINT_NAME = /[A-Za-z0-9.-]/;
44
+ const LETTER = /[A-Za-z]/;
45
+ const DIGIT = /\d/;
46
+ const WORD = /\w/;
47
+ /** The characters redactWords' four scans read in its last call, for tests: a few per character. */
48
+ export let redactWordsReads = 0;
49
+ /** Whether a word character (\w) is at `at`; none is before the start or past the end. */
50
+ function wordAt(words, at) {
51
+ return at >= 0 && at < words.length && WORD.test(words[at]);
52
+ }
53
+ /** The end of the run of `part` characters that starts at `from`. */
54
+ function runEnd(words, from, part) {
55
+ let at = from;
56
+ while (at < words.length && part.test(words[at]))
57
+ at++;
58
+ redactWordsReads += at - from + 1;
59
+ return at;
60
+ }
61
+ /**
62
+ * A URL of any scheme: a letter where \b holds, more scheme characters, :// and one or more characters. Every start in
63
+ * a run of scheme characters meets the same :// at the run's end, so the run is read to that end once, and the cut
64
+ * starts at its first letter that follows no word character.
65
+ */
66
+ function cutUrls(words) {
67
+ let cut = "";
68
+ let kept = 0;
69
+ let at = 0;
70
+ while (at < words.length) {
71
+ const schemeEnd = runEnd(words, at, URL_SCHEME);
72
+ if (schemeEnd + 3 < words.length && words.startsWith("://", schemeEnd) && URL_REST.test(words[schemeEnd + 3])) {
73
+ let start = at;
74
+ while (start < schemeEnd && !(LETTER.test(words[start]) && !wordAt(words, start - 1)))
75
+ start++;
76
+ redactWordsReads += start - at + 4;
77
+ if (start < schemeEnd) {
78
+ cut += `${words.slice(kept, start)}[a URL]`;
79
+ kept = at = runEnd(words, schemeEnd + 3, URL_REST);
80
+ continue;
81
+ }
82
+ }
83
+ at = schemeEnd + 1;
84
+ }
85
+ return cut + words.slice(kept);
86
+ }
87
+ /**
88
+ * A login in a host's place, user:password@host, each part one or more characters. A user part runs to the end of its
89
+ * run, so every start in a run meets the same colon, password and @ host, and fails when the first does. The scan then
90
+ * goes on past the password: a user part that starts inside it ends at a colon whose password ends where this one
91
+ * did, or at that end itself, which is no colon. So each character is read about twice, where the regex this replaces
92
+ * read to the end of the run from every start in it.
93
+ */
94
+ function cutLogins(words) {
95
+ let cut = "";
96
+ let kept = 0;
97
+ let at = 0;
98
+ while (at < words.length) {
99
+ const userEnd = runEnd(words, at, LOGIN_USER);
100
+ if (userEnd === at || words[userEnd] !== ":") {
101
+ at = userEnd + 1;
102
+ continue;
103
+ }
104
+ const passwordEnd = runEnd(words, userEnd + 1, LOGIN_PASSWORD);
105
+ if (passwordEnd > userEnd + 1 && words[passwordEnd] === "@") {
106
+ const hostEnd = runEnd(words, passwordEnd + 1, LOGIN_HOST);
107
+ if (hostEnd > passwordEnd + 1) {
108
+ cut += `${words.slice(kept, at)}[a login]`;
109
+ kept = at = hostEnd;
110
+ continue;
111
+ }
112
+ }
113
+ at = passwordEnd + 1;
114
+ }
115
+ return cut + words.slice(kept);
116
+ }
117
+ /**
118
+ * A secret-named parameter, its name with a prefix or suffix too (api_key=, access_token=, client_secret=): a run of
119
+ * [\w-] holding a secret word, then = and a value. The cut starts at the run's first word character, where \b holds,
120
+ * so a leading dash is kept. The value is read only when it is cut, so a run that fails is read once.
121
+ */
122
+ function cutSecretParams(words) {
123
+ let cut = "";
124
+ let kept = 0;
125
+ let at = 0;
126
+ while (at < words.length) {
127
+ const nameEnd = runEnd(words, at, PARAM_NAME);
128
+ if (nameEnd < words.length - 1 && words[nameEnd] === "=" && PARAM_VALUE.test(words[nameEnd + 1])) {
129
+ const name = words.slice(at, nameEnd);
130
+ redactWordsReads += name.length;
131
+ if (PARAM_SECRET.test(name)) {
132
+ const valueEnd = runEnd(words, nameEnd + 1, PARAM_VALUE);
133
+ cut += `${words.slice(kept, at + name.search(/\w/))}[a secret]`;
134
+ kept = at = valueEnd;
135
+ continue;
136
+ }
137
+ }
138
+ at = nameEnd + 1;
139
+ }
140
+ return cut + words.slice(kept);
141
+ }
142
+ /**
143
+ * An endpoint with a DNS name, as adb names a phone's: labels of [A-Za-z0-9-], a dot after each, a top-level name of
144
+ * two or more letters, a colon and a port of one to five digits that no word character follows. The name runs to the
145
+ * end of its run of [A-Za-z0-9.-], so every start in a run meets the same top-level name, colon and port. The port is
146
+ * read six digits at most, so a run that fails is read once.
147
+ */
148
+ function cutEndpoints(words) {
149
+ let cut = "";
150
+ let kept = 0;
151
+ let at = 0;
152
+ while (at < words.length) {
153
+ const nameEnd = runEnd(words, at, ENDPOINT_NAME);
154
+ if (words[nameEnd] === ":") {
155
+ let portEnd = nameEnd + 1;
156
+ while (portEnd < words.length && portEnd <= nameEnd + 6 && DIGIT.test(words[portEnd]))
157
+ portEnd++;
158
+ redactWordsReads += portEnd - nameEnd;
159
+ const digits = portEnd - nameEnd - 1;
160
+ const start = digits >= 1 && digits <= 5 && !wordAt(words, portEnd) ? endpointStart(words, at, nameEnd) : -1;
161
+ if (start >= 0) {
162
+ cut += `${words.slice(kept, start)}[an endpoint]`;
163
+ kept = at = portEnd;
164
+ continue;
165
+ }
166
+ }
167
+ at = nameEnd + 1;
168
+ }
169
+ return cut + words.slice(kept);
170
+ }
171
+ /**
172
+ * Where an endpoint's name in words[from, end) starts, or -1: the first place where \b holds, that is no dot, and
173
+ * that has no empty label between it and the last dot, which the top-level name follows.
174
+ */
175
+ function endpointStart(words, from, end) {
176
+ let dot = end - 1;
177
+ while (dot >= from && LETTER.test(words[dot]))
178
+ dot--;
179
+ redactWordsReads += end - dot;
180
+ if (dot < from || words[dot] !== "." || end - dot - 1 < 2)
181
+ return -1;
182
+ let low = from;
183
+ for (let at = from + 1; at <= dot; at++)
184
+ if (words[at] === "." && words[at - 1] === ".")
185
+ low = at + 1;
186
+ redactWordsReads += 2 * (dot - from);
187
+ for (let at = low; at < dot; at++)
188
+ if (words[at] !== "." && wordAt(words, at - 1) !== wordAt(words, at))
189
+ return at;
190
+ return -1;
191
+ }
34
192
  /**
35
193
  * Words with no URL and no secret: a URL of any scheme, a login, a bearer, a secret-named parameter, a key- or
36
- * token-shaped value and an endpoint (a host or an IPv4 address with a port) are taken out.
194
+ * token-shaped value and an endpoint (a host or an IPv4 address with a port) are taken out. The URL, the login, the
195
+ * parameter and the endpoint with a DNS name are scans that read each character a few times: as regexes with no
196
+ * anchored start they read to the end of a long word run from every character in it. The JWT starts only at the first
197
+ * eyJ of its run, for the same reason.
37
198
  */
38
199
  export function redactWords(words) {
39
- return (words
40
- .replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]+/gi, "[a URL]")
41
- // A login in a host's place: user:password@host.
42
- .replace(/[\w.+-]+:[^\s@/'"]+@[\w.-]+/g, "[a login]")
43
- .replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]+/gi, "[a secret]")
44
- // A secret-named parameter, its name with a prefix or suffix too: api_key=, access_token=, client_secret=.
45
- .replace(/\b[\w-]*(?:token|password|passwd|secret|key|jwt|auth|code|signingKey|credential)[\w-]*=[^\s&"';,]+/gi, "[a secret]")
200
+ redactWordsReads = 0;
201
+ const loginsCut = cutLogins(cutUrls(words));
202
+ return cutEndpoints(cutSecretParams(loginsCut.replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]+/gi, "[a secret]"))
46
203
  // A token from the first "eyJ" of its run, glued to a word ("id_eyJ...") too.
47
204
  .replace(/eyJ(?<!eyJ[A-Za-z0-9_-]*?eyJ)[A-Za-z0-9_-]+\.[A-Za-z0-9._-]*/g, "[a secret]")
48
205
  .replace(/\b(?:sk|pk|rk)-[A-Za-z0-9_-]{8,}/g, "[a secret]")
49
206
  .replace(/\bgh[pousr]_[A-Za-z0-9]{16,}/g, "[a secret]")
50
- .replace(/\b(?:sk|pk|pck|ph|tok|pw|jwt)_[A-Za-z0-9_-]{6,}/g, "[a secret]")
51
- // An endpoint: a DNS name or an IPv4 address with a port, as adb names a phone's.
52
- .replace(/\b(?:[A-Za-z0-9-]+\.)+[A-Za-z]{2,}:\d{1,5}\b/g, "[an endpoint]")
53
- .replace(/\b\d{1,3}(?:\.\d{1,3}){3}(?::\d{1,5})?\b/g, "[an endpoint]"));
207
+ .replace(/\b(?:sk|pk|pck|ph|tok|pw|jwt)_[A-Za-z0-9_-]{6,}/g, "[a secret]")).replace(/\b\d{1,3}(?:\.\d{1,3}){3}(?::\d{1,5})?\b/g, "[an endpoint]");
54
208
  }
55
209
  /** The code a watch ends with for an error the computer gave. */
56
210
  export function watchEndCode(code) {
@@ -0,0 +1,9 @@
1
+ /** The code of the error vendorSdk throws when the SDK is not installed: serve's Settings shows its words alone. */
2
+ export declare const SDK_MISSING = "sdk_missing";
3
+ /**
4
+ * The SDK package `name` that `vendor`'s provider calls. When it is not installed, an error with code SDK_MISSING whose
5
+ * words name the package and the install step at this package's pin, such as "E2B needs the e2b package: npm install
6
+ * e2b@2.63.0". "Not installed" is read from resolving `name` itself, before it loads: an installed SDK whose own import
7
+ * fails (a file or a dependency of its own missing) throws that failure as it is, naming the module that is missing.
8
+ */
9
+ export declare function vendorSdk<T>(vendor: string, name: string): Promise<T>;
@@ -0,0 +1,26 @@
1
+ // A vendor's SDK, loaded when its provider is made. Each is one of this package's optionalDependencies, pinned exactly
2
+ // (package.json), so a plain `npm install` brings it and `npm install --omit=optional` leaves it out. The name is an
3
+ // argument here, never an import literal, so no type checker resolves an SDK's types from this package: a provider names
4
+ // only the slice it calls. test/vendor-sdks.test.mjs finds every call and holds each name to a pinned optional
5
+ // dependency.
6
+ import { readFileSync } from "node:fs";
7
+ /** The code of the error vendorSdk throws when the SDK is not installed: serve's Settings shows its words alone. */
8
+ export const SDK_MISSING = "sdk_missing";
9
+ /**
10
+ * The SDK package `name` that `vendor`'s provider calls. When it is not installed, an error with code SDK_MISSING whose
11
+ * words name the package and the install step at this package's pin, such as "E2B needs the e2b package: npm install
12
+ * e2b@2.63.0". "Not installed" is read from resolving `name` itself, before it loads: an installed SDK whose own import
13
+ * fails (a file or a dependency of its own missing) throws that failure as it is, naming the module that is missing.
14
+ */
15
+ export async function vendorSdk(vendor, name) {
16
+ try {
17
+ import.meta.resolve(name);
18
+ }
19
+ catch (error) {
20
+ if (error?.code !== "ERR_MODULE_NOT_FOUND")
21
+ throw error;
22
+ const pins = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).optionalDependencies;
23
+ throw Object.assign(new Error(`${vendor} needs the ${name} package: npm install ${name}@${pins?.[name]}`, { cause: error }), { code: SDK_MISSING });
24
+ }
25
+ return (await import(name));
26
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-computer",
3
- "version": "0.1.0-beta.57",
3
+ "version": "0.1.0-beta.59",
4
4
  "description": "The open platform's computer protocol: a daemon in every computer, and one provisioner per vendor, starting with Docker.",
5
5
  "keywords": [
6
6
  "agentrun",
@@ -117,6 +117,13 @@
117
117
  "NOTICE"
118
118
  ],
119
119
  "sideEffects": false,
120
+ "optionalDependencies": {
121
+ "@boxd-sh/sdk": "0.3.1",
122
+ "disk": "1.12.0",
123
+ "e2b": "2.63.0",
124
+ "modal": "0.11.1",
125
+ "ssh2": "1.17.0"
126
+ },
120
127
  "scripts": {
121
128
  "build": "tsc -p tsconfig.json",
122
129
  "build:daemon": "node scripts/build-daemon.mjs",