@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
@@ -34,9 +34,9 @@ export const quote = (word) => `'${word.replaceAll("'", "'\\''")}'`;
34
34
  /** An argv as one bash command line. */
35
35
  export const commandLine = (argv) => argv.map(quote).join(" ");
36
36
  const codeOfStatus = (status) => status === 401 || status === 403 ? "denied" : status === 404 ? "not_found" : status === 429 ? "limit" : status === 400 || status === 422 ? "invalid" : status === 409 ? "refused" : "vendor";
37
- /** Orgo's REST API with a key: every call bounded, every failure a code and words that never hold the key. */
38
- export function orgoRest({ apiKey, apiUrl = ORGO_API_URL, fetch: fetcher = globalThis.fetch }) {
39
- const base = apiUrl.replace(/\/+$/, "");
37
+ /** Orgo's REST API with a key: every call bounded, every failure a code and words that never hold the key. `apiUrl` is
38
+ * httpsBase's answer, as the providers pass it. */
39
+ export function orgoRest({ apiKey, apiUrl: base = ORGO_API_URL, fetch: fetcher = globalThis.fetch }) {
40
40
  const scrub = (text) => text.replaceAll(apiKey, "[key]").replace(/\s+/g, " ").slice(0, 300);
41
41
  return {
42
42
  origin: new URL(base).origin,
@@ -357,9 +357,7 @@ export class OrgoDesktopProvider {
357
357
  throw new Error("options.apiKey, an Orgo API key, is required");
358
358
  if (workspaceId !== undefined && (typeof workspaceId !== "string" || !WORKSPACE_ID.test(workspaceId)))
359
359
  throw new Error("options.workspaceId, the Orgo workspace this deployment's computers live in, is an Orgo workspace id when given");
360
- const url = new URL(httpsBase(apiUrl, "the Orgo API URL"));
361
- if (url.username !== "" || url.password !== "")
362
- throw new Error("the Orgo API URL holds no credentials: the key goes to it");
360
+ const base = httpsBase(apiUrl, "the Orgo API URL");
363
361
  if (!Number.isSafeInteger(maxLifetimeMs) || maxLifetimeMs <= 0 || maxLifetimeMs > MAX_LIFETIME_MS)
364
362
  throw new Error(`maxLifetimeMs must be a whole number of ms above 0 and at most 720 h (${MAX_LIFETIME_MS} ms)`);
365
363
  const merged = { ...DEFAULTS, ...timeouts };
@@ -367,7 +365,7 @@ export class OrgoDesktopProvider {
367
365
  if (!Number.isSafeInteger(value) || value <= 0 || value > 2 ** 31 - 1)
368
366
  throw new Error(`timeouts.${key} must be a whole number of ms above 0`);
369
367
  }
370
- this.#rest = orgoRest({ apiKey, apiUrl: url.href, ...(fetch ? { fetch } : {}) });
368
+ this.#rest = orgoRest({ apiKey, apiUrl: base, ...(fetch ? { fetch } : {}) });
371
369
  this.#workspace = workspaceHolder(workspaceId, this.#rest, merged.requestMs);
372
370
  this.#profile = PROFILES[os];
373
371
  this.#maxLifetimeMs = maxLifetimeMs;
package/dist/orgo.d.ts CHANGED
@@ -94,6 +94,12 @@ export declare class OrgoProvider implements ComputerProvider {
94
94
  */
95
95
  capabilities(): ComputerCapabilities;
96
96
  check(spec: ComputerSpec): Refusal[];
97
+ /**
98
+ * Makes a computer, once per request (provider.md, Idempotent create): context.requestId's name (computerNameFor)
99
+ * begins the computer's Orgo name, the run's hash, epoch and deadline after it. A request whose computer Orgo still
100
+ * holds answers that one (#held); one whose computer was deleted here is refused exists; a create of a request in
101
+ * flight here waits for the first (CreateRequests).
102
+ */
97
103
  create(spec: ComputerSpec, context: CreateContext): Promise<Result<CreatedComputer>>;
98
104
  /** The live view: screen.watch on a connection of the watch's own (daemonWatch), never Orgo's VNC (proxy only). */
99
105
  watch(ref: ComputerRef, handlers: ScreenWatchHandlers, options?: WatchOptions): Promise<Result<ScreenWatch>>;
package/dist/orgo.js CHANGED
@@ -22,6 +22,7 @@ import { ORGO, ORGO_BASE_IMAGE } from "./descriptors/orgo.js";
22
22
  import { DESKTOP_GROUPS } from "./desktop.js";
23
23
  import { DAEMON_IN_COMPUTER, helloDrift, probeNetworkDrift, probeNotes, probeReportOf, SOCKET_DIR, WORK } from "./drift.js";
24
24
  import { EPOCH_LABEL, OWNER_LABEL, OWNER_SERVER_LABEL, ownerLabels, RUN_HASH_LABEL, RUN_LABEL, runHash } from "./labels.js";
25
+ import { CreateRequests, endedWords, labelsDiffer, otherSpecWords, readBackDiffer } from "./create-requests.js";
25
26
  import { checkMount } from "./mount.js";
26
27
  import { ORGO_API_URL, orgoRest, orgoTerminalChannel, START_LOG } from "./orgo-channel.js";
27
28
  import { OrgoDesktopProvider } from "./orgo-desktop.js";
@@ -67,9 +68,13 @@ const DEFAULT_DAEMON_PATH = fileURLToPath(new URL("./computerd-linux-amd64", imp
67
68
  export const LABELS_FILE = "/opt/agentrun/labels.json";
68
69
  const STAGING = "/tmp/agentrun-computerd-";
69
70
  const LISTEN_RETRY_MS = 250;
71
+ /** The order a request's computers are read in (#held, #converge): the oldest first, by created_at, then id. */
72
+ const oldestFirst = (a, b) => String(a.created_at ?? "").localeCompare(String(b.created_at ?? "")) || a.id.localeCompare(b.id);
70
73
  /** How often a delete that answers 409 (the computer waking) is tried again. */
71
74
  const DELETE_TRIES = 5;
72
75
  const SPEC_FIELDS = new Set(["image", "lifetimeMs", "network", "cpus", "memoryMb", "labels", "gpu"]);
76
+ /** The request's name (computerNameFor) a computer's Orgo name begins with. */
77
+ const requestOf = (name) => `computer-${nameParts(name)?.hex ?? ""}`;
73
78
  /** The states in which a computer runs, or is on its way to. */
74
79
  const RUNNING = new Set(["running", "creating", "restarting", "updating", "resuming"]);
75
80
  /** Why a network other than "none" is refused, in the words every hosted provider uses (hosted/network.ts), and why:
@@ -192,14 +197,14 @@ export class OrgoProvider {
192
197
  #extending = new Map();
193
198
  /** Each agent's computer's attach or detach in flight, by id: the next waits for it, so two never overlap here. */
194
199
  #owning = new Map();
200
+ /** Idempotent create's in-process half: one computer per request id (provider.md). */
201
+ #requests = new CreateRequests();
195
202
  constructor({ apiKey, workspaceId, apiUrl = ORGO_API_URL, fetch, webSocket, channel, daemonPath = DEFAULT_DAEMON_PATH, maxLifetimeMs = MAX_LIFETIME_MS, user = "2510:2510", start = "bash", display = ":99", timeouts = {}, probeTargets = DEFAULT_PROBE_TARGETS, ledger = orgoMemoryLedger() }) {
196
203
  if (typeof apiKey !== "string" || apiKey === "")
197
204
  throw new Error("options.apiKey, an Orgo API key, is required");
198
205
  if (workspaceId !== undefined && (typeof workspaceId !== "string" || !WORKSPACE_ID.test(workspaceId)))
199
206
  throw new Error("options.workspaceId, the Orgo workspace this deployment's computers live in, is an Orgo workspace id when given");
200
- const url = new URL(httpsBase(apiUrl, "the Orgo API URL"));
201
- if (url.username !== "" || url.password !== "")
202
- throw new Error("the Orgo API URL holds no credentials: the key goes to it");
207
+ const base = httpsBase(apiUrl, "the Orgo API URL");
203
208
  if (!Number.isSafeInteger(maxLifetimeMs) || maxLifetimeMs <= 0 || maxLifetimeMs > MAX_LIFETIME_MS)
204
209
  throw new Error(`maxLifetimeMs must be a whole number of ms above 0 and at most Orgo's 720 h (${MAX_LIFETIME_MS} ms)`);
205
210
  const ids = USER.exec(user);
@@ -219,7 +224,7 @@ export class OrgoProvider {
219
224
  if (!Array.isArray(probeTargets) || probeTargets.length === 0 || probeTargets.some((target) => typeof target !== "string" || !TARGET.test(target))) {
220
225
  throw new Error("probeTargets must name at least one address for the probe, each host:port or host:port/udp");
221
226
  }
222
- this.#rest = orgoRest({ apiKey, apiUrl: url.href, ...(fetch ? { fetch } : {}) });
227
+ this.#rest = orgoRest({ apiKey, apiUrl: base, ...(fetch ? { fetch } : {}) });
223
228
  this.#workspace = workspaceHolder(workspaceId, this.#rest, merged.requestMs);
224
229
  this.#channel = channel ?? orgoTerminalChannel({ rest: this.#rest, workspace: (signal) => this.#workspace.read(signal), ...(webSocket ? { webSocket } : {}) });
225
230
  this.#daemonPath = daemonPath;
@@ -294,11 +299,22 @@ export class OrgoProvider {
294
299
  }
295
300
  return refusals;
296
301
  }
302
+ /**
303
+ * Makes a computer, once per request (provider.md, Idempotent create): context.requestId's name (computerNameFor)
304
+ * begins the computer's Orgo name, the run's hash, epoch and deadline after it. A request whose computer Orgo still
305
+ * holds answers that one (#held); one whose computer was deleted here is refused exists; a create of a request in
306
+ * flight here waits for the first (CreateRequests).
307
+ */
297
308
  async create(spec, context) {
298
- const signal = context?.signal;
299
309
  const refusals = this.check(spec);
300
- if (refusals.length > 0)
301
- return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
310
+ return this.#requests.create(spec, context, {
311
+ refuse: fail,
312
+ ...(refusals.length > 0 ? { refused: refusals.map(({ field, message }) => `${field}: ${message}`).join("; ") } : {}),
313
+ make: (request) => this.#createNamed(spec, request, context.signal),
314
+ });
315
+ }
316
+ /** Everything create does under the request's name: the computer Orgo holds under it, or a new one. */
317
+ async #createNamed(spec, request, signal) {
302
318
  let daemon;
303
319
  try {
304
320
  daemon = readFileSync(this.#daemonPath);
@@ -320,10 +336,13 @@ export class OrgoProvider {
320
336
  const maxDeadline = new Date(now + this.#maxLifetimeMs).toISOString();
321
337
  const deadline = owner === undefined ? new Date(now + runLifetimeMs(spec)).toISOString() : maxDeadline;
322
338
  const init = owner === undefined ? { deadline, maxDeadline } : this.#ownedInit(now);
323
- // The janitor's deadline is in the name, so list() and the sweep read it with nothing run inside.
324
- const name = orgoName(labels, randomBytes(6).toString("hex"), owner === undefined ? new Date(deadline) : undefined, owner);
339
+ // The request's name first, then the janitor's deadline, so list() and the sweep read it with nothing run inside.
340
+ const name = orgoName(labels, request.slice("computer-".length), owner === undefined ? new Date(deadline) : undefined, owner);
325
341
  if (name.length > NAME_MAX || nameParts(name) === undefined)
326
342
  return fail("invalid", `the name ${name} is not one Orgo holds: at most ${NAME_MAX} of letters, digits and dashes`);
343
+ const held = await this.#held(spec, request, labels, signal);
344
+ if (!held.ok || held.value !== undefined)
345
+ return held;
327
346
  const ram = spec.memoryMb === undefined ? 4 : spec.memoryMb / 1024;
328
347
  const cpu = spec.cpus ?? CPU_FOR_RAM[ram];
329
348
  const body = {
@@ -338,15 +357,29 @@ export class OrgoProvider {
338
357
  };
339
358
  const made = await this.#rest.request("POST", "/computers", { body, timeoutMs: this.#timeouts.createMs, ...(signal ? { signal } : {}) });
340
359
  if (!made.ok) {
360
+ // A name Orgo holds already (409) is another process's create of this request in the same second: that computer
361
+ // is answered as a retry's would be.
362
+ if (made.status === 409) {
363
+ const theirs = await this.#held(spec, request, labels, signal);
364
+ return !theirs.ok || theirs.value !== undefined ? theirs : made;
365
+ }
341
366
  // A create Orgo refused (a 4xx) made nothing. One whose answer never came may have: it goes by its name.
342
367
  if (["invalid", "denied", "limit", "not_found", "refused"].includes(made.error.code))
343
368
  return made;
369
+ this.#requests.end(request);
344
370
  return fail(made.error.code, `${made.error.message}${await this.#deleteNamed(name)}`);
345
371
  }
346
372
  const id = made.value?.id;
347
- if (typeof id !== "string" || !COMPUTER_ID.test(id))
373
+ if (typeof id !== "string" || !COMPUTER_ID.test(id)) {
374
+ this.#requests.end(request);
348
375
  return vendorFail("orgo", `Orgo's create answered no computer id${await this.#deleteNamed(name)}`);
376
+ }
377
+ this.#requests.made(request);
349
378
  const ref = { id, name };
379
+ // Another process's create of this request may have made one too (#converge): the older is kept.
380
+ const first = await this.#converge(spec, request, labels, made.value, signal);
381
+ if (first !== undefined)
382
+ return first;
350
383
  // An agent's computer's labels go in the ledger at once, so list finds it as the agent's whatever happens next.
351
384
  if (owner !== undefined) {
352
385
  const kept = await this.#keep({ id, labels });
@@ -357,9 +390,109 @@ export class OrgoProvider {
357
390
  const prepared = await this.#prepare(ref, made.value.status, file, daemon, signal, init);
358
391
  if (signal?.aborted)
359
392
  return this.#abandon(ref, { code: "aborted", message: "create was aborted" });
360
- if (prepared.ok)
361
- return ok(prepared.value.length > 0 ? { ...ref, notes: prepared.value } : ref);
362
- return this.#abandon(ref, prepared.error);
393
+ if (!prepared.ok)
394
+ return this.#abandon(ref, prepared.error);
395
+ // The last read of the workspace, once this computer is up: an older one listed only now is answered here.
396
+ const last = await this.#converge(spec, request, labels, made.value, signal);
397
+ if (last !== undefined)
398
+ return last;
399
+ return ok(prepared.value.length > 0 ? { ...ref, notes: prepared.value } : ref);
400
+ }
401
+ /**
402
+ * The one computer a request keeps. Two creates of one request in two processes can both find no computer for it
403
+ * (#held) and both make one: CreateRequests holds within one provider alone, and the names differ once the
404
+ * deadline in them does. So after Orgo's answer the workspace is read again: where an older computer of this request
405
+ * is there (the oldest by created_at, then id, the order #held reads), this one is deleted and the older answered
406
+ * through #held, as a retry's create answers it. Every process picks the same one from the same listing, so the
407
+ * newer creates delete their own and the oldest keeps its. Undefined when this computer is the request's oldest (or
408
+ * the listing fails: the create goes on with its own); an abort deletes this computer (#abandon, never under the
409
+ * caller's signal), and the create is aborted.
410
+ */
411
+ async #converge(spec, request, labels, mine, signal) {
412
+ const listed = await this.#desktops(signal);
413
+ if (!listed.ok) {
414
+ if (listed.error.code !== "aborted" && !signal?.aborted)
415
+ return undefined;
416
+ // The caller is gone: the computer this POST made is deleted, never under the caller's signal.
417
+ return this.#abandon({ id: mine.id, name: mine.name }, { code: "aborted", message: "create was aborted" });
418
+ }
419
+ const hex = request.slice("computer-".length);
420
+ const holders = listed.value.filter((one) => nameParts(one.name)?.hex === hex && this.#ours(one) && RUNNING.has(one.status));
421
+ // Not listed yet, it was made just now: no older than now.
422
+ if (!holders.some((one) => one.id === mine.id))
423
+ holders.push({ ...mine, created_at: mine.created_at ?? new Date().toISOString() });
424
+ const [kept] = holders.sort(oldestFirst);
425
+ if (kept === undefined || kept.id === mine.id)
426
+ return undefined;
427
+ const ref = { id: mine.id, name: mine.name };
428
+ const deleted = await this.#delete(ref);
429
+ if (!deleted.ok)
430
+ return fail(deleted.error.code, `${kept.name}, the older computer of this request, is kept, and ${ref.name} could not be deleted (${deleted.error.message}); Orgo ends it at its end`);
431
+ const theirs = await this.#held(spec, request, labels, signal);
432
+ if (!theirs.ok || theirs.value !== undefined)
433
+ return theirs;
434
+ this.#requests.end(request);
435
+ return fail("exists", `${ref.name} was deleted for ${kept.name}, the older computer of this request, which is gone now: create with a new request id`);
436
+ }
437
+ /**
438
+ * The computer Orgo holds for this request, when it holds one: undefined when it holds none, so create makes it. It
439
+ * is found by the request's name, the start of every name create gives (the rest moves with the deadline), among the
440
+ * workspace's computers, the oldest first. Up and sound (its labels file and its daemon, as attach reads them), it is
441
+ * returned when it is what this spec asks for, and refused exists when it is another spec's. One still being made
442
+ * (by another process's create) is waited for, within the time a create of its own takes; one that no longer runs,
443
+ * or whose deadline has passed, is refused exists.
444
+ */
445
+ async #held(spec, request, labels, signal) {
446
+ const hex = request.slice("computer-".length);
447
+ const { createMs, uploadMs, helloMs, probeMs, pollMs } = this.#timeouts;
448
+ const wait = createMs + uploadMs + helloMs + probeMs;
449
+ const until = Date.now() + wait;
450
+ let last;
451
+ for (;;) {
452
+ const listed = await this.#desktops(signal);
453
+ if (!listed.ok)
454
+ return listed;
455
+ const found = listed.value.filter((one) => nameParts(one.name)?.hex === hex && this.#ours(one)).sort(oldestFirst);
456
+ const record = found[0];
457
+ if (record === undefined)
458
+ return ok(undefined);
459
+ const ref = { id: record.id, name: record.name };
460
+ const deadline = nameParts(record.name)?.deadline;
461
+ if (deadline !== undefined && deadline.getTime() <= Date.now())
462
+ return fail("exists", endedWords(record.name));
463
+ if (!RUNNING.has(record.status))
464
+ return fail("exists", `${record.name} was made for this request and is ${record.status}, not running: create with a new request id`);
465
+ if (record.status === "running") {
466
+ const file = await this.#readLabels(ref, signal);
467
+ if (file.ok) {
468
+ const differ = [
469
+ ...labelsDiffer(labels, file.value.labels, "read back"),
470
+ ...readBackDiffer(spec, { image: file.value.image, user: `${this.#uid}:${this.#gid}`, network: "none", ...(file.value.cpus === undefined ? {} : { cpus: file.value.cpus }), ...(file.value.memoryMb === undefined ? {} : { memoryMb: file.value.memoryMb }) }, ["image", "cpus", "memoryMb"]),
471
+ ];
472
+ if (differ.length > 0)
473
+ return fail("exists", otherSpecWords(record.name, "was made", differ));
474
+ const inside = await this.#inside(ref, signal);
475
+ if (inside.ok)
476
+ return ok(inside.value.length > 0 ? { ...ref, notes: inside.value } : ref);
477
+ if (inside.error.code === "aborted")
478
+ return inside;
479
+ // Its daemon is not up yet: the create that made it is still preparing it.
480
+ last = inside.error.message;
481
+ }
482
+ else {
483
+ if (file.error.code === "aborted")
484
+ return file;
485
+ last = file.error.message;
486
+ }
487
+ }
488
+ else
489
+ last = `Orgo reads it ${record.status}`;
490
+ if (Date.now() + pollMs >= until)
491
+ return fail("timeout", `${record.name}, made for this request, was not up within ${seconds(wait)}: ${last}`);
492
+ await pause(pollMs, signal);
493
+ if (signal?.aborted)
494
+ return fail("aborted", `create was aborted while ${record.name}, made for this request, came up`);
495
+ }
363
496
  }
364
497
  /**
365
498
  * Everything between Orgo's answer and a computer that passed the drift check: running, computerd uploaded and
@@ -611,6 +744,7 @@ export class OrgoProvider {
611
744
  }
612
745
  /** Deletes a computer create gives up on, and waits until Orgo no longer has it. Never signalled: it outlives an abort. */
613
746
  async #abandon(ref, error) {
747
+ this.#requests.end(requestOf(ref.name));
614
748
  const deleted = await this.#delete(ref);
615
749
  return fail(error.code, `the computer ${ref.name} ${deleted.ok ? "was deleted" : `could not be deleted (${deleted.error.message}); Orgo ends it at its end`}: ${error.message}`);
616
750
  }
@@ -1130,8 +1264,17 @@ export class OrgoProvider {
1130
1264
  return how === "delete" ? ok(undefined) : fail("not_found", `${ref.name} is deleted: there is nothing to detach`);
1131
1265
  if (!this.#ours(read.value, ref.name))
1132
1266
  return fail("not_found", `no Orgo computer of this provider is ${ref.name} (${ref.id}), so it is left as it is`);
1133
- if (how === "delete")
1134
- return claim === undefined ? this.#delete(ref, signal) : this.#claimedDelete(ref, read.value.name, claim, signal);
1267
+ if (how === "delete") {
1268
+ // The request's computer is ended here: a later create of it is refused exists, never made again.
1269
+ if (claim === undefined) {
1270
+ this.#requests.end(requestOf(read.value.name));
1271
+ return this.#delete(ref, signal);
1272
+ }
1273
+ const deleted = await this.#claimedDelete(ref, read.value.name, claim, signal);
1274
+ if (deleted.ok)
1275
+ this.#requests.end(requestOf(read.value.name));
1276
+ return deleted;
1277
+ }
1135
1278
  const owner = nameParts(read.value.name)?.owner;
1136
1279
  if (owner === undefined)
1137
1280
  return fail("refused", `${ref.name} is a run's computer, not an agent's own: it is deleted at its release, never detached`);
@@ -91,10 +91,11 @@ export declare const ADB_SERVER_PORT = 5037;
91
91
  * The adb CLI (Android platform-tools) at path, by execFile, never a shell, and the adb server it starts, on the
92
92
  * loopback at port (adb's own default), spoken to by its socket protocol.
93
93
  *
94
- * env is the environment a spawned adb starts from, with every adb variable dropped from it (ADB_SERVER_SOCKET,
95
- * ANDROID_ADB_SERVER_SOCKET, ANDROID_ADB_SERVER_ADDRESS, ANDROID_SERIAL, ...), so nothing in it points the CLI at
96
- * another server than its socket requests reach. The library reads no environment of its own: a caller passes it (the
97
- * conformance module passes process.env). Without env, a spawned adb inherits the process's environment as it is.
94
+ * env is the environment the host passes: a spawned adb, and the adb server it starts, hold its ADB_ENV_NAMES alone
95
+ * (adbEnv), never a key, and none of the variables that point adb at another server or device (ADB_SERVER_SOCKET,
96
+ * ANDROID_ADB_SERVER_ADDRESS, ANDROID_SERIAL, ...) than its socket requests reach. The library reads no environment of
97
+ * its own: the provider passes its env, the conformance module process.env. Without env, adb starts with none, and a
98
+ * bare "adb" is found only on the default path: pass env, or adb's absolute path.
98
99
  */
99
100
  export declare function adbCli(path?: string, { port, env }?: {
100
101
  port?: number;
@@ -144,7 +145,8 @@ export interface PhoneProviderOptions {
144
145
  * PHONE_HARNESS_APKS, else none. A connect that cannot install one fails in words.
145
146
  */
146
147
  apks?: readonly PinnedApk[];
147
- /** The host's own variables its descriptor declares (hostEnv): PHONE_HARNESS_APKS alone, the server's apks. */
148
+ /** The host's own variables its descriptor declares (hostEnv): PHONE_HARNESS_APKS, the server's apks, and what adb
149
+ * reads (ADB_ENV_NAMES), the only environment an adb this provider runs starts with. */
148
150
  env?: Readonly<Record<string, string | undefined>>;
149
151
  }
150
152
  /** An APK the provider installs: its file's absolute path, and the sha256 of its bytes (64 lowercase hex digits). */
@@ -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.