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

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.
@@ -14,6 +14,7 @@ import { isDeepStrictEqual } from "node:util";
14
14
  import { CreateRequests, endedWords, otherSpecWords, readBackDiffer } from "../create-requests.js";
15
15
  import { desktopOf, startDisplay } from "../desktop.js";
16
16
  import { COMPUTER_LABEL, DAEMON_IN_COMPUTER, DEADLINE_LABEL, helloDrift, probeNetworkDrift, probeNotes, probeReportOf, show, WORK } from "../drift.js";
17
+ import { BACKSTOP_MARGIN_MS } from "../host.js";
17
18
  import { readOwnNetwork, TOOL_USER } from "../isolation.js";
18
19
  import { releaseOlder } from "../janitor.js";
19
20
  import { RUN_LABEL } from "../labels.js";
@@ -24,10 +25,10 @@ import { failFor, ok } from "../result.js";
24
25
  import { daemonWatch } from "../screen-watch.js";
25
26
  import { countTested } from "../test-connection.js";
26
27
  import { waitUntil } from "../wait.js";
27
- import { bounded, CALL_SLACK_MS, hostCall, openBridge, pause, rootOf, runToExit, seconds, uploadThroughExec } from "./process.js";
28
+ import { bounded, CALL_SLACK_MS, hostCall, OUTPUT_MAX, openBridge, pause, rootOf, runToExit, seconds, uploadThroughExec } from "./process.js";
28
29
  import { isWhole, packLabels } from "./values.js";
29
30
  import { EGRESS_POLICY, EGRESS_PROXY_USER, EGRESS_RELAY, HOSTED_ALLOW, NETWORK_LABEL, networkFormOf, networkOfForm, networkRefusal, throughProxy } from "./network.js";
30
- import { ARCHIL_GATE, closedSocketsOf, daemonDrift, hostedCommands, installerOf } from "./scripts.js";
31
+ import { ARCHIL_GATE, closedSocketsOf, daemonDrift, hostedCommands, installerOf, LABEL_FILE, labelsCommand } from "./scripts.js";
31
32
  const VERSION = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
32
33
  export const NAME_LABEL = `${COMPUTER_LABEL}.name`;
33
34
  /** The image create was asked for: a vendor may report another name for it (a template's id). */
@@ -63,9 +64,14 @@ const ARCHIL_USER = `${ARCHIL_TOOL_UID}:${ARCHIL_TOOL_UID}`;
63
64
  const RELEASE_POLL_MAX_MS = 5_000;
64
65
  const LISTED_POLL_MS = 150;
65
66
  const LISTED_ROUNDS = 2;
66
- const LISTED_POLL_MAX_MS = 1_000;
67
67
  const LISTEN_RETRY_MS = 250;
68
68
  const START_POLL_MS = 500;
69
+ /**
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.
73
+ */
74
+ const UNFILED_MARGIN_MS = 300_000;
69
75
  /** The longest a Node timer or AbortSignal.timeout holds. */
70
76
  const MAX_TIMER_MS = 2 ** 31 - 1;
71
77
  /** The longest timeout the adapter takes: the race of a call bounded by it must still fit a Node timer. */
@@ -166,6 +172,8 @@ export class HostedProvider {
166
172
  #requests = new CreateRequests();
167
173
  /** Each computer's last extend, by machine id, while one runs: the next waits for it. */
168
174
  #extending = new Map();
175
+ /** Each held computer's keepalive timer, by machine id (facts.idleMs). */
176
+ #kept = new Map();
169
177
  constructor(host, options) {
170
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;
171
179
  const { id, label, capabilities } = host.descriptor;
@@ -184,6 +192,17 @@ export class HostedProvider {
184
192
  if (!isWhole(maxLifetimeMs) || maxLifetimeMs <= 0 || maxLifetimeMs > host.facts.maxLifetimeMs) {
185
193
  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`);
186
194
  }
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`);
205
+ }
187
206
  const user = USER.exec(daemonUser);
188
207
  if (user === null || Number(user[1]) > MAX_ID || Number(user[2]) > MAX_ID)
189
208
  throw new Error(`the daemon user ${daemonUser} must be uid:gid in numbers, such as 1000:1000`);
@@ -299,6 +318,44 @@ export class HostedProvider {
299
318
  refusals.push(...this.host.check(given));
300
319
  return refusals;
301
320
  }
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
+ }
325
+ /**
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
+ */
330
+ get #unfiledMs() {
331
+ const { createMs, listMs, requestMs, execMs } = this.#timeouts;
332
+ return 2 * createMs + listMs + requestMs + execMs + UNFILED_MARGIN_MS;
333
+ }
334
+ /**
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.
339
+ */
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);
358
+ }
302
359
  /** Whether the host takes a spec's user (facts.user): then a computer's daemon runs as the one a spec names. */
303
360
  get #takesUser() {
304
361
  return this.host.facts.user !== undefined;
@@ -313,12 +370,18 @@ export class HostedProvider {
313
370
  * they fit.
314
371
  */
315
372
  #labelsOver(spec) {
316
- const { count, bytes: max, packed } = this.host.facts.labels ?? {};
373
+ const room = this.host.facts.labels ?? {};
317
374
  // Stand-ins as long as create's name and deadlines and as mixed, fixed so a spec's answer never changes (attach and a
318
375
  // retry check the spec again): a packed map deflates them as it does create's, give or take a byte, and create packs
319
376
  // its own before the host's call (#packedOver).
320
377
  const name = "computer-5f3a9c1e7b2d";
321
378
  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;
322
385
  if (packed) {
323
386
  const why = this.#packedOver(labels, name);
324
387
  return why === undefined ? undefined : { bytes: true, why };
@@ -339,7 +402,8 @@ export class HostedProvider {
339
402
  }
340
403
  /** Why labels don't fit packed (facts.labels.packed), in words; undefined when they fit or the host keeps them as they are. */
341
404
  #packedOver(labels, name) {
342
- const fit = this.host.facts.labels?.packed ? packLabels(labels, name, this.host.facts.labels) : { labels };
405
+ const room = this.host.facts.labels;
406
+ const fit = room !== "machine" && room?.packed ? packLabels(labels, name, room) : { labels };
343
407
  return "problem" in fit ? `${a(this.#label)} computer keeps its labels packed, and ${fit.problem}: ${shorterWords(labels)}` : undefined;
344
408
  }
345
409
  /** A host call bounded by ms, the caller's signal when given. */
@@ -385,7 +449,12 @@ export class HostedProvider {
385
449
  const listed = await foundBy(this.host, "the listing by the request's name", byName(name), this.#timeouts, signal);
386
450
  if (!listed.ok)
387
451
  return listed;
388
- const found = listed.value.filter((machine) => ours(machine.labels, name));
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
+ }
389
458
  if (found.length > 1)
390
459
  return this.#fail("exists", `${found.length} machines carry the name ${name} (${found.map((m) => m.id).join(", ")}): create with a new request id`);
391
460
  if (found.length === 1)
@@ -396,6 +465,7 @@ export class HostedProvider {
396
465
  if (!launched.ok)
397
466
  return launched.error.code === "exists" ? this.#createOnce(spec, name, signal, launched) : launched;
398
467
  const { ref, made } = launched.value;
468
+ this.#keepAlive(ref);
399
469
  // From here the machine exists: every step takes the caller's signal, and a failure or an abort deletes it.
400
470
  // Another provider instance's create of this request may have made one too (#converge): the oldest is kept.
401
471
  const first = await this.#converge(name, ref.id, signal);
@@ -469,7 +539,11 @@ export class HostedProvider {
469
539
  const deadline = deadlineOf(machine);
470
540
  if (deadline !== undefined && deadline.getTime() <= Date.now())
471
541
  return this.#fail("exists", endedWords(name));
472
- if (machine.state === "running") {
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) {
473
547
  const differ = this.#labelDiffer(spec, name, machine.labels, "read back");
474
548
  if (differ.length > 0)
475
549
  return this.#fail("exists", otherSpecWords(name, "was made", differ));
@@ -564,6 +638,7 @@ export class HostedProvider {
564
638
  image: spec.image,
565
639
  labels,
566
640
  lifetimeMs,
641
+ backstopAt: new Date(now + this.#maxLifetimeMs + BACKSTOP_MARGIN_MS).toISOString(),
567
642
  // The machine has egress where its tools' network is open or a list, which init's proxy holds to the public
568
643
  // internet (./network.ts), and where an Archil computer's root reaches Archil. Its tools' none is init's own
569
644
  // either way, read back by the probe from inside, as the tool user.
@@ -611,48 +686,101 @@ export class HostedProvider {
611
686
  * Every machine carrying a name create gave, deleted and read back gone: for a create that may have made one whose
612
687
  * id never came (mayHaveMade), never after a refusal, where a machine under the name is another's. The
613
688
  * listing shows a new machine a moment after the vendor makes it, so it is read for the name until one shows or
614
- * listedMs passes. Best effort, in words.
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.
615
691
  */
616
692
  async #deleteNamed(name) {
617
693
  const { listedMs, pollMs } = this.#timeouts;
618
694
  const until = Date.now() + listedMs;
619
- let found;
620
- for (;;) {
695
+ let named;
696
+ for (let delay = Math.min(LISTED_POLL_MS, pollMs);; delay = Math.min(delay * 2, pollMs)) {
621
697
  const listed = await foundBy(this.host, "the listing by name", byName(name), this.#timeouts);
622
698
  if (!listed.ok)
623
699
  return `; a machine named ${name} may be left (${listed.error.message}), which ends at its deadline`;
624
- found = listed.value.filter((machine) => ours(machine.labels, name));
625
- if (found.length > 0 || Date.now() >= until)
700
+ named = listed.value.filter((machine) => ours(machine.labels, name) || this.#unfiled(machine, name) !== undefined);
701
+ if (named.length > 0 || Date.now() >= until)
626
702
  break;
627
- await pause(Math.min(LISTED_POLL_MS, pollMs));
703
+ await pause(Math.min(delay, until - Date.now()));
628
704
  }
629
- if (found.length === 0)
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)
630
709
  return `; no machine named ${name} was listed within ${seconds(listedMs)}, and any it made ends at its deadline`;
710
+ if (found.length === 0)
711
+ return left;
631
712
  const said = [];
632
713
  for (const machine of found) {
633
714
  const { gone } = await this.#remove({ id: machine.id, name }, undefined);
634
715
  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`);
635
716
  }
636
- return `; the machine named ${name} it made: ${said.join("; ")}`;
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);
637
756
  }
638
757
  /** The host's delete, never signalled: a delete that cleans up after an abort must outlive it. Not found is done. */
639
758
  async #kill(id) {
759
+ this.#unkeep(id);
640
760
  const killed = await this.#call(`the delete of ${id}`, (ctx) => this.host.delete(id, ctx), this.#timeouts.requestMs);
641
- return killed.ok || killed.error.code === "not_found" ? ok(undefined) : killed;
761
+ if (!killed.ok && killed.error.code !== "not_found")
762
+ return killed;
763
+ filedOf(this.host).delete(id);
764
+ return ok(undefined);
642
765
  }
643
766
  /** The pause between two reads of a machine that is starting: the next read comes after it, within createMs. */
644
767
  #startPollMs() {
645
768
  return Math.min(START_POLL_MS, this.#timeouts.pollMs * 10);
646
769
  }
647
- /** The host's get, bounded by requestMs; a machine the vendor reports as not found is none. */
648
- #get(id, signal) {
649
- return readMachine(this.host, id, this.#timeouts.requestMs, signal);
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;
650
777
  }
651
778
  /** The machine running, read while it starts (within createMs); gone or failed is refused in words. */
652
779
  async #running(ref, signal) {
653
780
  const until = Date.now() + this.#timeouts.createMs;
654
781
  for (;;) {
655
- const read = await this.#get(ref.id, signal);
782
+ // Its labels are read after this, as written (#prepare).
783
+ const read = await readMachine(this.host, ref.id, this.#timeouts.requestMs, signal);
656
784
  if (!read.ok)
657
785
  return read;
658
786
  const machine = read.value;
@@ -692,7 +820,11 @@ export class HostedProvider {
692
820
  const running = await this.#running(ref, signal);
693
821
  if (!running.ok)
694
822
  return running;
695
- const drift = this.#machineDrift(running.value, labels);
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);
696
828
  if (drift.length > 0)
697
829
  return this.#fail("refused", `it did not match its spec: ${drift.join("; ")}`);
698
830
  // Before anything of this create's is in the machine: what root runs is root's alone (the Archil helper's sha256,
@@ -941,12 +1073,13 @@ export class HostedProvider {
941
1073
  /**
942
1074
  * Create waits until the listing shows the new computer on two consecutive polls at least listedStableMs apart (and on
943
1075
  * every poll between), so list() shows it once create returns: a listing that showed it once and then not starts over.
1076
+ * The polls are 150 ms apart at first, the pause doubling up to pollMs, so a vendor slow to list costs a few calls.
944
1077
  */
945
1078
  async #waitListed(ref, signal) {
946
1079
  const { listedMs, listMs, pollMs, listedStableMs } = this.#timeouts;
947
1080
  const until = Date.now() + listedMs;
948
1081
  let since;
949
- for (let hits = 0;;) {
1082
+ for (let hits = 0, delay = Math.min(LISTED_POLL_MS, pollMs);; delay = Math.min(delay * 2, pollMs)) {
950
1083
  const listed = await listedBy(this.host, "the listing by name", byName(ref.name), listMs, signal);
951
1084
  if (!listed.ok)
952
1085
  return listed;
@@ -960,14 +1093,14 @@ export class HostedProvider {
960
1093
  return ok(undefined);
961
1094
  if (Date.now() >= until)
962
1095
  return this.#fail("timeout", `the computer was not listed within ${seconds(listedMs)} of its creation`);
963
- await pause(Math.min(LISTED_POLL_MS, LISTED_POLL_MAX_MS, pollMs), signal);
1096
+ await pause(Math.min(delay, until - Date.now()), signal);
964
1097
  if (signal?.aborted)
965
1098
  return this.#fail("aborted", "create was aborted while it waited for the listing");
966
1099
  }
967
1100
  }
968
1101
  /** This provider's machine for ref, as the vendor reads it, or why not. */
969
- async #own(ref, signal) {
970
- const found = await this.#get(ref.id, signal);
1102
+ async #own(ref, signal, fresh = false) {
1103
+ const found = await this.#get(ref.id, signal, fresh);
971
1104
  if (!found.ok)
972
1105
  return found;
973
1106
  if (found.value === undefined)
@@ -1095,6 +1228,7 @@ export class HostedProvider {
1095
1228
  found.push(`mount: ${name} is ${machine.state}, so its mount cannot be read back from inside`);
1096
1229
  if (found.length > 0)
1097
1230
  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);
1098
1232
  return ok({
1099
1233
  ...ref,
1100
1234
  spec: {
@@ -1116,7 +1250,9 @@ export class HostedProvider {
1116
1250
  */
1117
1251
  async testConnection({ signal } = {}) {
1118
1252
  const listed = await listedBy(this.host, "the listing", { [COMPUTER_LABEL]: "1" }, this.#timeouts.listMs, signal);
1119
- return countTested(this.#label, listed.ok ? ok({ count: listed.value.filter((machine) => ours(machine.labels) && alive(machine.state)).length }) : listed);
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);
1255
+ return countTested(this.#label, listed.ok ? ok({ count: listed.value.filter(counted).length }) : listed);
1120
1256
  }
1121
1257
  /**
1122
1258
  * Every computer this provider made that carries all of these labels, running or stopped: the listing finds them, and
@@ -1210,11 +1346,12 @@ export class HostedProvider {
1210
1346
  }
1211
1347
  /**
1212
1348
  * Moves the deadline to now + ttlMs, refusing one earlier than it is (before any vendor call), never past create's time
1213
- * plus the cap (init's maximum): the host's extend first (its timer or its deadline label), then the end it reads back
1214
- * (get, deadlineOf), then init's own deadline, to that end. The deadline returned is the one init took.
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.
1215
1351
  */
1216
1352
  async #extend(ref, ttlMs, signal) {
1217
- const found = await this.#own(ref, 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);
1218
1355
  if (!found.ok)
1219
1356
  return found;
1220
1357
  const machine = found.value;
@@ -1240,6 +1377,11 @@ export class HostedProvider {
1240
1377
  const moved = await this.#call(`${this.#label}'s end of ${ref.name}`, (ctx) => extend(ref.id, new Date(target), ctx), this.#timeouts.requestMs, signal);
1241
1378
  if (!moved.ok)
1242
1379
  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
+ }
1243
1385
  const after = await this.#get(ref.id, signal);
1244
1386
  const end = after.ok && after.value !== undefined ? deadlineOf(after.value) : undefined;
1245
1387
  if (end === undefined) {
@@ -1285,8 +1427,10 @@ export class HostedProvider {
1285
1427
  const found = await this.#get(ref.id);
1286
1428
  if (!found.ok)
1287
1429
  return found;
1288
- if (found.value === undefined)
1430
+ if (found.value === undefined) {
1431
+ this.#unkeep(ref.id);
1289
1432
  return ok(undefined);
1433
+ }
1290
1434
  if (!ours(found.value.labels, ref.name))
1291
1435
  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`);
1292
1436
  this.#end(ref.name);
@@ -1331,29 +1475,82 @@ export class HostedProvider {
1331
1475
  const byName = (name) => ({ [COMPUTER_LABEL]: "1", [NAME_LABEL]: name });
1332
1476
  /**
1333
1477
  * The host's listing by labels, bounded by ms: only the machines that carry every one of them, since a vendor's listing
1334
- * may answer more (MachineHost.list).
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.
1335
1480
  */
1336
1481
  export async function listedBy(host, what, labels, ms, signal) {
1337
1482
  const listed = await hostCall(host, what, (ctx) => host.list(labels, ctx), ms, signal);
1338
- return listed.ok ? ok(listed.value.filter((machine) => carries(machine, labels))) : listed;
1483
+ 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 } });
1339
1529
  }
1340
1530
  /** Whether a machine carries every one of these labels. */
1341
1531
  const carries = (machine, labels) => Object.entries(labels).every(([key, value]) => machine.labels?.[key] === value);
1342
1532
  /**
1343
1533
  * The listing finds, get answers (MachineHost.list): the machines the host's listing by labels names, each read now by
1344
- * readMachine, within requestMs. One the vendor no longer has (not found) is dropped, and so is one whose get carries
1345
- * not every label. A read that fails otherwise fails the whole.
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.
1346
1537
  */
1347
1538
  export async function foundBy(host, what, labels, { listMs, requestMs }, signal) {
1348
1539
  const listed = await listedBy(host, what, labels, listMs, signal);
1349
1540
  if (!listed.ok)
1350
1541
  return listed;
1351
- const reads = await Promise.all(listed.value.map(({ id }) => readMachine(host, id, requestMs, signal)));
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;
1352
1549
  const found = [];
1353
1550
  for (const read of reads) {
1354
1551
  if (!read.ok)
1355
1552
  return read;
1356
- if (read.value !== undefined && carries(read.value, labels))
1553
+ if (read.value !== undefined && (carries(read.value, labels) || unfiled(read.value)))
1357
1554
  found.push(read.value);
1358
1555
  }
1359
1556
  return ok(found);
@@ -53,11 +53,21 @@ export interface RestOptions {
53
53
  }
54
54
  /** The JSON a body holds; null for none or for text that is not JSON. */
55
55
  export declare function jsonOf(bytes: Uint8Array): unknown;
56
+ /** An accepted answer whose body is read as it comes: an event stream. */
57
+ export interface RestStream {
58
+ status: number;
59
+ body: AsyncIterable<Uint8Array>;
60
+ }
56
61
  export interface Rest {
57
62
  url(path: string): string;
58
63
  call(method: string, url: string, init?: RestInit, signal?: AbortSignal): Promise<Result<RestAnswer>>;
59
64
  /** call, with the body read as JSON (null for none). */
60
65
  json(method: string, url: string, init?: RestInit, signal?: AbortSignal): Promise<Result<unknown>>;
66
+ /**
67
+ * call, with an accepted answer's body handed back unread, as it comes (a process's events). The bound covers the
68
+ * answer's start alone: the body has none but the caller's signal, which ends it too.
69
+ */
70
+ stream(method: string, url: string, init?: RestInit, signal?: AbortSignal): Promise<Result<RestStream>>;
61
71
  }
62
72
  export declare function rest(options: RestOptions): Rest;
63
73
  /**
@@ -40,11 +40,13 @@ function redirected(cause) {
40
40
  const inner = cause?.cause;
41
41
  return /redirect/i.test(`${cause?.message ?? ""} ${inner?.message ?? ""}`);
42
42
  }
43
+ const NO_BODY = { async *[Symbol.asyncIterator]() { } };
43
44
  export function rest(options) {
44
45
  const base = options.base.replace(/\/+$/, "");
45
46
  const fetcher = options.fetch ?? fetch;
46
47
  const wait = options.retry?.pause ?? pause;
47
- async function call(method, url, init = {}, signal) {
48
+ /** One call, sent again as init.retry says; an accepted answer is what take makes of it, within the call's bound. */
49
+ async function exchange(method, url, init, signal, take) {
48
50
  const what = `${method} ${new URL(url).pathname}`;
49
51
  const attempts = init.retry === undefined || init.retry === false || options.retry === undefined ? 1 : options.retry.attempts;
50
52
  const timeoutMs = init.timeoutMs ?? options.timeoutMs;
@@ -52,7 +54,9 @@ export function rest(options) {
52
54
  for (let attempt = 1;; attempt++) {
53
55
  if (signal?.aborted)
54
56
  return fail("aborted", `${what} was aborted`);
55
- const timeout = AbortSignal.timeout(timeoutMs);
57
+ // A bound that lets go once the answer is taken, so a body read after it (a stream's) is never cut by it.
58
+ const timeout = new AbortController();
59
+ const timer = setTimeout(() => timeout.abort(), timeoutMs);
56
60
  let failure;
57
61
  let retryable;
58
62
  try {
@@ -63,11 +67,11 @@ export function rest(options) {
63
67
  headers,
64
68
  body: init.json === undefined ? init.form : JSON.stringify(init.json),
65
69
  redirect: "error",
66
- signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
70
+ signal: signal ? AbortSignal.any([signal, timeout.signal]) : timeout.signal,
67
71
  });
68
- const bytes = new Uint8Array(await response.arrayBuffer());
69
72
  if (accepted(response.status))
70
- return ok({ status: response.status, bytes });
73
+ return ok(await take(response));
74
+ const bytes = new Uint8Array(await response.arrayBuffer());
71
75
  const own = typeof init.retry === "function";
72
76
  retryable = own ? init.retry(response.status, bytes) : init.retry === true && (response.status === 429 || response.status >= 500);
73
77
  const text = decoder.decode(bytes).replace(/\s+/g, " ").slice(0, 300);
@@ -79,18 +83,22 @@ export function rest(options) {
79
83
  return fail("aborted", `${what} was aborted`);
80
84
  // No answer: the request may have reached the vendor, so only a call that may run twice is sent again.
81
85
  retryable = init.retry === true;
82
- if (timeout.aborted)
86
+ if (timeout.signal.aborted)
83
87
  failure = { code: "timeout", message: `${what} did not answer within ${timeoutMs / 1000} s` };
84
88
  else if (redirected(cause))
85
89
  return vendorFail(options.vendor, `${what}: the API answered with a redirect, which is never followed: it would carry the key`);
86
90
  else
87
91
  failure = { code: "vendor", vendor: options.vendor, message: `${what}: ${cause.message}` };
88
92
  }
93
+ finally {
94
+ clearTimeout(timer);
95
+ }
89
96
  if (!retryable || attempt >= attempts)
90
97
  return { ok: false, error: failure };
91
98
  await wait((options.retry?.baseMs ?? 0) * 2 ** (attempt - 1), signal);
92
99
  }
93
100
  }
101
+ const call = (method, url, init = {}, signal) => exchange(method, url, init, signal, async (response) => ({ status: response.status, bytes: new Uint8Array(await response.arrayBuffer()) }));
94
102
  return {
95
103
  url: (path) => `${base}${path}`,
96
104
  call,
@@ -98,6 +106,7 @@ export function rest(options) {
98
106
  const answer = await call(method, url, init, signal);
99
107
  return answer.ok ? ok(jsonOf(answer.value.bytes)) : answer;
100
108
  },
109
+ stream: (method, url, init = {}, signal) => exchange(method, url, init, signal, async (response) => ({ status: response.status, body: response.body ?? NO_BODY })),
101
110
  };
102
111
  }
103
112
  /**
@@ -16,6 +16,14 @@ export declare const INIT_LOG = "/run/agentrun-init.log";
16
16
  export declare const SESSION_BUSES: readonly string[];
17
17
  /** The sockets the sockets script closed, from its `closed <path>` lines. */
18
18
  export declare function closedSocketsOf(output: string): string[];
19
+ /**
20
+ * Where a machine of a host that keeps no labels (HostFacts.labels "machine") holds its label map, as JSON. Under
21
+ * /var/lib, on the machine's disk, so it outlives a restart: /run is a tmpfs, and /run/agentrun is the daemon user's.
22
+ * In a directory root's alone (0700), so the computer's user can neither read nor change it.
23
+ */
24
+ export declare const LABEL_FILE = "/var/lib/agentrun/labels.json";
25
+ /** The label file's read, or given the byte length of the JSON on stdin, its write and then its read. */
26
+ export declare const labelsCommand: (bytes?: number) => string[];
19
27
  /**
20
28
  * Where a pid1 Archil computer's entrypoint waits for root's word that the run's folder is mounted: beside the daemon,
21
29
  * in the directory install makes root's alone before root makes the gate, so no other user can make it early. (A path
@@ -142,6 +142,28 @@ export function closedSocketsOf(output) {
142
142
  }
143
143
  /** The last words init wrote to its log, as root; nothing when it wrote none. */
144
144
  const LOG_SCRIPT = ["# agentrun-computer: log", "l=$1", ROOT, '$p tail -c 2000 "$l" 2>/dev/null || true'].join("\n");
145
+ /**
146
+ * Where a machine of a host that keeps no labels (HostFacts.labels "machine") holds its label map, as JSON. Under
147
+ * /var/lib, on the machine's disk, so it outlives a restart: /run is a tmpfs, and /run/agentrun is the daemon user's.
148
+ * In a directory root's alone (0700), so the computer's user can neither read nor change it.
149
+ */
150
+ export const LABEL_FILE = "/var/lib/agentrun/labels.json";
151
+ /**
152
+ * The label file, as root. With write <bytes>, that many bytes of stdin replace it, read by length so no end of stdin
153
+ * is needed: written to a file of its own beside it (two writers never share one) and renamed in, 0600 in a 0700
154
+ * directory, both root's. Then it prints the file; exit 3 when there is none.
155
+ */
156
+ const LABELS_SCRIPT = [
157
+ "# agentrun-computer: labels",
158
+ "f=$1",
159
+ ROOT,
160
+ 'if [ "${2-}" = write ]; then',
161
+ `\t$p sh -c 'umask 077; d=\${0%/*}; mkdir -p "$d" && chown 0:0 "$d" && chmod 700 "$d" && t=$(mktemp "$0.XXXXXX") || exit 5; head -c "$1" >"$t" && [ "$(wc -c <"$t")" -eq "$1" ] && mv -f "$t" "$0" || { rm -f "$t"; exit 5; }' "$f" "$3" || exit 5`,
162
+ "fi",
163
+ `exec $p sh -c '[ -e "$0" ] || exit 3; exec cat "$0"' "$f"`,
164
+ ].join("\n");
165
+ /** The label file's read, or given the byte length of the JSON on stdin, its write and then its read. */
166
+ export const labelsCommand = (bytes) => argvOf(LABELS_SCRIPT, [LABEL_FILE, ...(bytes === undefined ? [] : ["write", String(bytes)])]);
145
167
  /**
146
168
  * A pid1 machine's main process: waits, bounded, for the daemon this create installed to be moved into place executable
147
169
  * (the marker beside it, `<daemon>.installed`, holds this create's nonce: a daemon the image had at the path, or one an
@@ -17,7 +17,7 @@ export declare const PACKED_NAME = "agentrun";
17
17
  * host of a string list stores each as name=value. unpackLabels reads the map back exactly. A map that does not fit
18
18
  * room (count, bytes and valueBytes, of the packed labels), or whose JSON is past PACKED_JSON_MAX, is refused in words.
19
19
  */
20
- export declare function packLabels(labels: Record<string, string>, name: string, room?: HostFacts["labels"]): {
20
+ export declare function packLabels(labels: Record<string, string>, name: string, room?: Exclude<HostFacts["labels"], "machine">): {
21
21
  labels: Record<string, string>;
22
22
  } | {
23
23
  problem: string;