@parcha/agentrun-computer 0.1.0-beta.33 → 0.1.0-beta.34

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 (59) hide show
  1. package/README.md +169 -15
  2. package/dist/browser.d.ts +1 -1
  3. package/dist/browser.js +6 -3
  4. package/dist/browserbase.d.ts +3 -1
  5. package/dist/browserbase.js +3 -1
  6. package/dist/child.d.ts +2 -0
  7. package/dist/child.js +13 -2
  8. package/dist/chrome.d.ts +73 -0
  9. package/dist/chrome.js +224 -0
  10. package/dist/computerd-linux-amd64 +0 -0
  11. package/dist/computerd-linux-arm64 +0 -0
  12. package/dist/conformance/cases/gpu.d.ts +2 -0
  13. package/dist/conformance/cases/gpu.js +108 -0
  14. package/dist/conformance/cases/health.js +83 -3
  15. package/dist/conformance/cases/index.js +2 -0
  16. package/dist/conformance/cases/mount.d.ts +8 -1
  17. package/dist/conformance/cases/mount.js +4 -3
  18. package/dist/conformance/cases/provider.js +14 -0
  19. package/dist/conformance/cli.js +46 -7
  20. package/dist/conformance/local.d.ts +30 -0
  21. package/dist/conformance/local.js +36 -0
  22. package/dist/conformance/report.js +10 -5
  23. package/dist/conformance/runner.js +45 -13
  24. package/dist/conformance/types.d.ts +63 -16
  25. package/dist/daytona.d.ts +32 -3
  26. package/dist/daytona.js +96 -24
  27. package/dist/docker.d.ts +3 -1
  28. package/dist/docker.js +11 -3
  29. package/dist/drift.d.ts +3 -1
  30. package/dist/drift.js +9 -0
  31. package/dist/e2b.d.ts +3 -1
  32. package/dist/e2b.js +7 -4
  33. package/dist/index.d.ts +4 -2
  34. package/dist/index.js +4 -2
  35. package/dist/isolation.d.ts +0 -2
  36. package/dist/isolation.js +0 -16
  37. package/dist/kernel.d.ts +3 -1
  38. package/dist/kernel.js +3 -1
  39. package/dist/kinds.d.ts +10 -4
  40. package/dist/kinds.js +26 -6
  41. package/dist/labels.d.ts +6 -0
  42. package/dist/labels.js +26 -1
  43. package/dist/local-supervisor.d.ts +51 -0
  44. package/dist/local-supervisor.js +221 -0
  45. package/dist/local.d.ts +89 -0
  46. package/dist/local.js +472 -0
  47. package/dist/modal.d.ts +31 -4
  48. package/dist/modal.js +90 -30
  49. package/dist/orgo.d.ts +3 -1
  50. package/dist/orgo.js +14 -27
  51. package/dist/phone-harness.d.ts +3 -1
  52. package/dist/phone-harness.js +7 -4
  53. package/dist/protocol.d.ts +20 -0
  54. package/dist/protocol.js +9 -0
  55. package/dist/provider.d.ts +63 -3
  56. package/dist/provider.js +28 -0
  57. package/dist/providers.d.ts +7 -1
  58. package/dist/providers.js +1 -0
  59. package/package.json +1 -1
package/dist/chrome.js ADDED
@@ -0,0 +1,224 @@
1
+ // Launching a Chrome on this machine, the pieces the local browser (local.ts, local-supervisor.ts) is made of. Moved
2
+ // here from pi-browser, which starts its own local Chrome (packages/pi-browser/src/providers/chrome-args.ts findChrome, and
3
+ // src/providers/cdp.ts alive, leadsOwnGroup, killTree, ownDebugger and singletonDir), so pi-browser can import them back
4
+ // once it depends on this package; and the fence and sandbox check of PR #1718's local Chrome for serve
5
+ // (packages/serve/src/local-chrome.ts chromeFence and checkChrome), less what was there for Stagehand's extension.
6
+ //
7
+ // The library reads no environment: where pi-browser read CHROME_PATH and PATH from process.env, findChrome takes the
8
+ // environment it is given.
9
+ import { spawn } from "node:child_process";
10
+ import { constants, existsSync, readFileSync } from "node:fs";
11
+ import { access, mkdtemp, readFile, readlink, rm, stat } from "node:fs/promises";
12
+ import { tmpdir } from "node:os";
13
+ import { basename, delimiter, dirname, join, resolve } from "node:path";
14
+ import { fail, ok } from "./result.js";
15
+ /** The names a Chrome or Chromium goes by on a Linux PATH. */
16
+ const LINUX_NAMES = ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"];
17
+ /** Where a Chrome is installed when no PATH names it: Linux's packages, macOS's and Windows' installers. */
18
+ const FIXED = [
19
+ "/usr/bin/google-chrome",
20
+ "/usr/bin/chromium",
21
+ "/usr/bin/chromium-browser",
22
+ "/opt/google/chrome/chrome",
23
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
24
+ "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
25
+ ];
26
+ /** The environment names a Chrome is found by: pi-browser's own, then the common one. */
27
+ export const CHROME_ENV = ["PI_BROWSER_CHROME", "CHROME_PATH"];
28
+ /**
29
+ * The Chrome or Chromium on this machine: the one PI_BROWSER_CHROME or CHROME_PATH names in `env`, else the first on
30
+ * env.PATH, else the first of the usual install places; null when there is none. `env` is the caller's: the library
31
+ * reads none.
32
+ */
33
+ export function findChrome(env = {}, exists = existsSync) {
34
+ for (const name of CHROME_ENV) {
35
+ const named = env[name];
36
+ if (named && exists(named))
37
+ return named;
38
+ }
39
+ const onPath = (env.PATH ?? "")
40
+ .split(delimiter)
41
+ .filter(Boolean)
42
+ .flatMap((dir) => LINUX_NAMES.map((name) => join(dir, name)));
43
+ return [...onPath, ...FIXED].find((file) => exists(file)) ?? null;
44
+ }
45
+ /** What to do when there is no Chrome, in words: what to install, and the settings that point at one. */
46
+ export const NO_CHROME = "no Chrome or Chromium was found on this machine: install Google Chrome or Chromium (on Debian or Ubuntu, `apt install chromium` or Google's google-chrome-stable package), or name the executable with the provider's executablePath option, or CHROME_PATH (or PI_BROWSER_CHROME) in the environment the host passes as its env option";
47
+ /**
48
+ * The switches every local Chrome starts with, beside the fence, its profile and its debugging port: no first-run
49
+ * screens, no sign-in or sync, no background traffic of Chrome's own (component updates, field trials, safe-browsing
50
+ * pings), no keychain prompt, no sound.
51
+ */
52
+ export const CHROME_FLAGS = [
53
+ "--no-first-run",
54
+ "--no-default-browser-check",
55
+ "--disable-background-networking",
56
+ "--disable-component-update",
57
+ "--disable-sync",
58
+ "--disable-default-apps",
59
+ "--disable-client-side-phishing-detection",
60
+ "--disable-domain-reliability",
61
+ "--metrics-recording-only",
62
+ "--password-store=basic",
63
+ "--use-mock-keychain",
64
+ "--mute-audio",
65
+ "--disable-features=Translate,OptimizationHints,MediaRouter,DialMediaRouteProvider,AutofillServerCommunication",
66
+ ];
67
+ /**
68
+ * The arguments that hold a local Chrome to its egress proxy at `proxy` (an http URL of a loopback port, the relay to
69
+ * the proxy, which decides): every request through the proxy, loopback too (`<-loopback>` takes away the bypass Chrome
70
+ * gives it by default), so this machine's own services, private networks, link-local and a cloud's metadata address are
71
+ * each refused by the proxy after its lookup; no name or address resolved by Chrome itself but the proxy's, so a request
72
+ * a page sends around the proxy reaches nothing; no QUIC, which goes around an HTTP proxy; and WebRTC on no UDP but the
73
+ * proxy's, which carries none, so no ICE candidate is gathered and no STUN packet leaves. That last is
74
+ * `--webrtc-ip-handling-policy`: Chrome 155 and 156 ignore the `--force-` spelling (#1718 measured a STUN server on
75
+ * loopback sent its binding requests under it). From #1718's chromeFence, less the bypass it kept for the DevTools guard
76
+ * Stagehand's extension dialled: nothing in this browser reaches its own DevTools socket.
77
+ */
78
+ export function chromeFence(proxy) {
79
+ const { hostname, port } = new URL(proxy);
80
+ return [
81
+ `--proxy-server=${proxy}`,
82
+ "--proxy-bypass-list=<-loopback>",
83
+ `--host-resolver-rules=MAP ${hostname}:${port} ${hostname}:${port}, MAP * ~NOTFOUND`,
84
+ "--disable-quic",
85
+ "--webrtc-ip-handling-policy=disable_non_proxied_udp",
86
+ ];
87
+ }
88
+ /** Signal 0 only asks; EPERM means the process exists under another user. */
89
+ export const alive = (pid) => {
90
+ try {
91
+ process.kill(pid, 0);
92
+ return true;
93
+ }
94
+ catch (error) {
95
+ return error.code === "EPERM";
96
+ }
97
+ };
98
+ /** Whether `pid` leads its own process group (a detached child does); null where there is no /proc to ask. */
99
+ export function leadsOwnGroup(pid) {
100
+ if (process.platform !== "linux")
101
+ return null;
102
+ try {
103
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
104
+ // pid (comm) state ppid pgrp ...: the name may hold spaces and brackets, so the fields are counted from its last ")".
105
+ return Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[2]) === pid;
106
+ }
107
+ catch {
108
+ return false;
109
+ }
110
+ }
111
+ /**
112
+ * Kills `pid` and its group. A pid reaches here from a file a restart reads back: `kill(-1)` signals every process the
113
+ * user can, `kill(0)` this process's own group, so neither a pid below 2 nor our own is ever signalled, and a negative
114
+ * pid (a whole group) only for a process that leads one.
115
+ */
116
+ export function killTree(pid, io = {}, signal = "SIGKILL") {
117
+ if (!Number.isInteger(pid) || pid <= 1 || pid === process.pid)
118
+ return;
119
+ const kill = io.kill ?? ((target, how) => process.kill(target, how));
120
+ if ((io.leadsGroup ?? leadsOwnGroup)(pid) !== false) {
121
+ try {
122
+ return kill(-pid, signal);
123
+ }
124
+ catch {
125
+ /* no such group: the process alone */
126
+ }
127
+ }
128
+ try {
129
+ kill(pid, signal);
130
+ }
131
+ catch {
132
+ /* already gone */
133
+ }
134
+ }
135
+ /**
136
+ * Whether `pid` is a process whose command line holds `marker` (a Chrome's `--user-data-dir=<profile>`, a supervisor's
137
+ * directory), so a pid read back from a file never names a recycled process. Where there is no /proc to ask (macOS),
138
+ * whether it is alive.
139
+ */
140
+ export function runsWith(pid, marker) {
141
+ if (!Number.isInteger(pid) || pid <= 1)
142
+ return false;
143
+ if (process.platform !== "linux")
144
+ return alive(pid);
145
+ try {
146
+ // Chrome rewrites its own process title: its arguments then read as one string, joined by spaces.
147
+ const words = ` ${readFileSync(`/proc/${pid}/cmdline`, "utf8").replaceAll("\0", " ")} `;
148
+ return words.includes(` ${marker} `);
149
+ }
150
+ catch {
151
+ return false;
152
+ }
153
+ }
154
+ /** The port and browser path a Chrome on `profile` wrote to its DevToolsActivePort: only that Chrome writes it there. */
155
+ export async function ownDebugger(profile) {
156
+ const [port, browser] = (await readFile(join(profile, "DevToolsActivePort"), "utf8").catch(() => "")).split("\n");
157
+ return /^\d+$/.test(port ?? "") && browser?.startsWith("/devtools/browser/") ? { port: Number(port), path: browser.trim() } : null;
158
+ }
159
+ /** The browser path the DevTools socket on `port` answers /json/version with, or null; bounded, so a socket that takes the connection and never answers holds no one. */
160
+ export async function answeringPath(port, timeoutMs = 2_000) {
161
+ try {
162
+ const reply = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(timeoutMs) }); // key-gate: loopback-rule the local Chrome's own DevTools socket
163
+ const url = (await reply.json()).webSocketDebuggerUrl;
164
+ return typeof url === "string" ? new URL(url).pathname : null;
165
+ }
166
+ catch {
167
+ return null;
168
+ }
169
+ }
170
+ /** Chrome's singleton socket directory under the temp directory outlives every Chrome exit; the profile's link names it. */
171
+ export async function singletonDir(profile) {
172
+ const socket = await readlink(join(profile, "SingletonSocket")).catch(() => null);
173
+ const dir = socket && basename(socket) === "SingletonSocket" ? dirname(socket) : null;
174
+ return dir && /^\.?(org\.chromium\.Chromium|com\.google\.Chrome)\.[A-Za-z0-9]{6}$/.test(basename(dir)) ? dir : null;
175
+ }
176
+ /** What a start whose Chrome could not start its sandbox is told: never to turn it off, which nothing here can. */
177
+ export const NO_SANDBOX = "this machine's Chrome could not start its sandbox, and the local browser never runs Chrome without it, so no browser was started: on Ubuntu 23.10 and later give this Chrome an AppArmor profile that allows it user namespaces, or use a Chrome whose setuid sandbox helper is installed (Google's package installs one)";
178
+ /** What a start as root is told: Chrome refuses root with its sandbox on, and the sandbox is never turned off here. */
179
+ export const AS_ROOT = "the local browser does not start Chrome as root: Chrome refuses root with its sandbox on, and the sandbox is never turned off here. Run AgentRun as a user that is not root";
180
+ /** How long the sandbox check may take: one headless Chrome that loads a blank page and exits. */
181
+ export const CHECK_MS = 30_000;
182
+ /**
183
+ * Whether the Chrome at `path` starts here with its sandbox on: an executable file, a user that is not root, and one
184
+ * headless start on a blank page (`--dump-dom about:blank`) in a profile of its own that goes with it, with a proxy no
185
+ * name or address reaches, so nothing leaves the machine. ok with the resolved path; refused in words that never offer
186
+ * to turn the sandbox off. From #1718's checkChrome. `uid`: the user this process runs as (a test's seam).
187
+ */
188
+ export async function checkChrome(path, { uid = process.getuid?.(), timeoutMs = CHECK_MS } = {}) {
189
+ const at = resolve(path);
190
+ const runs = (await stat(at).then((info) => info.isFile(), () => false)) && (await access(at, constants.X_OK).then(() => true, () => false));
191
+ if (!runs)
192
+ return fail("not_found", `${at} is not an executable file: name a Chrome or Chromium binary with the executablePath option, or leave it out to look in the usual places`);
193
+ if (uid === 0)
194
+ return fail("refused", AS_ROOT);
195
+ // A short directory: Chrome's singleton socket must stay within a Unix socket's 107 bytes.
196
+ const dir = await mkdtemp(join(existsSync("/tmp") ? "/tmp" : tmpdir(), "agentrun-chrome-check-"));
197
+ const profile = join(dir, "profile");
198
+ try {
199
+ const said = await new Promise((done) => {
200
+ const child = spawn(at, ["--headless=new", `--user-data-dir=${profile}`, "--no-first-run", "--proxy-server=http://agentrun-check.invalid:9", "--host-resolver-rules=MAP * ~NOTFOUND", "--dump-dom", "about:blank"], {
201
+ stdio: ["ignore", "ignore", "pipe"],
202
+ timeout: timeoutMs,
203
+ killSignal: "SIGKILL",
204
+ });
205
+ let stderr = "";
206
+ child.stderr.on("data", (chunk) => void (stderr = (stderr + chunk).slice(-8_192)));
207
+ child.once("error", (error) => done({ code: null, signal: null, stderr: error.message }));
208
+ child.once("exit", (code, signal) => done({ code, signal, stderr }));
209
+ });
210
+ if (said.code === 0)
211
+ return ok(at);
212
+ // Chrome's own words name the sandbox and go on to offer --no-sandbox: only the first are passed on.
213
+ if (/No usable sandbox|sandbox/i.test(said.stderr))
214
+ return fail("refused", `${at} did not start with its sandbox on (No usable sandbox): ${NO_SANDBOX}`);
215
+ const why = said.signal ? `it ended on ${said.signal}` : `it exited ${said.code ?? "without starting"}`;
216
+ return fail("refused", `${at} did not start here (${why}), so no local browser can start on it`);
217
+ }
218
+ finally {
219
+ const socket = await singletonDir(profile);
220
+ if (socket)
221
+ await rm(socket, { recursive: true, force: true }).catch(() => undefined);
222
+ await rm(dir, { recursive: true, force: true }).catch(() => undefined);
223
+ }
224
+ }
Binary file
Binary file
@@ -0,0 +1,2 @@
1
+ import type { Case } from "../types.js";
2
+ export declare const gpuCases: Case[];
@@ -0,0 +1,108 @@
1
+ // GPU: a computer asked for with a GPU the provider declares has it, as the vendor reports it (attach's read-back) and
2
+ // as its programs see it from inside (nvidia-smi, as the computer's user). The run names the GPU it pays for (t.gpu()):
3
+ // a GPU bills by the second, so each case makes one computer and keeps it no longer than it takes to look.
4
+ //
5
+ // gpu.present makes a GPU computer alone. It needs exec but does not name it among its needs: the runner checks a group
6
+ // need on the run's shared computer, which it would make for this case alone, a second computer billed for nothing. The
7
+ // provider's declared groups and its own GPU computer's hello hold it to exec instead. It also records, as evidence and
8
+ // nothing more, what the computer's user sees of FUSE, which an Archil mount needs: nothing is mounted.
9
+ //
10
+ // gpu.archil makes ONE computer with both the GPU and the run's Archil folder, where the provider's GPU computers take an
11
+ // Archil mount (capabilities().gpu.mounts lists it, or names none): the folder reads at /workspace, a program's write
12
+ // there is on the disk once the computer is released, and the GPUs are seen from inside. Everything is collected before
13
+ // the GPU verdict, so a computer whose image lacks the GPU's tools still shows whether the mount held.
14
+ import { randomBytes } from "node:crypto";
15
+ import { readBackOf, WORKSPACE } from "../../mount.js";
16
+ import { mounted } from "./mount.js";
17
+ import { CASE_LABEL } from "./util.js";
18
+ /** An AMD type: its programs see it through ROCm, not nvidia-smi, so the count from inside is recorded, not asserted. */
19
+ const AMD = /^MI\d/;
20
+ /** What the computer's user sees of FUSE, with nothing mounted: the device, the kernel's filesystems, whether the device
21
+ * opens, and the kernel (gVisor's says so). */
22
+ const FUSE_PROBE = 'ls -l /dev/fuse 2>&1; grep -w fuse /proc/filesystems 2>&1 || echo "fuse: not in /proc/filesystems"; if (exec 3<>/dev/fuse) 2>/dev/null; then echo "/dev/fuse: opens read-write"; else echo "/dev/fuse: does not open"; fi; echo "kernel $(uname -r)"';
23
+ /** The GPUs the computer's user sees, recorded; and the verdict on them, for the case to give once it has looked at the
24
+ * rest (none for an AMD type, whose count is recorded only). */
25
+ async function lookAtGpus(t, gpu, client) {
26
+ if (AMD.test(gpu.type)) {
27
+ const seen = await t.exec(["sh", "-c", "rocm-smi --showproductname 2>&1; true"], {}, client);
28
+ t.observe(`the GPUs the computer's user sees (rocm-smi): ${seen.out.trim().slice(0, 600) || "nothing"}`);
29
+ return () => { };
30
+ }
31
+ // nvidia-smi -L: one "GPU <n>: <name> (UUID: ...)" line per GPU the computer's programs can use.
32
+ const seen = await t.exec(["sh", "-c", "nvidia-smi -L"], {}, client);
33
+ t.observe(`the GPUs the computer's user sees (nvidia-smi -L): ${(seen.out.trim() || seen.err.trim()).slice(0, 600) || "nothing"}`);
34
+ return () => {
35
+ t.equal(seen.exitCode, 0, `nvidia-smi -L as the computer's user: a GPU computer's image carries the driver's tools, and its user reaches the GPU (stderr: ${seen.err.trim().slice(0, 300)})`);
36
+ const listed = seen.out.split("\n").filter((line) => /^GPU \d+: /.test(line.trim()));
37
+ t.equal(listed.length, gpu.count, "the GPUs nvidia-smi lists, as the computer's user");
38
+ };
39
+ }
40
+ /** Records what the computer's user sees of FUSE; never fails the case. */
41
+ async function lookAtFuse(t, client) {
42
+ const seen = await t.exec(["sh", "-c", FUSE_PROBE], {}, client);
43
+ t.observe(`FUSE as the computer's user sees it, nothing mounted (an Archil mount needs it): ${(seen.out.trim() || seen.err.trim()).replace(/\n/g, " | ").slice(0, 600) || "nothing"}`);
44
+ }
45
+ export const gpuCases = [
46
+ {
47
+ id: "gpu.present",
48
+ level: "full",
49
+ group: "gpu",
50
+ needs: ["gpu"],
51
+ computer: "none",
52
+ timeoutMs: 600_000,
53
+ async run(t) {
54
+ const gpu = t.gpu();
55
+ t.assert(t.provider.capabilities().groups.includes("exec"), "the provider declares exec: nvidia-smi runs as the computer's user");
56
+ const labels = { ...t.runLabels, [CASE_LABEL]: "gpu" };
57
+ t.deepEqual(t.provider.check(t.spec({ labels, gpu })), [], `check of a spec with gpu ${JSON.stringify(gpu)}`);
58
+ const ref = await t.create({ labels, gpu });
59
+ const attached = t.ok(await t.provider.attach({ id: ref.id }, { signal: t.signal }), "attach by id");
60
+ t.deepEqual(attached.spec.gpu, gpu, "the GPUs attach reads back: the vendor's report, or what create recorded where the vendor reports none");
61
+ const connected = await t.connect(ref);
62
+ t.assert(connected.hello.groups.includes("exec"), "the GPU computer's hello declares exec");
63
+ const verdict = await lookAtGpus(t, gpu, connected.client);
64
+ await lookAtFuse(t, connected.client);
65
+ await connected.close();
66
+ t.ok(await t.provider.release(ref, "delete"), "release delete, at once: a GPU bills by the second");
67
+ verdict();
68
+ },
69
+ },
70
+ {
71
+ id: "gpu.archil",
72
+ level: "full",
73
+ group: "gpu",
74
+ needs: ["gpu", "mount:archil"],
75
+ computer: "none",
76
+ timeoutMs: 900_000,
77
+ async run(t) {
78
+ const gpu = t.gpu();
79
+ const offered = t.provider.capabilities();
80
+ t.assert(offered.groups.includes("exec"), "the provider declares exec: nvidia-smi and the program's write run as the computer's user");
81
+ if (offered.gpu?.mounts !== undefined && !offered.gpu.mounts.includes("archil")) {
82
+ t.skip("the provider's GPU computers take no archil mount (capabilities().gpu.mounts): check() refuses one, as provider.check-refuses holds");
83
+ }
84
+ const folder = await t.runFolder("archil");
85
+ const nonce = randomBytes(6).toString("hex");
86
+ const before = `gpu-before-${nonce}.txt`;
87
+ const beforeText = `written outside before the GPU computer ${nonce}\n`;
88
+ await folder.write(before, Buffer.from(beforeText));
89
+ // check() takes it, create makes it, and attach and list read the mount back as asked, with no token (mount.ts).
90
+ const { ref } = await mounted(t, folder, 1, "gpu-archil", { gpu });
91
+ const attached = t.ok(await t.provider.attach({ id: ref.id }, { signal: t.signal }), "attach by id");
92
+ t.deepEqual(attached.spec.gpu, gpu, "the GPUs attach reads back, beside the mount");
93
+ t.deepEqual(attached.spec.mount, readBackOf(folder.mount, 1), "the mount attach reads back, beside the GPUs");
94
+ const connected = await t.connect(ref);
95
+ t.assert(connected.hello.groups.includes("exec"), "the GPU computer's hello declares exec");
96
+ const read = await t.exec(["cat", before], { cwd: WORKSPACE }, connected.client);
97
+ t.equal(read.out, beforeText, `cat ${before} at ${WORKSPACE}, a file written outside before the computer (${read.err.trim()})`);
98
+ const wrote = await t.exec(["sh", "-c", 'printf "%s\\n" "$1" >> "$2"', "sh", nonce, `${WORKSPACE}/gpu-${nonce}.txt`], {}, connected.client);
99
+ t.equal(wrote.exitCode, 0, `a program's write at ${WORKSPACE}: its exit code (${wrote.err.trim()})`);
100
+ const verdict = await lookAtGpus(t, gpu, connected.client);
101
+ await connected.close();
102
+ t.ok(await t.provider.release(ref, "delete"), "release delete, at once: a GPU bills by the second");
103
+ const back = await folder.read(`gpu-${nonce}.txt`);
104
+ t.equal(back === undefined ? undefined : Buffer.from(back).toString("utf8"), `${nonce}\n`, `gpu-${nonce}.txt, written by a program in the GPU computer, read outside once it is released`);
105
+ verdict();
106
+ },
107
+ },
108
+ ];
@@ -1,6 +1,7 @@
1
- // The daemon answers: hello, ping, and an error in words for a method it does not have; and the computer is the kind
2
- // it says it is.
3
- import { GROUPS } from "../../protocol.js";
1
+ // The daemon answers: hello, ping, and an error in words for a method it does not have; the computer is the kind it
2
+ // says it is; what the provider declares of itself, its capabilities() and each hello agree, at this protocol's
3
+ // version; and no error the provider answers holds a key.
4
+ import { GROUPS, PROTOCOL_VERSION } from "../../protocol.js";
4
5
  import { kindRefusals } from "../../provider.js";
5
6
  import { coreGroups } from "../types.js";
6
7
  export const healthCases = [
@@ -68,4 +69,83 @@ export const healthCases = [
68
69
  }
69
70
  },
70
71
  },
72
+ {
73
+ // The provider says what it is three times: in what it declares of itself (its descriptor), in capabilities(), and
74
+ // in each computer's hello. A runner trusts the first to pick a provider, the second to call it, and the third to
75
+ // hand a computer out; where they disagree, it picks a computer that cannot do the work. kind-consistent above
76
+ // holds hello to capabilities(); this holds capabilities() to the declaration, and hello to the protocol.
77
+ id: "health.declared",
78
+ level: "core",
79
+ group: "health",
80
+ needs: [],
81
+ async run(t) {
82
+ t.equal(t.hello.protocol, PROTOCOL_VERSION, `hello carries the protocol version this suite speaks, ${PROTOCOL_VERSION}`);
83
+ const declared = t.declared;
84
+ if (declared === undefined) {
85
+ return t.skip("the run was given no declaration of the provider: its descriptor, its PROVIDERS entry, or its module's CAPABILITIES");
86
+ }
87
+ const { kind, groups } = t.provider.capabilities();
88
+ const same = (a, b) => [...a].sort().join(",") === [...b].sort().join(",");
89
+ const configurations = declared.map((one) => `${one.kind} [${one.groups.join(", ")}]`).join("; ");
90
+ t.assert(declared.some((one) => one.kind === kind && same(one.groups, groups)), `capabilities(), kind ${kind} [${groups.join(", ")}], is one of the configurations the provider declares: ${configurations}`);
91
+ },
92
+ },
93
+ {
94
+ // A key in an error is a key in a log, a report and a model's context. The provider is built again with a planted
95
+ // value in place of each secret, so every call fails on it, and every refusal path is asked: none of what comes
96
+ // back, an error thrown included, may hold the value, or its last 12 characters (a vendor that echoes a key cut
97
+ // short). A planted key never makes a computer; one that did is deleted with the case, and the case fails.
98
+ id: "health.no-key-in-errors",
99
+ level: "core",
100
+ group: "health",
101
+ // A provider that takes no secret (Docker) has none to leak: the case is skipped as undeclared, apart from Core.
102
+ needs: ["secrets"],
103
+ async run(t) {
104
+ const { provider, secrets } = await t.planted();
105
+ t.assert(secrets.length > 0 && secrets.every((secret) => typeof secret === "string" && secret.length >= 16), "the planted secrets are named, each 16 characters or more");
106
+ const networks = provider.capabilities().network;
107
+ const network = networks.includes("none") ? "none" : "open";
108
+ // The case's own computer, a real one of the provider's: each path that takes a ref passes the provider's own
109
+ // checks of its shape and reaches the vendor with the planted secret, where a made-up ref could be refused first.
110
+ const ref = t.ref;
111
+ const paths = [
112
+ ["testConnection", async () => provider.testConnection?.({ signal: t.signal }) ?? "no testConnection"],
113
+ ["list", () => provider.list(t.runLabels, { signal: t.signal })],
114
+ ["attach by id", () => provider.attach({ id: ref.id }, { signal: t.signal })],
115
+ ["attach by labels", () => provider.attach({ labels: t.runLabels }, { signal: t.signal })],
116
+ ["network", () => provider.network(ref, undefined, { signal: t.signal })],
117
+ ["connect", () => provider.connect(ref)],
118
+ ["release", () => provider.release(ref, "delete")],
119
+ ["create", () => t.attempt(t.spec({ network }), provider)],
120
+ ];
121
+ for (const [name, call] of paths) {
122
+ let answer;
123
+ try {
124
+ answer = await call();
125
+ }
126
+ catch (error) {
127
+ answer = { threw: error instanceof Error ? `${error.name}: ${error.message}\n${error.stack ?? ""}` : String(error) };
128
+ }
129
+ // A connection made anyway (a vendor whose connect reads no key) is closed whatever the checks find: the runner
130
+ // never saw it, so its cleanup can't close it.
131
+ const opened = answer;
132
+ try {
133
+ const words = JSON.stringify(answer, (_key, value) => (value instanceof Error ? `${value.name}: ${value.message}` : value)) ?? String(answer);
134
+ for (const secret of secrets) {
135
+ for (const piece of [secret, secret.slice(-12)])
136
+ t.assert(!words.includes(piece), `${name}: what the provider answered holds none of a planted secret`);
137
+ }
138
+ if (name === "create")
139
+ t.assert(opened?.ok !== true, "create with a planted secret made no computer");
140
+ }
141
+ finally {
142
+ if (name === "connect" && opened?.ok === true)
143
+ await opened.value?.close?.().catch(() => undefined);
144
+ }
145
+ }
146
+ // A release the vendor refused for its key let nothing go: the computer is still the provider's.
147
+ const still = await t.provider.attach({ id: ref.id }, { signal: t.signal });
148
+ t.assert(still.ok, `the computer is still there after a release with a planted secret${still.ok ? "" : `: ${still.error.code}: ${still.error.message}`}`);
149
+ },
150
+ },
71
151
  ];
@@ -3,6 +3,7 @@ import { browserCases } from "./browser.js";
3
3
  import { driftCases } from "./drift.js";
4
4
  import { execCases } from "./exec.js";
5
5
  import { filesCases } from "./files.js";
6
+ import { gpuCases } from "./gpu.js";
6
7
  import { healthCases } from "./health.js";
7
8
  import { inputCases } from "./input.js";
8
9
  import { isolationCases } from "./isolation.js";
@@ -27,6 +28,7 @@ export const conformanceCases = [
27
28
  ...touchCases,
28
29
  ...appsCases,
29
30
  ...lifetimeCases,
31
+ ...gpuCases,
30
32
  ];
31
33
  /**
32
34
  * The cases a run takes when it is given none, by the machine kind of the computer: a browser's own (health, then the
@@ -1,2 +1,9 @@
1
- import type { Case } from "../types.js";
1
+ import type { ComputerRef, ComputerSpec } from "../../provider.js";
2
+ import type { Case, CaseContext, RunFolder } from "../types.js";
3
+ /** A computer made with the folder's mount under `epoch`, and `extra` (a GPU case's gpu), after check() takes it; and its
4
+ * read-back, checked. */
5
+ export declare function mounted(t: CaseContext, folder: RunFolder, epoch: number, name: string, extra?: Partial<ComputerSpec>): Promise<{
6
+ ref: ComputerRef;
7
+ labels: Record<string, string>;
8
+ }>;
2
9
  export declare const mountCases: Case[];
@@ -41,11 +41,12 @@ function labelsFor(t, folder, epoch, name) {
41
41
  const ofFolder = folder.mount.kind === "archil" ? /^agents\/[^/]+\/runs\/([^/]+)\/work$/.exec(folder.mount.folder)?.[1] : undefined;
42
42
  return { ...t.runLabels, ...claimLabels(folder.run ?? ofFolder ?? `mount-${randomBytes(6).toString("hex")}`, epoch), [CASE_LABEL]: name };
43
43
  }
44
- /** A computer made with the folder's mount under `epoch`, after check() takes it; and its read-back, checked. */
45
- async function mounted(t, folder, epoch, name) {
44
+ /** A computer made with the folder's mount under `epoch`, and `extra` (a GPU case's gpu), after check() takes it; and its
45
+ * read-back, checked. */
46
+ export async function mounted(t, folder, epoch, name, extra = {}) {
46
47
  const asked = folder.mount;
47
48
  const labels = labelsFor(t, folder, epoch, name);
48
- const spec = t.spec({ labels, mount: asked });
49
+ const spec = t.spec({ labels, mount: asked, ...extra });
49
50
  const refusals = t.provider.check(spec);
50
51
  tokenless(t, asked, refusals, "check's refusal of a spec that mounts the run's folder");
51
52
  // A provider that declares the kind but whose host cannot give it (a Docker host that remaps user ids, for a bind)
@@ -116,6 +116,20 @@ export const providerCases = [
116
116
  const refusals = t.provider.check(over);
117
117
  t.assert(refusals.some((r) => r.field === "lifetimeMs" && r.message !== ""), `check of lifetimeMs ${maxLifetimeMs + 1}, past maxLifetimeMs, refuses lifetimeMs in words: ${JSON.stringify(refusals)}`);
118
118
  await refusedCreate(t, over, "create of a spec past maxLifetimeMs");
119
+ // GPUs are a capability too: one the provider does not offer is refused with no vendor call, and a provider that
120
+ // declares no gpu refuses any.
121
+ const { gpu } = t.provider.capabilities();
122
+ if (gpu !== undefined) {
123
+ t.assert(Array.isArray(gpu.types) && gpu.types.length > 0 && gpu.types.every((type) => typeof type === "string" && type !== "") && Number.isSafeInteger(gpu.max) && gpu.max >= 1, `capabilities().gpu is { types: [one or more names], max: a whole number from 1 }, not ${JSON.stringify(gpu)}`);
124
+ }
125
+ const offered = gpu?.types[0] ?? "T4";
126
+ const outside = gpu === undefined ? [{ type: offered, count: 1 }] : [{ type: `not-${offered}`, count: 1 }, { type: offered, count: 0 }, { type: offered, count: gpu.max + 1 }];
127
+ for (const asked of outside) {
128
+ const spec = t.spec({ labels, gpu: asked });
129
+ const refused = t.provider.check(spec);
130
+ t.assert(refused.some((r) => r.field === "gpu" && r.message !== ""), `check of gpu ${JSON.stringify(asked)}, which the provider ${gpu === undefined ? "declares no gpu for" : "does not offer"}, refuses gpu in words: ${JSON.stringify(refused)}`);
131
+ await refusedCreate(t, spec, `create with gpu ${JSON.stringify(asked)}`);
132
+ }
119
133
  t.deepEqual(await names(t, labels), [], "the computers the refused creates made");
120
134
  }),
121
135
  provider("create-release", async (t) => {