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

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 (57) hide show
  1. package/README.md +56 -21
  2. package/box/Dockerfile +11 -58
  3. package/box/README.md +15 -2
  4. package/box/build-daytona.py +4 -2
  5. package/box/build-e2b.mjs +1 -1
  6. package/box/install.sh +148 -0
  7. package/box/recipe.mjs +12 -10
  8. package/dist/agent37.js +2 -1
  9. package/dist/attach.d.ts +46 -1
  10. package/dist/attach.js +48 -4
  11. package/dist/box-image.d.ts +2 -0
  12. package/dist/box-image.js +10 -0
  13. package/dist/computerd-linux-amd64 +0 -0
  14. package/dist/computerd-linux-arm64 +0 -0
  15. package/dist/computerd.json +2 -2
  16. package/dist/conformance/cases/isolation.js +17 -1
  17. package/dist/conformance/cases/lifetime.js +30 -0
  18. package/dist/conformance/cases/provider.js +63 -1
  19. package/dist/conformance/cli.js +27 -5
  20. package/dist/conformance/daytona.d.ts +25 -0
  21. package/dist/conformance/daytona.js +26 -1
  22. package/dist/conformance/exec-stream.d.ts +37 -7
  23. package/dist/conformance/exec-stream.js +349 -89
  24. package/dist/conformance/report.js +3 -0
  25. package/dist/conformance/runner.js +134 -12
  26. package/dist/conformance/sweep.d.ts +7 -2
  27. package/dist/conformance/sweep.js +17 -7
  28. package/dist/conformance/types.d.ts +42 -0
  29. package/dist/daytona.d.ts +8 -1
  30. package/dist/daytona.js +126 -101
  31. package/dist/descriptor.d.ts +22 -1
  32. package/dist/descriptor.js +18 -0
  33. package/dist/descriptors/daytona.d.ts +12 -3
  34. package/dist/descriptors/daytona.js +15 -7
  35. package/dist/descriptors/index.d.ts +8 -1
  36. package/dist/e2b.js +1 -1
  37. package/dist/host.d.ts +91 -26
  38. package/dist/host.js +5 -0
  39. package/dist/hosted/framed-exec.d.ts +38 -0
  40. package/dist/hosted/framed-exec.js +119 -0
  41. package/dist/hosted/process.d.ts +13 -5
  42. package/dist/hosted/process.js +39 -14
  43. package/dist/hosted/provider.d.ts +48 -6
  44. package/dist/hosted/provider.js +435 -64
  45. package/dist/hosted/rest.d.ts +29 -0
  46. package/dist/hosted/rest.js +91 -6
  47. package/dist/hosted/scripts.d.ts +58 -0
  48. package/dist/hosted/scripts.js +138 -1
  49. package/dist/hosted/ssh-exec.d.ts +7 -6
  50. package/dist/hosted/ssh-exec.js +35 -52
  51. package/dist/hosted/values.d.ts +1 -1
  52. package/dist/index.d.ts +2 -2
  53. package/dist/index.js +2 -2
  54. package/dist/kinds.d.ts +2 -0
  55. package/dist/modal.js +21 -8
  56. package/dist/providers.d.ts +4 -2
  57. package/package.json +1 -1
@@ -1,22 +1,32 @@
1
1
  // The exec pre-check: the one thing a new vendor proves before writing anything else of its host. AgentRun installs its
2
2
  // daemon through MachineHost.exec and then talks to it over that one process's stdin and stdout for the computer's whole
3
- // life, so exec must be a live, two-way, byte-exact stream with no timeout (the contract is exec's doc comment in
4
- // ../host.ts). This runs exec alone, on a machine the vendor made by hand, and says in plain words what it did wrong:
3
+ // life, so exec must be a live, two-way stream that keeps UTF-8 text intact, with no timeout (the contract is exec's doc
4
+ // comment in ../host.ts). This runs exec alone, on a machine the vendor made by hand, and says in plain words what it
5
+ // did wrong:
5
6
  //
6
7
  // npm run conformance -w @parcha/agentrun-computer -- --provider <id | ./module.js> --exec-stream --machine <id> [--quick]
7
8
  //
8
9
  // It calls nothing but host.exec, so a host whose other members are still stubs can run it. Each check starts its own
9
- // process and kills it when it is done with it, pass or fail.
10
+ // process and kills it when it is done with it, pass or fail. No check ends stdin: the adapter never needs a vendor's
11
+ // end of file, so one with none passes. After the checks, one more exec reads what the machine offers the rest of the
12
+ // host (root's network namespace, /dev/fuse, the arch, the kernel, the TCP listeners): facts, each with what it means
13
+ // for the provider, never a pass or a fail of exec.
10
14
  import { createHash, randomBytes } from "node:crypto";
11
- import { words } from "../hosted/process.js";
15
+ import { execOf, words } from "../hosted/process.js";
12
16
  /** The checks, in the order they run. */
13
- export const EXEC_STREAM_CHECKS = ["stdout-bytes", "stdin-bytes", "large", "stdout-live", "stdin-live", "stderr", "exit-code", "kill", "no-timeout"];
17
+ export const EXEC_STREAM_CHECKS = ["stdout-text", "stdin-text", "large", "stdout-live", "stdin-live", "stdout-unread", "stderr", "exit-code", "kill", "no-timeout"];
18
+ /** What the capability probe reads, in the order the report gives it. */
19
+ export const EXEC_STREAM_FACTS = ["root", "netns", "fuse", "arch", "kernel", "listeners"];
14
20
  export const DEFAULT_LONG_MS = 75_000;
15
21
  /** --quick's no-timeout check: long enough to cross a second, short enough for CI. */
16
22
  export const QUICK_LONG_MS = 5_000;
17
23
  const DEFAULT_STEP_MS = 30_000;
18
24
  const DEFAULT_LARGE_BYTES = 8 * 1024 * 1024;
19
25
  const DEFAULT_LARGE_MS = 180_000;
26
+ const DEFAULT_UNREAD_MS = 10_000;
27
+ /** stdout-unread's writes: this many, of UNREAD_CHUNK bytes each, spread over unreadMs; 4 MiB, far past a 64 KiB window. */
28
+ const UNREAD_WRITES = 64;
29
+ const UNREAD_CHUNK = 64 * 1024;
20
30
  /** What one write gives exec's stdin, as the adapter's own upload does (runToExit). */
21
31
  const WRITE_CHUNK = 256 * 1024;
22
32
  /** How long stdout-live watches, after "early", that stdout stays open and wait() has no answer. */
@@ -32,42 +42,100 @@ export const PID_STATE_SCRIPT = 'st=$(sed -n "s/^State:[[:space:]]*\\([A-Z]\\).*
32
42
  class Problem extends Error {
33
43
  }
34
44
  const hex = (bytes) => [...bytes].map((b) => b.toString(16).padStart(2, "0")).join(" ");
35
- const byte = (b) => `0x${b.toString(16).padStart(2, "0")}`;
36
45
  const secondsOf = (ms) => `${Math.round(ms / 100) / 10} s`;
37
46
  const shown = (argv) => argv.map((word) => (/^[\w./=:-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`)).join(" ");
38
- const ALL_BYTES = Uint8Array.from({ length: 256 }, (_, i) => i);
39
- /** printf's format for every byte value, 0 to 255, each as an octal escape: dash, bash and busybox all read it. */
40
- const PRINTF_ALL = [...ALL_BYTES].map((b) => `\\${b.toString(8).padStart(3, "0")}`).join("");
47
+ const range = (from, to) => String.fromCodePoint(...Array.from({ length: to - from + 1 }, (_, i) => from + i));
41
48
  /**
42
- * Why `got` is not `sent`, in words, or undefined when they are the same bytes. `way` is where they went ("on stdout");
43
- * the first byte that differs is named, and the usual ways an exec mangles bytes are named for what they are.
49
+ * A BOM first, which a TextDecoder drops from the start of a stream unless told to keep it (ignoreBOM). Then one of
50
+ * each class of code point: all of ASCII but NUL (no text the adapter carries holds one: JSON escapes it), all of
51
+ * Latin-1, the BMP's scripts and its odd ones (the line and paragraph separators, a BOM, U+FFFD), astral ones, and
52
+ * combining marks and a joined emoji, which a normalizer would change. Then \r alone and \r\n, which a terminal changes.
44
53
  */
45
- export function bytesProblem(sent, got, way) }ĀſΩЖאعह中文日本語한국어€

�𝄞😀\u{
54
+ const CODE_POINTS = `\u{feff}${range(0x01, 0x7f)}${range(0x80, 0xff)}ĀſΩЖאعह中文日本語한국어€

�𝄞😀\u{10ffff}éä\u{1f469}‍\u{1f4bb}carriage\rreturn\r\nline`;
55
+ /** 16 KiB of text of every width (1, 2, 3 and 4 bytes a character), no newline: 64 of them are the 1 MiB line. */
56
+ const LONG_UNIT = "aé€𝄞";
57
+ const LONG_UNITS = 1638;
58
+ /** ASCII, so the script writes it as it is. */
59
+ const LONG_TAIL = "abcd";
60
+ const LONG_PIECE = `${LONG_UNIT.repeat(LONG_UNITS)}${LONG_TAIL}`;
61
+ const LONG_PIECES = 64;
62
+ /** What stdout-text and stdin-text carry: every class of code point, \r and \r\n, a line of 1 MiB, and a lone \n at the end. */
63
+ const TEXT = Buffer.from(`${CODE_POINTS}${LONG_PIECE.repeat(LONG_PIECES)}\n`, "utf8");
64
+ /**
65
+ * length bytes of random UTF-8 text: characters of 1, 2, 3 and 4 bytes at random, any code point of each width but NUL
66
+ * and the surrogates (which are no text).
67
+ */
68
+ export function randomText(length) {
69
+ const text = Buffer.alloc(length);
70
+ const random = randomBytes(4 * length);
71
+ let r = 0;
72
+ const next = (bytes) => {
73
+ let value = 0;
74
+ for (let i = 0; i < bytes; i++)
75
+ value = value * 256 + random[r++];
76
+ return value;
77
+ };
78
+ for (let at = 0; at < length;) {
79
+ const width = Math.min(length - at, 1 + (next(1) & 3));
80
+ if (width === 1)
81
+ text[at] = 1 + (next(1) % 0x7f);
82
+ else if (width === 2)
83
+ text.write(String.fromCodePoint(0x80 + (next(2) % 0x780)), at, "utf8");
84
+ else if (width === 3) {
85
+ const point = 0x800 + (next(2) % 0xf000);
86
+ text.write(String.fromCodePoint(point >= 0xd800 ? point + 0x800 : point), at, "utf8");
87
+ }
88
+ else
89
+ text.write(String.fromCodePoint(0x10000 + (next(3) % 0x100000)), at, "utf8");
90
+ at += width;
91
+ }
92
+ return text;
93
+ }
94
+ /** printf's format for text: each of its UTF-8 bytes as an octal escape, which dash, bash and busybox all read. */
95
+ const printfOf = (text) => [...Buffer.from(text, "utf8")].map((b) => `\\${b.toString(8).padStart(3, "0")}`).join("");
96
+ /** The code point of the character the byte at i is part of, as U+XXXX, and where that character starts. */
97
+ function characterAt(bytes, i) {
98
+ let start = i;
99
+ while (start > 0 && (bytes[start] & 0xc0) === 0x80)
100
+ start--;
101
+ const point = Buffer.from(bytes.subarray(start, start + 4)).toString("utf8").codePointAt(0) ?? 0;
102
+ return { name: `U+${point.toString(16).toUpperCase().padStart(4, "0")}`, start };
103
+ }
104
+ /**
105
+ * Why `got` is not `sent`, in words, or undefined when they are the same text. Both are UTF-8; `way` is where it went
106
+ * ("on stdout"). The first character that differs is named, and the usual ways an exec changes text are named for what
107
+ * they are.
108
+ */
109
+ export function textProblem(sent, got, way) {
46
110
  let i = 0;
47
111
  while (i < sent.length && i < got.length && sent[i] === got[i])
48
112
  i++;
49
113
  if (i === sent.length && i === got.length)
50
114
  return undefined;
51
- if (i === got.length) {
52
- const nul = sent[i] === 0 ? ": the first missing byte is 0x00, so your exec may treat output as C strings and stop at a NUL" : "";
53
- return `only ${got.length} of ${sent.length} bytes came back ${way}${nul}. Pass every byte on as it comes`;
54
- }
115
+ if (i === got.length)
116
+ return `only ${got.length} of ${sent.length} bytes of text came back ${way}. Pass every character on as it comes`;
55
117
  if (i === sent.length)
56
- return `${got.length - sent.length} bytes came back ${way} that were never sent, after all ${sent.length} that were (${hex(got.subarray(i, i + 8))}): your exec adds output of its own (a shell's login banner, a prompt). Pass only the process's own bytes`;
57
- const b = sent[i];
58
- const at = got.subarray(i, i + 3);
59
- const was = `byte ${byte(b)} came back ${way} as ${hex(at)}`;
60
- if (b >= 0x80 && at[0] === 0xef && at[1] === 0xbf && at[2] === 0xbd) {
61
- return `${was}: your exec decodes UTF-8, which turns each byte that is not UTF-8 into U+FFFD (ef bf bd). Pass the bytes on as bytes, never as text`;
118
+ return `${got.length - sent.length} bytes came back ${way} that were never sent, after all ${sent.length} that were (${hex(got.subarray(i, i + 8))}): your exec adds output of its own (a shell's login banner, a prompt). Pass only the process's own output`;
119
+ const { name, start } = characterAt(sent, i);
120
+ const was = got.subarray(start, start + 4);
121
+ const said = `${name} (at byte ${start}) came back ${way} as ${hex(was)}`;
122
+ const b = sent[start];
123
+ if (b === 0x0a && was[0] === 0x0d && was[1] === 0x0a)
124
+ return `${said}: your exec turns \\n into \\r\\n, as a terminal does. Run the process on pipes, not a terminal`;
125
+ if (b === 0x0d && was[0] === 0x0a)
126
+ return `${said}: your exec turns \\r into \\n, as newline translation does. Pass every character on as it comes`;
127
+ if (b === 0x0d)
128
+ return `${said}: your exec drops \\r, as newline translation does. Pass every character on as it comes`;
129
+ if (b >= 0x80 && was[0] === (0xc0 | (b >> 6)) && was[1] === (0x80 | (b & 0x3f))) {
130
+ return `${said}: your exec reads UTF-8 as Latin-1 and writes it back as UTF-8 again. Read the process's output as UTF-8`;
62
131
  }
63
- if (b >= 0x80 && at[0] === (0xc0 | (b >> 6)) && at[1] === (0x80 | (b & 0x3f))) {
64
- return `${was}: your exec reads bytes as Latin-1 text and writes them back as UTF-8. Pass the bytes on as bytes, never as text`;
132
+ if (name === "U+FEFF" && Buffer.from(got.subarray(start, start + 8)).equals(Buffer.from(sent.subarray(start + 3, start + 11)))) {
133
+ return `${said}: your exec drops a U+FEFF that starts its text, as a TextDecoder does unless given ignoreBOM: true. Keep it: it is text like any other`;
65
134
  }
66
- if (b === 0x0a && at[0] === 0x0d && at[1] === 0x0a)
67
- return `${was}: your exec turns \\n into \\r\\n, as a terminal does. Run the process on pipes, not a terminal`;
68
- if (b === 0x0d && at[0] === 0x0a)
69
- return `${was}: your exec drops \\r, as newline translation does. Pass every byte on as it comes`;
70
- return `${was} (offset ${i}): your exec changes bytes. Pass every byte on as it comes, unchanged`;
135
+ if (was[0] === 0xef && was[1] === 0xbf && was[2] === 0xbd) {
136
+ return `${said}: U+FFFD (ef bf bd), as a decoder makes of half a character: your exec decodes each piece of output as text on its own. Decode the stream as one (TextDecoder's stream: true)`;
137
+ }
138
+ return `${said}: your exec changes text (a terminal, a normalizer, an escape filter). Pass every character on as it comes, unchanged`;
71
139
  }
72
140
  /** One output stream of a process, read as it comes: its bytes so far, whether it ended, and a wait for more. */
73
141
  class Reader {
@@ -76,10 +144,12 @@ class Reader {
76
144
  ended = false;
77
145
  error;
78
146
  #wake = [];
79
- constructor(stream) {
80
- void this.#pump(stream);
147
+ /** Reads the stream as it comes; with `from`, not a byte until it settles: the stream is left unread until then. */
148
+ constructor(stream, from) {
149
+ void this.#pump(stream, from);
81
150
  }
82
- async #pump(stream) {
151
+ async #pump(stream, from) {
152
+ await from;
83
153
  try {
84
154
  for await (const chunk of stream) {
85
155
  // A copy: a vendor's client may reuse its buffer.
@@ -144,6 +214,8 @@ function within(promise, ms, late, signal) {
144
214
  });
145
215
  }
146
216
  const LATE = Symbol("late");
217
+ /** Waits ms, or less when signal aborts. */
218
+ const pause = (ms, signal) => within(new Promise(() => { }), Math.max(0, ms), undefined, signal);
147
219
  /** The pre-check's run of host.exec on one machine. */
148
220
  class Session {
149
221
  #host;
@@ -165,13 +237,13 @@ class Session {
165
237
  }
166
238
  /**
167
239
  * exec(argv), answered within the step's bound; any failure (a throw) is a Problem naming the command. Without stdin,
168
- * end() is called at once, as the adapter does.
240
+ * end() is called at once, as the adapter does. With `readFrom`, stdout is left unread until it settles.
169
241
  */
170
- async start(argv, stdin) {
242
+ async start(argv, stdin, readFrom) {
171
243
  const what = `exec of ${shown(argv)}`;
172
244
  let answer;
173
245
  try {
174
- answer = Promise.resolve(this.#host.exec(this.#machine, argv, { timeoutMs: this.#stepMs, ...(this.#signal ? { signal: this.#signal } : {}) }));
246
+ answer = Promise.resolve(execOf(this.#host)(this.#machine, argv, { timeoutMs: this.#stepMs, ...(this.#signal ? { signal: this.#signal } : {}) }));
175
247
  }
176
248
  catch (error) {
177
249
  throw new Problem(`${what} threw: ${words(error)}`);
@@ -198,7 +270,7 @@ class Session {
198
270
  lacks.unshift("stderr");
199
271
  if (lacks.length > 0)
200
272
  throw new Problem(`${what} answered a process that lacks ${lacks.join(", ")}: a MachineProcess (src/host.ts) has stdout, stderr, write, end, wait and kill`);
201
- const run = { proc, out: new Reader(proc.stdout), err: new Reader(proc.stderr), exited: Promise.resolve(0) };
273
+ const run = { proc, out: new Reader(proc.stdout, readFrom), err: new Reader(proc.stderr), exited: Promise.resolve(0) };
202
274
  run.exited = Promise.resolve()
203
275
  .then(() => proc.wait())
204
276
  .then((code) => {
@@ -213,16 +285,21 @@ class Session {
213
285
  return run;
214
286
  }
215
287
  /**
216
- * Writes bytes to the process's stdin, in WRITE_CHUNK pieces, one after another; a refusal is a Problem. Each write
217
- * is bounded by the step, and by `by` when the check has one deadline for all of its steps.
288
+ * Writes UTF-8 text to the process's stdin, in pieces of at most WRITE_CHUNK bytes, each whole characters as the
289
+ * adapter's are, one after another; a refusal is a Problem. Each write is bounded by the step, and by `by` when the
290
+ * check has one deadline for all of its steps.
218
291
  */
219
292
  async write(run, bytes, what, by) {
220
- for (let at = 0; at < bytes.length; at += WRITE_CHUNK) {
293
+ for (let at = 0, end = 0; at < bytes.length; at = end) {
294
+ end = Math.min(at + WRITE_CHUNK, bytes.length);
295
+ while (end < bytes.length && (bytes[end] & 0xc0) === 0x80)
296
+ end--;
297
+ const piece = bytes.subarray(at, end);
221
298
  const ms = by ? by.left(this.#stepMs) : this.#stepMs;
222
299
  // Whether the deadline, not the step, set this bound. Asking by.passed() after the timeout is not enough: a
223
300
  // timer can fire a millisecond before Date.now() reads the deadline.
224
301
  const deadlineBound = by !== undefined && ms < this.#stepMs;
225
- const written = await within(Promise.resolve().then(() => run.proc.write(bytes.subarray(at, at + WRITE_CHUNK))), ms, LATE, this.#signal).catch((error) => {
302
+ const written = await within(Promise.resolve().then(() => run.proc.write(piece)), ms, LATE, this.#signal).catch((error) => {
226
303
  throw new Problem(`write() of ${what} failed while the process ran: ${words(error)}`);
227
304
  });
228
305
  // within() answers LATE for an abort too: a stopped write names no bound that did not run out.
@@ -232,15 +309,6 @@ class Session {
232
309
  throw new Problem(by && (deadlineBound || by.passed()) ? `writing ${what} ran past ${secondsOf(by.ms)}, with ${at} bytes written` : `write() of ${what} did not answer within ${secondsOf(ms)}`);
233
310
  }
234
311
  }
235
- /** Ends the process's stdin; a refusal is a Problem. */
236
- async end(run, by) {
237
- const ms = by ? by.left(this.#stepMs) : this.#stepMs;
238
- const ended = await within(Promise.resolve().then(() => run.proc.end()), ms, LATE, this.#signal).catch((error) => {
239
- throw new Problem(`end() failed: ${words(error)}`);
240
- });
241
- if (ended === LATE)
242
- throw new Problem(`end() did not answer within ${secondsOf(ms)}`);
243
- }
244
312
  /** wait()'s exit code within ms; one that never comes, or a wait() that throws, is a Problem. */
245
313
  async exit(run, ms, what) {
246
314
  let code;
@@ -281,55 +349,55 @@ class Deadline {
281
349
  }
282
350
  }
283
351
  const CHECKS = {
284
- /** Every byte value out, on stdout alone: printf in the machine writes them. */
285
- async "stdout-bytes"(s) {
286
- const argv = ["sh", "-c", 'printf "$1"', "sh", PRINTF_ALL];
287
- const run = await s.start(argv, false);
352
+ /**
353
+ * Text of every kind out, on stdout alone: printf in the machine writes it, the 1 MiB line a piece at a time. Only the
354
+ * piece's short unit crosses argv; sh repeats it, doubling, into the piece, so the command stays far under a vendor's
355
+ * 64 KiB argv cap (Modal's).
356
+ */
357
+ async "stdout-text"(s) {
358
+ const script = `printf "$1"; u=$(printf "$2"); n=${LONG_UNITS}; p=; while [ "$n" -gt 0 ]; do if [ $((n % 2)) -eq 1 ]; then p="$p$u"; fi; u="$u$u"; n=$((n / 2)); done; p="$p"${LONG_TAIL}; i=0; while [ "$i" -lt ${LONG_PIECES} ]; do printf '%s' "$p"; i=$((i+1)); done; printf '\\n'`;
359
+ const run = await s.start(["sh", "-c", script, "sh", printfOf(CODE_POINTS), printfOf(LONG_UNIT)], false);
288
360
  if (!(await run.out.end(s.stepMs, s.signal)))
289
361
  throw new Problem(`stdout of printf did not end within ${secondsOf(s.stepMs)} of its start`);
290
362
  const code = await s.exit(run, s.stepMs, "printf");
291
363
  if (code !== 0)
292
- throw new Problem(`printf of the 256 byte values exited ${code} (stderr: ${run.err.bytes().toString("utf8").trim().slice(0, 200) || "none"})`);
293
- const problem = bytesProblem(ALL_BYTES, run.out.bytes(), "on stdout");
364
+ throw new Problem(`printf of the text exited ${code} (stderr: ${run.err.bytes().toString("utf8").trim().slice(0, 200) || "none"})`);
365
+ const problem = textProblem(TEXT, run.out.bytes(), "on stdout");
294
366
  if (problem)
295
367
  throw new Problem(problem);
296
- return "all 256 byte values printed in the machine came back unchanged on stdout";
368
+ return "text of every class of code point, \\r and \\r\\n, and a 1 MiB line, printed in the machine, came back unchanged on stdout";
297
369
  },
298
- /** Every byte value in on stdin and out again, through cat. */
299
- async "stdin-bytes"(s, _options, earlier) {
370
+ /** The same text in on stdin and out again, through cat, read until it has all come back: no end of stdin. */
371
+ async "stdin-text"(s, _options, earlier) {
300
372
  const run = await s.start(["cat"], true);
301
- await s.write(run, ALL_BYTES, "the 256 byte values");
302
- await s.end(run);
303
- if (!(await run.out.end(s.stepMs, s.signal)))
304
- throw new Problem(`cat's stdout did not end within ${secondsOf(s.stepMs)} of end(): end() must close the process's stdin, so it reads end of file`);
305
- await s.exit(run, s.stepMs, "cat");
306
- const outOk = earlier.get("stdout-bytes")?.status === "pass";
307
- const problem = bytesProblem(ALL_BYTES, run.out.bytes(), "through cat");
373
+ await s.write(run, TEXT, "the text");
374
+ const came = await run.out.until(() => run.out.length >= TEXT.length, s.stepMs, s.signal);
375
+ const got = run.out.bytes();
376
+ // What came back is checked as far as it goes: a character changed on the way says so, before any that never came.
377
+ const problem = textProblem(came ? TEXT : TEXT.subarray(0, got.length), got, "through cat");
308
378
  if (problem)
309
- throw new Problem(outOk ? `${problem}. stdout alone passes every byte (stdout-bytes), so they changed on the way in, on stdin` : problem);
310
- return "all 256 byte values written to stdin came back unchanged through cat";
379
+ throw new Problem(earlier.get("stdout-text")?.status === "pass" ? `${problem}. stdout alone passes it (stdout-text), so it changed on the way in, on stdin` : problem);
380
+ if (!came)
381
+ throw new Problem(`only ${got.length} of ${TEXT.length} bytes of text came back through cat within ${secondsOf(s.stepMs)} of the last write: your exec holds stdin, or drops some of it. Pass each write on as it comes`);
382
+ return "the same text written to stdin came back unchanged through cat";
311
383
  },
312
- /** A large random payload through cat, read while it is written, compared by sha256, all within largeMs. */
384
+ /** Large random text through cat, read while it is written, compared by sha256, all within largeMs. */
313
385
  async large(s, { largeBytes, largeMs }) {
314
- const payload = randomBytes(largeBytes);
386
+ const payload = randomText(largeBytes);
315
387
  const started = Date.now();
316
388
  const by = new Deadline(largeMs);
317
389
  const run = await s.start(["cat"], true);
318
- await s.write(run, payload, `${largeBytes} random bytes`, by);
319
- await s.end(run, by);
320
- if (!(await run.out.end(by.left(largeMs), s.signal))) {
321
- throw new Problem(`${run.out.length} of ${largeBytes} bytes came back through cat within ${secondsOf(largeMs)}, and its stdout had not ended: your exec is too slow, or stops passing output on`);
390
+ await s.write(run, payload, `${largeBytes} bytes of random text`, by);
391
+ if (!(await run.out.until(() => run.out.length >= largeBytes, by.left(largeMs), s.signal))) {
392
+ throw new Problem(`${run.out.length} of ${largeBytes} bytes of text came back through cat within ${secondsOf(largeMs)}: your exec is too slow, or stops passing output on`);
322
393
  }
323
- await s.exit(run, by.left(s.stepMs), "cat");
324
- if (by.passed())
325
- throw new Problem(`${largeBytes} bytes through cat took ${secondsOf(Date.now() - started)}, past ${secondsOf(largeMs)}: your exec is too slow`);
326
394
  const got = run.out.bytes();
327
395
  const sent = createHash("sha256").update(payload).digest("hex");
328
396
  const back = createHash("sha256").update(got).digest("hex");
329
397
  if (sent !== back) {
330
- throw new Problem(`${largeBytes} random bytes went in, ${got.length} came back with sha256 ${back.slice(0, 16)}…, not ${sent.slice(0, 16)}…: ${bytesProblem(payload, got, "through cat") ?? "they differ"}`);
398
+ throw new Problem(`${largeBytes} bytes of random text went in, ${got.length} came back with sha256 ${back.slice(0, 16)}…, not ${sent.slice(0, 16)}…: ${textProblem(payload, got, "through cat") ?? "they differ"}`);
331
399
  }
332
- return `${largeBytes} random bytes came back through cat with the same sha256 in ${secondsOf(Date.now() - started)}`;
400
+ return `${largeBytes} bytes of random text came back through cat with the same sha256 in ${secondsOf(Date.now() - started)}`;
333
401
  },
334
402
  /** Output comes back while the process runs: printf, then a sleep that never ends on its own. */
335
403
  async "stdout-live"(s) {
@@ -368,15 +436,58 @@ const CHECKS = {
368
436
  : `write ${i + 1} to cat, with stdin still open, never came back on stdout in ${secondsOf(s.stepMs)}: your exec holds stdin until end(), or output until the process exits (see stdout-live)`);
369
437
  }
370
438
  }
371
- const problem = bytesProblem(Buffer.concat(rounds), run.out.bytes(), "through cat");
439
+ const problem = textProblem(Buffer.concat(rounds), run.out.bytes(), "through cat");
372
440
  if (problem)
373
441
  throw new Problem(problem);
374
- await s.end(run);
375
- const code = await s.exit(run, s.stepMs, "cat");
376
- if (code !== 0)
377
- throw new Problem(`cat exited ${code} after end(), not 0`);
378
442
  return "two writes came back through cat, each before the next was written, while stdin stayed open";
379
443
  },
444
+ /**
445
+ * stdin keeps coming while stdout is left unread for unreadMs; then stdout is read, and every byte comes back, in
446
+ * order. A write may wait while nobody reads stdout, but once stdout is read it goes on: an exec whose stdin waits on
447
+ * a stalled reader for good deadlocks the daemon's one stream (microsandbox holds a 64 KiB stdin window per execution).
448
+ */
449
+ async "stdout-unread"(s, { unreadMs }) {
450
+ let read = () => { };
451
+ const run = await s.start(["cat"], true, new Promise((done) => (read = done)));
452
+ const started = Date.now();
453
+ const readAt = started + unreadMs;
454
+ const reading = setTimeout(read, unreadMs);
455
+ const sent = [];
456
+ let written = 0;
457
+ try {
458
+ // Every write, paced over unreadMs: one that waits for the reader goes on once stdout is read, and the rest follow.
459
+ // All of them are answered within stepMs of stdout being read: one deadline, not a step per write.
460
+ for (let i = 0; i < UNREAD_WRITES && !s.signal?.aborted; i++) {
461
+ await pause(started + (i * unreadMs) / UNREAD_WRITES - Date.now(), s.signal);
462
+ const chunk = Buffer.alloc(UNREAD_CHUNK, `write ${String(i + 1).padStart(2, "0")} `);
463
+ const madeUnread = Date.now() < readAt;
464
+ const answered = await within(Promise.resolve().then(() => run.proc.write(chunk)), Math.max(1, readAt + s.stepMs - Date.now()), LATE, s.signal).catch((error) => {
465
+ throw new Problem(`write() to cat failed while its stdout was left unread, with ${written} bytes written: ${words(error)}`);
466
+ });
467
+ if (answered === LATE && s.signal?.aborted)
468
+ throw new Problem(`writing to cat was stopped, with ${written} bytes written`);
469
+ if (answered === LATE && !madeUnread)
470
+ throw new Problem(`the ${UNREAD_WRITES} writes to cat ran past ${secondsOf(s.stepMs)} after stdout was read, with ${written} bytes written: your exec's writes are too slow`);
471
+ if (answered === LATE) {
472
+ throw new Problem(`write ${i + 1} to cat, made while its stdout was left unread, still had no answer ${secondsOf(s.stepMs)} after stdout was read again (${written} bytes written): your exec's stdin waits for stdout to be read and does not go on once it is, so one stalled reader deadlocks the stream. Let stdin wait only until stdout is read`);
473
+ }
474
+ sent.push(chunk);
475
+ written += chunk.length;
476
+ }
477
+ await pause(readAt - Date.now(), s.signal);
478
+ }
479
+ finally {
480
+ clearTimeout(reading);
481
+ read();
482
+ }
483
+ if (!(await run.out.until(() => run.out.length >= written, s.stepMs, s.signal))) {
484
+ throw new Problem(`${run.out.length} of ${written} bytes came back through cat within ${secondsOf(s.stepMs)} of stdout being read`);
485
+ }
486
+ const problem = textProblem(Buffer.concat(sent), run.out.bytes(), "through cat");
487
+ if (problem)
488
+ throw new Problem(`${problem}; stdout was left unread ${secondsOf(unreadMs)} while stdin was written: output nobody reads yet is held until it is read, never dropped`);
489
+ return `${written} bytes written to cat while its stdout was left unread for ${secondsOf(unreadMs)} all came back, in order, once it was read`;
490
+ },
380
491
  /** stderr comes back apart from stdout. */
381
492
  async stderr(s) {
382
493
  const run = await s.start(["sh", "-c", "printf to-stdout; printf to-stderr >&2"], false);
@@ -449,12 +560,144 @@ const CHECKS = {
449
560
  return `a process that slept ${seconds} s, silent, ran to its end and printed "done"`;
450
561
  },
451
562
  };
563
+ /**
564
+ * The capability probe, one sh script run through exec (as root, as exec runs): a tab-separated line for each thing it
565
+ * reads, each value on one line, and every line of the kernel's TCP tables as a "tcp" line. readFacts reads it. It needs
566
+ * no ss, ip or util-linux beyond unshare, and says "none" where the machine lacks unshare.
567
+ */
568
+ export const CAPABILITY_SCRIPT = [
569
+ `line() { printf '%s\\t%s\\n' "$1" "$(printf '%s' "$2" | tr '\\n\\t' ' ')"; }`,
570
+ 'line uid "$(id -u 2>&1)"',
571
+ 'line arch "$(uname -m 2>&1)"',
572
+ 'line kernel "$(uname -sr 2>&1)"',
573
+ `if d=$(dmesg 2>/dev/null); then line gvisor "$(printf '%s' "$d" | grep -i gvisor | head -n 1)"; else line gvisor unread; fi`,
574
+ 'if command -v unshare >/dev/null 2>&1; then e=$(unshare -n true 2>&1); line netns "$? $e"; e=$(unshare -Urn true 2>&1); line userns "$? $e"; else line netns none; fi',
575
+ 'if [ -e /dev/fuse ]; then e=$( (: <>/dev/fuse) 2>&1); line fuse "$? $e"; else line fuse absent; fi',
576
+ `for f in /proc/net/tcp /proc/net/tcp6; do if [ -r "$f" ]; then line table "$f"; while read -r l; do printf 'tcp\\t%s\\n' "$l"; done < "$f"; else line unreadable "$f"; fi; done`,
577
+ "true",
578
+ ].join("\n");
579
+ /** A /proc/net/tcp{,6} address, hex as the kernel writes it (each 32-bit word in host order, little-endian here), as text. */
580
+ function tcpAddress(hex) {
581
+ const bytes = Buffer.from(hex, "hex");
582
+ for (let at = 0; at + 4 <= bytes.length; at += 4)
583
+ bytes.subarray(at, at + 4).reverse();
584
+ if (bytes.length === 4)
585
+ return [...bytes].join(".");
586
+ const groups = Array.from({ length: 8 }, (_, i) => bytes.readUInt16BE(i * 2).toString(16));
587
+ return new URL(`http://[${groups.join(":")}]`).hostname;
588
+ }
589
+ /** The most listeners the report names; a vendor's machine has a handful, a developer's box hundreds. */
590
+ const MAX_LISTENERS_SHOWN = 24;
591
+ /** The TCP listeners in the probe's "tcp" lines: address:port, each once, in the order the kernel lists them. */
592
+ export function tcpListeners(lines) {
593
+ const found = [];
594
+ for (const line of lines) {
595
+ const [, local = "", , state] = line.trim().split(/\s+/);
596
+ const match = /^([0-9A-F]{8}|[0-9A-F]{32}):([0-9A-F]{4})$/i.exec(local);
597
+ if (state !== "0A" || match === null)
598
+ continue;
599
+ const at = `${tcpAddress(match[1])}:${Number.parseInt(match[2], 16)}`;
600
+ if (!found.includes(at))
601
+ found.push(at);
602
+ }
603
+ return found;
604
+ }
605
+ /** What `<code> <words>` says of a command the probe ran: whether it worked, and its words. */
606
+ function ranOf(text) {
607
+ const match = /^(\d+) ?(.*)$/.exec(text ?? "");
608
+ return match === null ? undefined : { ok: match[1] === "0", said: match[2].trim() };
609
+ }
610
+ /** The probe's output as facts, each with what it means for the provider. */
611
+ export function readFacts(output) {
612
+ const values = new Map();
613
+ const tcp = [];
614
+ /** The TCP tables read, and those that could not be. */
615
+ const tables = { read: [], unreadable: [] };
616
+ for (const line of output.split("\n")) {
617
+ const tab = line.indexOf("\t");
618
+ if (tab < 0)
619
+ continue;
620
+ const [key, value] = [line.slice(0, tab), line.slice(tab + 1).trim()];
621
+ if (key === "tcp")
622
+ tcp.push(value);
623
+ else if (key === "table")
624
+ tables.read.push(value);
625
+ else if (key === "unreadable")
626
+ tables.unreadable.push(value);
627
+ else if (!values.has(key))
628
+ values.set(key, value);
629
+ }
630
+ const facts = [];
631
+ const uid = values.get("uid") ?? "";
632
+ facts.push(uid === "0"
633
+ ? { id: "root", value: "uid 0", means: "exec runs as root, as the adapter needs: the lines below are what root can do" }
634
+ : { id: "root", value: uid === "" ? "not read" : `uid ${uid}`, means: "exec does not run as root: the adapter installs its daemon as root through exec, so run it as root (or through passwordless sudo); the lines below are what this user can do" });
635
+ const netns = values.get("netns");
636
+ const own = ranOf(netns);
637
+ const inUser = ranOf(values.get("userns"));
638
+ if (netns === "none")
639
+ facts.push({ id: "netns", value: "no unshare program", means: "not read: the machine has no unshare (util-linux), so whether root can make a network namespace shows only at the Core run" });
640
+ else if (own?.ok)
641
+ facts.push({ id: "netns", value: "unshare -n works", means: "root makes a network namespace: our fence holds network none, open and allow (netns)" });
642
+ else if (own !== undefined && inUser?.ok) {
643
+ facts.push({ id: "netns", value: `unshare -n failed (${own.said || "no words"}); unshare -Urn works`, means: "root makes a network namespace only inside a user namespace, as on gVisor: our fence holds network none, open and allow there (userns-netns)" });
644
+ }
645
+ else {
646
+ const why = [own && `unshare -n failed (${own.said || "no words"})`, inUser && `unshare -Urn failed (${inUser.said || "no words"})`].filter(Boolean).join("; ") || "not read";
647
+ facts.push({ id: "netns", value: why, means: "no netns: network none, open and allow can't be held by our fence on this vendor" });
648
+ }
649
+ const fuse = values.get("fuse");
650
+ const opened = ranOf(fuse);
651
+ if (fuse === "absent")
652
+ facts.push({ id: "fuse", value: "no /dev/fuse", means: "no Archil mount (mount:archil) on this vendor: the Archil client needs /dev/fuse" });
653
+ else if (opened?.ok)
654
+ facts.push({ id: "fuse", value: "/dev/fuse opens", means: "an Archil mount (mount:archil) can be made here" });
655
+ else
656
+ facts.push({ id: "fuse", value: opened ? `/dev/fuse does not open (${opened.said || "no words"})` : "not read", means: "no Archil mount (mount:archil) on this vendor until root can open /dev/fuse" });
657
+ const arch = values.get("arch") ?? "";
658
+ const goArch = arch === "x86_64" || arch === "amd64" ? "amd64" : arch === "aarch64" || arch === "arm64" ? "arm64" : undefined;
659
+ facts.push({ id: "arch", value: arch || "not read", means: goArch ? `facts.arch "${goArch}"` : "neither amd64 nor arm64: computerd is built for those two alone" });
660
+ const kernel = values.get("kernel") || "not read";
661
+ const gvisor = values.get("gvisor") ?? "unread";
662
+ const isolationCases = "the isolation cases show how its fences hold";
663
+ if (gvisor !== "unread" && gvisor !== "") {
664
+ facts.push({ id: "kernel", value: `gVisor (${kernel} as it reports; dmesg: ${gvisor.slice(0, 80)})`, means: "gVisor: root has no CAP_SYS_ADMIN and the network stack is gVisor's own, so run the isolation cases here; a Docker stand-in does not show how it behaves" });
665
+ }
666
+ else {
667
+ const marker = gvisor === "" ? "no gVisor marker in dmesg" : "dmesg could not be read, so gVisor is not ruled out";
668
+ facts.push({ id: "kernel", value: `${kernel} (${marker})`, means: `the kernel as it reports itself: ${isolationCases}` });
669
+ }
670
+ const listeners = tcpListeners(tcp);
671
+ const shownListeners = listeners.length > MAX_LISTENERS_SHOWN ? `${listeners.slice(0, MAX_LISTENERS_SHOWN).join(", ")} and ${listeners.length - MAX_LISTENERS_SHOWN} more` : listeners.join(", ");
672
+ const unread = tables.unreadable.length > 0 ? ` (${tables.unreadable.join(" and ")} could not be read)` : "";
673
+ if (tables.read.length === 0) {
674
+ facts.push({ id: "listeners", value: `not read${unread}`, means: "the listeners are unknown: find the vendor agent's ports some other way before you set facts.vendorAgentPorts" });
675
+ }
676
+ else if (listeners.length > 0) {
677
+ facts.push({ id: "listeners", value: `${shownListeners}${unread}`, means: "TCP listeners before AgentRun runs anything: the vendor's agent and services. Put the agent's ports in facts.vendorAgentPorts, so isolation.vendor-agent checks the computer's programs reach none of them" });
678
+ }
679
+ else {
680
+ facts.push({ id: "listeners", value: `none${unread}`, means: unread === "" ? "no TCP listener before AgentRun runs anything: facts.vendorAgentPorts may be []" : `no TCP listener in ${tables.read.join(" or ")}: check the table that could not be read before you set facts.vendorAgentPorts to []` });
681
+ }
682
+ return facts;
683
+ }
684
+ /** The capability probe through exec: its facts, or a Problem in words when exec could not run it. */
685
+ async function probe(session) {
686
+ const run = await session.start(["sh", "-c", CAPABILITY_SCRIPT], false);
687
+ if (!(await run.out.end(session.stepMs, session.signal)))
688
+ throw new Problem(`its stdout did not end within ${secondsOf(session.stepMs)}`);
689
+ // The script ends in `true`: any other exit is a shell that broke partway, whose output is not read as facts.
690
+ const code = await session.exit(run, session.stepMs, "the probe");
691
+ if (code !== 0)
692
+ throw new Problem(`the probe's sh exited ${code} (stderr: ${run.err.bytes().toString("utf8").trim().slice(0, 200) || "none"})`);
693
+ return readFacts(run.out.bytes().toString("utf8"));
694
+ }
452
695
  /**
453
696
  * The exec pre-check on one machine: each check in EXEC_STREAM_CHECKS runs in turn, and the report passes when every one
454
- * does. host.exec is the only member called.
697
+ * does; then the capability probe, which passes or fails nothing. host.exec is the only member called.
455
698
  */
456
699
  export async function checkExecStream(host, machine, options = {}) {
457
- const { longMs = DEFAULT_LONG_MS, stepMs = DEFAULT_STEP_MS, largeBytes = DEFAULT_LARGE_BYTES, largeMs = DEFAULT_LARGE_MS, signal, onCheck } = options;
700
+ const { longMs = DEFAULT_LONG_MS, stepMs = DEFAULT_STEP_MS, largeBytes = DEFAULT_LARGE_BYTES, largeMs = DEFAULT_LARGE_MS, unreadMs = DEFAULT_UNREAD_MS, signal, onCheck } = options;
458
701
  const session = new Session(host, machine, stepMs, signal);
459
702
  const done = new Map();
460
703
  for (const id of EXEC_STREAM_CHECKS) {
@@ -464,7 +707,7 @@ export async function checkExecStream(host, machine, options = {}) {
464
707
  check = { id, status: "fail", words: "the run was aborted before this check", ms: 0 };
465
708
  else {
466
709
  try {
467
- const said = await CHECKS[id](session, { longMs, largeBytes, largeMs }, done);
710
+ const said = await CHECKS[id](session, { longMs, largeBytes, largeMs, unreadMs }, done);
468
711
  check = { id, status: "pass", words: said, ms: Date.now() - started };
469
712
  }
470
713
  catch (error) {
@@ -477,17 +720,34 @@ export async function checkExecStream(host, machine, options = {}) {
477
720
  onCheck?.(check);
478
721
  }
479
722
  const checks = [...done.values()];
480
- return { host: host.descriptor.id, machine, checks, pass: checks.every((check) => check.status === "pass") };
723
+ const report = { host: host.descriptor.id, machine, checks, pass: checks.every((check) => check.status === "pass"), facts: [] };
724
+ if (signal?.aborted)
725
+ report.factsProblem = "the run was aborted before the probe";
726
+ else {
727
+ try {
728
+ report.facts = await probe(session);
729
+ }
730
+ catch (error) {
731
+ report.factsProblem = error instanceof Problem ? error.message : `the probe itself failed: ${words(error)}`;
732
+ }
733
+ await session.killAll();
734
+ }
735
+ return report;
481
736
  }
482
- /** The report as a person reads it: one line per check, what failed in words, the verdict last. */
737
+ /** The report as a person reads it: one line per check, what failed in words, the machine's facts, the verdict last. */
483
738
  export function formatExecStream(report) {
484
739
  const width = Math.max(...EXEC_STREAM_CHECKS.map((id) => id.length));
485
740
  const lines = [`exec pre-check · ${report.host} · machine ${report.machine}`];
486
741
  for (const check of report.checks)
487
742
  lines.push(`${check.status === "pass" ? "✓" : "✗"} ${check.id.padEnd(width)} ${check.words}`);
743
+ lines.push("what the machine offers (facts for the rest of your host, not checks of exec):");
744
+ if (report.factsProblem !== undefined)
745
+ lines.push(` not read: ${report.factsProblem}`);
746
+ for (const fact of report.facts)
747
+ lines.push(`· ${fact.id.padEnd(width)} ${fact.value}: ${fact.means}`);
488
748
  const failed = report.checks.filter((check) => check.status === "fail").length;
489
749
  lines.push(report.pass
490
- ? "exec PASS: a live, two-way, byte-exact stream with no timeout. Write the rest of your host next."
750
+ ? "exec PASS: a live, two-way stream that keeps text intact, with no timeout. Write the rest of your host next."
491
751
  : `exec FAIL: ${failed} of ${report.checks.length} checks failed. Fix exec before you write the rest of your host: AgentRun reaches its daemon through it.`);
492
752
  return `${lines.join("\n")}\n`;
493
753
  }
@@ -67,6 +67,9 @@ export function formatReport(report) {
67
67
  // What a provider said through onNote, such as a release whose final sync or checkin did not go cleanly.
68
68
  for (const { computer, note } of report.providerNotes ?? [])
69
69
  lines.push(`provider note ${computer}: ${note}`);
70
+ // What a vendor plan or rate limit that keeps fewer would refuse: --concurrency caps it.
71
+ const { peak, cap } = report.computers;
72
+ lines.push(`computers alive at once: ${peak} at most${cap === undefined ? "" : ` (--concurrency ${cap})`}`);
70
73
  const core = results.filter((r) => levelOf(r) === "core");
71
74
  const notDeclared = results.filter((r) => levelOf(r) === "optional").length;
72
75
  const full = results.filter((r) => r.level === "full");