@parcha/agentrun-computer 0.1.0-beta.40 → 0.1.0-beta.42

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 (96) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +285 -28
  3. package/box/Dockerfile +6 -4
  4. package/box/README.md +10 -2
  5. package/box/build-daytona.py +3 -1
  6. package/box/build-e2b.mjs +1 -1
  7. package/box/install.sh +68 -7
  8. package/dist/attach.d.ts +46 -1
  9. package/dist/attach.js +48 -4
  10. package/dist/box-image.d.ts +1 -1
  11. package/dist/box-image.js +1 -1
  12. package/dist/boxd.d.ts +126 -0
  13. package/dist/boxd.js +418 -0
  14. package/dist/cloudflare.d.ts +32 -0
  15. package/dist/cloudflare.js +179 -0
  16. package/dist/computerd-linux-amd64 +0 -0
  17. package/dist/computerd-linux-arm64 +0 -0
  18. package/dist/computerd.json +2 -2
  19. package/dist/conformance/boxd.d.ts +77 -0
  20. package/dist/conformance/boxd.js +113 -0
  21. package/dist/conformance/cases/isolation.js +1 -17
  22. package/dist/conformance/cases/provider.js +42 -26
  23. package/dist/conformance/cli.js +4 -1
  24. package/dist/conformance/cloudflare.d.ts +42 -0
  25. package/dist/conformance/cloudflare.js +54 -0
  26. package/dist/conformance/daytona.d.ts +25 -0
  27. package/dist/conformance/daytona.js +26 -1
  28. package/dist/conformance/dial-only.d.ts +6 -0
  29. package/dist/conformance/dial-only.js +9 -0
  30. package/dist/conformance/e2b.d.ts +12 -3
  31. package/dist/conformance/e2b.js +21 -4
  32. package/dist/conformance/exec-stream.js +14 -6
  33. package/dist/conformance/fly.d.ts +52 -0
  34. package/dist/conformance/fly.js +52 -0
  35. package/dist/conformance/modal.d.ts +15 -2
  36. package/dist/conformance/modal.js +36 -3
  37. package/dist/conformance/morph.d.ts +59 -0
  38. package/dist/conformance/morph.js +95 -0
  39. package/dist/conformance/phone-harness.js +2 -2
  40. package/dist/conformance/runner.js +5 -1
  41. package/dist/conformance/sweep.d.ts +1 -1
  42. package/dist/conformance/sweep.js +1 -1
  43. package/dist/conformance/types.d.ts +21 -0
  44. package/dist/daytona.d.ts +8 -1
  45. package/dist/daytona.js +124 -101
  46. package/dist/descriptor.d.ts +22 -1
  47. package/dist/descriptor.js +18 -0
  48. package/dist/descriptors/boxd.d.ts +52 -0
  49. package/dist/descriptors/boxd.js +29 -0
  50. package/dist/descriptors/cloudflare.d.ts +21 -0
  51. package/dist/descriptors/cloudflare.js +29 -0
  52. package/dist/descriptors/daytona.d.ts +12 -3
  53. package/dist/descriptors/daytona.js +15 -7
  54. package/dist/descriptors/e2b.d.ts +4 -0
  55. package/dist/descriptors/e2b.js +3 -0
  56. package/dist/descriptors/fly.d.ts +19 -0
  57. package/dist/descriptors/fly.js +28 -0
  58. package/dist/descriptors/index.d.ts +121 -2
  59. package/dist/descriptors/index.js +7 -2
  60. package/dist/descriptors/modal.d.ts +3 -0
  61. package/dist/descriptors/modal.js +7 -2
  62. package/dist/descriptors/morph.d.ts +15 -0
  63. package/dist/descriptors/morph.js +21 -0
  64. package/dist/descriptors/phone-harness.d.ts +1 -0
  65. package/dist/descriptors/phone-harness.js +2 -0
  66. package/dist/e2b.d.ts +7 -1
  67. package/dist/e2b.js +87 -44
  68. package/dist/fly.d.ts +43 -0
  69. package/dist/fly.js +245 -0
  70. package/dist/host.d.ts +52 -48
  71. package/dist/hosted/framed-exec.d.ts +8 -19
  72. package/dist/hosted/framed-exec.js +21 -87
  73. package/dist/hosted/process.d.ts +21 -0
  74. package/dist/hosted/process.js +37 -2
  75. package/dist/hosted/provider.d.ts +32 -6
  76. package/dist/hosted/provider.js +239 -236
  77. package/dist/hosted/rest.d.ts +19 -0
  78. package/dist/hosted/rest.js +76 -0
  79. package/dist/hosted/scripts.d.ts +52 -8
  80. package/dist/hosted/scripts.js +118 -23
  81. package/dist/hosted/ssh-exec.d.ts +9 -7
  82. package/dist/hosted/ssh-exec.js +93 -54
  83. package/dist/hosted/values.d.ts +5 -0
  84. package/dist/hosted/values.js +9 -0
  85. package/dist/index.d.ts +3 -3
  86. package/dist/index.js +4 -4
  87. package/dist/kinds.d.ts +2 -0
  88. package/dist/modal.d.ts +6 -0
  89. package/dist/modal.js +40 -17
  90. package/dist/morph.d.ts +65 -0
  91. package/dist/morph.js +495 -0
  92. package/dist/phone-harness.d.ts +15 -5
  93. package/dist/phone-harness.js +50 -15
  94. package/dist/providers.d.ts +4 -2
  95. package/dist/screen-watch.js +2 -2
  96. package/package.json +20 -2
@@ -11,6 +11,7 @@ import { readFileSync } from "node:fs";
11
11
  import { resolve } from "node:path";
12
12
  import { fileURLToPath } from "node:url";
13
13
  import { isDeepStrictEqual } from "node:util";
14
+ import { ATTACH_PATH, DAEMON_PATH } from "../attach.js";
14
15
  import { CreateRequests, endedWords, otherSpecWords, readBackDiffer } from "../create-requests.js";
15
16
  import { desktopOf, startDisplay } from "../desktop.js";
16
17
  import { COMPUTER_LABEL, DAEMON_IN_COMPUTER, DEADLINE_LABEL, helloDrift, probeNetworkDrift, probeNotes, probeReportOf, show, WORK } from "../drift.js";
@@ -25,10 +26,10 @@ import { failFor, ok } from "../result.js";
25
26
  import { daemonWatch } from "../screen-watch.js";
26
27
  import { countTested } from "../test-connection.js";
27
28
  import { waitUntil } from "../wait.js";
28
- import { bounded, CALL_SLACK_MS, hostCall, OUTPUT_MAX, openBridge, pause, rootOf, runToExit, seconds, uploadThroughExec } from "./process.js";
29
- import { isWhole, packLabels } from "./values.js";
29
+ import { bounded, CALL_SLACK_MS, hostCall, openBridge, pause, rootOf, runToExit, seconds, uploadThroughExec, words } from "./process.js";
30
+ import { isWhole, PACKED_NAME, packLabels, unpackLabels } from "./values.js";
30
31
  import { EGRESS_POLICY, EGRESS_PROXY_USER, EGRESS_RELAY, HOSTED_ALLOW, NETWORK_LABEL, networkFormOf, networkOfForm, networkRefusal, throughProxy } from "./network.js";
31
- import { ARCHIL_GATE, closedSocketsOf, daemonDrift, hostedCommands, installerOf, LABEL_FILE, labelsCommand } from "./scripts.js";
32
+ import { ARCHIL_GATE, closedSocketsOf, daemonDrift, hostedCommands, initFlags, installerOf } from "./scripts.js";
32
33
  const VERSION = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
33
34
  export const NAME_LABEL = `${COMPUTER_LABEL}.name`;
34
35
  /** The image create was asked for: a vendor may report another name for it (a template's id). */
@@ -67,11 +68,14 @@ const LISTED_ROUNDS = 2;
67
68
  const LISTEN_RETRY_MS = 250;
68
69
  const START_POLL_MS = 500;
69
70
  /**
70
- * With labels kept in the machine: what a machine of a request's name with no label file must be older than, past the
71
- * longest a create takes to write the file (#unfiledMs), before a sweep of the name takes it: another instance's longer
72
- * timeouts, and the vendor's clock against this one's.
71
+ * The computerd build a hosted machine of arch runs: HostedProvider's default daemonPath, and the file serve's daemon
72
+ * route serves, so the sha256 a dial machine checks (AGENTRUN_DAEMON_SHA256) is this file's.
73
73
  */
74
- const UNFILED_MARGIN_MS = 300_000;
74
+ export function hostedDaemonPath(arch) {
75
+ return fileURLToPath(new URL(`../computerd-linux-${arch}`, import.meta.url));
76
+ }
77
+ /** The dial creates in flight per request name, keyed by the server's AttachHub (#inTurn). */
78
+ const DIAL_TURNS = new WeakMap();
75
79
  /** The longest a Node timer or AbortSignal.timeout holds. */
76
80
  const MAX_TIMER_MS = 2 ** 31 - 1;
77
81
  /** The longest timeout the adapter takes: the race of a call bounded by it must still fit a Node timer. */
@@ -97,7 +101,7 @@ const REFUSED_CREATE = new Set(["invalid", "denied", "limit", "not_found", "refu
97
101
  * nothing: a machine under the name then is another's (exists: another instance's create of the request), never
98
102
  * deleted. Any other failure (the vendor's, a timeout) may have made one, answered in time or after create gave up.
99
103
  */
100
- const mayHaveMade = (code) => !REFUSED_CREATE.has(code);
104
+ export const mayHaveMade = (code) => !REFUSED_CREATE.has(code);
101
105
  /** An ISO time a label holds, or undefined when it is missing or not the ISO time create writes. */
102
106
  export function isoOf(written) {
103
107
  const at = written === undefined ? Number.NaN : Date.parse(written);
@@ -172,10 +176,10 @@ export class HostedProvider {
172
176
  #requests = new CreateRequests();
173
177
  /** Each computer's last extend, by machine id, while one runs: the next waits for it. */
174
178
  #extending = new Map();
175
- /** Each held computer's keepalive timer, by machine id (facts.idleMs). */
176
- #kept = new Map();
179
+ /** A dial host's server: what its machines reach, and what holds their tokens and sockets. */
180
+ #dial;
177
181
  constructor(host, options) {
178
- const { kind = "linux", desktop = {}, maxLifetimeMs = host.facts.maxLifetimeMs, daemonPath = fileURLToPath(new URL(`../computerd-linux-${host.facts.arch}`, import.meta.url)), daemonUser = TOOL_USER, timeouts = {}, probeTargets = DEFAULT_PROBE_TARGETS, onNote, archilEgress, } = options;
182
+ const { kind = "linux", desktop = {}, maxLifetimeMs = host.facts.maxLifetimeMs, daemonPath = hostedDaemonPath(host.facts.arch), daemonUser = TOOL_USER, timeouts = {}, probeTargets = DEFAULT_PROBE_TARGETS, onNote, archilEgress, } = options;
179
183
  const { id, label, capabilities } = host.descriptor;
180
184
  if (kind !== "desktop" && kind !== "linux")
181
185
  throw new Error(`kind is desktop or linux, not ${String(kind)}`);
@@ -192,16 +196,12 @@ export class HostedProvider {
192
196
  if (!isWhole(maxLifetimeMs) || maxLifetimeMs <= 0 || maxLifetimeMs > host.facts.maxLifetimeMs) {
193
197
  throw new Error(`maxLifetimeMs must be a whole number of ms above 0 and at most ${host.facts.maxLifetimeMs} ms, the longest ${label} keeps a computer`);
194
198
  }
195
- const { idleMs } = host.facts;
196
- if (idleMs !== undefined && (!isWhole(idleMs) || idleMs <= 0 || idleMs > MAX_TIMER_MS))
197
- throw new Error(`facts.idleMs must be a whole number of ms above 0 and at most ${MAX_TIMER_MS}, not ${idleMs}`);
198
- if (idleMs !== undefined && !host.keepalive) {
199
- throw new Error(`${label} declares an idle timer (facts.idleMs ${idleMs}) and no keepalive, so a quiet computer would end under its run: give the host keepalive, the vendor's call that restarts the timer`);
200
- }
201
- // A machine whose create was cut off before its labels were written carries none the janitor lists: only a vendor's
202
- // timer ends it, at its deadline (lifetime vendor) or at the backstop.
203
- if (host.facts.labels === "machine" && host.facts.lifetime !== "vendor" && host.facts.backstop !== true) {
204
- throw new Error(`${label} keeps no labels (facts.labels "machine"), so a vendor timer must end its machines: a machine whose create stopped before its labels were written has none the janitor lists. Declare lifetime "vendor", or set the vendor's delete timer from req.backstopAt and declare backstop: true`);
199
+ if (host.facts.connect === "dial") {
200
+ // Every connection goes over the socket the machine dials: nothing reaches into it from here.
201
+ if (host.exec || host.upload)
202
+ throw new Error(`${label}'s machines dial this server (facts.connect "dial"), so its host has no exec and no upload: leave them out`);
203
+ if (kind === "desktop")
204
+ throw new Error(`${label}'s machines dial this server (facts.connect "dial"), and agentrun-dial starts init with no display: make it kind linux`);
205
205
  }
206
206
  const user = USER.exec(daemonUser);
207
207
  if (user === null || Number(user[1]) > MAX_ID || Number(user[2]) > MAX_ID)
@@ -228,6 +228,7 @@ export class HostedProvider {
228
228
  [this.#uid, this.#gid] = [String(Number(user[1])), String(Number(user[2]))];
229
229
  this.#timeouts = merged;
230
230
  this.#probeTargets = [...probeTargets];
231
+ this.#dial = host.facts.connect === "dial" ? options.dial : undefined;
231
232
  // Extend only where the end can follow it: the host moves its timer or its deadline label.
232
233
  if (host.extend)
233
234
  this.extend = (ref, ttlMs, context) => this.#extendSerial(ref, ttlMs, context?.signal);
@@ -250,7 +251,7 @@ export class HostedProvider {
250
251
  groups: [...this.#configuration.groups],
251
252
  maxLifetimeMs: this.#maxLifetimeMs,
252
253
  release: ["delete"],
253
- mount: [...descriptor.mounts],
254
+ mount: descriptor.mounts.filter((kind) => !(this.#dialing && kind === "archil")),
254
255
  vendorAgentPorts: [...facts.vendorAgentPorts],
255
256
  ...(gpu === undefined ? {} : { gpu: structuredClone(gpu) }),
256
257
  ...(facts.user === undefined ? {} : { user: [...facts.user] }),
@@ -265,7 +266,9 @@ export class HostedProvider {
265
266
  const label = this.#label;
266
267
  // An Archil mount's own rules hold only where the provider takes one; elsewhere checkMount's refusal says why alone.
267
268
  const archil = mount?.kind === "archil" && (capabilities.mount ?? []).includes("archil");
268
- refusals.push(...checkMount(mount, capabilities.mount ?? [], this.host.descriptor.unmounted), ...(archil ? archilRefusals(given) : []));
269
+ // A machine that dials takes no Archil mount yet: its helper's steps run as root through exec, which it has none of.
270
+ const unmounted = this.#dialing ? { ...this.host.descriptor.unmounted, archil: `${label}'s machines dial this server, and a machine that dials takes no Archil mount yet` } : this.host.descriptor.unmounted;
271
+ refusals.push(...checkMount(mount, capabilities.mount ?? [], unmounted), ...(archil ? archilRefusals(given) : []));
269
272
  const daemonUser = `${this.#uid}:${this.#gid}`;
270
273
  const asked = this.#takesUser ? given.user : undefined;
271
274
  if (asked !== undefined) {
@@ -318,43 +321,58 @@ export class HostedProvider {
318
321
  refusals.push(...this.host.check(given));
319
322
  return refusals;
320
323
  }
321
- /** Whether the host keeps no labels (facts.labels "machine"): the adapter keeps them in the machine, at LABEL_FILE. */
322
- get #keeps() {
323
- return this.host.facts.labels === "machine";
324
+ /** Whether the host's machines dial this server (facts.connect "dial"): every connection goes over that socket. */
325
+ get #dialing() {
326
+ return this.host.facts.connect === "dial";
324
327
  }
325
328
  /**
326
- * The longest a create takes from the vendor's create to the label file: its own call and the wait for the machine to
327
- * run (createMs each), the listing of the name between them (listMs, and a read), and the file's write (execMs), plus
328
- * UNFILED_MARGIN_MS.
329
+ * Where a dial host's machines reach this server: its attach route as ws(s) and its daemon route, from dial.url, an
330
+ * https address (http only on 127.0.0.1, for tests); or the refusal of a create, in words, where it has none or where
331
+ * the provider was given no dial (no hub, so no process to take the machine's socket).
329
332
  */
330
- get #unfiledMs() {
331
- const { createMs, listMs, requestMs, execMs } = this.#timeouts;
332
- return 2 * createMs + listMs + requestMs + execMs + UNFILED_MARGIN_MS;
333
+ #dialed() {
334
+ if (this.#dial === undefined) {
335
+ return { problem: `${this.#label} machines dial in to this server, and this process has no attach hub: start them from serve's own process` };
336
+ }
337
+ const url = this.#dial.url;
338
+ const at = URL.canParse(url ?? "") ? new URL(url) : undefined;
339
+ if (at === undefined || !(at.protocol === "https:" || (at.protocol === "http:" && at.hostname === "127.0.0.1"))) {
340
+ return {
341
+ problem: `${this.#label} machines dial this server, and it has no public https address: set AGENTRUN_PUBLIC_URL to one the internet reaches (a tunnel such as cloudflared or tailscale funnel works), or use a provider whose host has exec`,
342
+ };
343
+ }
344
+ // From the parsed address, whose scheme and host are lowercase: "HTTPS://Example.com/" is https://example.com.
345
+ const path = at.pathname.replace(/\/+$/, "");
346
+ return {
347
+ attach: `${at.protocol === "https:" ? "wss:" : "ws:"}//${at.host}${path}${ATTACH_PATH}`,
348
+ daemon: `${at.origin}${path}${DAEMON_PATH}?arch=${this.host.facts.arch}`,
349
+ dial: this.#dial,
350
+ };
333
351
  }
334
352
  /**
335
- * With labels kept in the machine, a machine with no label file is the request's whose name it has (Machine.name, the
336
- * request's own name, never a bare computer- prefix), and a sweep of the name takes it only once it is older than
337
- * #unfiledMs: before that, another instance's create of the request may still be writing its file (provider.md,
338
- * Idempotent create). A machine with no createdAt is never old enough: the vendor's timer ends it.
353
+ * A dial machine's token revoked, then its socket closed, best effort: the token first, so a redial while the revoke
354
+ * is written can't stay attached after the close. A token not revoked is refused past backstopAt.
339
355
  */
340
- #unfiled(machine, name) {
341
- if (!this.#keeps || machine.labels[COMPUTER_LABEL] !== undefined || machine.name !== name)
342
- return undefined;
343
- const age = machine.createdAt instanceof Date ? Date.now() - machine.createdAt.getTime() : Number.NaN;
344
- return age > this.#unfiledMs ? "old" : "young";
345
- }
346
- /** Writes labels to the machine's label file, root's alone, and answers them as the file reads back. */
347
- async #keep(ref, labels, signal) {
348
- const what = `writing ${ref.name}'s labels to ${LABEL_FILE}`;
349
- const json = Buffer.from(JSON.stringify(labels));
350
- const wrote = await runToExit(this.host, ref.id, labelsCommand(json.length), { stdin: [json], ms: this.#timeouts.execMs, ...(signal ? { signal } : {}), what });
351
- if (!wrote.ok)
352
- return wrote;
353
- const read = wrote.value.exitCode === 0 ? labelMapOf(wrote.value.stdout) : undefined;
354
- if (read === undefined)
355
- return this.#fail("refused", `${what} failed (exit ${wrote.value.exitCode}): ${`${wrote.value.stdout} ${wrote.value.stderr}`.trim().slice(0, 300)}`);
356
- filedOf(this.host).set(ref.id, read);
357
- return ok(read);
356
+ async #revoke(name) {
357
+ const dial = this.#dial;
358
+ if (dial === undefined)
359
+ return;
360
+ const { requestMs } = this.#timeouts;
361
+ const said = (why) => this.#onNote?.({ computer: name, note: `its machine token could not be revoked (${why}): it is refused past the machine's backstop either way` });
362
+ let timer;
363
+ try {
364
+ // Bounded by requestMs: a store that never answers must not hold the socket open or the vendor's delete back.
365
+ const late = await Promise.race([dial.tokens.revoke(name).then(() => false), new Promise((done) => (timer = setTimeout(done, requestMs, true)))]);
366
+ if (late)
367
+ said(`the token store did not answer within ${requestMs / 1000} s`);
368
+ }
369
+ catch (error) {
370
+ said(words(error));
371
+ }
372
+ finally {
373
+ clearTimeout(timer);
374
+ dial.hub.revoke(name, `${name} was deleted`);
375
+ }
358
376
  }
359
377
  /** Whether the host takes a spec's user (facts.user): then a computer's daemon runs as the one a spec names. */
360
378
  get #takesUser() {
@@ -370,21 +388,15 @@ export class HostedProvider {
370
388
  * they fit.
371
389
  */
372
390
  #labelsOver(spec) {
373
- const room = this.host.facts.labels ?? {};
391
+ const { count, bytes: max, packed } = this.host.facts.labels ?? {};
374
392
  // Stand-ins as long as create's name and deadlines and as mixed, fixed so a spec's answer never changes (attach and a
375
393
  // retry check the spec again): a packed map deflates them as it does create's, give or take a byte, and create packs
376
- // its own before the host's call (#packedOver).
394
+ // its own before the host's call (#stored).
377
395
  const name = "computer-5f3a9c1e7b2d";
378
396
  const labels = this.#labelsOf(spec, name, "2026-11-16T04:15:29.481Z", "2026-11-17T04:05:29.481Z");
379
- if (room === "machine") {
380
- // The label file is read back whole only up to what a run keeps of its output.
381
- const json = Buffer.byteLength(JSON.stringify(labels));
382
- return json <= OUTPUT_MAX ? undefined : { bytes: true, why: `${a(this.#label)} computer keeps its labels in the machine, at most ${OUTPUT_MAX} bytes as JSON, and this computer's would come to ${json}: ${shorterWords(labels)}` };
383
- }
384
- const { count, bytes: max, packed } = room;
385
397
  if (packed) {
386
- const why = this.#packedOver(labels, name);
387
- return why === undefined ? undefined : { bytes: true, why };
398
+ const fit = this.#stored(labels, name);
399
+ return "problem" in fit ? { bytes: true, why: fit.problem } : undefined;
388
400
  }
389
401
  const keys = Object.keys(labels);
390
402
  if (count !== undefined && keys.length > count) {
@@ -400,11 +412,13 @@ export class HostedProvider {
400
412
  return undefined;
401
413
  return { bytes: true, why: `${a(this.#label)} computer's labels come to at most ${max} bytes, names and values together, and this computer's would come to ${bytes} (${sizes.map(([key, size]) => `${key} ${size}`).join(", ")}): ${shorterWords(labels)}` };
402
414
  }
403
- /** Why labels don't fit packed (facts.labels.packed), in words; undefined when they fit or the host keeps them as they are. */
404
- #packedOver(labels, name) {
405
- const room = this.host.facts.labels;
406
- const fit = room !== "machine" && room?.packed ? packLabels(labels, name, room) : { labels };
407
- return "problem" in fit ? `${a(this.#label)} computer keeps its labels packed, and ${fit.problem}: ${shorterWords(labels)}` : undefined;
415
+ /** The labels as the host is given them: packed where it declares facts.labels.packed, else as they are; or why they don't fit packed, in words. */
416
+ #stored(labels, name) {
417
+ const room = packedRoom(this.host);
418
+ if (room === undefined)
419
+ return { labels };
420
+ const fit = packLabels(labels, name, room);
421
+ return "problem" in fit ? { problem: `${a(this.#label)} computer keeps its labels packed, and ${fit.problem}: ${shorterWords(labels)}` } : fit;
408
422
  }
409
423
  /** A host call bounded by ms, the caller's signal when given. */
410
424
  #call(what, run, ms, signal) {
@@ -418,6 +432,10 @@ export class HostedProvider {
418
432
  * for the first and answers what it does.
419
433
  */
420
434
  async create(spec, context) {
435
+ // Before any call to the vendor, so a machine that could never reach this server is never made or billed.
436
+ const dialed = this.#dialing ? this.#dialed() : undefined;
437
+ if (dialed !== undefined && "problem" in dialed)
438
+ return this.#fail("refused", dialed.problem);
421
439
  const refusals = this.check(spec);
422
440
  return this.#requests.create(spec, context, {
423
441
  refuse: (code, message) => this.#fail(code, message),
@@ -425,9 +443,37 @@ export class HostedProvider {
425
443
  // The checks #again makes of a computer listed already, made here of the spec in flight: what it gives is shared
426
444
  // only with a create that asks the same.
427
445
  userOf: (asked) => this.#userOf(asked),
428
- make: (name) => this.#createOnce(spec, name, context.signal),
446
+ make: (name) => (dialed === undefined ? this.#createOnce(spec, name, context.signal) : this.#inTurn(dialed.dial.hub, name, context.signal, () => this.#createOnce(spec, name, context.signal))),
429
447
  });
430
448
  }
449
+ /**
450
+ * A dial create of one request after any other of it on this server, whichever provider instance makes it. A
451
+ * machine's token and socket go by the request's name, so two machines of one request must never dial at once: the
452
+ * second create finds the first's computer instead (#createOnce). One server process is what dial asks for. A caller
453
+ * that aborts while it waits stops waiting; the turn after it still waits for the create before it.
454
+ */
455
+ async #inTurn(hub, name, signal, make) {
456
+ const turns = DIAL_TURNS.get(hub) ?? new Map();
457
+ DIAL_TURNS.set(hub, turns);
458
+ const before = turns.get(name) ?? Promise.resolve();
459
+ let done = () => { };
460
+ const mine = before.then(() => new Promise((resolve) => (done = resolve)));
461
+ turns.set(name, mine);
462
+ try {
463
+ if ((await untilAborted(before.then(() => true), [signal])) === undefined) {
464
+ return this.#fail("aborted", "create was aborted while another create of this request was in flight");
465
+ }
466
+ return await make();
467
+ }
468
+ finally {
469
+ // Once before has settled: a turn that stopped waiting holds the next one no longer than the create before it.
470
+ void before.then(() => done());
471
+ void mine.then(() => {
472
+ if (turns.get(name) === mine)
473
+ turns.delete(name);
474
+ });
475
+ }
476
+ }
431
477
  /** A request's computer given up on or deleted: its request is refused from now on. */
432
478
  #end(name) {
433
479
  this.#requests.end(name);
@@ -449,12 +495,7 @@ export class HostedProvider {
449
495
  const listed = await foundBy(this.host, "the listing by the request's name", byName(name), this.#timeouts, signal);
450
496
  if (!listed.ok)
451
497
  return listed;
452
- // With labels kept in the machine, a young one of the name with none written yet is this request's still being made
453
- // (#again waits for its labels); an old one never got them, and is deleted.
454
- const found = listed.value.filter((machine) => ours(machine.labels, name) || this.#unfiled(machine, name) === "young");
455
- if (found.length === 0 && listed.value.some((machine) => this.#unfiled(machine, name) === "old")) {
456
- return this.#fail("exists", `${name} was made for this request and its labels were never written: create with a new request id${await this.#deleteNamed(name)}`);
457
- }
498
+ const found = listed.value.filter((machine) => ours(machine.labels, name));
458
499
  if (found.length > 1)
459
500
  return this.#fail("exists", `${found.length} machines carry the name ${name} (${found.map((m) => m.id).join(", ")}): create with a new request id`);
460
501
  if (found.length === 1)
@@ -465,7 +506,6 @@ export class HostedProvider {
465
506
  if (!launched.ok)
466
507
  return launched.error.code === "exists" ? this.#createOnce(spec, name, signal, launched) : launched;
467
508
  const { ref, made } = launched.value;
468
- this.#keepAlive(ref);
469
509
  // From here the machine exists: every step takes the caller's signal, and a failure or an abort deletes it.
470
510
  // Another provider instance's create of this request may have made one too (#converge): the oldest is kept.
471
511
  const first = await this.#converge(name, ref.id, signal);
@@ -539,11 +579,7 @@ export class HostedProvider {
539
579
  const deadline = deadlineOf(machine);
540
580
  if (deadline !== undefined && deadline.getTime() <= Date.now())
541
581
  return this.#fail("exists", endedWords(name));
542
- // With labels kept in the machine: the create making it has not written them yet.
543
- const unwritten = machine.state === "running" && this.#unfiled(machine, name) !== undefined;
544
- if (unwritten)
545
- last = { code: "refused", message: "has no labels written" };
546
- if (machine.state === "running" && !unwritten) {
582
+ if (machine.state === "running") {
547
583
  const differ = this.#labelDiffer(spec, name, machine.labels, "read back");
548
584
  if (differ.length > 0)
549
585
  return this.#fail("exists", otherSpecWords(name, "was made", differ));
@@ -613,9 +649,9 @@ export class HostedProvider {
613
649
  const maxDeadline = new Date(now + this.#maxLifetimeMs).toISOString();
614
650
  const labels = this.#labelsOf(spec, name, deadline, maxDeadline);
615
651
  // check() packed stand-ins; these deflate a byte apart from them, so the host is never given labels that don't fit.
616
- const over = this.#packedOver(labels, name);
617
- if (over !== undefined)
618
- return this.#fail("refused", `labels: ${over}`);
652
+ const stored = this.#stored(labels, name);
653
+ if ("problem" in stored)
654
+ return this.#fail("refused", `labels: ${stored.problem}`);
619
655
  const archil = spec.mount?.kind === "archil";
620
656
  const user = this.#userOf(spec);
621
657
  const commands = hostedCommands({
@@ -633,17 +669,22 @@ export class HostedProvider {
633
669
  rootOnly: this.host.facts.rootOnly ?? [],
634
670
  network: formOf(spec.network),
635
671
  });
672
+ const backstopAt = new Date(now + this.#maxLifetimeMs + BACKSTOP_MARGIN_MS).toISOString();
673
+ const boot = this.#dialing ? await this.#boot(name, backstopAt, { deadline, user, maxDeadline, network: formOf(spec.network) }, sha256) : undefined;
674
+ if (boot !== undefined && !boot.ok)
675
+ return boot;
636
676
  const request = {
637
677
  name,
638
678
  image: spec.image,
639
- labels,
679
+ labels: stored.labels,
640
680
  lifetimeMs,
641
- backstopAt: new Date(now + this.#maxLifetimeMs + BACKSTOP_MARGIN_MS).toISOString(),
681
+ backstopAt,
642
682
  // The machine has egress where its tools' network is open or a list, which init's proxy holds to the public
643
683
  // internet (./network.ts), and where an Archil computer's root reaches Archil. Its tools' none is init's own
644
- // either way, read back by the probe from inside, as the tool user.
645
- egress: archil || throughProxy(spec.network),
646
- ...(this.host.facts.daemon === "pid1" ? { command: commands.entrypoint } : {}),
684
+ // either way, read back by the probe from inside, as the tool user. A dial machine's root reaches this server.
685
+ egress: archil || throughProxy(spec.network) || boot !== undefined,
686
+ ...(this.host.facts.daemon === "pid1" && boot === undefined ? { command: commands.entrypoint } : {}),
687
+ ...(boot === undefined ? {} : { boot: { env: boot.value } }),
647
688
  ...(spec.gpu === undefined ? {} : { gpu: spec.gpu }),
648
689
  ...(spec.cpus === undefined ? {} : { cpus: spec.cpus }),
649
690
  ...(spec.memoryMb === undefined ? {} : { memoryMb: spec.memoryMb }),
@@ -654,6 +695,8 @@ export class HostedProvider {
654
695
  // after this gave up is deleted by its id; one that fails after it, by its name where it may have made one.
655
696
  const created = await hostCall(this.host, `${this.#label}'s create`, (ctx) => this.host.create(request, { timeoutMs: ctx.timeoutMs }), createMs, signal, (made) => made.ok ? this.#kill(made.value.id) : mayHaveMade(made.error.code) ? this.#deleteNamed(name) : undefined);
656
697
  if (!created.ok) {
698
+ // A machine of this create's that lands after this never dials: its token goes with the create.
699
+ await this.#revoke(name);
657
700
  const { code, message } = created.error;
658
701
  if (code === "aborted" || code === "timeout") {
659
702
  this.#end(name);
@@ -668,6 +711,29 @@ export class HostedProvider {
668
711
  this.#requests.made(name);
669
712
  return ok({ ref: { id: created.value.id, name }, made: { deadline, maxDeadline, labels, daemon, sha256, commands, user } });
670
713
  }
714
+ /**
715
+ * A dial machine's environment (MachineRequest.boot.env, spec/computer/attach.md): its own token, minted here to stop
716
+ * at backstopAt, where it dials and fetches the daemon, the daemon's sha256, and init's flags as start gives them.
717
+ */
718
+ async #boot(name, backstopAt, init, sha256) {
719
+ const dialed = this.#dialed();
720
+ if ("problem" in dialed)
721
+ return this.#fail("refused", dialed.problem);
722
+ let token;
723
+ try {
724
+ token = await dialed.dial.tokens.mint(name, { kind: this.#kind, os: "linux", arch: this.host.facts.arch, expiresAt: new Date(backstopAt) });
725
+ }
726
+ catch (error) {
727
+ return this.#fail("refused", `minting ${name}'s machine token failed, so ${this.#label} was not called: ${words(error)}`);
728
+ }
729
+ return ok({
730
+ AGENTRUN_ATTACH_URL: dialed.attach,
731
+ AGENTRUN_ATTACH_TOKEN: token,
732
+ AGENTRUN_DAEMON_URL: dialed.daemon,
733
+ AGENTRUN_DAEMON_SHA256: sha256,
734
+ AGENTRUN_INIT_ARGS: initFlags(init).join(" "),
735
+ });
736
+ }
671
737
  /** Deletes a machine create gives up on, then waits, under the caller's signal, until get answers none for it. */
672
738
  async #abandon(ref, error, signal, mounted = false) {
673
739
  this.#end(ref.name);
@@ -686,94 +752,44 @@ export class HostedProvider {
686
752
  * Every machine carrying a name create gave, deleted and read back gone: for a create that may have made one whose
687
753
  * id never came (mayHaveMade), never after a refusal, where a machine under the name is another's. The
688
754
  * listing shows a new machine a moment after the vendor makes it, so it is read for the name until one shows or
689
- * listedMs passes, as create's own wait reads it. With labels kept in the machine, one with no label file yet is taken
690
- * only once it is old (#unfiled). Best effort, in words.
755
+ * listedMs passes, as create's own wait reads it. Best effort, in words.
691
756
  */
692
757
  async #deleteNamed(name) {
693
758
  const { listedMs, pollMs } = this.#timeouts;
694
759
  const until = Date.now() + listedMs;
695
- let named;
760
+ let found;
696
761
  for (let delay = Math.min(LISTED_POLL_MS, pollMs);; delay = Math.min(delay * 2, pollMs)) {
697
762
  const listed = await foundBy(this.host, "the listing by name", byName(name), this.#timeouts);
698
763
  if (!listed.ok)
699
764
  return `; a machine named ${name} may be left (${listed.error.message}), which ends at its deadline`;
700
- named = listed.value.filter((machine) => ours(machine.labels, name) || this.#unfiled(machine, name) !== undefined);
701
- if (named.length > 0 || Date.now() >= until)
765
+ found = listed.value.filter((machine) => ours(machine.labels, name));
766
+ if (found.length > 0 || Date.now() >= until)
702
767
  break;
703
768
  await pause(Math.min(delay, until - Date.now()));
704
769
  }
705
- const found = named.filter((machine) => this.#unfiled(machine, name) !== "young");
706
- const young = named.length - found.length;
707
- const left = young === 0 ? "" : `; ${young} machine${young === 1 ? "" : "s"} named ${name} with no labels written yet, younger than ${seconds(this.#unfiledMs)}, left: another create of this request may still be making it`;
708
- if (named.length === 0)
709
- return `; no machine named ${name} was listed within ${seconds(listedMs)}, and any it made ends at its deadline`;
710
770
  if (found.length === 0)
711
- return left;
771
+ return `; no machine named ${name} was listed within ${seconds(listedMs)}, and any it made ends at its deadline`;
712
772
  const said = [];
713
773
  for (const machine of found) {
714
774
  const { gone } = await this.#remove({ id: machine.id, name }, undefined);
715
775
  said.push(gone.ok ? `${machine.id} was deleted and read back gone` : `${machine.id} may be left (${gone.error.message}), which ends at its deadline`);
716
776
  }
717
- return `; the machine named ${name} it made: ${said.join("; ")}${left}`;
718
- }
719
- /**
720
- * Calls the host's keepalive on the machine every idleMs / 3 (facts.idleMs), from create or attach until release or
721
- * the delete of a create that gave up, one call at a time: a tick while the host's last call has not settled, even
722
- * past its timeout, is skipped. One that fails is told through onNote and the next tries again; a machine the vendor
723
- * no longer has stops it. The timer holds no process open. An attach calls once at once too (now): a computer a
724
- * restarted server finds may have been quiet for most of its idle window already.
725
- */
726
- #keepAlive(ref, now = false) {
727
- const { idleMs } = this.host.facts;
728
- const keepalive = this.host.keepalive?.bind(this.host);
729
- if (idleMs === undefined || keepalive === undefined || this.#kept.has(ref.id))
730
- return;
731
- let calling = false;
732
- const keep = async () => {
733
- if (calling)
734
- return;
735
- calling = true;
736
- let call = Promise.resolve();
737
- const kept = await this.#call(`the keepalive of ${ref.name}`, (ctx) => (call = keepalive(ref.id, ctx)), this.#timeouts.requestMs);
738
- const free = () => (calling = false);
739
- call.then(free, free);
740
- if (kept.ok || this.#kept.get(ref.id) !== timer)
741
- return;
742
- if (kept.error.code === "not_found")
743
- this.#unkeep(ref.id);
744
- else
745
- this.#onNote?.({ computer: ref.name, note: `${kept.error.message}; the next keepalive tries again in ${seconds(idleMs / 3)}` });
746
- };
747
- const timer = setInterval(keep, idleMs / 3);
748
- timer.unref();
749
- this.#kept.set(ref.id, timer);
750
- if (now)
751
- void keep();
752
- }
753
- #unkeep(id) {
754
- clearInterval(this.#kept.get(id));
755
- this.#kept.delete(id);
777
+ return `; the machine named ${name} it made: ${said.join("; ")}`;
756
778
  }
757
779
  /** The host's delete, never signalled: a delete that cleans up after an abort must outlive it. Not found is done. */
758
780
  async #kill(id) {
759
- this.#unkeep(id);
760
781
  const killed = await this.#call(`the delete of ${id}`, (ctx) => this.host.delete(id, ctx), this.#timeouts.requestMs);
761
782
  if (!killed.ok && killed.error.code !== "not_found")
762
783
  return killed;
763
- filedOf(this.host).delete(id);
764
784
  return ok(undefined);
765
785
  }
766
786
  /** The pause between two reads of a machine that is starting: the next read comes after it, within createMs. */
767
787
  #startPollMs() {
768
788
  return Math.min(START_POLL_MS, this.#timeouts.pollMs * 10);
769
789
  }
770
- /**
771
- * The host's get, bounded by requestMs; a machine the vendor reports as not found is none. Labels kept in the machine
772
- * are read from its file once and then as last read, or now with fresh.
773
- */
774
- async #get(id, signal, fresh = false) {
775
- const read = await readMachine(this.host, id, this.#timeouts.requestMs, signal);
776
- return read.ok ? labelled(this.host, read.value, this.#timeouts.requestMs, signal, fresh) : read;
790
+ /** The host's get, bounded by requestMs; a machine the vendor reports as not found is none. */
791
+ #get(id, signal) {
792
+ return readMachine(this.host, id, this.#timeouts.requestMs, signal);
777
793
  }
778
794
  /** The machine running, read while it starts (within createMs); gone or failed is refused in words. */
779
795
  async #running(ref, signal) {
@@ -820,13 +836,15 @@ export class HostedProvider {
820
836
  const running = await this.#running(ref, signal);
821
837
  if (!running.ok)
822
838
  return running;
823
- // A host that keeps no labels: they go in the machine first, and are read back from there.
824
- const kept = this.#keeps ? await this.#keep(ref, labels, signal) : ok(running.value.labels);
825
- if (!kept.ok)
826
- return kept;
827
- const drift = this.#machineDrift({ ...running.value, labels: kept.value }, labels);
839
+ const drift = this.#machineDrift(running.value, labels);
828
840
  if (drift.length > 0)
829
841
  return this.#fail("refused", `it did not match its spec: ${drift.join("; ")}`);
842
+ const gpu = spec.gpu !== undefined;
843
+ const want = { user, isolation: (gpu ? this.#configuration.gpu?.isolation : undefined) ?? this.host.facts.isolation, gpu };
844
+ // A dial machine's agentrun-dial fetched the daemon, held it to AGENTRUN_DAEMON_SHA256 (this create's daemon's) and
845
+ // started init itself: the drift check holds by that sha, so nothing is installed or read back here.
846
+ if (this.#dialing)
847
+ return this.#start(spec, ref, commands, want, signal);
830
848
  // Before anything of this create's is in the machine: what root runs is root's alone (the Archil helper's sha256,
831
849
  // read at the mount's preflight, is read after this).
832
850
  if ((this.host.facts.rootOnly ?? []).length > 0) {
@@ -858,9 +876,7 @@ export class HostedProvider {
858
876
  // The run's folder, after the daemon is in place (serve runs it) and before init starts: no tool program runs before
859
877
  // it is mounted. A folder mounted for a computer create then gives up on is let go before the delete, never signalled.
860
878
  const started = async () => {
861
- const gpu = spec.gpu !== undefined;
862
- const isolation = (gpu ? this.#configuration.gpu?.isolation : undefined) ?? this.host.facts.isolation;
863
- const done = await this.#start(spec, ref, commands, { user, isolation, gpu }, signal);
879
+ const done = await this.#start(spec, ref, commands, want, signal);
864
880
  return done.ok && installer !== undefined ? ok([installer, ...done.value]) : done;
865
881
  };
866
882
  if (spec.mount?.kind !== "archil")
@@ -885,7 +901,7 @@ export class HostedProvider {
885
901
  /** The rest of #prepare from the daemon's install on: init started, its first connection checked, the listing waited for. */
886
902
  async #start(spec, ref, commands, want, signal) {
887
903
  const closed = [];
888
- if (this.host.facts.daemon === "child") {
904
+ if (this.host.facts.daemon === "child" && !this.#dialing) {
889
905
  // The session buses in /tmp, closed to the computer's user before any program of its runs.
890
906
  const shut = await runToExit(this.host, ref.id, commands.sockets, { ms: this.#timeouts.execMs, ...(signal ? { signal } : {}), what: `closing the session buses in /tmp in ${ref.name}` });
891
907
  if (!shut.ok)
@@ -901,9 +917,9 @@ export class HostedProvider {
901
917
  if (init.value.exitCode !== 0)
902
918
  return this.#fail("refused", `starting the daemon failed (exit ${init.value.exitCode}): ${`${init.value.stdout} ${init.value.stderr}`.trim().slice(0, 500)}`);
903
919
  }
904
- const opened = await this.#openWhenListening(ref, signal);
920
+ const opened = this.#dialing ? await this.#whenDialed(ref, signal) : await this.#openWhenListening(ref, signal);
905
921
  if (!opened.ok) {
906
- if (opened.error.code === "aborted")
922
+ if (opened.error.code === "aborted" || this.#dialing)
907
923
  return opened;
908
924
  const why = await this.#initWords(ref);
909
925
  return this.#fail(opened.error.code, `the daemon did not answer: ${opened.error.message}${why ? `; init wrote: ${why}` : ""}`);
@@ -1003,6 +1019,14 @@ export class HostedProvider {
1003
1019
  /** One stdio bridge into the machine, after hello, unchecked; its client says so once the machine is deleted. */
1004
1020
  async #open(ref, signal, helloMs = this.#timeouts.helloMs) {
1005
1021
  const { requestMs } = this.#timeouts;
1022
+ if (this.#dialing) {
1023
+ // A dial machine's connection is over the socket it dialed, which the hub holds under its name: a drop fails the
1024
+ // calls in flight gone, and the first call after a redial is refused gone (attach.ts, AttachHub.connection).
1025
+ const connection = this.#dial?.hub.connection(ref.name);
1026
+ if (connection === undefined)
1027
+ return this.#fail("gone", `${ref.name} is not attached to this server now: its computerd dials back on its own, so try again shortly`);
1028
+ return ok(deletedSaid(this.host, ref, this.#label, requestMs, connection));
1029
+ }
1006
1030
  const opened = await openBridge(this.host, ref.id, { argv: hostedCommands().stdio, name: ref.name, version: VERSION, requestMs, helloMs, ...(signal ? { signal } : {}) });
1007
1031
  return opened.ok ? ok(deletedSaid(this.host, ref, this.#label, requestMs, opened.value)) : opened;
1008
1032
  }
@@ -1016,6 +1040,28 @@ export class HostedProvider {
1016
1040
  await pause(LISTEN_RETRY_MS, signal);
1017
1041
  }
1018
1042
  }
1043
+ /**
1044
+ * A dial machine's first connection: its socket waited for in the hub, from its start, within createMs. One that never
1045
+ * dials (a server it cannot reach, a daemon whose sha256 it refused, a hello the hub refused) fails timeout, naming the
1046
+ * address it was given; create then deletes it.
1047
+ */
1048
+ async #whenDialed(ref, signal) {
1049
+ const { createMs } = this.#timeouts;
1050
+ const until = Date.now() + createMs;
1051
+ for (;;) {
1052
+ const opened = await this.#open(ref, signal);
1053
+ if (opened.ok)
1054
+ return opened;
1055
+ if (Date.now() + this.#startPollMs() >= until) {
1056
+ const dialed = this.#dialed();
1057
+ const to = "problem" in dialed ? "this server" : dialed.attach;
1058
+ return this.#fail("timeout", `${ref.name} did not dial ${to} within ${seconds(createMs)}: the machine must reach that address, and run agentrun-dial (the box image's entrypoint while AGENTRUN_ATTACH_URL is set)`);
1059
+ }
1060
+ await pause(this.#startPollMs(), signal);
1061
+ if (signal?.aborted)
1062
+ return this.#fail("aborted", `create was aborted while it waited for ${ref.name} to dial`);
1063
+ }
1064
+ }
1019
1065
  /**
1020
1066
  * Its tools' network as they meet it, against the one create made: the probe, as the computer's own user. Under none,
1021
1067
  * no target answers. Under open or a list, still none answers directly (their own loopback alone), init's relay
@@ -1099,8 +1145,8 @@ export class HostedProvider {
1099
1145
  }
1100
1146
  }
1101
1147
  /** This provider's machine for ref, as the vendor reads it, or why not. */
1102
- async #own(ref, signal, fresh = false) {
1103
- const found = await this.#get(ref.id, signal, fresh);
1148
+ async #own(ref, signal) {
1149
+ const found = await this.#get(ref.id, signal);
1104
1150
  if (!found.ok)
1105
1151
  return found;
1106
1152
  if (found.value === undefined)
@@ -1228,7 +1274,6 @@ export class HostedProvider {
1228
1274
  found.push(`mount: ${name} is ${machine.state}, so its mount cannot be read back from inside`);
1229
1275
  if (found.length > 0)
1230
1276
  return this.#fail("refused", `the computer ${name} does not match this provider, so attach refuses it and it is left as it is: ${found.join("; ")}`);
1231
- this.#keepAlive(ref, true);
1232
1277
  return ok({
1233
1278
  ...ref,
1234
1279
  spec: {
@@ -1250,8 +1295,7 @@ export class HostedProvider {
1250
1295
  */
1251
1296
  async testConnection({ signal } = {}) {
1252
1297
  const listed = await listedBy(this.host, "the listing", { [COMPUTER_LABEL]: "1" }, this.#timeouts.listMs, signal);
1253
- // A host that keeps no labels lists them by their name alone.
1254
- const counted = (machine) => (this.#keeps ? NAME.test(machine.name ?? "") : ours(machine.labels)) && alive(machine.state);
1298
+ const counted = (machine) => ours(machine.labels) && alive(machine.state);
1255
1299
  return countTested(this.#label, listed.ok ? ok({ count: listed.value.filter(counted).length }) : listed);
1256
1300
  }
1257
1301
  /**
@@ -1346,12 +1390,12 @@ export class HostedProvider {
1346
1390
  }
1347
1391
  /**
1348
1392
  * Moves the deadline to now + ttlMs, refusing one earlier than it is (before any vendor call), never past create's time
1349
- * plus the cap (init's maximum): the host's extend first (its timer or its deadline label), and the label file where the
1350
- * labels are kept in the machine, then the end it reads back (get, deadlineOf), then init's own deadline, to that end. The deadline returned is the one init took.
1393
+ * plus the cap (init's maximum): the host's extend first (its timer or its deadline label), then the end it reads back
1394
+ * (get, deadlineOf), then init's own deadline, to that end. The deadline returned is the one init took. A host that
1395
+ * keeps labels in the machine has no extend (the constructor).
1351
1396
  */
1352
1397
  async #extend(ref, ttlMs, signal) {
1353
- // Labels kept in the machine are read now: another instance may have moved the deadline.
1354
- const found = await this.#own(ref, signal, true);
1398
+ const found = await this.#own(ref, signal);
1355
1399
  if (!found.ok)
1356
1400
  return found;
1357
1401
  const machine = found.value;
@@ -1377,11 +1421,6 @@ export class HostedProvider {
1377
1421
  const moved = await this.#call(`${this.#label}'s end of ${ref.name}`, (ctx) => extend(ref.id, new Date(target), ctx), this.#timeouts.requestMs, signal);
1378
1422
  if (!moved.ok)
1379
1423
  return moved.error.code === "limit" ? moved : this.#fail(moved.error.code, `${this.#label} did not move ${ref.name}'s end, so nothing did: ${moved.error.message}`);
1380
- if (this.#keeps) {
1381
- const kept = await this.#keep(ref, { ...machine.labels, [DEADLINE_LABEL]: new Date(target).toISOString() }, signal);
1382
- if (!kept.ok)
1383
- return this.#fail(kept.error.code, `${ref.name}'s deadline label did not move, nor did init's deadline: ${kept.error.message}`);
1384
- }
1385
1424
  const after = await this.#get(ref.id, signal);
1386
1425
  const end = after.ok && after.value !== undefined ? deadlineOf(after.value) : undefined;
1387
1426
  if (end === undefined) {
@@ -1428,7 +1467,8 @@ export class HostedProvider {
1428
1467
  if (!found.ok)
1429
1468
  return found;
1430
1469
  if (found.value === undefined) {
1431
- this.#unkeep(ref.id);
1470
+ // Gone already (deleted by hand, or the vendor's timer): its token and socket still go.
1471
+ await this.#revoke(ref.name);
1432
1472
  return ok(undefined);
1433
1473
  }
1434
1474
  if (!ours(found.value.labels, ref.name))
@@ -1448,6 +1488,7 @@ export class HostedProvider {
1448
1488
  */
1449
1489
  async #remove(ref, machine, signal) {
1450
1490
  const letGo = await this.#letGoOf(ref, machine, signal);
1491
+ await this.#revoke(ref.name);
1451
1492
  const killed = await this.#kill(ref.id);
1452
1493
  return { letGo, gone: killed.ok ? await this.#settle(ref, signal) : killed };
1453
1494
  }
@@ -1473,92 +1514,54 @@ export class HostedProvider {
1473
1514
  }
1474
1515
  /** The labels a listing by one computer's name asks for. */
1475
1516
  const byName = (name) => ({ [COMPUTER_LABEL]: "1", [NAME_LABEL]: name });
1517
+ /** The room of a host that keeps its labels packed (facts.labels.packed), or undefined. */
1518
+ function packedRoom(host) {
1519
+ const room = host.facts.labels;
1520
+ return room?.packed ? room : undefined;
1521
+ }
1522
+ /** A machine as the host read it, with a packed host's labels unpacked: none where it holds no packed map (not the adapter's). */
1523
+ const unpacked = (host, machine) => (packedRoom(host) === undefined ? machine : { ...machine, labels: unpackLabels(machine.labels) ?? {} });
1476
1524
  /**
1477
1525
  * The host's listing by labels, bounded by ms: only the machines that carry every one of them, since a vendor's listing
1478
- * may answer more (MachineHost.list). A host that keeps labels in the machine lists none: its machines of another name
1479
- * are left out, and the rest kept for foundBy to read.
1526
+ * may answer more (MachineHost.list). A packed host is asked for PACKED_NAME alone, the name's where one is asked, and
1527
+ * its machines' labels unpacked.
1480
1528
  */
1481
1529
  export async function listedBy(host, what, labels, ms, signal) {
1482
- const listed = await hostCall(host, what, (ctx) => host.list(labels, ctx), ms, signal);
1483
1530
  const name = labels[NAME_LABEL];
1484
- const keeps = (machine) => (host.facts.labels === "machine" ? name === undefined || machine.name === undefined || machine.name === name : carries(machine, labels));
1485
- return listed.ok ? ok(listed.value.filter(keeps)) : listed;
1486
- }
1487
- /** With labels kept in the machine: each machine's label map as its file was last read, by host and machine id. */
1488
- const filed = new WeakMap();
1489
- function filedOf(host) {
1490
- let known = filed.get(host);
1491
- if (known === undefined)
1492
- filed.set(host, (known = new Map()));
1493
- return known;
1494
- }
1495
- /** A label file's JSON as a label map, or undefined where it is not one. */
1496
- function labelMapOf(text) {
1497
- try {
1498
- const map = JSON.parse(text);
1499
- return typeof map === "object" && map !== null && !Array.isArray(map) && Object.values(map).every((value) => typeof value === "string") ? map : undefined;
1500
- }
1501
- catch {
1502
- return undefined;
1503
- }
1504
- }
1505
- /**
1506
- * A machine of a host that keeps labels in the machine, with the labels its file holds: read through exec while it runs
1507
- * (fresh), else as last read, or none. No file (exit 3) is none; a read that fails otherwise is an error, never none, so
1508
- * a listing never leaves out a computer it could not read. Another host's machine is as read.
1509
- */
1510
- async function labelled(host, machine, ms, signal, fresh) {
1511
- if (host.facts.labels !== "machine" || machine === undefined)
1512
- return ok(machine);
1513
- const known = filedOf(host);
1514
- const held = known.get(machine.id);
1515
- if (machine.state !== "running" || (held !== undefined && !fresh))
1516
- return ok({ ...machine, labels: { ...held } });
1517
- const what = `reading the labels in ${machine.id}`;
1518
- const read = await runToExit(host, machine.id, labelsCommand(), { ms, ...(signal ? { signal } : {}), what });
1519
- // Gone since the vendor's read: as a read that finds none.
1520
- if (!read.ok)
1521
- return read.error.code === "not_found" ? ok(undefined) : read;
1522
- if (read.value.exitCode === 3)
1523
- return ok({ ...machine, labels: {} });
1524
- const labels = read.value.exitCode === 0 ? labelMapOf(read.value.stdout) : undefined;
1525
- if (labels === undefined)
1526
- return failFor(host.descriptor.id)("vendor", `${what} failed (exit ${read.value.exitCode}): ${`${read.value.stdout} ${read.value.stderr}`.trim().slice(0, 300)}`);
1527
- known.set(machine.id, labels);
1528
- return ok({ ...machine, labels: { ...labels } });
1531
+ const asked = packedRoom(host) === undefined ? labels : name === undefined ? {} : { [PACKED_NAME]: name };
1532
+ const listed = await hostCall(host, what, (ctx) => host.list(asked, ctx), ms, signal);
1533
+ return listed.ok ? ok(listed.value.map((machine) => unpacked(host, machine)).filter((machine) => carries(machine, labels))) : listed;
1529
1534
  }
1530
1535
  /** Whether a machine carries every one of these labels. */
1531
1536
  const carries = (machine, labels) => Object.entries(labels).every(([key, value]) => machine.labels?.[key] === value);
1532
1537
  /**
1533
1538
  * The listing finds, get answers (MachineHost.list): the machines the host's listing by labels names, each read now by
1534
- * readMachine, within requestMs, and its label file where the host keeps labels in the machine. One the vendor no longer
1535
- * has (not found) is dropped, and so is one whose get carries not every label, but a machine of the name asked for whose
1536
- * labels are not written yet. A read that fails otherwise fails the whole.
1539
+ * readMachine, within requestMs. One the vendor no longer has (not found) is dropped, and so is one whose get carries
1540
+ * not every label. A get that fails fails the whole listing.
1537
1541
  */
1538
1542
  export async function foundBy(host, what, labels, { listMs, requestMs }, signal) {
1539
1543
  const listed = await listedBy(host, what, labels, listMs, signal);
1540
1544
  if (!listed.ok)
1541
1545
  return listed;
1542
- const reads = await Promise.all(listed.value.map(async ({ id }) => {
1543
- const read = await readMachine(host, id, requestMs, signal);
1544
- return read.ok ? labelled(host, read.value, requestMs, signal, true) : read;
1545
- }));
1546
- // With labels in the machine, one of the name asked for with none written yet is kept too, for the caller to judge.
1547
- const name = labels[NAME_LABEL];
1548
- const unfiled = (machine) => host.facts.labels === "machine" && name !== undefined && machine.name === name && machine.labels[COMPUTER_LABEL] === undefined;
1546
+ const reads = await Promise.all(listed.value.map(({ id }) => readMachine(host, id, requestMs, signal)));
1549
1547
  const found = [];
1550
1548
  for (const read of reads) {
1551
1549
  if (!read.ok)
1552
1550
  return read;
1553
- if (read.value !== undefined && (carries(read.value, labels) || unfiled(read.value)))
1551
+ if (read.value !== undefined && carries(read.value, labels))
1554
1552
  found.push(read.value);
1555
1553
  }
1556
1554
  return ok(found);
1557
1555
  }
1558
- /** The host's get of one machine, bounded by ms: a machine the vendor reports as not found is none, never an error. */
1556
+ /**
1557
+ * The host's get of one machine, bounded by ms, a packed host's labels unpacked: a machine the vendor reports as not
1558
+ * found is none, never an error.
1559
+ */
1559
1560
  async function readMachine(host, id, ms, signal) {
1560
1561
  const read = await hostCall(host, `the read of ${id}`, (ctx) => host.get(id, ctx), ms, signal);
1561
- return !read.ok && read.error.code === "not_found" ? ok(undefined) : read;
1562
+ if (!read.ok)
1563
+ return read.error.code === "not_found" ? ok(undefined) : read;
1564
+ return ok(read.value === undefined ? undefined : unpacked(host, read.value));
1562
1565
  }
1563
1566
  /** What reading answers, or undefined once a signal aborts first: a caller that stopped waiting never waits on a read. */
1564
1567
  function untilAborted(reading, signals) {