@parcha/agentrun-computer 0.1.0-beta.37 → 0.1.0-beta.38

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 (93) hide show
  1. package/README.md +259 -203
  2. package/box/Dockerfile +18 -1
  3. package/box/README.md +13 -0
  4. package/box/build-agent37.mjs +8 -27
  5. package/box/build-daytona.py +2 -2
  6. package/box/build-e2b.mjs +41 -18
  7. package/box/recipe.mjs +43 -0
  8. package/dist/agent37-ssh.d.ts +89 -0
  9. package/dist/agent37-ssh.js +445 -0
  10. package/dist/agent37.d.ts +2 -63
  11. package/dist/agent37.js +104 -461
  12. package/dist/browserbase.d.ts +0 -6
  13. package/dist/browserbase.js +1 -5
  14. package/dist/client.d.ts +12 -3
  15. package/dist/client.js +39 -4
  16. package/dist/computerd-linux-amd64 +0 -0
  17. package/dist/computerd-linux-arm64 +0 -0
  18. package/dist/computerd.json +4 -0
  19. package/dist/conformance/cases/apps.d.ts +6 -0
  20. package/dist/conformance/cases/apps.js +18 -5
  21. package/dist/conformance/cases/isolation.d.ts +7 -5
  22. package/dist/conformance/cases/isolation.js +44 -14
  23. package/dist/conformance/cases/mount.js +1 -1
  24. package/dist/conformance/cli.js +66 -6
  25. package/dist/conformance/daytona.d.ts +9 -20
  26. package/dist/conformance/daytona.js +12 -21
  27. package/dist/conformance/exec-stream.d.ts +45 -0
  28. package/dist/conformance/exec-stream.js +486 -0
  29. package/dist/conformance/sweep.js +8 -8
  30. package/dist/conformance/types.d.ts +2 -2
  31. package/dist/create-requests.d.ts +1 -1
  32. package/dist/daytona.d.ts +20 -131
  33. package/dist/daytona.js +405 -1450
  34. package/dist/descriptor.d.ts +6 -1
  35. package/dist/descriptor.js +7 -0
  36. package/dist/descriptors/agent37.d.ts +1 -1
  37. package/dist/descriptors/agent37.js +1 -1
  38. package/dist/descriptors/daytona.d.ts +6 -5
  39. package/dist/descriptors/daytona.js +9 -5
  40. package/dist/descriptors/index.d.ts +4 -5
  41. package/dist/descriptors/shared.d.ts +1 -1
  42. package/dist/descriptors/shared.js +2 -2
  43. package/dist/desktop.d.ts +18 -4
  44. package/dist/desktop.js +89 -9
  45. package/dist/docker.d.ts +0 -6
  46. package/dist/docker.js +1 -5
  47. package/dist/drift.js +4 -4
  48. package/dist/e2b.d.ts +10 -128
  49. package/dist/e2b.js +130 -233
  50. package/dist/host.d.ts +106 -87
  51. package/dist/host.js +8 -1
  52. package/dist/hosted/process.d.ts +22 -8
  53. package/dist/hosted/process.js +75 -44
  54. package/dist/hosted/provider.d.ts +35 -21
  55. package/dist/hosted/provider.js +312 -261
  56. package/dist/hosted/rest.d.ts +66 -0
  57. package/dist/hosted/rest.js +121 -0
  58. package/dist/hosted/scripts.d.ts +8 -2
  59. package/dist/hosted/scripts.js +27 -2
  60. package/dist/hosted/values.d.ts +5 -0
  61. package/dist/hosted/values.js +8 -0
  62. package/dist/index.d.ts +1 -1
  63. package/dist/index.js +1 -1
  64. package/dist/kernel.d.ts +0 -6
  65. package/dist/kernel.js +1 -5
  66. package/dist/kinds.d.ts +3 -1
  67. package/dist/local-chrome.d.ts +0 -6
  68. package/dist/local-chrome.js +1 -5
  69. package/dist/modal.d.ts +7 -84
  70. package/dist/modal.js +50 -174
  71. package/dist/mount-archil.d.ts +8 -4
  72. package/dist/mount-archil.js +22 -11
  73. package/dist/mount.d.ts +10 -4
  74. package/dist/mount.js +8 -4
  75. package/dist/orgo.d.ts +0 -9
  76. package/dist/orgo.js +2 -9
  77. package/dist/phone-harness.d.ts +0 -6
  78. package/dist/phone-harness.js +0 -4
  79. package/dist/protocol.d.ts +4 -1
  80. package/dist/protocol.js +1 -0
  81. package/dist/provider.d.ts +2 -2
  82. package/dist/providers.d.ts +11 -12
  83. package/dist/screen-watch.js +34 -6
  84. package/dist/surface/api.d.ts +14 -2
  85. package/dist/surface/core.d.ts +16 -3
  86. package/dist/surface/core.js +95 -13
  87. package/dist/surface/outline.d.ts +2 -0
  88. package/dist/surface/outline.js +2 -1
  89. package/dist/surface/script.js +2 -0
  90. package/dist/ui-engine.js +19 -3
  91. package/package.json +2 -3
  92. package/dist/conformance/daytona-sweep.d.ts +0 -18
  93. package/dist/conformance/daytona-sweep.js +0 -126
@@ -1,4 +1,4 @@
1
- // The shared machine-host adapter: hostedProvider(host, options) is a whole ComputerProvider over a vendor's
1
+ // The shared machine-host adapter: new HostedProvider(host, options) is a whole ComputerProvider over a vendor's
2
2
  // MachineHost (../host.ts). The vendor answers create, get, list, delete and exec about its own machines; everything a
3
3
  // computer is beyond that is here, once, for every vendor: the spec's check, the computer's name from its create's
4
4
  // request id (one create per request: a retry finds the first), the daemon's upload, install and sha256 read-back,
@@ -12,19 +12,20 @@ import { resolve } from "node:path";
12
12
  import { fileURLToPath } from "node:url";
13
13
  import { CreateRequests, endedWords, otherSpecWords, readBackDiffer } from "../create-requests.js";
14
14
  import { DESKTOP_GROUPS, desktopOf, startDisplay } from "../desktop.js";
15
- import { COMPUTER_LABEL, DAEMON_IN_COMPUTER, DEADLINE_LABEL, helloDrift, probeNetworkDrift, probeNotes, probeReportOf, WORK } from "../drift.js";
15
+ import { COMPUTER_LABEL, DAEMON_IN_COMPUTER, DEADLINE_LABEL, helloDrift, probeNetworkDrift, probeNotes, probeReportOf, show, WORK } from "../drift.js";
16
16
  import { OWN_NETWORK_ONLY, readOwnNetwork, TOOL_USER } from "../isolation.js";
17
17
  import { releaseOlder } from "../janitor.js";
18
18
  import { RUN_LABEL } from "../labels.js";
19
19
  import { checkMount, readBackOf } from "../mount.js";
20
20
  import { ARCHIL_MOUNT_LABEL, ARCHIL_TOOL_UID, archilEgressOf, archilLabels, archilMount, archilRefusals, archilRelease, claimEpoch, mountDrift, readArchilMount, recordedArchil as recordedArchilOf, recordedMount, syncingClient, } from "../mount-archil.js";
21
21
  import { checkGpu, checkTenure, runLifetimeMs, } from "../provider.js";
22
- import { ok } from "../result.js";
22
+ import { failFor, ok } from "../result.js";
23
23
  import { daemonWatch } from "../screen-watch.js";
24
24
  import { countTested } from "../test-connection.js";
25
25
  import { waitUntil } from "../wait.js";
26
- import { bounded, CALL_SLACK_MS, failOf, hostCall, openBridge, pause, race, rootOf, runToExit, seconds, uploadThroughExec, words } from "./process.js";
27
- import { ARCHIL_GATE, daemonDrift, hostedCommands, installerOf } from "./scripts.js";
26
+ import { bounded, CALL_SLACK_MS, hostCall, openBridge, pause, rootOf, runToExit, seconds, uploadThroughExec } from "./process.js";
27
+ import { isWhole } from "./values.js";
28
+ import { ARCHIL_GATE, closedSocketsOf, daemonDrift, hostedCommands, installerOf } from "./scripts.js";
28
29
  const VERSION = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
29
30
  export const NAME_LABEL = `${COMPUTER_LABEL}.name`;
30
31
  /** The image create was asked for: a vendor may report another name for it (a template's id). */
@@ -51,6 +52,8 @@ const DEFAULTS = {
51
52
  listedStableMs: 1_000,
52
53
  mountMs: 120_000,
53
54
  };
55
+ /** The adapter's timeouts, the caller's over its defaults: what a host reads for its own requestMs or pollMs. */
56
+ export const timeoutsOf = (timeouts = {}) => ({ ...DEFAULTS, ...timeouts });
54
57
  /** The user an Archil computer's tools run as: the image's agentrun-tool, with no sudo and no capability. */
55
58
  const ARCHIL_USER = `${ARCHIL_TOOL_UID}:${ARCHIL_TOOL_UID}`;
56
59
  const RELEASE_POLL_MAX_MS = 5_000;
@@ -72,29 +75,18 @@ const DEFAULT_PROBE_TARGETS = ["1.1.1.1:443", "8.8.8.8:443", "[2606:4700:4700::1
72
75
  /** A probe target: host:port, over TCP, or host:port/udp, a DNS query over UDP. */
73
76
  const TARGET = /^(?:\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9.-]+):[0-9]{1,5}(?:\/udp)?$/;
74
77
  const SPEC_FIELDS = new Set(["image", "lifetimeMs", "network", "labels", "mount", "gpu", "owner"]);
75
- const isWhole = (value) => typeof value === "number" && Number.isSafeInteger(value);
76
- const show = (value) => (value === undefined ? "nothing" : JSON.stringify(value));
77
78
  const policyWords = (policy) => (typeof policy === "string" ? policy : "other" in policy ? policy.other : JSON.stringify(policy));
78
- const alive = (state) => state === "running" || state === "stopped" || state === "starting";
79
+ const alive = (state) => state !== "gone";
79
80
  /** An ISO time a label holds, or undefined when it is missing or not the ISO time create writes. */
80
- function isoOf(written) {
81
+ export function isoOf(written) {
81
82
  const at = written === undefined ? Number.NaN : Date.parse(written);
82
83
  return Number.isNaN(at) || new Date(at).toISOString() !== written ? undefined : new Date(at);
83
84
  }
84
85
  /**
85
- * When a machine ends: the deadline create wrote; or, once an extend moved the vendor's own timer past where create set
86
- * it (the vendor keeps no label change), that end, up to the most the computer may live, which is what init was given.
86
+ * When a machine ends: its deadline label, as the vendor reads it back. A vendor that keeps no label change reads it
87
+ * as the end its timer moved to (E2B's get), so a restarted provider reads an extend all the same.
87
88
  */
88
- export function deadlineOf(machine) {
89
- const written = isoOf(machine.labels[DEADLINE_LABEL]);
90
- if (written === undefined)
91
- return undefined;
92
- const end = machine.endsAt instanceof Date ? machine.endsAt.getTime() : Number.NaN;
93
- if (machine.timerMoved !== true || Number.isNaN(end))
94
- return written;
95
- const most = isoOf(machine.labels[MAX_LABEL]);
96
- return new Date(most === undefined ? end : Math.min(end, most.getTime()));
97
- }
89
+ export const deadlineOf = (machine) => isoOf(machine.labels[DEADLINE_LABEL]);
98
90
  /** Only a machine this adapter made counts: its label, a name of its making, and the name asked for when one is. */
99
91
  export const ours = (labels, name) => labels?.[COMPUTER_LABEL] === "1" && NAME.test(labels[NAME_LABEL] ?? "") && (name === undefined || labels[NAME_LABEL] === name);
100
92
  /** The Archil mount a computer's agentrun.mount label records, or undefined when it has none. */
@@ -125,7 +117,7 @@ function specUserOf(value) {
125
117
  }
126
118
  /** The caller's labels of a machine: every one but the adapter's own namespace and the Archil mount's. */
127
119
  const callerLabels = (labels) => Object.fromEntries(Object.entries(labels).filter(([key]) => key !== COMPUTER_LABEL && !key.startsWith(`${COMPUTER_LABEL}.`) && key !== ARCHIL_MOUNT_LABEL));
128
- /** hostedProvider's provider: a ComputerProvider whose vendor is host. */
120
+ /** The shared adapter's provider: a ComputerProvider whose vendor is host. */
129
121
  export class HostedProvider {
130
122
  id;
131
123
  version = VERSION;
@@ -150,11 +142,12 @@ export class HostedProvider {
150
142
  /** Each computer's last extend, by machine id, while one runs: the next waits for it. */
151
143
  #extending = new Map();
152
144
  constructor(host, options) {
153
- const { label, 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;
154
- this.id = host.id;
145
+ 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;
146
+ const { id, label } = host.descriptor;
147
+ this.id = id;
155
148
  this.host = host;
156
149
  this.#label = label;
157
- this.#fail = failOf(host);
150
+ this.#fail = failFor(id);
158
151
  this.#onNote = onNote;
159
152
  this.#archilEgress = archilEgress === undefined || archilEgress === "" ? undefined : archilEgressOf(archilEgress);
160
153
  if (kind !== "desktop" && kind !== "linux")
@@ -168,7 +161,7 @@ export class HostedProvider {
168
161
  // The numbers, not the text: "00" is root as much as "0" is.
169
162
  if (Number(user[1]) === 0 || Number(user[2]) === 0)
170
163
  throw new Error(`the daemon user ${daemonUser} is root or in root's group; ${a(label)} computer's daemon runs as neither`);
171
- const merged = { ...DEFAULTS, ...timeouts };
164
+ const merged = timeoutsOf(timeouts);
172
165
  // AbortSignal.timeout and Node's timers take whole ms up to 2^31 - 1 (a fraction throws, a longer one fires at
173
166
  // once), and a call's race adds CALL_SLACK_MS to its bound: refused here, before any machine exists. The listing's
174
167
  // stability window alone may be 0: two consecutive polls, with no time between them asked for.
@@ -187,27 +180,26 @@ export class HostedProvider {
187
180
  [this.#uid, this.#gid] = [String(Number(user[1])), String(Number(user[2]))];
188
181
  this.#timeouts = merged;
189
182
  this.#probeTargets = [...probeTargets];
190
- // Extend only where the deadline can follow it: the vendor's timer moved, or the janitor's label.
191
- const { lifetime } = host.facts;
192
- if ((lifetime === "vendor" && host.setTimer) || (lifetime === "janitor" && host.setLabels))
183
+ // Extend only where the end can follow it: the host moves its timer or its deadline label.
184
+ if (host.extend)
193
185
  this.extend = (ref, ttlMs, context) => this.#extendSerial(ref, ttlMs, context?.signal);
194
186
  }
195
187
  /** The computer's facts, from the host's and the adapter's options alone. */
196
188
  capabilities() {
197
- const { facts } = this.host;
189
+ const { facts, descriptor } = this.host;
198
190
  return {
199
191
  kind: this.#kind,
200
192
  lifetime: facts.lifetime,
201
- network: [...facts.network],
202
- networkReadBack: facts.networkReadBack,
193
+ network: [...descriptor.network],
194
+ // The probe from inside is the network's truth: no vendor's read of it is taken.
195
+ networkReadBack: false,
203
196
  isolation: facts.isolation,
204
197
  os: "linux",
205
198
  daemon: facts.daemon,
206
199
  groups: ["exec", "files", "processes", ...(this.#desktop ? DESKTOP_GROUPS : [])],
207
200
  maxLifetimeMs: this.#maxLifetimeMs,
208
- release: [...facts.release],
209
- ...(facts.stopDeletes === undefined ? {} : { stopDeletes: facts.stopDeletes }),
210
- ...(facts.mounts === undefined ? {} : { mount: [...facts.mounts] }),
201
+ release: ["delete"],
202
+ mount: [...descriptor.mounts],
211
203
  vendorAgentPorts: [...facts.vendorAgentPorts],
212
204
  ...(facts.gpu === undefined ? {} : { gpu: structuredClone(facts.gpu) }),
213
205
  ...(facts.user === undefined ? {} : { user: [...facts.user] }),
@@ -220,9 +212,10 @@ export class HostedProvider {
220
212
  const { image, network, labels, mount } = given;
221
213
  const capabilities = this.capabilities();
222
214
  const label = this.#label;
223
- refusals.push(...checkMount(mount, capabilities.mount ?? []), ...archilRefusals(given));
215
+ // An Archil mount's own rules hold only where the provider takes one; elsewhere checkMount's refusal says why alone.
216
+ const archil = mount?.kind === "archil" && (capabilities.mount ?? []).includes("archil");
217
+ refusals.push(...checkMount(mount, capabilities.mount ?? [], this.host.descriptor.unmounted), ...(archil ? archilRefusals(given) : []));
224
218
  const daemonUser = `${this.#uid}:${this.#gid}`;
225
- const archil = mount?.kind === "archil";
226
219
  const asked = this.#takesUser() ? given.user : undefined;
227
220
  if (asked !== undefined) {
228
221
  const user = specUserOf(asked);
@@ -245,11 +238,14 @@ export class HostedProvider {
245
238
  refuse("network", OWN_NETWORK_ONLY);
246
239
  else if (network !== "none")
247
240
  refuse("network", 'network is required: "none"');
248
- if (labels !== undefined) {
249
- const entries = typeof labels === "object" && labels !== null && !Array.isArray(labels) ? Object.entries(labels) : undefined;
250
- const bad = entries === undefined ? "labels must map names to strings" : (entries.map(([key, value]) => labelProblem(key, value, this.host.facts.labelRules?.key)).find(Boolean) ?? this.#labelCount(entries.length, mount));
251
- if (bad)
252
- refuse("labels", bad);
241
+ const entries = labels === undefined ? [] : typeof labels === "object" && labels !== null && !Array.isArray(labels) ? Object.entries(labels) : undefined;
242
+ const bad = entries === undefined ? "labels must map names to strings" : (entries.map(([key, value]) => labelProblem(key, value)).find(Boolean) ?? this.#labelCount(entries.length, given));
243
+ if (bad)
244
+ refuse("labels", bad);
245
+ else if (typeof image === "string" && (!archil || ["disk", "region", "folder"].every((key) => typeof mount[key] === "string"))) {
246
+ const over = this.#labelBytes(given);
247
+ if (over)
248
+ refuse(archil ? "mount" : "labels", over);
253
249
  }
254
250
  refusals.push(...checkGpu(given.gpu, capabilities, mount));
255
251
  const taken = new Set(this.host.facts.specFields ?? []);
@@ -266,7 +262,7 @@ export class HostedProvider {
266
262
  refuse(field, `${a(label)} computer does not support ${field}`);
267
263
  }
268
264
  if (this.host.check)
269
- refusals.push(...this.host.check(spec));
265
+ refusals.push(...this.host.check(given));
270
266
  return refusals;
271
267
  }
272
268
  /** Whether the host takes a spec's user (facts.specFields): then a computer's daemon runs as the one a spec names. */
@@ -277,14 +273,32 @@ export class HostedProvider {
277
273
  #userOf(spec) {
278
274
  return (this.#takesUser() ? specUserOf(spec.user) : undefined) ?? `${this.#uid}:${this.#gid}`;
279
275
  }
276
+ /** The labels create would give a spec's computer, the adapter's own at their longest (#labelsOf). */
277
+ #longestLabels(spec, caller) {
278
+ const at = new Date(0).toISOString();
279
+ return this.#labelsOf({ ...spec, labels: caller ? spec.labels : {} }, "computer-000000000000", at, at);
280
+ }
280
281
  /** Why a spec's labels, with the adapter's own, are more than the vendor takes; undefined when they fit. */
281
- #labelCount(count, mount) {
282
+ #labelCount(count, spec) {
282
283
  const max = this.host.facts.labelRules?.max;
283
284
  if (max === undefined)
284
285
  return undefined;
285
- const own = 5 + (mount?.kind === "archil" ? Object.keys(archilLabels({ kind: "archil", disk: "d", region: "r", folder: "f", token: "t" })).length : 0);
286
+ const own = Object.keys(this.#longestLabels(spec, false)).length;
286
287
  return count + own > max ? `${a(this.#label)} computer takes ${max} labels, ${own} of them the provider's own: ${count} is ${count + own - max} too many` : undefined;
287
288
  }
289
+ /** Why a spec's labels, with the adapter's own at their longest, come to more bytes than the vendor takes; undefined when they fit. */
290
+ #labelBytes(spec) {
291
+ const { maxBytes, measure = "pairs" } = this.host.facts.labelRules ?? {};
292
+ if (maxBytes === undefined)
293
+ return undefined;
294
+ const labels = this.#longestLabels(spec, true);
295
+ const sizes = Object.entries(labels).map(([key, value]) => [key, Buffer.byteLength(key) + Buffer.byteLength(value)]);
296
+ const bytes = measure === "json" ? Buffer.byteLength(JSON.stringify(labels)) : sizes.reduce((sum, [, size]) => sum + size, 0);
297
+ if (bytes <= maxBytes)
298
+ return undefined;
299
+ const how = measure === "json" ? "as JSON" : "names and values together";
300
+ return `${a(this.#label)} computer's labels come to at most ${maxBytes} bytes, ${how}, and this computer's would come to ${bytes} (${sizes.map(([key, size]) => `${key} ${size}`).join(", ")}): give a shorter image, mount folder or labels`;
301
+ }
288
302
  /** A host call bounded by ms, the caller's signal when given. */
289
303
  #call(what, run, ms, signal) {
290
304
  return hostCall(this.host, what, run, ms, signal);
@@ -323,8 +337,7 @@ export class HostedProvider {
323
337
  return differ;
324
338
  }
325
339
  async #createOnce(spec, name, signal) {
326
- const { listMs } = this.#timeouts;
327
- const listed = await this.#call("the listing by the request's name", (ctx) => this.host.list({ [COMPUTER_LABEL]: "1", [NAME_LABEL]: name }, ctx), listMs, signal);
340
+ const listed = await foundBy(this.host, "the listing by the request's name", byName(name), this.#timeouts, signal);
328
341
  if (!listed.ok)
329
342
  return listed;
330
343
  const found = listed.value.filter((machine) => ours(machine.labels, name));
@@ -371,7 +384,7 @@ export class HostedProvider {
371
384
  * same listing. Its value is the machine kept, or undefined when mine holds the name alone (or nothing is listed yet).
372
385
  */
373
386
  async #converge(name, mine, signal) {
374
- const listed = await this.#call("the listing by the request's name", (ctx) => this.host.list({ [COMPUTER_LABEL]: "1", [NAME_LABEL]: name }, ctx), this.#timeouts.listMs, signal);
387
+ const listed = await foundBy(this.host, "the listing by the request's name", byName(name), this.#timeouts, signal);
375
388
  if (!listed.ok)
376
389
  return listed;
377
390
  const holders = listed.value.filter((machine) => ours(machine.labels, name) && alive(machine.state));
@@ -384,30 +397,27 @@ export class HostedProvider {
384
397
  }
385
398
  const [kept, ...others] = holders.sort(oldestFirst(holders));
386
399
  for (const other of others) {
387
- const gone = await this.#discard(other, signal);
400
+ const { letGo, gone } = await this.#remove({ id: other.id, name }, other, signal);
401
+ if (!letGo.ok)
402
+ this.#onNote?.({ computer: name, note: `${other.id}, a second machine of one request, was deleted, and ${letGo.error.message}` });
388
403
  if (!gone.ok)
389
404
  return this.#fail(gone.error.code, `${holders.length} machines carry the name ${name}: ${kept?.id}, the oldest, is kept, and ${other.id} could not be deleted (${gone.error.message})`);
390
405
  }
391
406
  return ok(kept);
392
407
  }
393
- /** A machine create does not keep, deleted and read back gone; a running Archil computer lets go of its folder first. */
394
- async #discard(machine, signal) {
395
- const ref = { id: machine.id, name: machine.labels[NAME_LABEL] };
396
- if (recordedArchil(machine.labels) !== undefined && machine.state === "running") {
397
- const letGo = await this.#letGo(ref, signal);
398
- if (!letGo.ok)
399
- this.#onNote?.({ computer: ref.name, note: `${machine.id}, a second machine of one request, was deleted, and ${letGo.error.message}` });
400
- }
401
- const killed = await this.#kill(machine.id);
402
- return killed.ok ? this.#settle(ref, signal) : killed;
403
- }
404
- /** A create of a request whose computer is listed already: the same create, the computer as it is; see create. */
408
+ /**
409
+ * A create of a request whose computer is listed already: the same create, the computer as it is, read by get (a
410
+ * listing may leave its network out); see create.
411
+ */
405
412
  async #again(spec, name, first, signal) {
406
413
  const until = Date.now() + this.#timeouts.createMs;
407
- let machine = first;
414
+ const read = await this.#get(first.id, signal);
415
+ if (!read.ok)
416
+ return read;
417
+ let machine = read.value;
408
418
  let last;
409
419
  for (;;) {
410
- if (machine === undefined || !alive(machine.state) || machine.state === "stopped")
420
+ if (machine === undefined || (machine.state !== "starting" && machine.state !== "running"))
411
421
  return this.#fail("exists", endedWords(name));
412
422
  const deadline = deadlineOf(machine);
413
423
  if (deadline !== undefined && deadline.getTime() <= Date.now())
@@ -417,10 +427,10 @@ export class HostedProvider {
417
427
  if (differ.length > 0)
418
428
  return this.#fail("exists", otherSpecWords(name, "was made", differ));
419
429
  const attached = await this.#attached(machine, signal);
420
- // The image and an Archil mount are in the labels; the user, the network, and a size where the vendor takes
421
- // one in a spec and reads it back, are read back. A vendor that reads no size back (Modal) cannot show a drift.
422
- const sizes = ["cpus", "memoryMb"].filter((field) => this.host.facts.specFields?.includes(field) && attached.ok && attached.value.spec[field] !== undefined);
423
- const drift = attached.ok ? readBackDiffer({ ...spec, user: this.#userOf(spec) }, attached.value.spec, ["user", "network", ...sizes]) : [];
430
+ // The image and an Archil mount are in the labels; the user, the network, and the GPUs where the vendor reads them
431
+ // back, are read back. A vendor that reads no GPU back (Modal) cannot show a drift in it, nor any vendor in a size.
432
+ const gpu = this.host.facts.gpuReadBack ? ["gpu"] : [];
433
+ const drift = attached.ok ? readBackDiffer({ ...spec, user: this.#userOf(spec) }, attached.value.spec, ["user", "network", ...gpu]) : [];
424
434
  if (drift.length > 0)
425
435
  return this.#fail("exists", otherSpecWords(name, "was made", drift));
426
436
  if (attached.ok)
@@ -489,6 +499,7 @@ export class HostedProvider {
489
499
  nonce: randomBytes(16).toString("hex"),
490
500
  waitS: Math.ceil((this.#timeouts.createMs + this.#timeouts.uploadMs + this.#timeouts.execMs + (archil ? this.#timeouts.mountMs * 3 : 0)) / 1000),
491
501
  ...(archil && this.host.facts.daemon === "pid1" ? { gate: ARCHIL_GATE } : {}),
502
+ ...(this.host.facts.daemon === "child" && this.host.facts.vendorSockets !== undefined ? { vendorSockets: this.host.facts.vendorSockets } : {}),
492
503
  });
493
504
  const taken = new Set(this.host.facts.specFields ?? []);
494
505
  const request = {
@@ -508,22 +519,13 @@ export class HostedProvider {
508
519
  };
509
520
  const runtime = this.host.facts.runtime?.(request);
510
521
  const { createMs } = this.#timeouts;
511
- // Never cancelled, only raced: an aborted call could leave a machine made whose id never came back.
512
- let creating;
513
- try {
514
- creating = Promise.resolve(this.host.create(request, { timeoutMs: createMs }));
515
- }
516
- catch (error) {
517
- return this.#fail(this.host.errorCode(error), `${this.#label}'s create failed: ${words(error)}`);
518
- }
519
- const raced = await race(this.host, creating, `${this.#label}'s create`, createMs + CALL_SLACK_MS, signal);
520
- const created = raced.ok ? raced.value : raced;
522
+ // Never signalled, only raced: an aborted call could leave a machine made whose id never came back. One that lands
523
+ // after this gave up is deleted by its id; one whose answer never comes, by its name.
524
+ 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) : this.#deleteNamed(name));
521
525
  if (!created.ok) {
522
526
  const { code, message } = created.error;
523
527
  if (code === "aborted" || code === "timeout") {
524
- // One that lands is deleted by its id; one whose answer never comes, by its name.
525
528
  this.#end(name);
526
- creating.then(async (made) => void (made.ok ? await this.#kill(made.value.id) : await this.#deleteNamed(name)), async () => void (await this.#deleteNamed(name)));
527
529
  return this.#fail(code, `${message}; a machine it makes after this is deleted as it lands, and ${this.#label} ends it by ${deadline} either way`);
528
530
  }
529
531
  // A create the vendor refused made nothing. One that failed otherwise may have: it goes by its name.
@@ -536,20 +538,16 @@ export class HostedProvider {
536
538
  this.#requests.made(name);
537
539
  return ok({ ref: { id: created.value.id, name }, made: { deadline, maxDeadline, labels, daemon, sha256, commands, user, ...(runtime === undefined ? {} : { runtime }) } });
538
540
  }
539
- /** Deletes a machine create gives up on, then waits, under the caller's signal, until the vendor reads it gone. */
541
+ /** Deletes a machine create gives up on, then waits, under the caller's signal, until get answers none for it. */
540
542
  async #abandon(ref, error, signal, mounted = false) {
541
543
  this.#end(ref.name);
542
544
  // A computer create made whole (its Archil folder mounted) lets go of the folder first, as release does.
543
- if (mounted) {
544
- const read = await this.#get(ref.id);
545
- if (read.ok && read.value !== undefined && recordedArchil(read.value.labels) !== undefined && read.value.state === "running")
546
- await this.#letGo(ref, signal);
547
- }
548
- const killed = await this.#kill(ref.id);
549
- const gone = killed.ok ? await this.#settle(ref, signal) : killed;
545
+ const read = mounted ? await this.#get(ref.id) : undefined;
546
+ const { gone } = await this.#remove(ref, read?.ok ? read.value : undefined, signal);
547
+ // The delete is never signalled, so an abort is the wait's, after the delete took.
550
548
  const after = gone.ok
551
549
  ? "was deleted"
552
- : killed.ok && gone.error.code === "aborted"
550
+ : gone.error.code === "aborted"
553
551
  ? `was deleted, and the wait for it to go was aborted; ${this.#label} ends it at its deadline if the delete did not take`
554
552
  : `could not be deleted (${gone.error.message}); it ends at its deadline`;
555
553
  return this.#fail(error.code, `the computer ${ref.name} ${after}: ${error.message}`);
@@ -560,11 +558,11 @@ export class HostedProvider {
560
558
  * listedMs passes. Best effort, in words.
561
559
  */
562
560
  async #deleteNamed(name) {
563
- const { listedMs, pollMs, listMs } = this.#timeouts;
561
+ const { listedMs, pollMs } = this.#timeouts;
564
562
  const until = Date.now() + listedMs;
565
563
  let found;
566
564
  for (;;) {
567
- const listed = await this.#call("the listing by name", (ctx) => this.host.list({ [COMPUTER_LABEL]: "1", [NAME_LABEL]: name }, ctx), listMs);
565
+ const listed = await foundBy(this.host, "the listing by name", byName(name), this.#timeouts);
568
566
  if (!listed.ok)
569
567
  return `; a machine named ${name} may be left (${listed.error.message}), which ends at its deadline`;
570
568
  found = listed.value.filter((machine) => ours(machine.labels, name));
@@ -576,8 +574,7 @@ export class HostedProvider {
576
574
  return `; no machine named ${name} was listed within ${seconds(listedMs)}, and any it made ends at its deadline`;
577
575
  const said = [];
578
576
  for (const machine of found) {
579
- const killed = await this.#kill(machine.id);
580
- const gone = killed.ok ? await this.#settle({ id: machine.id, name }) : killed;
577
+ const { gone } = await this.#remove({ id: machine.id, name }, undefined);
581
578
  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`);
582
579
  }
583
580
  return `; the machine named ${name} it made: ${said.join("; ")}`;
@@ -591,9 +588,9 @@ export class HostedProvider {
591
588
  #startPollMs() {
592
589
  return Math.min(START_POLL_MS, this.#timeouts.pollMs * 10);
593
590
  }
594
- /** The host's get, bounded by requestMs. */
591
+ /** The host's get, bounded by requestMs; a machine the vendor reports as not found is none. */
595
592
  #get(id, signal) {
596
- return this.#call(`the read of ${id}`, (ctx) => this.host.get(id, ctx), this.#timeouts.requestMs, signal);
593
+ return readMachine(this.host, id, this.#timeouts.requestMs, signal);
597
594
  }
598
595
  /** The machine running, read while it starts (within createMs); gone or failed is refused in words. */
599
596
  async #running(ref, signal) {
@@ -603,10 +600,11 @@ export class HostedProvider {
603
600
  if (!read.ok)
604
601
  return read;
605
602
  const machine = read.value;
606
- if (machine === undefined)
603
+ // A machine the vendor failed is gone in its words: the create stops in them, not at createMs.
604
+ if (machine?.why !== undefined && machine.state === "gone")
605
+ return this.#fail("vendor", `${this.#label} could not start ${ref.name}: ${machine.why}`);
606
+ if (machine === undefined || machine.state === "gone")
607
607
  return this.#fail("gone", `${ref.name} was gone before it ran`);
608
- if (machine.state === "failed")
609
- return this.#fail("vendor", `${this.#label} could not start ${ref.name}${machine.why ? `: ${machine.why}` : ""}`);
610
608
  if (machine.state !== "starting")
611
609
  return ok(machine);
612
610
  if (Date.now() + this.#startPollMs() >= until)
@@ -616,25 +614,17 @@ export class HostedProvider {
616
614
  return this.#fail("aborted", "create was aborted while the machine started");
617
615
  }
618
616
  }
619
- /** Every way a machine, as the vendor reads it back, differs from what create asked for. Pure: no call. */
620
- #machineDrift(spec, machine, labels) {
621
- const found = [...(machine.drift ?? [])];
617
+ /**
618
+ * Every way a machine, as the vendor reads it back, differs from what create asked for: its labels and its state. The
619
+ * rest is read from inside (the daemon, the probe). Pure: no call.
620
+ */
621
+ #machineDrift(machine, labels) {
622
+ const found = [];
622
623
  for (const [key, value] of Object.entries(labels))
623
624
  if (machine.labels[key] !== value)
624
625
  found.push(`label ${key}: declared ${show(value)}, read back ${show(machine.labels[key])}`);
625
- if (this.host.facts.networkReadBack) {
626
- // An Archil computer's vendor network is open, for root to reach Archil; its tools' none is read from inside.
627
- const archil = spec.mount?.kind === "archil";
628
- const vendor = archil ? "open" : spec.network;
629
- const network = machine.network ?? { other: `${this.#label} read no network back` };
630
- if (network !== vendor)
631
- found.push(`network: declared ${policyWords(vendor)}${archil ? ` (${this.#label}'s, for root to reach Archil)` : ""}, read back ${policyWords(network)}`);
632
- }
633
626
  if (machine.state !== "running")
634
627
  found.push(`state: declared "running", read back ${show(machine.state)}`);
635
- // No extend has run on a machine create just made: a timer that reads moved ends it later than its spec.
636
- if (machine.timerMoved === true)
637
- found.push(`timer: declared the spec's lifetime, read back an end of ${machine.endsAt instanceof Date ? machine.endsAt.toISOString() : "nothing"}, later than create set it`);
638
628
  return found;
639
629
  }
640
630
  /**
@@ -642,17 +632,11 @@ export class HostedProvider {
642
632
  * recorded that does not refuse it (notes).
643
633
  */
644
634
  async #prepare(spec, ref, { labels, daemon, sha256, commands, user, runtime }, signal) {
645
- const { uploadMs, execMs, requestMs } = this.#timeouts;
635
+ const { uploadMs, execMs } = this.#timeouts;
646
636
  const running = await this.#running(ref, signal);
647
637
  if (!running.ok)
648
638
  return running;
649
- if (this.host.prepare) {
650
- const prepare = this.host.prepare.bind(this.host);
651
- const prepared = await this.#call(`${this.#label}'s settings of ${ref.name}`, (ctx) => prepare(ref.id, ctx), requestMs, signal);
652
- if (!prepared.ok)
653
- return prepared;
654
- }
655
- const drift = this.#machineDrift(spec, running.value, labels);
639
+ const drift = this.#machineDrift(running.value, labels);
656
640
  if (drift.length > 0)
657
641
  return this.#fail("refused", `it did not match its spec: ${drift.join("; ")}`);
658
642
  const staging = commands.install[4];
@@ -701,7 +685,18 @@ export class HostedProvider {
701
685
  }
702
686
  /** The rest of #prepare from the daemon's install on: init started, its first connection checked, the listing waited for. */
703
687
  async #start(spec, ref, commands, want, signal) {
688
+ const closed = [];
704
689
  if (this.host.facts.daemon === "child") {
690
+ // The vendor's own sockets outside /run, closed to the computer's user before any program of its runs.
691
+ if (commands.sockets !== undefined) {
692
+ const shut = await runToExit(this.host, ref.id, commands.sockets, { ms: this.#timeouts.execMs, ...(signal ? { signal } : {}), what: `closing ${this.#label}'s own sockets in ${ref.name}` });
693
+ if (!shut.ok)
694
+ return shut;
695
+ if (shut.value.exitCode !== 0)
696
+ return this.#fail("refused", `closing ${this.#label}'s own sockets to the computer's user failed (exit ${shut.value.exitCode}): ${`${shut.value.stdout} ${shut.value.stderr}`.trim().slice(0, 300)}`);
697
+ const found = closedSocketsOf(shut.value.stdout);
698
+ closed.push(`${this.#label}'s own sockets closed to the computer's user: ${found.join(", ") || `none found (${(this.host.facts.vendorSockets ?? []).join(", ")})`}`);
699
+ }
705
700
  const init = await runToExit(this.host, ref.id, commands.start, { ms: this.#timeouts.execMs, ...(signal ? { signal } : {}), what: `starting the daemon in ${ref.name}` });
706
701
  if (!init.ok)
707
702
  return init;
@@ -728,7 +723,7 @@ export class HostedProvider {
728
723
  await opened.value.close();
729
724
  }
730
725
  const listed = await this.#waitListed(ref, signal);
731
- return listed.ok ? ok(notes) : listed;
726
+ return listed.ok ? ok([...closed, ...notes]) : listed;
732
727
  }
733
728
  /** What init wrote to its log (child) or the vendor's words of the machine (pid1): the end of it, or nothing. */
734
729
  async #initWords(ref) {
@@ -753,7 +748,7 @@ export class HostedProvider {
753
748
  async #checkInside(connection, name, network, starting, want, signal, archil) {
754
749
  let current = connection;
755
750
  if (starting && this.#desktop) {
756
- const shown = await startDisplay(connection.client, this.#desktop, { version: VERSION, vendor: this.id, signal });
751
+ const shown = await startDisplay(connection.client, this.#desktop, { version: VERSION, vendor: this.id, signal, windowManager: this.host.facts.windowManager === true });
757
752
  if (!shown.ok)
758
753
  return shown;
759
754
  const hello = await connection.client.call("hello", { client: `@parcha/agentrun-computer ${VERSION}` }, { signal: bounded(this.#timeouts.helloMs, signal) });
@@ -809,9 +804,11 @@ export class HostedProvider {
809
804
  const [uid, gid] = user === undefined ? [] : user.split(":");
810
805
  return { version: VERSION, ...(uid === undefined || gid === undefined ? {} : { uid, gid }), arch: this.host.facts.arch, kind, groups };
811
806
  }
812
- /** One stdio bridge into the machine, after hello, unchecked. */
813
- #open(ref, signal, helloMs = this.#timeouts.helloMs) {
814
- return openBridge(this.host, ref.id, { argv: hostedCommands().stdio, name: ref.name, version: VERSION, requestMs: this.#timeouts.requestMs, helloMs, ...(signal ? { signal } : {}) });
807
+ /** One stdio bridge into the machine, after hello, unchecked; its client says so once the machine is deleted. */
808
+ async #open(ref, signal, helloMs = this.#timeouts.helloMs) {
809
+ const { requestMs } = this.#timeouts;
810
+ const opened = await openBridge(this.host, ref.id, { argv: hostedCommands().stdio, name: ref.name, version: VERSION, requestMs, helloMs, ...(signal ? { signal } : {}) });
811
+ return opened.ok ? ok(deletedSaid(this.host, ref, this.#label, requestMs, opened.value)) : opened;
815
812
  }
816
813
  /** #open, tried again while the bridge finds no daemon listening, until hello or helloMs in all. */
817
814
  async #openWhenListening(ref, signal) {
@@ -852,7 +849,7 @@ export class HostedProvider {
852
849
  const until = Date.now() + listedMs;
853
850
  let since;
854
851
  for (let hits = 0;;) {
855
- const listed = await this.#call("the listing by name", (ctx) => this.host.list({ [COMPUTER_LABEL]: "1", [NAME_LABEL]: ref.name }, ctx), listMs, signal);
852
+ const listed = await listedBy(this.host, "the listing by name", byName(ref.name), listMs, signal);
856
853
  if (!listed.ok)
857
854
  return listed;
858
855
  if (listed.value.some((machine) => machine.id === ref.id)) {
@@ -874,7 +871,7 @@ export class HostedProvider {
874
871
  async #own(ref, signal) {
875
872
  const found = await this.#get(ref.id, signal);
876
873
  if (!found.ok)
877
- return found.error.code === "not_found" ? this.#fail("not_found", `no ${this.#label} computer is ${ref.name} (${ref.id})`) : found;
874
+ return found;
878
875
  if (found.value === undefined)
879
876
  return this.#fail("not_found", `no ${this.#label} computer is ${ref.name} (${ref.id})`);
880
877
  if (!ours(found.value.labels, ref.name))
@@ -900,6 +897,9 @@ export class HostedProvider {
900
897
  const found = await this.#own(ref);
901
898
  if (!found.ok)
902
899
  return found;
900
+ // A machine on its way out (past its deadline or released, the vendor still deleting it) is gone, not merely stopped.
901
+ if (found.value.state === "gone")
902
+ return this.#fail("gone", `${ref.name} passed its deadline or was released: it is going`);
903
903
  if (found.value.state !== "running")
904
904
  return this.#fail("refused", `${ref.name} is ${found.value.state}, not running: its daemon does not run`);
905
905
  const opened = await this.#open(ref);
@@ -923,7 +923,7 @@ export class HostedProvider {
923
923
  return this.#fail("invalid", `${String(id)} is not ${a(this.#label)} machine id`);
924
924
  const found = await this.#get(id, signal);
925
925
  if (!found.ok)
926
- return found.error.code === "not_found" ? this.#fail("not_found", `no ${this.#label} computer has the id ${id}`) : found;
926
+ return found;
927
927
  if (found.value === undefined || !ours(found.value.labels))
928
928
  return this.#fail("not_found", `no ${this.#label} computer has the id ${id}`);
929
929
  return this.#attached(found.value, signal);
@@ -959,20 +959,11 @@ export class HostedProvider {
959
959
  if (deadline === undefined)
960
960
  found.push(`deadline: the label ${DEADLINE_LABEL} reads ${show(machine.labels[DEADLINE_LABEL])}, not the ISO time create writes`);
961
961
  const archil = recordedArchil(machine.labels);
962
- const network = this.#toolsNetwork(machine);
963
- if (typeof network === "object")
964
- found.push(`network: ${policyWords(network)}, which this provider never makes`);
965
- const resolved = machine.image?.resolved;
966
- const image = machine.labels[IMAGE_LABEL] ?? resolved ?? "";
967
- // The size the vendor reads back is held to check() where the vendor takes it in a spec, and reported either way.
968
- const taken = new Set(this.host.facts.specFields ?? []);
969
- const cpus = machine.size?.cpus;
970
- const memoryMb = machine.size?.memoryMb;
971
- const sized = { ...(taken.has("cpus") && cpus !== undefined ? { cpus } : {}), ...(taken.has("memoryMb") && memoryMb !== undefined ? { memoryMb } : {}) };
972
- const spec = { image, lifetimeMs: 1, network: typeof network === "object" ? "open" : network, labels: callerLabels(machine.labels), ...sized };
962
+ // Its tools' network is none, read from inside (#checkInside's probe): no vendor's read of it is taken.
963
+ const network = "none";
964
+ const image = machine.labels[IMAGE_LABEL] ?? "";
965
+ const spec = { image, lifetimeMs: 1, network, labels: callerLabels(machine.labels) };
973
966
  found.push(...this.check(spec).map(({ field, message }) => `${field}: ${message}, read back from the computer`));
974
- // The vendor's own create options read back, as create holds them (#machineDrift).
975
- found.push(...(machine.drift ?? []));
976
967
  let kind;
977
968
  let notes = [];
978
969
  let mount;
@@ -1009,11 +1000,8 @@ export class HostedProvider {
1009
1000
  ...ref,
1010
1001
  spec: {
1011
1002
  image,
1012
- ...(resolved !== undefined && resolved !== image ? { snapshot: resolved } : {}),
1013
1003
  user: (this.#takesUser() ? user : undefined) ?? `${this.#uid}:${this.#gid}`,
1014
- network: spec.network,
1015
- ...(cpus === undefined ? {} : { cpus }),
1016
- ...(memoryMb === undefined ? {} : { memoryMb }),
1004
+ network,
1017
1005
  workdir: WORK,
1018
1006
  ...(deadline === undefined ? {} : { deadline }),
1019
1007
  ...(kind === undefined ? {} : { kind }),
@@ -1024,34 +1012,29 @@ export class HostedProvider {
1024
1012
  });
1025
1013
  }
1026
1014
  /**
1027
- * Settings' test: the host's own, or one list by the adapter's label, counted, which makes nothing; a refused key is
1028
- * unauthorized, a vendor not reached unreachable, the message never carrying a key.
1015
+ * Settings' test: one list by the adapter's label, its computers counted as the listing reads them (no get of each),
1016
+ * which makes nothing; a refused key is unauthorized, a vendor not reached unreachable, the message never carrying a key.
1029
1017
  */
1030
1018
  async testConnection({ signal } = {}) {
1031
- const { requestMs, listMs } = this.#timeouts;
1032
- const tested = this.host.testConnection?.bind(this.host);
1033
- if (tested)
1034
- return countTestedAs(this.#label, await this.#call(`${this.#label}'s test`, (ctx) => tested(ctx), requestMs, signal));
1035
- const listed = await this.#call("the listing", (ctx) => this.host.list({ [COMPUTER_LABEL]: "1" }, ctx), listMs, signal);
1036
- return countTested(this.#label, listed.ok ? ok({ count: listed.value.filter((machine) => ours(machine.labels)).length }) : listed);
1019
+ const listed = await listedBy(this.host, "the listing", { [COMPUTER_LABEL]: "1" }, this.#timeouts.listMs, signal);
1020
+ return countTested(this.#label, listed.ok ? ok({ count: listed.value.filter((machine) => ours(machine.labels) && alive(machine.state)).length }) : listed);
1037
1021
  }
1038
1022
  /**
1039
- * Every computer this provider made that carries all of these labels, running or stopped, each one's network read
1040
- * back. One deadline, listMs from the call, bounds every page and every read-back.
1023
+ * Every computer this provider made that carries all of these labels, running or stopped: the listing finds them, and
1024
+ * a get of each reads its state, labels and end (foundBy). Its network is none, as create made it and the probe reads
1025
+ * it from inside.
1041
1026
  */
1042
1027
  async list(labels, { signal } = {}) {
1043
1028
  const problem = filterProblem(labels);
1044
1029
  if (problem)
1045
1030
  return this.#fail("invalid", problem);
1046
1031
  const { listMs } = this.#timeouts;
1047
- const listed = await this.#call("the listing", (ctx) => this.host.list({ ...labels, [COMPUTER_LABEL]: "1" }, ctx), listMs, signal);
1032
+ const listed = await foundBy(this.host, "the listing", { ...labels, [COMPUTER_LABEL]: "1" }, this.#timeouts, signal);
1048
1033
  if (!listed.ok)
1049
1034
  return listed.error.code === "timeout" ? this.#fail("timeout", `list did not finish within ${seconds(listMs)}: ${listed.error.message}`) : listed;
1050
1035
  const infos = [];
1051
1036
  for (const machine of listed.value) {
1052
- if (!ours(machine.labels) || !Object.entries(labels).every(([key, value]) => machine.labels[key] === value))
1053
- continue;
1054
- if (machine.state !== "running" && machine.state !== "stopped")
1037
+ if (!ours(machine.labels) || (machine.state !== "running" && machine.state !== "stopped"))
1055
1038
  continue;
1056
1039
  // list runs nothing in a computer: an Archil computer's mount is the one its label records, under its epoch label.
1057
1040
  const archil = recordedArchil(machine.labels);
@@ -1060,13 +1043,13 @@ export class HostedProvider {
1060
1043
  labels: { ...machine.labels },
1061
1044
  deadline: deadlineOf(machine),
1062
1045
  state: machine.state,
1063
- network: this.#toolsNetwork(machine),
1046
+ network: "none",
1064
1047
  ...(archil === undefined ? {} : { mount: archil.expected }),
1065
1048
  });
1066
1049
  }
1067
1050
  return ok(infos);
1068
1051
  }
1069
- /** The vendor reads the policy back (or the probe stands for it). A change is refused: the network is fixed at create. */
1052
+ /** The probe reads the policy back from inside. A change is refused: the network is fixed at create. */
1070
1053
  async network(ref, policy, { signal } = {}) {
1071
1054
  const problem = this.#refProblem(ref);
1072
1055
  if (problem)
@@ -1079,12 +1062,11 @@ export class HostedProvider {
1079
1062
  const found = await this.#own(ref, signal);
1080
1063
  if (!found.ok)
1081
1064
  return found;
1082
- let read = this.#toolsNetwork(found.value);
1083
- // Its tools' none is read from inside, as the tool user, where the vendor's network is root's (an Archil computer's)
1084
- // or the vendor reads none back: the daemon's own network namespace's live interfaces are lo alone, none can be
1085
- // raised (computerd probe), and no probe target answers.
1086
- const inside = (recordedArchil(found.value.labels) !== undefined || !this.host.facts.networkReadBack) && found.value.state === "running";
1087
- if (read === "none" && inside) {
1065
+ let read = "none";
1066
+ // Its tools' none is read from inside, as the tool user, whatever the vendor's network is (an Archil computer's root
1067
+ // reaches Archil): the daemon's own network namespace's live interfaces are lo alone, none can be raised (computerd
1068
+ // probe), and no probe target answers.
1069
+ if (found.value.state === "running") {
1088
1070
  const opened = await this.#open(ref, signal);
1089
1071
  if (!opened.ok)
1090
1072
  return opened;
@@ -1108,18 +1090,6 @@ export class HostedProvider {
1108
1090
  return ok(read);
1109
1091
  return this.#fail("refused", `${fixed}: ${ref.name} reads back network ${policyWords(read)}, not ${policy}`);
1110
1092
  }
1111
- /**
1112
- * The tools' network as the vendor's policy shows it: the vendor's own (none where it reads none back), except for an
1113
- * Archil computer, whose open vendor network is root's, to reach Archil: its tools' network is init's own, none.
1114
- */
1115
- #toolsNetwork(machine) {
1116
- const vendor = this.host.facts.networkReadBack ? (machine.network ?? { other: `${this.#label} read no network back` }) : "none";
1117
- if (recordedArchil(machine.labels) === undefined)
1118
- return vendor;
1119
- if (vendor === "open" || !this.host.facts.networkReadBack)
1120
- return "none";
1121
- return { other: `an Archil computer whose ${this.#label} network reads ${policyWords(vendor)}, not the open one create makes for root to reach Archil` };
1122
- }
1123
1093
  /** One extend of a computer at a time, each reading the deadline the one before it left. */
1124
1094
  async #extendSerial(ref, ttlMs, signal) {
1125
1095
  const problem = this.#refProblem(ref);
@@ -1140,9 +1110,9 @@ export class HostedProvider {
1140
1110
  }
1141
1111
  }
1142
1112
  /**
1143
- * Moves the deadline to now + ttlMs, refusing one earlier than it is (before any vendor call), never past create's time plus the cap (init's maximum):
1144
- * the vendor's timer (setTimer, then read back) or the janitor's label (setLabels) first, then init's own deadline, to
1145
- * the end the vendor reads back. The deadline returned is the one init took.
1113
+ * Moves the deadline to now + ttlMs, refusing one earlier than it is (before any vendor call), never past create's time
1114
+ * plus the cap (init's maximum): the host's extend first (its timer or its deadline label), then the end it reads back
1115
+ * (get, deadlineOf), then init's own deadline, to that end. The deadline returned is the one init took.
1146
1116
  */
1147
1117
  async #extend(ref, ttlMs, signal) {
1148
1118
  const found = await this.#own(ref, signal);
@@ -1165,28 +1135,17 @@ export class HostedProvider {
1165
1135
  }
1166
1136
  if (current !== undefined && target === current.getTime())
1167
1137
  return ok({ deadline: current });
1168
- const { requestMs } = this.#timeouts;
1169
- let end;
1170
- const setTimer = this.host.setTimer?.bind(this.host);
1171
- if (this.host.facts.lifetime === "vendor" && setTimer) {
1172
- const moved = await this.#call(`${this.#label}'s timer of ${ref.name}`, (ctx) => setTimer(ref.id, { end: new Date(target), most }, ctx), requestMs, signal);
1173
- if (!moved.ok)
1174
- return moved.error.code === "limit" ? moved : this.#fail(moved.error.code, `${this.#label}'s timer did not move, so nothing did: ${moved.error.message}`);
1175
- const after = await this.#get(ref.id, signal);
1176
- if (!after.ok || after.value?.endsAt === undefined) {
1177
- const why = after.ok ? `${ref.name} read back with no end` : after.error.message;
1178
- return this.#fail(after.ok ? "gone" : after.error.code, `${this.#label}'s timer was asked to move, and reading it back failed: ${why}; init's deadline did not move`);
1179
- }
1180
- end = after.value.endsAt;
1181
- }
1182
- else {
1183
- const setLabels = this.host.setLabels?.bind(this.host);
1184
- if (!setLabels)
1185
- return this.#fail("unsupported", `${a(this.#label)} computer's deadline cannot move`);
1186
- end = new Date(target);
1187
- const moved = await this.#call(`the deadline label of ${ref.name}`, (ctx) => setLabels(ref.id, { [DEADLINE_LABEL]: end.toISOString() }, ctx), requestMs, signal);
1188
- if (!moved.ok)
1189
- return this.#fail(moved.error.code, `the deadline label did not move, so nothing did: ${moved.error.message}`);
1138
+ const extend = this.host.extend?.bind(this.host);
1139
+ if (!extend)
1140
+ return this.#fail("unsupported", `${a(this.#label)} computer's deadline cannot move`);
1141
+ const moved = await this.#call(`${this.#label}'s end of ${ref.name}`, (ctx) => extend(ref.id, new Date(target), ctx), this.#timeouts.requestMs, signal);
1142
+ if (!moved.ok)
1143
+ return moved.error.code === "limit" ? moved : this.#fail(moved.error.code, `${this.#label}'s end did not move, so nothing did: ${moved.error.message}`);
1144
+ const after = await this.#get(ref.id, signal);
1145
+ const end = after.ok && after.value !== undefined ? deadlineOf(after.value) : undefined;
1146
+ if (end === undefined) {
1147
+ const why = after.ok ? `${ref.name} read back with no end` : after.error.message;
1148
+ return this.#fail(after.ok ? "gone" : after.error.code, `${this.#label}'s end was asked to move, and reading it back failed: ${why}; init's deadline did not move`);
1190
1149
  }
1191
1150
  const opened = await this.#open(ref, signal);
1192
1151
  if (!opened.ok)
@@ -1207,12 +1166,12 @@ export class HostedProvider {
1207
1166
  /**
1208
1167
  * delete reads the machine back to check it is this provider's, then deletes it, both never signalled, so a release
1209
1168
  * after an abort, or one aborted during the read, still sends the delete; it is idempotent: one the vendor no longer
1210
- * has is ok. The vendor answers a delete before the machine is gone, so release then waits (#settle) until the vendor
1211
- * reads it gone and no longer lists it, within goneMs and the caller's signal, the one step the signal ends. A running
1169
+ * has is ok. The vendor answers a delete before the machine is gone, so release then waits (#settle) until get
1170
+ * answers none (twice running), within goneMs and the caller's signal, the one step the signal ends. A running
1212
1171
  * Archil computer lets go of the run's folder first (archilRelease: the final sync through computerd, then checkin as
1213
1172
  * root); the delete runs whatever that answers. A folder not let go cleanly loses nothing (every call that changed it
1214
1173
  * synced, and the next claim revokes the hold), so it is said through onNote, and the release succeeds once the
1215
- * machine is gone. stop, where the host declares it, stops the machine and keeps it.
1174
+ * machine is gone. A computer here is deleted, never stopped: release stop is refused in words.
1216
1175
  */
1217
1176
  async release(ref, how, { signal } = {}) {
1218
1177
  const problem = this.#refProblem(ref);
@@ -1220,35 +1179,39 @@ export class HostedProvider {
1220
1179
  return this.#fail("invalid", problem);
1221
1180
  if (how === "detach")
1222
1181
  return this.#fail("unsupported", `the ${this.#label} provider keeps no computer for an agent (it declares no persistence), so release detach is refused: release it with delete`);
1223
- if (how !== "stop" && how !== "delete")
1224
- return this.#fail("invalid", `release is "stop" or "delete", not ${String(how)}`);
1225
- const stop = this.host.stop?.bind(this.host);
1226
- if (how === "stop" && !(stop && this.host.facts.release.includes("stop")))
1227
- return this.#fail("unsupported", `${a(this.#label)} computer has no stop that this provider declares: release it with delete`);
1182
+ if (how === "stop")
1183
+ return this.#fail("unsupported", `${a(this.#label)} computer is deleted, never stopped and kept: release it with delete`);
1184
+ if (how !== "delete")
1185
+ return this.#fail("invalid", `release is "delete", not ${String(how)}`);
1228
1186
  const found = await this.#get(ref.id);
1229
1187
  if (!found.ok)
1230
- return found.error.code === "not_found" ? ok(undefined) : found;
1188
+ return found;
1231
1189
  if (found.value === undefined)
1232
1190
  return ok(undefined);
1233
1191
  if (!ours(found.value.labels, ref.name))
1234
1192
  return this.#fail("not_found", `no ${this.#label} computer is ${ref.name} (${ref.id}): the machine is not this provider's, so it is left as it is`);
1235
- // A stop and a delete alike let go of a running Archil computer's folder first: a stopped one holds no folder.
1236
- const letGo = recordedArchil(found.value.labels) !== undefined && found.value.state === "running" ? await this.#letGo(ref, signal) : ok(undefined);
1237
- let done;
1238
- if (how === "stop" && stop)
1239
- done = await this.#call(`the stop of ${ref.name}`, (ctx) => stop(ref.id, ctx), this.#timeouts.goneMs, signal);
1240
- else {
1241
- this.#end(ref.name);
1242
- const killed = await this.#kill(ref.id);
1243
- done = killed.ok ? await this.#settle(ref, signal) : killed;
1244
- }
1193
+ this.#end(ref.name);
1194
+ const { letGo, gone: done } = await this.#remove(ref, found.value, signal);
1245
1195
  if (letGo.ok)
1246
1196
  return done;
1247
1197
  if (!done.ok)
1248
1198
  return this.#fail(done.error.code, `${done.error.message}; and ${letGo.error.message}`);
1249
- this.#onNote?.({ computer: ref.name, note: `${ref.name} was ${how === "stop" ? "stopped" : "deleted"}, and ${letGo.error.message}` });
1199
+ this.#onNote?.({ computer: ref.name, note: `${ref.name} was deleted, and ${letGo.error.message}` });
1250
1200
  return done;
1251
1201
  }
1202
+ /**
1203
+ * The one delete: machine's folder let go first (where it is a running Archil computer, as read; none for undefined),
1204
+ * then the host's delete, then the wait until get answers none for it. The callers word what failed.
1205
+ */
1206
+ async #remove(ref, machine, signal) {
1207
+ const letGo = await this.#letGoOf(ref, machine, signal);
1208
+ const killed = await this.#kill(ref.id);
1209
+ return { letGo, gone: killed.ok ? await this.#settle(ref, signal) : killed };
1210
+ }
1211
+ /** #letGo where machine, as read, is a running Archil computer: a stopped one holds no folder. */
1212
+ #letGoOf(ref, machine, signal) {
1213
+ return machine !== undefined && recordedArchil(machine.labels) !== undefined && machine.state === "running" ? this.#letGo(ref, signal) : Promise.resolve(ok(undefined));
1214
+ }
1252
1215
  /** A running Archil computer's folder let go: the final sync through a connection when it answers, then checkin as root. */
1253
1216
  async #letGo(ref, signal) {
1254
1217
  const opened = await this.#open(ref, signal);
@@ -1260,48 +1223,146 @@ export class HostedProvider {
1260
1223
  await opened.value.close();
1261
1224
  }
1262
1225
  }
1263
- /**
1264
- * Waits, through waitUntil, until the vendor reads the machine gone (get answers none, or a state that is neither
1265
- * running, stopped nor starting) and its name's listing no longer shows it, twice running. Pauses double from pollMs
1266
- * to 5 s, bounded by goneMs and the caller's signal; a failed read ends the wait with that error.
1267
- */
1268
- async #settle(ref, signal) {
1269
- const settled = await settleGone(this.host, ref, { ...this.#timeouts, ...(signal ? { signal } : {}) });
1270
- return settled;
1226
+ /** Waits until the vendor reads the machine gone after its delete (settle). */
1227
+ #settle(ref, signal) {
1228
+ return settle(this.host, ref, { ...this.#timeouts, ...(signal ? { signal } : {}) });
1229
+ }
1230
+ }
1231
+ /** The labels a listing by one computer's name asks for. */
1232
+ const byName = (name) => ({ [COMPUTER_LABEL]: "1", [NAME_LABEL]: name });
1233
+ /**
1234
+ * The host's listing by labels, bounded by ms: only the machines that carry every one of them, since a vendor's listing
1235
+ * may answer more (MachineHost.list).
1236
+ */
1237
+ export async function listedBy(host, what, labels, ms, signal) {
1238
+ const listed = await hostCall(host, what, (ctx) => host.list(labels, ctx), ms, signal);
1239
+ return listed.ok ? ok(listed.value.filter((machine) => carries(machine, labels))) : listed;
1240
+ }
1241
+ /** Whether a machine carries every one of these labels. */
1242
+ const carries = (machine, labels) => Object.entries(labels).every(([key, value]) => machine.labels?.[key] === value);
1243
+ /**
1244
+ * The listing finds, get answers (MachineHost.list): the machines the host's listing by labels names, each read now by
1245
+ * readMachine, within requestMs. One the vendor no longer has (not found) is dropped, and so is one whose get carries
1246
+ * not every label. A read that fails otherwise fails the whole.
1247
+ */
1248
+ export async function foundBy(host, what, labels, { listMs, requestMs }, signal) {
1249
+ const listed = await listedBy(host, what, labels, listMs, signal);
1250
+ if (!listed.ok)
1251
+ return listed;
1252
+ const reads = await Promise.all(listed.value.map(({ id }) => readMachine(host, id, requestMs, signal)));
1253
+ const found = [];
1254
+ for (const read of reads) {
1255
+ if (!read.ok)
1256
+ return read;
1257
+ if (read.value !== undefined && carries(read.value, labels))
1258
+ found.push(read.value);
1271
1259
  }
1260
+ return ok(found);
1261
+ }
1262
+ /** The host's get of one machine, bounded by ms: a machine the vendor reports as not found is none, never an error. */
1263
+ async function readMachine(host, id, ms, signal) {
1264
+ const read = await hostCall(host, `the read of ${id}`, (ctx) => host.get(id, ctx), ms, signal);
1265
+ return !read.ok && read.error.code === "not_found" ? ok(undefined) : read;
1266
+ }
1267
+ /** What reading answers, or undefined once a signal aborts first: a caller that stopped waiting never waits on a read. */
1268
+ function untilAborted(reading, signals) {
1269
+ const given = signals.filter((signal) => signal !== undefined);
1270
+ if (given.length === 0)
1271
+ return reading;
1272
+ const signal = AbortSignal.any(given);
1273
+ if (signal.aborted)
1274
+ return Promise.resolve(undefined);
1275
+ return new Promise((settle) => {
1276
+ const onAbort = () => settle(undefined);
1277
+ signal.addEventListener("abort", onAbort, { once: true });
1278
+ reading.then((value) => {
1279
+ signal.removeEventListener("abort", onAbort);
1280
+ settle(value);
1281
+ });
1282
+ });
1283
+ }
1284
+ /**
1285
+ * A connection that says its computer was deleted (the vendor's own API can delete it mid-run). Once its client answers
1286
+ * gone (the stream ended or failed), the machine is read once, and that one read answers every call in flight at that
1287
+ * moment and every later call. A machine the vendor no longer has, or reads gone with no why (going), makes each of them
1288
+ * not_found in these words; one still there, a failed one, or a read that failed, leaves the client's own answer, as does
1289
+ * a caller's abort or a close during the read. A call with no answer by its own timeout answers timeout at once, as the
1290
+ * client says; the machine is read beside it, and a deleted one ends the connection, so every call still waiting on the
1291
+ * hung transport and every later call answers not_found. A connection its caller closed is never read back.
1292
+ */
1293
+ function deletedSaid(host, ref, label, requestMs, connection) {
1294
+ const { client } = connection;
1295
+ const closing = new AbortController();
1296
+ let deleted;
1297
+ let ended;
1298
+ let checking;
1299
+ const read = async () => {
1300
+ const got = await readMachine(host, ref.id, requestMs, closing.signal);
1301
+ // Gone with no why is being deleted; a failed machine (gone with its why) keeps the client's own answer.
1302
+ if (got.ok && (got.value === undefined || (got.value.state === "gone" && got.value.why === undefined)) && deleted === undefined && !closing.signal.aborted) {
1303
+ const how = got.value === undefined ? `${label} no longer has it` : `${label} reads it going`;
1304
+ deleted = { code: "not_found", message: `the computer ${ref.name} (${ref.id}) was deleted: ${how}` };
1305
+ // Every call still waiting on the transport settles now, with these words, as later ones do.
1306
+ void connection.close();
1307
+ }
1308
+ return deleted;
1309
+ };
1310
+ const close = () => {
1311
+ closing.abort();
1312
+ return connection.close();
1313
+ };
1314
+ return {
1315
+ ...connection,
1316
+ client: {
1317
+ async call(method, params, options) {
1318
+ if (deleted)
1319
+ return { ok: false, error: deleted };
1320
+ const answered = await client.call(method, params, options);
1321
+ if (answered.ok)
1322
+ return answered;
1323
+ if (deleted)
1324
+ return { ok: false, error: deleted };
1325
+ if (closing.signal.aborted)
1326
+ return answered;
1327
+ if (answered.error.code === "timeout") {
1328
+ checking ??= read().finally(() => (checking = undefined));
1329
+ return answered;
1330
+ }
1331
+ if (answered.error.code !== "gone")
1332
+ return answered;
1333
+ const found = await untilAborted((ended ??= read()), [options?.signal, closing.signal]);
1334
+ return found ? { ok: false, error: found } : answered;
1335
+ },
1336
+ close() {
1337
+ void close();
1338
+ },
1339
+ },
1340
+ close,
1341
+ };
1272
1342
  }
1273
1343
  /**
1274
- * Waits until the host reads a machine gone and no longer lists it under its name, twice running (see #settle). Shared
1275
- * with the live sweep, which waits the same way.
1344
+ * Waits, through waitUntil, until get answers none for a machine after its delete, twice running: the vendor no longer
1345
+ * has it. A machine read gone is still going (a vendor still destroying it), so it holds the wait like any other state.
1346
+ * A listing may show a deleted machine for a while (MachineHost.list), so it is not read. Pauses double from pollMs to
1347
+ * 5 s, bounded by goneMs and the caller's signal; a failed read ends the wait with that error. Shared with the live sweep.
1276
1348
  */
1277
- export async function settleGone(host, ref, { requestMs, listMs, pollMs, goneMs, signal }) {
1278
- const fail = failOf(host);
1349
+ export async function settle(host, ref, { requestMs, pollMs, goneMs, signal }) {
1350
+ const fail = failFor(host.descriptor.id);
1279
1351
  let agreed = 0;
1280
1352
  let last = "unread";
1281
1353
  const read = async (readSignal) => {
1282
- const got = await hostCall(host, `the read of ${ref.id}`, (ctx) => host.get(ref.id, ctx), requestMs, readSignal);
1283
- if (!got.ok && got.error.code !== "not_found") {
1354
+ const got = await readMachine(host, ref.id, requestMs, readSignal);
1355
+ if (!got.ok) {
1284
1356
  if (got.error.code === "aborted")
1285
1357
  return { last };
1286
1358
  return { failed: fail(got.error.code, `release of ${ref.name}: reading it back failed (${got.error.message}); it last read ${last}`) };
1287
1359
  }
1288
- const state = got.ok ? got.value?.state : undefined;
1360
+ const state = got.value?.state;
1289
1361
  last = state ?? "gone (not found)";
1290
- if (state !== undefined && alive(state)) {
1362
+ if (state !== undefined) {
1291
1363
  agreed = 0;
1292
1364
  return { last };
1293
1365
  }
1294
- const listed = await hostCall(host, "the listing by name", (ctx) => host.list({ [COMPUTER_LABEL]: "1", [NAME_LABEL]: ref.name }, ctx), listMs, readSignal);
1295
- if (!listed.ok) {
1296
- if (listed.error.code === "aborted")
1297
- return { last };
1298
- return { failed: fail(listed.error.code, `release of ${ref.name}: the listing failed (${listed.error.message}); it last read ${last}`) };
1299
- }
1300
- if (listed.value.some((machine) => machine.id === ref.id)) {
1301
- agreed = 0;
1302
- last = `${last}, still listed`;
1303
- return { last };
1304
- }
1305
1366
  return ++agreed >= LISTED_ROUNDS ? { settled: true } : { last };
1306
1367
  };
1307
1368
  const waited = await waitUntil(read, (state) => !("last" in state), {
@@ -1335,11 +1396,7 @@ function runtimeDrift(runtime, kernel) {
1335
1396
  return [`runtime: declared gVisor (a GPU computer), read back another kernel (${JSON.stringify(kernel)})`];
1336
1397
  return [];
1337
1398
  }
1338
- /** A host's own test, its words kept: unauthorized and unreachable as the shared rule reads them. */
1339
- function countTestedAs(label, tested) {
1340
- return tested.ok ? tested : countTested(label, tested);
1341
- }
1342
- function labelProblem(key, value, rule) {
1399
+ function labelProblem(key, value) {
1343
1400
  if (typeof value !== "string")
1344
1401
  return `the label ${key} must be a string`;
1345
1402
  if (key.includes("\0") || value.includes("\0"))
@@ -1350,15 +1407,9 @@ function labelProblem(key, value, rule) {
1350
1407
  return `the label ${key} is in the provider's own namespace (${COMPUTER_LABEL})`;
1351
1408
  if (key === ARCHIL_MOUNT_LABEL)
1352
1409
  return `the label ${key} is the provider's own: it records an Archil computer's mount`;
1353
- if (rule !== undefined && !rule.test(key))
1354
- return `the label name ${JSON.stringify(key)} is not one the vendor takes (${rule.source})`;
1355
1410
  return undefined;
1356
1411
  }
1357
1412
  /** "a" or "an" before a vendor's name, by its first letter. */
1358
1413
  function a(label) {
1359
1414
  return `${/^[AEIOU]/i.test(label) ? "an" : "a"} ${label}`;
1360
1415
  }
1361
- /** The shared machine-host adapter: host's machines as a ComputerProvider (see HostedProvider). */
1362
- export function hostedProvider(host, options) {
1363
- return new HostedProvider(host, options);
1364
- }