@parcha/agentrun-computer 0.1.0-beta.36 → 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 (155) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +547 -478
  3. package/box/Dockerfile +18 -1
  4. package/box/README.md +13 -0
  5. package/box/build-agent37.mjs +158 -0
  6. package/box/build-daytona.py +2 -2
  7. package/box/build-e2b.mjs +41 -18
  8. package/box/recipe.mjs +43 -0
  9. package/dist/agent37-ssh.d.ts +89 -0
  10. package/dist/agent37-ssh.js +445 -0
  11. package/dist/agent37.d.ts +104 -0
  12. package/dist/agent37.js +402 -0
  13. package/dist/attach.d.ts +146 -0
  14. package/dist/attach.js +469 -0
  15. package/dist/browserbase.d.ts +2 -10
  16. package/dist/browserbase.js +3 -6
  17. package/dist/client.d.ts +45 -4
  18. package/dist/client.js +92 -4
  19. package/dist/computerd-linux-amd64 +0 -0
  20. package/dist/computerd-linux-arm64 +0 -0
  21. package/dist/computerd.json +4 -0
  22. package/dist/conformance/agent37.d.ts +96 -0
  23. package/dist/conformance/agent37.js +154 -0
  24. package/dist/conformance/cases/apps.d.ts +11 -0
  25. package/dist/conformance/cases/apps.js +173 -73
  26. package/dist/conformance/cases/health.js +14 -0
  27. package/dist/conformance/cases/index.js +2 -0
  28. package/dist/conformance/cases/isolation.d.ts +7 -5
  29. package/dist/conformance/cases/isolation.js +44 -14
  30. package/dist/conformance/cases/mount.js +1 -1
  31. package/dist/conformance/cases/provider.js +27 -1
  32. package/dist/conformance/cases/screen.d.ts +3 -0
  33. package/dist/conformance/cases/screen.js +18 -0
  34. package/dist/conformance/cases/settings.d.ts +29 -23
  35. package/dist/conformance/cases/settings.js +76 -58
  36. package/dist/conformance/cases/touch.js +19 -17
  37. package/dist/conformance/cases/ui.d.ts +2 -0
  38. package/dist/conformance/cases/ui.js +475 -0
  39. package/dist/conformance/cli.d.ts +9 -0
  40. package/dist/conformance/cli.js +94 -9
  41. package/dist/conformance/daytona.d.ts +9 -20
  42. package/dist/conformance/daytona.js +12 -21
  43. package/dist/conformance/e2b.d.ts +6 -0
  44. package/dist/conformance/e2b.js +9 -2
  45. package/dist/conformance/exec-stream.d.ts +45 -0
  46. package/dist/conformance/exec-stream.js +486 -0
  47. package/dist/conformance/fixture.d.ts +1 -1
  48. package/dist/conformance/fixture.js +25 -1
  49. package/dist/conformance/modal.d.ts +17 -13
  50. package/dist/conformance/modal.js +18 -9
  51. package/dist/conformance/orgo.d.ts +3 -3
  52. package/dist/conformance/orgo.js +6 -8
  53. package/dist/conformance/phone-harness.d.ts +6 -2
  54. package/dist/conformance/phone-harness.js +21 -4
  55. package/dist/conformance/report.js +1 -1
  56. package/dist/conformance/runner.js +23 -4
  57. package/dist/conformance/sweep.d.ts +50 -0
  58. package/dist/conformance/sweep.js +187 -0
  59. package/dist/conformance/types.d.ts +13 -5
  60. package/dist/conformance/ui-fixture.d.ts +56 -0
  61. package/dist/conformance/ui-fixture.js +43 -0
  62. package/dist/create-requests.d.ts +51 -0
  63. package/dist/create-requests.js +121 -0
  64. package/dist/daytona.d.ts +20 -133
  65. package/dist/daytona.js +405 -1449
  66. package/dist/descriptor.d.ts +11 -1
  67. package/dist/descriptor.js +9 -0
  68. package/dist/descriptors/agent37.d.ts +41 -0
  69. package/dist/descriptors/agent37.js +28 -0
  70. package/dist/descriptors/daytona.d.ts +6 -5
  71. package/dist/descriptors/daytona.js +9 -5
  72. package/dist/descriptors/index.d.ts +42 -7
  73. package/dist/descriptors/index.js +4 -2
  74. package/dist/descriptors/orgo.d.ts +2 -1
  75. package/dist/descriptors/orgo.js +3 -2
  76. package/dist/descriptors/phone-harness.d.ts +1 -1
  77. package/dist/descriptors/phone-harness.js +2 -2
  78. package/dist/descriptors/shared.d.ts +1 -1
  79. package/dist/descriptors/shared.js +2 -2
  80. package/dist/desktop.d.ts +18 -4
  81. package/dist/desktop.js +89 -9
  82. package/dist/docker.d.ts +7 -10
  83. package/dist/docker.js +272 -34
  84. package/dist/drift.js +4 -4
  85. package/dist/e2b.d.ts +16 -290
  86. package/dist/e2b.js +230 -1393
  87. package/dist/fake-ui-driver.d.ts +97 -0
  88. package/dist/fake-ui-driver.js +717 -0
  89. package/dist/host.d.ts +201 -0
  90. package/dist/host.js +8 -0
  91. package/dist/hosted/process.d.ts +81 -0
  92. package/dist/hosted/process.js +259 -0
  93. package/dist/hosted/provider.d.ts +160 -0
  94. package/dist/hosted/provider.js +1415 -0
  95. package/dist/hosted/rest.d.ts +66 -0
  96. package/dist/hosted/rest.js +121 -0
  97. package/dist/hosted/scripts.d.ts +82 -0
  98. package/dist/{child.js → hosted/scripts.js} +118 -12
  99. package/dist/hosted/values.d.ts +5 -0
  100. package/dist/hosted/values.js +8 -0
  101. package/dist/index.d.ts +7 -3
  102. package/dist/index.js +7 -4
  103. package/dist/kernel.d.ts +2 -10
  104. package/dist/kernel.js +3 -6
  105. package/dist/kinds.d.ts +11 -2
  106. package/dist/kinds.js +20 -4
  107. package/dist/local-chrome.d.ts +2 -10
  108. package/dist/local-chrome.js +3 -6
  109. package/dist/modal.d.ts +22 -257
  110. package/dist/modal.js +183 -1280
  111. package/dist/mount-archil.d.ts +8 -4
  112. package/dist/mount-archil.js +22 -11
  113. package/dist/mount.d.ts +10 -4
  114. package/dist/mount.js +8 -4
  115. package/dist/orgo-channel.d.ts +3 -2
  116. package/dist/orgo-channel.js +5 -2
  117. package/dist/orgo-desktop.d.ts +9 -4
  118. package/dist/orgo-desktop.js +33 -13
  119. package/dist/orgo-workspaces.d.ts +47 -0
  120. package/dist/orgo-workspaces.js +94 -0
  121. package/dist/orgo.d.ts +10 -13
  122. package/dist/orgo.js +32 -21
  123. package/dist/phone-harness.d.ts +31 -28
  124. package/dist/phone-harness.js +510 -702
  125. package/dist/png.d.ts +4 -0
  126. package/dist/png.js +27 -0
  127. package/dist/protocol.d.ts +339 -33
  128. package/dist/protocol.js +97 -3
  129. package/dist/provider.d.ts +36 -8
  130. package/dist/provider.js +16 -0
  131. package/dist/providers.d.ts +11 -12
  132. package/dist/result.d.ts +1 -1
  133. package/dist/screen-watch.js +34 -6
  134. package/dist/surface/api.d.ts +260 -0
  135. package/dist/surface/api.js +1 -0
  136. package/dist/surface/core.d.ts +55 -0
  137. package/dist/surface/core.js +475 -0
  138. package/dist/surface/index.d.ts +5 -0
  139. package/dist/surface/index.js +3 -0
  140. package/dist/surface/outline.d.ts +10 -0
  141. package/dist/surface/outline.js +51 -0
  142. package/dist/surface/script.d.ts +10 -0
  143. package/dist/surface/script.js +94 -0
  144. package/dist/ui-engine.d.ts +114 -0
  145. package/dist/ui-engine.js +814 -0
  146. package/package.json +18 -3
  147. package/dist/child.d.ts +0 -42
  148. package/dist/conformance/daytona-sweep.d.ts +0 -18
  149. package/dist/conformance/daytona-sweep.js +0 -126
  150. package/dist/conformance/e2b-diagnose.d.ts +0 -16
  151. package/dist/conformance/e2b-diagnose.js +0 -61
  152. package/dist/conformance/e2b-sweep.d.ts +0 -18
  153. package/dist/conformance/e2b-sweep.js +0 -132
  154. package/dist/conformance/modal-sweep.d.ts +0 -22
  155. package/dist/conformance/modal-sweep.js +0 -213
@@ -0,0 +1,486 @@
1
+ // The exec pre-check: the one thing a new vendor proves before writing anything else of its host. AgentRun installs its
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:
5
+ //
6
+ // npm run conformance -w @parcha/agentrun-computer -- --provider <id | ./module.js> --exec-stream --machine <id> [--quick]
7
+ //
8
+ // 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
+ import { createHash, randomBytes } from "node:crypto";
11
+ import { words } from "../hosted/process.js";
12
+ /** 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"];
14
+ export const DEFAULT_LONG_MS = 75_000;
15
+ /** --quick's no-timeout check: long enough to cross a second, short enough for CI. */
16
+ export const QUICK_LONG_MS = 5_000;
17
+ const DEFAULT_STEP_MS = 30_000;
18
+ const DEFAULT_LARGE_BYTES = 8 * 1024 * 1024;
19
+ const DEFAULT_LARGE_MS = 180_000;
20
+ /** What one write gives exec's stdin, as the adapter's own upload does (runToExit). */
21
+ const WRITE_CHUNK = 256 * 1024;
22
+ /** How long stdout-live watches, after "early", that stdout stays open and wait() has no answer. */
23
+ const LIVE_GRACE_MS = 1_000;
24
+ /** A failed check: its words are the report's. */
25
+ class Problem extends Error {
26
+ }
27
+ const hex = (bytes) => [...bytes].map((b) => b.toString(16).padStart(2, "0")).join(" ");
28
+ const byte = (b) => `0x${b.toString(16).padStart(2, "0")}`;
29
+ const secondsOf = (ms) => `${Math.round(ms / 100) / 10} s`;
30
+ const shown = (argv) => argv.map((word) => (/^[\w./=:-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`)).join(" ");
31
+ const ALL_BYTES = Uint8Array.from({ length: 256 }, (_, i) => i);
32
+ /** printf's format for every byte value, 0 to 255, each as an octal escape: dash, bash and busybox all read it. */
33
+ const PRINTF_ALL = [...ALL_BYTES].map((b) => `\\${b.toString(8).padStart(3, "0")}`).join("");
34
+ /**
35
+ * Why `got` is not `sent`, in words, or undefined when they are the same bytes. `way` is where they went ("on stdout");
36
+ * the first byte that differs is named, and the usual ways an exec mangles bytes are named for what they are.
37
+ */
38
+ export function bytesProblem(sent, got, way) {
39
+ let i = 0;
40
+ while (i < sent.length && i < got.length && sent[i] === got[i])
41
+ i++;
42
+ if (i === sent.length && i === got.length)
43
+ return undefined;
44
+ if (i === got.length) {
45
+ 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" : "";
46
+ return `only ${got.length} of ${sent.length} bytes came back ${way}${nul}. Pass every byte on as it comes`;
47
+ }
48
+ if (i === sent.length)
49
+ 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`;
50
+ const b = sent[i];
51
+ const at = got.subarray(i, i + 3);
52
+ const was = `byte ${byte(b)} came back ${way} as ${hex(at)}`;
53
+ if (b >= 0x80 && at[0] === 0xef && at[1] === 0xbf && at[2] === 0xbd) {
54
+ 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`;
55
+ }
56
+ if (b >= 0x80 && at[0] === (0xc0 | (b >> 6)) && at[1] === (0x80 | (b & 0x3f))) {
57
+ 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`;
58
+ }
59
+ if (b === 0x0a && at[0] === 0x0d && at[1] === 0x0a)
60
+ return `${was}: your exec turns \\n into \\r\\n, as a terminal does. Run the process on pipes, not a terminal`;
61
+ if (b === 0x0d && at[0] === 0x0a)
62
+ return `${was}: your exec drops \\r, as newline translation does. Pass every byte on as it comes`;
63
+ return `${was} (offset ${i}): your exec changes bytes. Pass every byte on as it comes, unchanged`;
64
+ }
65
+ /** One output stream of a process, read as it comes: its bytes so far, whether it ended, and a wait for more. */
66
+ class Reader {
67
+ #chunks = [];
68
+ length = 0;
69
+ ended = false;
70
+ error;
71
+ #wake = [];
72
+ constructor(stream) {
73
+ void this.#pump(stream);
74
+ }
75
+ async #pump(stream) {
76
+ try {
77
+ for await (const chunk of stream) {
78
+ // A copy: a vendor's client may reuse its buffer.
79
+ this.#chunks.push(Buffer.from(chunk));
80
+ this.length += chunk.byteLength;
81
+ this.#nudge();
82
+ }
83
+ }
84
+ catch (error) {
85
+ this.error = error;
86
+ }
87
+ this.ended = true;
88
+ this.#nudge();
89
+ }
90
+ #nudge() {
91
+ const waiting = this.#wake;
92
+ this.#wake = [];
93
+ for (const wake of waiting)
94
+ wake();
95
+ }
96
+ bytes() {
97
+ return Buffer.concat(this.#chunks);
98
+ }
99
+ /** Waits until `enough` holds, the stream ends, or ms pass; answers whether `enough` holds. */
100
+ async until(enough, ms, signal) {
101
+ const deadline = Date.now() + ms;
102
+ while (!enough() && !this.ended && Date.now() < deadline && !signal?.aborted) {
103
+ await new Promise((done) => {
104
+ const timer = setTimeout(done, Math.max(1, deadline - Date.now()));
105
+ const finish = () => {
106
+ clearTimeout(timer);
107
+ signal?.removeEventListener("abort", finish);
108
+ done();
109
+ };
110
+ signal?.addEventListener("abort", finish, { once: true });
111
+ this.#wake.push(finish);
112
+ });
113
+ }
114
+ return enough();
115
+ }
116
+ /** Waits for the stream's end, at most ms; answers whether it ended. */
117
+ end(ms, signal) {
118
+ return this.until(() => this.ended, ms, signal);
119
+ }
120
+ }
121
+ /** A promise's value (or its rejection), or `late` once ms pass or signal aborts. */
122
+ function within(promise, ms, late, signal) {
123
+ return new Promise((settle, reject) => {
124
+ const timer = setTimeout(() => finish(() => settle(late)), ms);
125
+ const onAbort = () => finish(() => settle(late));
126
+ signal?.addEventListener("abort", onAbort, { once: true });
127
+ let settled = false;
128
+ function finish(then) {
129
+ if (settled)
130
+ return;
131
+ settled = true;
132
+ clearTimeout(timer);
133
+ signal?.removeEventListener("abort", onAbort);
134
+ then();
135
+ }
136
+ promise.then((value) => finish(() => settle(value)), (error) => finish(() => reject(error)));
137
+ });
138
+ }
139
+ const LATE = Symbol("late");
140
+ /** The pre-check's run of host.exec on one machine. */
141
+ class Session {
142
+ #host;
143
+ #machine;
144
+ #stepMs;
145
+ #signal;
146
+ #runs = [];
147
+ constructor(host, machine, stepMs, signal) {
148
+ this.#host = host;
149
+ this.#machine = machine;
150
+ this.#stepMs = stepMs;
151
+ this.#signal = signal;
152
+ }
153
+ get stepMs() {
154
+ return this.#stepMs;
155
+ }
156
+ get signal() {
157
+ return this.#signal;
158
+ }
159
+ /**
160
+ * exec(argv), answered within the step's bound; any failure (a throw) is a Problem naming the command. Without stdin,
161
+ * end() is called at once, as the adapter does.
162
+ */
163
+ async start(argv, stdin) {
164
+ const what = `exec of ${shown(argv)}`;
165
+ let answer;
166
+ try {
167
+ answer = Promise.resolve(this.#host.exec(this.#machine, argv, { timeoutMs: this.#stepMs, ...(this.#signal ? { signal: this.#signal } : {}) }));
168
+ }
169
+ catch (error) {
170
+ throw new Problem(`${what} threw: ${words(error)}`);
171
+ }
172
+ let answered;
173
+ try {
174
+ answered = await within(answer, this.#stepMs + 5_000, LATE, this.#signal);
175
+ }
176
+ catch (error) {
177
+ throw new Problem(`${what} failed: ${words(error)}`);
178
+ }
179
+ if (answered === LATE) {
180
+ // One that answers after this gave up is killed as it lands.
181
+ answer.then((late) => late?.kill?.()).catch(() => { });
182
+ throw new Problem(`${what} did not answer within ${secondsOf(this.#stepMs)}: exec answers once the process has started, not when it ends`);
183
+ }
184
+ if (answered === undefined || answered === null || typeof answered !== "object")
185
+ throw new Problem(`${what} answered ${String(answered)}, not a process: answer the MachineProcess or throw`);
186
+ const proc = answered;
187
+ const lacks = ["write", "end", "wait", "kill"].filter((name) => typeof proc?.[name] !== "function");
188
+ if (proc?.stdout?.[Symbol.asyncIterator] === undefined)
189
+ lacks.unshift("stdout");
190
+ if (proc?.stderr?.[Symbol.asyncIterator] === undefined)
191
+ lacks.unshift("stderr");
192
+ if (lacks.length > 0)
193
+ throw new Problem(`${what} answered a process that lacks ${lacks.join(", ")}: a MachineProcess (src/host.ts) has stdout, stderr, write, end, wait and kill`);
194
+ const run = { proc, out: new Reader(proc.stdout), err: new Reader(proc.stderr), exited: Promise.resolve(0) };
195
+ run.exited = Promise.resolve()
196
+ .then(() => proc.wait())
197
+ .then((code) => {
198
+ run.exitCode = code;
199
+ return code;
200
+ });
201
+ run.exited.catch(() => { });
202
+ this.#runs.push(run);
203
+ // Not awaited: a command that reads no input runs on whether or not the vendor answers the close.
204
+ if (!stdin)
205
+ Promise.resolve().then(() => proc.end()).catch(() => { });
206
+ return run;
207
+ }
208
+ /**
209
+ * Writes bytes to the process's stdin, in WRITE_CHUNK pieces, one after another; a refusal is a Problem. Each write
210
+ * is bounded by the step, and by `by` when the check has one deadline for all of its steps.
211
+ */
212
+ async write(run, bytes, what, by) {
213
+ for (let at = 0; at < bytes.length; at += WRITE_CHUNK) {
214
+ const ms = by ? by.left(this.#stepMs) : this.#stepMs;
215
+ // Whether the deadline, not the step, set this bound. Asking by.passed() after the timeout is not enough: a
216
+ // timer can fire a millisecond before Date.now() reads the deadline.
217
+ const deadlineBound = by !== undefined && ms < this.#stepMs;
218
+ const written = await within(Promise.resolve().then(() => run.proc.write(bytes.subarray(at, at + WRITE_CHUNK))), ms, LATE, this.#signal).catch((error) => {
219
+ throw new Problem(`write() of ${what} failed while the process ran: ${words(error)}`);
220
+ });
221
+ // within() answers LATE for an abort too: a stopped write names no bound that did not run out.
222
+ if (written === LATE && this.#signal?.aborted)
223
+ throw new Problem(`writing ${what} was stopped, with ${at} bytes written`);
224
+ if (written === LATE)
225
+ 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)}`);
226
+ }
227
+ }
228
+ /** Ends the process's stdin; a refusal is a Problem. */
229
+ async end(run, by) {
230
+ const ms = by ? by.left(this.#stepMs) : this.#stepMs;
231
+ const ended = await within(Promise.resolve().then(() => run.proc.end()), ms, LATE, this.#signal).catch((error) => {
232
+ throw new Problem(`end() failed: ${words(error)}`);
233
+ });
234
+ if (ended === LATE)
235
+ throw new Problem(`end() did not answer within ${secondsOf(ms)}`);
236
+ }
237
+ /** wait()'s exit code within ms; one that never comes, or a wait() that throws, is a Problem. */
238
+ async exit(run, ms, what) {
239
+ let code;
240
+ try {
241
+ code = await within(run.exited, ms, LATE, this.#signal);
242
+ }
243
+ catch (error) {
244
+ throw new Problem(`wait() for ${what} threw: ${words(error)}`);
245
+ }
246
+ if (code === LATE)
247
+ throw new Problem(`wait() for ${what} gave no exit code within ${secondsOf(ms)}`);
248
+ if (typeof code !== "number" || !Number.isInteger(code))
249
+ throw new Problem(`wait() for ${what} answered ${String(code)}, not an exit code`);
250
+ return code;
251
+ }
252
+ /**
253
+ * Kills every process this session started, after each check, pass or fail. Every one, ended or not: an exit code
254
+ * from the wait() under test is no proof the process is gone, and kill() of an ended one costs nothing.
255
+ */
256
+ async killAll() {
257
+ const runs = this.#runs.splice(0);
258
+ await Promise.all(runs.map((run) => within(Promise.resolve().then(() => run.proc.kill()), 10_000, undefined).catch(() => { })));
259
+ }
260
+ }
261
+ /** One deadline for every step of a check: what is left of it, at most a step's bound. */
262
+ class Deadline {
263
+ ms;
264
+ #at;
265
+ constructor(ms) {
266
+ this.ms = ms;
267
+ this.#at = Date.now() + ms;
268
+ }
269
+ left(most) {
270
+ return Math.max(1, Math.min(most, this.#at - Date.now()));
271
+ }
272
+ passed() {
273
+ return Date.now() >= this.#at;
274
+ }
275
+ }
276
+ const CHECKS = {
277
+ /** Every byte value out, on stdout alone: printf in the machine writes them. */
278
+ async "stdout-bytes"(s) {
279
+ const argv = ["sh", "-c", 'printf "$1"', "sh", PRINTF_ALL];
280
+ const run = await s.start(argv, false);
281
+ if (!(await run.out.end(s.stepMs, s.signal)))
282
+ throw new Problem(`stdout of printf did not end within ${secondsOf(s.stepMs)} of its start`);
283
+ const code = await s.exit(run, s.stepMs, "printf");
284
+ if (code !== 0)
285
+ throw new Problem(`printf of the 256 byte values exited ${code} (stderr: ${run.err.bytes().toString("utf8").trim().slice(0, 200) || "none"})`);
286
+ const problem = bytesProblem(ALL_BYTES, run.out.bytes(), "on stdout");
287
+ if (problem)
288
+ throw new Problem(problem);
289
+ return "all 256 byte values printed in the machine came back unchanged on stdout";
290
+ },
291
+ /** Every byte value in on stdin and out again, through cat. */
292
+ async "stdin-bytes"(s, _options, earlier) {
293
+ const run = await s.start(["cat"], true);
294
+ await s.write(run, ALL_BYTES, "the 256 byte values");
295
+ await s.end(run);
296
+ if (!(await run.out.end(s.stepMs, s.signal)))
297
+ 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`);
298
+ await s.exit(run, s.stepMs, "cat");
299
+ const outOk = earlier.get("stdout-bytes")?.status === "pass";
300
+ const problem = bytesProblem(ALL_BYTES, run.out.bytes(), "through cat");
301
+ if (problem)
302
+ throw new Problem(outOk ? `${problem}. stdout alone passes every byte (stdout-bytes), so they changed on the way in, on stdin` : problem);
303
+ return "all 256 byte values written to stdin came back unchanged through cat";
304
+ },
305
+ /** A large random payload through cat, read while it is written, compared by sha256, all within largeMs. */
306
+ async large(s, { largeBytes, largeMs }) {
307
+ const payload = randomBytes(largeBytes);
308
+ const started = Date.now();
309
+ const by = new Deadline(largeMs);
310
+ const run = await s.start(["cat"], true);
311
+ await s.write(run, payload, `${largeBytes} random bytes`, by);
312
+ await s.end(run, by);
313
+ if (!(await run.out.end(by.left(largeMs), s.signal))) {
314
+ 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`);
315
+ }
316
+ await s.exit(run, by.left(s.stepMs), "cat");
317
+ if (by.passed())
318
+ throw new Problem(`${largeBytes} bytes through cat took ${secondsOf(Date.now() - started)}, past ${secondsOf(largeMs)}: your exec is too slow`);
319
+ const got = run.out.bytes();
320
+ const sent = createHash("sha256").update(payload).digest("hex");
321
+ const back = createHash("sha256").update(got).digest("hex");
322
+ if (sent !== back) {
323
+ 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"}`);
324
+ }
325
+ return `${largeBytes} random bytes came back through cat with the same sha256 in ${secondsOf(Date.now() - started)}`;
326
+ },
327
+ /** Output comes back while the process runs: printf, then a sleep that never ends on its own. */
328
+ async "stdout-live"(s) {
329
+ const run = await s.start(["sh", "-c", "printf early; exec sleep 600"], false);
330
+ const came = await run.out.until(() => run.out.length >= 5, s.stepMs, s.signal);
331
+ if (!came) {
332
+ if (run.out.ended)
333
+ throw new Problem(`stdout ended with ${JSON.stringify(run.out.bytes().toString("latin1"))} before the process did: stdout must stay open until the process ends`);
334
+ throw new Problem(`the process printed "early" at once, then slept, and nothing came back on stdout in ${secondsOf(s.stepMs)}: your exec holds output until the process exits. Pass each byte on as it comes`);
335
+ }
336
+ const got = run.out.bytes().toString("latin1");
337
+ if (got !== "early")
338
+ throw new Problem(`stdout read ${JSON.stringify(got)}, not "early"`);
339
+ // "early" alone is not live: the sleep still runs, so stdout stays open and wait() has no answer yet.
340
+ if (await run.out.end(LIVE_GRACE_MS, s.signal))
341
+ throw new Problem(`stdout ended right after "early", while the process still slept: stdout must stay open until the process ends`);
342
+ if (run.exitCode !== undefined)
343
+ throw new Problem(`wait() answered ${run.exitCode} right after "early", while the process still slept: wait() answers once the process ends`);
344
+ return `"early" came back while the process still ran`;
345
+ },
346
+ /** stdin reaches the process as it is written: cat echoes one write, then another, with stdin still open. */
347
+ async "stdin-live"(s, _options, earlier) {
348
+ const run = await s.start(["cat"], true);
349
+ const outLive = earlier.get("stdout-live")?.status === "pass";
350
+ const rounds = [Buffer.from("first write\n"), Buffer.from("second write\n")];
351
+ let want = 0;
352
+ for (const [i, chunk] of rounds.entries()) {
353
+ await s.write(run, chunk, `write ${i + 1}`);
354
+ want += chunk.length;
355
+ const came = await run.out.until(() => run.out.length >= want, s.stepMs, s.signal);
356
+ if (!came) {
357
+ if (run.out.ended)
358
+ throw new Problem(`cat's stdout ended after write ${i + 1}, with stdin still open: exec must keep the process and its stdin open until end()`);
359
+ throw new Problem(outLive
360
+ ? `write ${i + 1} to cat, with stdin still open, never came back on stdout in ${secondsOf(s.stepMs)}, though output does come back as it is printed: your exec holds stdin until end(). Pass each write on as it comes`
361
+ : `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)`);
362
+ }
363
+ }
364
+ const problem = bytesProblem(Buffer.concat(rounds), run.out.bytes(), "through cat");
365
+ if (problem)
366
+ throw new Problem(problem);
367
+ await s.end(run);
368
+ const code = await s.exit(run, s.stepMs, "cat");
369
+ if (code !== 0)
370
+ throw new Problem(`cat exited ${code} after end(), not 0`);
371
+ return "two writes came back through cat, each before the next was written, while stdin stayed open";
372
+ },
373
+ /** stderr comes back apart from stdout. */
374
+ async stderr(s) {
375
+ const run = await s.start(["sh", "-c", "printf to-stdout; printf to-stderr >&2"], false);
376
+ await run.out.end(s.stepMs, s.signal);
377
+ await run.err.end(s.stepMs, s.signal);
378
+ await s.exit(run, s.stepMs, "the two printfs");
379
+ const out = run.out.bytes().toString("latin1");
380
+ const err = run.err.bytes().toString("latin1");
381
+ if (out.includes("to-stderr"))
382
+ throw new Problem(`what the process wrote to stderr came back on stdout (stdout read ${JSON.stringify(out)}): your exec merges the two streams. Keep them apart`);
383
+ if (err.includes("to-stdout"))
384
+ throw new Problem(`what the process wrote to stdout came back on stderr (stderr read ${JSON.stringify(err)}): keep the two streams apart`);
385
+ if (out !== "to-stdout")
386
+ throw new Problem(`stdout read ${JSON.stringify(out)}, not "to-stdout"`);
387
+ if (err !== "to-stderr")
388
+ throw new Problem(`stderr read ${JSON.stringify(err)}, not "to-stderr": your exec drops or changes stderr`);
389
+ return "stdout and stderr came back apart, each with its own bytes";
390
+ },
391
+ /** wait() gives the process's own exit code. */
392
+ async "exit-code"(s) {
393
+ const run = await s.start(["sh", "-c", "exit 7"], false);
394
+ const code = await s.exit(run, s.stepMs, "sh -c 'exit 7'");
395
+ if (code !== 7)
396
+ throw new Problem(`sh -c 'exit 7' gave ${code} from wait(), not 7: wait() answers the process's own exit code`);
397
+ return "wait() gave 7 for sh -c 'exit 7'";
398
+ },
399
+ /** kill() ends a process that would run for ten minutes, wait() then answers, and the process is gone. */
400
+ async kill(s) {
401
+ const run = await s.start(["sh", "-c", "echo $$; exec sleep 600"], false);
402
+ const line = await run.out.until(() => run.out.bytes().includes(0x0a), s.stepMs, s.signal);
403
+ if (!line)
404
+ throw new Problem(`the process's pid never came back on stdout in ${secondsOf(s.stepMs)}`);
405
+ const pid = run.out.bytes().toString("latin1").trim();
406
+ if (!/^[1-9][0-9]*$/.test(pid))
407
+ throw new Problem(`the process printed ${JSON.stringify(pid)}, not its pid`);
408
+ const killed = await within(Promise.resolve().then(() => run.proc.kill()), s.stepMs, LATE, s.signal).catch((error) => {
409
+ throw new Problem(`kill() threw: ${words(error)}. It ends the process best effort and never throws`);
410
+ });
411
+ if (killed === LATE)
412
+ throw new Problem(`kill() did not answer within ${secondsOf(s.stepMs)}`);
413
+ // wait() after kill, then the machine's own word on the pid, whichever fails first named by the second.
414
+ const waited = await s.exit(run, s.stepMs, "the killed sleep").then(() => undefined, (error) => error);
415
+ const probe = await s.start(["sh", "-c", 'if kill -0 "$1" 2>/dev/null; then echo running; else echo gone; fi', "sh", pid], false);
416
+ await probe.out.end(s.stepMs, s.signal);
417
+ await s.exit(probe, s.stepMs, "kill -0");
418
+ const state = probe.out.bytes().toString("latin1").trim();
419
+ if (state === "running")
420
+ throw new Problem(`kill() answered, but process ${pid} still runs in the machine: kill() must end the process, not only let go of its streams`);
421
+ if (state !== "gone")
422
+ throw new Problem(`kill -0 ${pid} printed ${JSON.stringify(state)}, not "gone"`);
423
+ if (waited !== undefined)
424
+ throw waited;
425
+ return `kill() ended a sleep of 600 s, wait() answered, and process ${pid} is gone`;
426
+ },
427
+ /** A process that runs, silent, past the usual command and idle timeouts is not cut off. */
428
+ async "no-timeout"(s, { longMs }) {
429
+ const seconds = Math.max(1, Math.round(longMs / 1000));
430
+ const started = Date.now();
431
+ const run = await s.start(["sh", "-c", `sleep ${seconds}; printf done`], false);
432
+ await run.out.end(seconds * 1000 + s.stepMs, s.signal);
433
+ const code = await s.exit(run, s.stepMs, `sleep ${seconds}`);
434
+ const ran = Date.now() - started;
435
+ const out = run.out.bytes().toString("latin1");
436
+ if (code !== 0 || out !== "done") {
437
+ const how = code !== 0 ? `exited ${code}` : `printed ${JSON.stringify(out)}`;
438
+ throw new Problem(`a process that sleeps ${seconds} s, silent, then prints "done", ${how} after ${secondsOf(ran)}: your exec has a command timeout, or the stream an idle timeout. Turn both off: AgentRun's daemon talks over one exec for the computer's whole life`);
439
+ }
440
+ if (ran < seconds * 1000 - 1000)
441
+ throw new Problem(`a sleep of ${seconds} s ended after ${secondsOf(ran)}`);
442
+ return `a process that slept ${seconds} s, silent, ran to its end and printed "done"`;
443
+ },
444
+ };
445
+ /**
446
+ * The exec pre-check on one machine: each check in EXEC_STREAM_CHECKS runs in turn, and the report passes when every one
447
+ * does. host.exec is the only member called.
448
+ */
449
+ export async function checkExecStream(host, machine, options = {}) {
450
+ const { longMs = DEFAULT_LONG_MS, stepMs = DEFAULT_STEP_MS, largeBytes = DEFAULT_LARGE_BYTES, largeMs = DEFAULT_LARGE_MS, signal, onCheck } = options;
451
+ const session = new Session(host, machine, stepMs, signal);
452
+ const done = new Map();
453
+ for (const id of EXEC_STREAM_CHECKS) {
454
+ const started = Date.now();
455
+ let check;
456
+ if (signal?.aborted)
457
+ check = { id, status: "fail", words: "the run was aborted before this check", ms: 0 };
458
+ else {
459
+ try {
460
+ const said = await CHECKS[id](session, { longMs, largeBytes, largeMs }, done);
461
+ check = { id, status: "pass", words: said, ms: Date.now() - started };
462
+ }
463
+ catch (error) {
464
+ const said = error instanceof Problem ? error.message : `the check itself failed: ${words(error)}`;
465
+ check = { id, status: "fail", words: signal?.aborted ? `aborted: ${said}` : said, ms: Date.now() - started };
466
+ }
467
+ await session.killAll();
468
+ }
469
+ done.set(id, check);
470
+ onCheck?.(check);
471
+ }
472
+ const checks = [...done.values()];
473
+ return { host: host.descriptor.id, machine, checks, pass: checks.every((check) => check.status === "pass") };
474
+ }
475
+ /** The report as a person reads it: one line per check, what failed in words, the verdict last. */
476
+ export function formatExecStream(report) {
477
+ const width = Math.max(...EXEC_STREAM_CHECKS.map((id) => id.length));
478
+ const lines = [`exec pre-check · ${report.host} · machine ${report.machine}`];
479
+ for (const check of report.checks)
480
+ lines.push(`${check.status === "pass" ? "✓" : "✗"} ${check.id.padEnd(width)} ${check.words}`);
481
+ const failed = report.checks.filter((check) => check.status === "fail").length;
482
+ lines.push(report.pass
483
+ ? "exec PASS: a live, two-way, byte-exact stream with no timeout. Write the rest of your host next."
484
+ : `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.`);
485
+ return `${lines.join("\n")}\n`;
486
+ }
@@ -6,7 +6,7 @@ export declare const FIXTURE_WINDOW: Rect;
6
6
  export declare const FIXTURE_COLORS: ReadonlyArray<readonly [number, number, number]>;
7
7
  /** The fixture APK's application id. */
8
8
  export declare const FIXTURE_APP_ID = "ai.agentrun.fixture";
9
- /** The APK's button, found in apps.ui_tree by its id. */
9
+ /** The APK's button, found in ui.observe by its id, its name the button's text. */
10
10
  export declare const FIXTURE_BUTTON: {
11
11
  readonly id: "ai.agentrun.fixture:id/button";
12
12
  readonly text: "agentrun fixture";
@@ -4,6 +4,8 @@
4
4
  // Android it is a small APK that logs touches and its own launch to its files directory and shows a button with a fixed
5
5
  // id. This file is their contract: the binary and the APK come with the PRs that first run them. On a Windows desktop it
6
6
  // is a PowerShell script this package carries (windows-fixture.ts), the same window, started detached with Start-Process.
7
+ // On a Mac it is UIFixture.app (daemon-macos) started with --input-log: the same quadrants at the display's top left,
8
+ // whose ready line gives its bounds in pixels.
7
9
  import { readFileSync } from "node:fs";
8
10
  import { readFile, writeFile } from "../files.js";
9
11
  import { WINDOWS_FIXTURE } from "./windows-fixture.js";
@@ -18,7 +20,7 @@ export const FIXTURE_COLORS = [
18
20
  ];
19
21
  /** The fixture APK's application id. */
20
22
  export const FIXTURE_APP_ID = "ai.agentrun.fixture";
21
- /** The APK's button, found in apps.ui_tree by its id. */
23
+ /** The APK's button, found in ui.observe by its id, its name the button's text. */
22
24
  export const FIXTURE_BUTTON = { id: `${FIXTURE_APP_ID}:id/button`, text: "agentrun fixture" };
23
25
  /** Where the APK is written on a phone before apps.install. */
24
26
  export const FIXTURE_APK_PATH = "/data/local/tmp/agentrun-fixture.apk";
@@ -82,6 +84,28 @@ export async function startFixture(t, path, launched) {
82
84
  await ready(t, events, "the Windows desktop fixture");
83
85
  return { bounds: FIXTURE_WINDOW, events, stop };
84
86
  }
87
+ if (kind === "desktop" && os === "macos") {
88
+ // A Mac's fixture is UIFixture.app already on it (path is the app), started by open with --input-log, so it
89
+ // comes to the front as an app does. Its ready line names its pid and its window in screenshot pixels: the
90
+ // window sits at the display's top left, its size in pixels the display's scale times 200 points.
91
+ needs(t, ["exec", "files"], "the macOS desktop fixture");
92
+ const log = `${await t.dir()}/events.jsonl`;
93
+ const started = await t.exec(["/usr/bin/open", "-n", "-a", path, "--args", "--input-log", log]);
94
+ t.equal(started.exitCode, 0, `open of the fixture ${path} (stderr ${JSON.stringify(started.err.trim())})`);
95
+ const events = () => logOf(t, log);
96
+ const readyLine = async () => (await events().catch(() => [])).find((e) => e.event === "ready");
97
+ const stop = async () => {
98
+ const pid = (await readyLine())?.pid;
99
+ if (Number.isSafeInteger(pid))
100
+ await t.client.call("exec.run", { argv: ["/bin/kill", String(pid)], timeoutMs: 30_000 });
101
+ };
102
+ launched(stop);
103
+ await ready(t, events, "the macOS desktop fixture");
104
+ const bounds = (await readyLine())?.bounds;
105
+ const isRect = Array.isArray(bounds) && bounds.length === 4 && bounds.every((n) => Number.isSafeInteger(n));
106
+ t.assert(isRect, `the macOS fixture's ready line gives its bounds as [x, y, w, h], not ${JSON.stringify(bounds)}`);
107
+ return { bounds: bounds, events, stop };
108
+ }
85
109
  if (kind === "desktop") {
86
110
  needs(t, ["exec", "files", "processes"], "the desktop fixture");
87
111
  const dir = await t.dir();
@@ -1,7 +1,7 @@
1
+ import type { MachineHost } from "../host.js";
2
+ import { type ModalClientConstructor, type ModalCreateOptions, type ModalProvider } from "../modal.js";
1
3
  import type { MountKind } from "../mount.js";
2
4
  import type { ProviderNote } from "../mount-archil.js";
3
- import type { ComputerProvider } from "../provider.js";
4
- import { type ModalClientConstructor, type ModalCreateOptions } from "../modal.js";
5
5
  import { type ArchilRunFolderOptions } from "./archil.js";
6
6
  import type { RunFolder } from "./types.js";
7
7
  /** The Archil disk's settings for the mount cases, by name (COMPUTER_ARCHIL_*: all five, or none). */
@@ -14,8 +14,6 @@ export declare const MODAL_ENV: {
14
14
  readonly tokenSecret: "COMPUTER_MODAL_TOKEN_SECRET";
15
15
  /** app, required: the Modal App the run's sandboxes live in, made when missing. */
16
16
  readonly app: "COMPUTER_MODAL_APP";
17
- /** daemonImage: an image holding the daemon, pinned by digest, to COPY --from instead of uploading it. */
18
- readonly daemonImage: "COMPUTER_MODAL_DAEMON_IMAGE";
19
17
  /** serverUrl: the server the token goes to; the SDK's default when unset. */
20
18
  readonly serverUrl: "COMPUTER_MODAL_SERVER_URL";
21
19
  };
@@ -27,13 +25,11 @@ export declare const ENV: {
27
25
  readonly tokenSecret: "COMPUTER_MODAL_TOKEN_SECRET";
28
26
  /** app, required: the Modal App the run's sandboxes live in, made when missing. */
29
27
  readonly app: "COMPUTER_MODAL_APP";
30
- /** daemonImage: an image holding the daemon, pinned by digest, to COPY --from instead of uploading it. */
31
- readonly daemonImage: "COMPUTER_MODAL_DAEMON_IMAGE";
32
28
  /** serverUrl: the server the token goes to; the SDK's default when unset. */
33
29
  readonly serverUrl: "COMPUTER_MODAL_SERVER_URL";
34
30
  };
35
- /** What this module reads from the environment: the token, the app, and the server and daemon image when set. */
36
- export type ModalSettings = Pick<ModalCreateOptions, "tokenId" | "tokenSecret" | "app" | "serverUrl" | "daemonImage">;
31
+ /** What this module reads from the environment: the token, the app, and the server when set. */
32
+ export type ModalSettings = Pick<ModalCreateOptions, "tokenId" | "tokenSecret" | "app" | "serverUrl">;
37
33
  /**
38
34
  * The provider's options this module reads from env; throws in words without the token or the app, or while
39
35
  * MODAL_SERVER_URL is set there (the SDK would send the token to it), never echoing a token.
@@ -46,7 +42,7 @@ export interface ModalModuleOptions {
46
42
  env?: Record<string, string | undefined>;
47
43
  /** The SDK's ModalClient; imported from the host's modal package by default. */
48
44
  ModalClient?: ModalClientConstructor;
49
- /** The daemon to upload, when COMPUTER_MODAL_DAEMON_IMAGE names no image; default this package's dist/computerd-linux-amd64. */
45
+ /** The daemon to upload; default this package's dist/computerd-linux-amd64. */
50
46
  daemonPath?: string;
51
47
  /** Builds this package's daemon for linux/amd64 stamped with version, and gives its path; default go build. */
52
48
  buildDaemon?: (version: string) => Promise<string>;
@@ -55,7 +51,8 @@ export interface ModalModuleOptions {
55
51
  /** What the provider says that is no failure: the CLI gives it and puts it in the report. */
56
52
  onNote?: ProviderNote;
57
53
  }
58
- export declare function createProvider({ env, ModalClient, daemonPath, onNote }?: ModalModuleOptions): Promise<ComputerProvider>;
54
+ /** The provider the CLI runs; throws in words without the live switch, or when a setting is missing or wrong. */
55
+ export declare function createProvider({ env, ModalClient, daemonPath, onNote }?: ModalModuleOptions): Promise<ModalProvider>;
59
56
  /**
60
57
  * A run folder for an Archil mount, and none for any other kind (a Modal computer takes no bind): a fresh folder on the
61
58
  * disk the COMPUTER_ARCHIL_* names name (archilSettings), none when they name none (archilRunFolder, ./archil.ts).
@@ -63,7 +60,14 @@ export declare function createProvider({ env, ModalClient, daemonPath, onNote }?
63
60
  */
64
61
  export declare function mountFor(kind: MountKind, { env, archil }?: ModalModuleOptions): Promise<RunFolder | undefined>;
65
62
  /**
66
- * The same provider uploading a daemon that reports version <version>-drift, for the drift.version case, whatever image
67
- * COMPUTER_MODAL_DAEMON_IMAGE names.
63
+ * The Modal host the live sweep (sweep.ts) lists and deletes through, from the same settings; it needs no live switch,
64
+ * since the sweep makes nothing, and it calls nothing until the sweep does.
68
65
  */
69
- export declare function createDriftedProvider({ env, ModalClient, buildDaemon }?: ModalModuleOptions): Promise<ComputerProvider>;
66
+ export declare function createHost({ env, ModalClient }?: Pick<ModalModuleOptions, "env" | "ModalClient">): Promise<MachineHost>;
67
+ /**
68
+ * Where the sweep lists, in words: the app and the server the settings name. A before file of another app, or of the
69
+ * same app name on another server, would make every computer there read as new, so the sweep refuses it.
70
+ */
71
+ export declare function sweepScope({ env }?: Pick<ModalModuleOptions, "env">): string;
72
+ /** The same provider uploading a daemon that reports version <version>-drift, for the drift.version case. */
73
+ export declare function createDriftedProvider({ env, ModalClient, buildDaemon }?: ModalModuleOptions): Promise<ModalProvider>;