@capybara-hq/device 0.0.0-stage → 0.1.0-rc.1

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 (61) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +2 -0
  3. package/README.md +103 -2
  4. package/bin/capybara-device.mjs +11 -0
  5. package/dist/api.d.ts +33 -0
  6. package/dist/api.js +48 -0
  7. package/dist/args.d.ts +39 -0
  8. package/dist/args.js +93 -0
  9. package/dist/cli.d.ts +18 -0
  10. package/dist/cli.js +93 -0
  11. package/dist/client.d.ts +39 -0
  12. package/dist/client.js +340 -0
  13. package/dist/command-log.d.ts +17 -0
  14. package/dist/command-log.js +28 -0
  15. package/dist/commands/drain.d.ts +2 -0
  16. package/dist/commands/drain.js +5 -0
  17. package/dist/commands/login.d.ts +20 -0
  18. package/dist/commands/login.js +132 -0
  19. package/dist/commands/logout.d.ts +13 -0
  20. package/dist/commands/logout.js +36 -0
  21. package/dist/commands/policy.d.ts +15 -0
  22. package/dist/commands/policy.js +74 -0
  23. package/dist/commands/service.d.ts +17 -0
  24. package/dist/commands/service.js +97 -0
  25. package/dist/commands/signal.d.ts +2 -0
  26. package/dist/commands/signal.js +18 -0
  27. package/dist/commands/start.d.ts +16 -0
  28. package/dist/commands/start.js +73 -0
  29. package/dist/commands/status.d.ts +2 -0
  30. package/dist/commands/status.js +32 -0
  31. package/dist/commands/stop.d.ts +2 -0
  32. package/dist/commands/stop.js +5 -0
  33. package/dist/exec/docker.d.ts +120 -0
  34. package/dist/exec/docker.js +673 -0
  35. package/dist/exec/fs-helper.d.ts +12 -0
  36. package/dist/exec/fs-helper.js +85 -0
  37. package/dist/exec/os.d.ts +80 -0
  38. package/dist/exec/os.js +398 -0
  39. package/dist/exec/procs.d.ts +11 -0
  40. package/dist/exec/procs.js +67 -0
  41. package/dist/exec/shared.d.ts +71 -0
  42. package/dist/exec/shared.js +240 -0
  43. package/dist/exec/types.d.ts +34 -0
  44. package/dist/exec/types.js +9 -0
  45. package/dist/index.d.ts +3 -0
  46. package/dist/index.js +3 -0
  47. package/dist/pid.d.ts +6 -0
  48. package/dist/pid.js +36 -0
  49. package/dist/policy.d.ts +42 -0
  50. package/dist/policy.js +97 -0
  51. package/dist/server-ops.d.ts +10 -0
  52. package/dist/server-ops.js +74 -0
  53. package/dist/service/launchd.d.ts +17 -0
  54. package/dist/service/launchd.js +59 -0
  55. package/dist/service/systemd.d.ts +5 -0
  56. package/dist/service/systemd.js +28 -0
  57. package/dist/state.d.ts +40 -0
  58. package/dist/state.js +117 -0
  59. package/dist/version.d.ts +2 -0
  60. package/dist/version.js +11 -0
  61. package/package.json +42 -3
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The file-operation helper the OS executor runs **inside the sandbox** (`node -e`), so a
3
+ * kernel-side read or write in the workspace or tmp root never touches the host file system with
4
+ * the program's own privileges: a parent directory swapped for a symlink mid-operation reaches
5
+ * only what any sandboxed command could reach anyway.
6
+ *
7
+ * argv: `<op> <path> <maxBytes> <root>...` with op `read` | `stat` | `write` (data on stdin).
8
+ * stdout: one JSON object, `{ "r": <result> }` or `{ "e": "policy" | "error", "m": <message> }`.
9
+ * read → `null` | `{ b64, truncated }`; stat → `null` | `{ size, isDir }`; write → `null`.
10
+ * Non-regular files (FIFOs, sockets, devices) are refused without blocking (`O_NONBLOCK`).
11
+ */
12
+ export const FS_HELPER_SCRIPT = `
13
+ (() => {
14
+ const fs = require("fs");
15
+ const path = require("path");
16
+ const C = fs.constants;
17
+ const [op, p, maxS, ...roots] = process.argv.slice(1);
18
+ const out = (o) => process.stdout.write(JSON.stringify(o));
19
+ const realRoots = roots.map((r) => { try { return fs.realpathSync(r); } catch { return r; } });
20
+ const under = (r) => realRoots.some((x) => r === x || r.startsWith(x + "/"));
21
+ const missing = (e) => e && (e.code === "ENOENT" || e.code === "ENOTDIR");
22
+ const real = (q) => { try { return fs.realpathSync(q); } catch (e) { if (missing(e)) return null; throw e; } };
23
+ const outside = (r) => out({ e: "policy", m: p + " resolves to " + r + ", outside the environment's roots" });
24
+ try {
25
+ if (op === "read" || op === "stat") {
26
+ const r = real(p);
27
+ if (r === null) return out({ r: null });
28
+ if (!under(r)) return outside(r);
29
+ const fd = fs.openSync(r, C.O_RDONLY | C.O_NONBLOCK | C.O_NOFOLLOW);
30
+ try {
31
+ const st = fs.fstatSync(fd);
32
+ if (op === "stat") return out({ r: { size: st.size, isDir: st.isDirectory() } });
33
+ if (st.isDirectory()) return out({ r: null });
34
+ if (!st.isFile()) return out({ e: "policy", m: p + " is not a regular file" });
35
+ const max = Number(maxS);
36
+ const want = Math.min(st.size, max);
37
+ const buf = Buffer.alloc(want);
38
+ let off = 0;
39
+ while (off < want) {
40
+ const n = fs.readSync(fd, buf, off, want - off, off);
41
+ if (n === 0) break;
42
+ off += n;
43
+ }
44
+ return out({ r: { b64: buf.subarray(0, off).toString("base64"), truncated: st.size > max } });
45
+ } finally {
46
+ fs.closeSync(fd);
47
+ }
48
+ }
49
+ if (op === "write") {
50
+ const data = fs.readFileSync(0);
51
+ const parent = path.dirname(p);
52
+ let anc = parent;
53
+ while (real(anc) === null && anc !== path.dirname(anc)) anc = path.dirname(anc);
54
+ const ra = real(anc);
55
+ if (ra === null || !under(ra)) return outside(ra);
56
+ fs.mkdirSync(parent, { recursive: true });
57
+ const rp = real(parent);
58
+ if (rp === null) return out({ e: "error", m: "cannot create " + parent });
59
+ if (!under(rp)) return outside(rp);
60
+ let file = path.join(rp, path.basename(p));
61
+ let st = null;
62
+ try { st = fs.lstatSync(file); } catch (e) { if (!missing(e)) throw e; }
63
+ if (st && st.isSymbolicLink()) {
64
+ const r = real(file);
65
+ if (r === null) return out({ e: "policy", m: p + " is a dangling symbolic link" });
66
+ if (!under(r)) return outside(r);
67
+ file = r;
68
+ }
69
+ const fd = fs.openSync(file, C.O_WRONLY | C.O_CREAT | C.O_NONBLOCK | C.O_NOFOLLOW, 0o644);
70
+ try {
71
+ if (!fs.fstatSync(fd).isFile()) return out({ e: "policy", m: p + " is not a regular file" });
72
+ fs.ftruncateSync(fd, 0);
73
+ let off = 0;
74
+ while (off < data.length) off += fs.writeSync(fd, data, off, data.length - off, off);
75
+ } finally {
76
+ fs.closeSync(fd);
77
+ }
78
+ return out({ r: null });
79
+ }
80
+ out({ e: "error", m: "unknown helper op " + op });
81
+ } catch (e) {
82
+ out({ e: "error", m: String((e && e.message) || e) });
83
+ }
84
+ })();
85
+ `;
@@ -0,0 +1,80 @@
1
+ import { type SandboxRuntimeConfig } from "@anthropic-ai/sandbox-runtime";
2
+ import type { DeviceExecArgs, ExecResult, SandboxRoots } from "@capybara-hq/plugin-sdk";
3
+ import type { Policy } from "../state.js";
4
+ import { type Executor } from "./types.js";
5
+ export { osRoots, ROOT_MARKER, utf8Prefix } from "./shared.js";
6
+ /** Whether the OS sandbox can run here, and why not. */
7
+ export declare function sandboxAvailability(): {
8
+ ok: true;
9
+ } | {
10
+ ok: false;
11
+ reason: string;
12
+ };
13
+ export interface OsExecutorOptions {
14
+ /** The environment directory (from login). */
15
+ dir: string;
16
+ policy: Policy;
17
+ /** The home whose secret paths are denied (default: the user's home). */
18
+ home?: string;
19
+ /** More paths commands may not read (this program's state directory). */
20
+ denyRead?: string[];
21
+ }
22
+ /**
23
+ * Runs every command inside `@anthropic-ai/sandbox-runtime` (macOS Seatbelt, Linux bubblewrap):
24
+ * writes only under the workspace and tmp roots, the secret paths unreadable, network only to
25
+ * the intersection of the local policy and the environment's egress. File operations in the
26
+ * workspace and tmp roots run in a sandboxed helper too. Construct it with
27
+ * {@link createOsExecutor}; the constructor alone serves only `ensureRoot` and the skills root.
28
+ */
29
+ export declare class OsExecutor implements Executor {
30
+ private readonly opts;
31
+ readonly mode: "os";
32
+ readonly roots: SandboxRoots;
33
+ private readonly dir;
34
+ /** Marks every process of this environment's commands: `<dirKey>.<tag>`. */
35
+ private readonly dirKey;
36
+ private readonly groups;
37
+ private pruneTimer;
38
+ private readonly guard;
39
+ private readonly files;
40
+ constructor(opts: OsExecutorOptions);
41
+ /** The configuration the sandbox is initialized with (no domains: those are per command). */
42
+ config(): SandboxRuntimeConfig;
43
+ ensureRoot(): Promise<"ok" | "gone">;
44
+ /** The marker value of a tag's processes. */
45
+ markerOf(tag: string): string;
46
+ /**
47
+ * Wraps `script` (run by bash inside the sandbox, after the request's `env` and TMPDIR are
48
+ * exported) and spawns it as the leader of a new process group.
49
+ */
50
+ private spawnSandboxed;
51
+ /** Tracks a spawned command's process group; returns the entry. */
52
+ private track;
53
+ /** Forgets finished groups with no members left (or whose id was taken by another process). */
54
+ private prune;
55
+ private killGroup;
56
+ exec(args: DeviceExecArgs, signal: AbortSignal): Promise<ExecResult>;
57
+ /** Runs one file operation in the sandboxed helper; returns its `r`, throws its `e`. */
58
+ private helper;
59
+ readFile(path: string, maxBytes: number): Promise<{
60
+ data: Uint8Array;
61
+ truncated: boolean;
62
+ } | null>;
63
+ writeFile(path: string, data: Uint8Array): Promise<void>;
64
+ stat(path: string): Promise<{
65
+ size: number;
66
+ isDir: boolean;
67
+ } | null>;
68
+ killTagged(tags: string[]): Promise<void>;
69
+ killAll(): Promise<void>;
70
+ /** Kills every process carrying this environment's marker (also a previous run's). */
71
+ killLeftovers(): Promise<void>;
72
+ /** Kills every running command and shuts the sandbox's proxies down. */
73
+ dispose(): Promise<void>;
74
+ }
75
+ /**
76
+ * The OS sandbox executor: checks the platform and dependencies, starts the sandbox's proxies
77
+ * once for this process, and kills what a previous run of this environment left running.
78
+ * Network is denied unless a command's own list allows it.
79
+ */
80
+ export declare function createOsExecutor(opts: OsExecutorOptions): Promise<OsExecutor>;
@@ -0,0 +1,398 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import { existsSync, realpathSync } from "node:fs";
4
+ import { constants as osConstants } from "node:os";
5
+ import { resolve } from "node:path";
6
+ import { SandboxManager } from "@anthropic-ai/sandbox-runtime";
7
+ import { effectiveEgress, srtConfig } from "../policy.js";
8
+ import { FS_HELPER_SCRIPT } from "./fs-helper.js";
9
+ import { EXEC_MARKER, killMarked } from "./procs.js";
10
+ import { ENV_NAME_RE, HostFiles, isUnder, OutputCap, osRoots, PIPE_GRACE_MS, policyError, RootGuard, shellQuote, } from "./shared.js";
11
+ import { DeviceOpError } from "./types.js";
12
+ export { osRoots, ROOT_MARKER, utf8Prefix } from "./shared.js";
13
+ /** A file operation in the sandboxed helper that takes longer than this is killed. */
14
+ const HELPER_TIMEOUT_MS = 30_000;
15
+ /** How often process groups of finished commands are checked for remaining members. */
16
+ const PRUNE_INTERVAL_MS = 5_000;
17
+ /**
18
+ * The outer process (the sandbox wrapper itself) runs with this environment only; the request's
19
+ * environment is applied inside the sandbox, so it can never steer the wrapper.
20
+ */
21
+ const OUTER_ENV = {
22
+ PATH: "/usr/bin:/bin:/usr/sbin:/sbin",
23
+ LANG: "C.UTF-8",
24
+ };
25
+ /** Whether the OS sandbox can run here, and why not. */
26
+ export function sandboxAvailability() {
27
+ if (!SandboxManager.isSupportedPlatform()) {
28
+ return { ok: false, reason: `the OS sandbox does not support ${process.platform}` };
29
+ }
30
+ const deps = SandboxManager.checkDependencies();
31
+ if (deps.errors.length > 0) {
32
+ return {
33
+ ok: false,
34
+ reason: `the OS sandbox is missing dependencies: ${deps.errors.join("; ")}`,
35
+ };
36
+ }
37
+ return { ok: true };
38
+ }
39
+ /** Sends SIGKILL to a process group; false when the group no longer exists. */
40
+ function killGroupId(pgid, signal = "SIGKILL") {
41
+ try {
42
+ process.kill(-pgid, signal);
43
+ return true;
44
+ }
45
+ catch {
46
+ return false;
47
+ }
48
+ }
49
+ function pidAlive(pid) {
50
+ try {
51
+ process.kill(pid, 0);
52
+ return true;
53
+ }
54
+ catch {
55
+ return false;
56
+ }
57
+ }
58
+ /**
59
+ * Runs every command inside `@anthropic-ai/sandbox-runtime` (macOS Seatbelt, Linux bubblewrap):
60
+ * writes only under the workspace and tmp roots, the secret paths unreadable, network only to
61
+ * the intersection of the local policy and the environment's egress. File operations in the
62
+ * workspace and tmp roots run in a sandboxed helper too. Construct it with
63
+ * {@link createOsExecutor}; the constructor alone serves only `ensureRoot` and the skills root.
64
+ */
65
+ export class OsExecutor {
66
+ opts;
67
+ mode = "os";
68
+ roots;
69
+ dir;
70
+ /** Marks every process of this environment's commands: `<dirKey>.<tag>`. */
71
+ dirKey;
72
+ groups = new Set();
73
+ pruneTimer;
74
+ guard;
75
+ files;
76
+ constructor(opts) {
77
+ this.opts = opts;
78
+ const dir = resolve(opts.dir);
79
+ // The roots are reported as real paths, so what commands print matches what the kernel sends.
80
+ this.dir = existsSync(dir) ? realpathSync(dir) : dir;
81
+ this.roots = osRoots(this.dir);
82
+ this.guard = new RootGuard(this.dir, this.roots);
83
+ this.files = new HostFiles(this.roots);
84
+ this.dirKey = createHash("sha256").update(this.dir).digest("hex").slice(0, 16);
85
+ }
86
+ /** The configuration the sandbox is initialized with (no domains: those are per command). */
87
+ config() {
88
+ return srtConfig(this.opts.policy, this.roots, [], {
89
+ ...(this.opts.home !== undefined && { home: this.opts.home }),
90
+ ...(this.opts.denyRead !== undefined && { denyRead: this.opts.denyRead }),
91
+ });
92
+ }
93
+ async ensureRoot() {
94
+ return this.guard.ensure();
95
+ }
96
+ /** The marker value of a tag's processes. */
97
+ markerOf(tag) {
98
+ return `${this.dirKey}.${tag}`;
99
+ }
100
+ /**
101
+ * Wraps `script` (run by bash inside the sandbox, after the request's `env` and TMPDIR are
102
+ * exported) and spawns it as the leader of a new process group.
103
+ */
104
+ async spawnSandboxed(script, o) {
105
+ const exports = [];
106
+ const inner = {
107
+ // The user's PATH applies inside the sandbox only (the wrapper runs with OUTER_ENV).
108
+ PATH: process.env.PATH ?? "/usr/bin:/bin:/usr/sbin:/sbin",
109
+ LANG: process.env.LANG ?? "C.UTF-8",
110
+ SHELL: "/bin/bash",
111
+ TERM: "dumb",
112
+ HOME: this.roots.workspace,
113
+ ...(process.env.USER !== undefined && { USER: process.env.USER }),
114
+ ...o.env,
115
+ // The runtime points TMPDIR at its own /tmp/claude (denied by the config): use the tmp root.
116
+ TMPDIR: this.roots.tmp,
117
+ [EXEC_MARKER]: this.markerOf(o.tag),
118
+ };
119
+ for (const [k, v] of Object.entries(inner)) {
120
+ if (!ENV_NAME_RE.test(k))
121
+ throw policyError(`invalid environment variable name ${JSON.stringify(k)}`);
122
+ exports.push(`export ${k}=${shellQuote(v)}`);
123
+ }
124
+ const commandId = randomBytes(16).toString("base64url");
125
+ const wrapped = await SandboxManager.wrapWithSandbox(`${exports.join("\n")}\n${script}`, "/bin/bash", undefined, o.signal, { commandId, commandText: script });
126
+ // The kernel may have cancelled while the wrap was prepared.
127
+ o.signal?.throwIfAborted();
128
+ if (o.egress.length > 0) {
129
+ SandboxManager.registerCommandNetworkLists(commandId, { allowedDomains: o.egress });
130
+ }
131
+ let child;
132
+ try {
133
+ // detached: the command leads its own process group, so a kill reaches its children too.
134
+ child = spawn("/bin/bash", ["-c", wrapped], {
135
+ cwd: o.cwd,
136
+ env: OUTER_ENV,
137
+ detached: true,
138
+ stdio: [o.stdin ? "pipe" : "ignore", "pipe", "pipe"],
139
+ });
140
+ }
141
+ catch (e) {
142
+ SandboxManager.unregisterCommandNetworkLists(commandId);
143
+ SandboxManager.cleanupAfterCommand();
144
+ throw e;
145
+ }
146
+ return { child, commandId };
147
+ }
148
+ /** Tracks a spawned command's process group; returns the entry. */
149
+ track(tag, child) {
150
+ if (child.pid === undefined)
151
+ return undefined;
152
+ const g = { tag, pgid: child.pid, exited: false };
153
+ this.groups.add(g);
154
+ if (this.pruneTimer === undefined) {
155
+ this.pruneTimer = setInterval(() => this.prune(), PRUNE_INTERVAL_MS);
156
+ this.pruneTimer.unref();
157
+ }
158
+ return g;
159
+ }
160
+ /** Forgets finished groups with no members left (or whose id was taken by another process). */
161
+ prune() {
162
+ for (const g of this.groups) {
163
+ if (!g.exited)
164
+ continue;
165
+ // A reaped leader's pid can be reused only once its group is gone: a live process with
166
+ // that pid means the id now belongs to someone else.
167
+ if (pidAlive(g.pgid) || !killGroupId(g.pgid, 0))
168
+ this.groups.delete(g);
169
+ }
170
+ if (this.groups.size === 0 && this.pruneTimer !== undefined) {
171
+ clearInterval(this.pruneTimer);
172
+ this.pruneTimer = undefined;
173
+ }
174
+ }
175
+ killGroup(g) {
176
+ if (g.exited) {
177
+ this.prune();
178
+ if (!this.groups.has(g))
179
+ return;
180
+ }
181
+ g.onKill?.();
182
+ if (!killGroupId(g.pgid) && g.exited)
183
+ this.groups.delete(g);
184
+ }
185
+ async exec(args, signal) {
186
+ signal.throwIfAborted();
187
+ const cwd = await this.files.inside(args.cwd ?? this.roots.workspace, "cwd");
188
+ const { child, commandId } = await this.spawnSandboxed(args.command, {
189
+ cwd,
190
+ ...(args.env !== undefined && { env: args.env }),
191
+ tag: args.tag,
192
+ egress: effectiveEgress(this.opts.policy, args.limits),
193
+ signal,
194
+ });
195
+ return new Promise((resolvePromise, reject) => {
196
+ const cap = new OutputCap(args.maxOutputBytes);
197
+ let timedOut = false;
198
+ let killed = false;
199
+ let exit;
200
+ let settled = false;
201
+ let grace;
202
+ const group = this.track(args.tag, child);
203
+ if (group) {
204
+ group.onKill = () => {
205
+ // A kill after a clean exit (a background child) leaves the result alone.
206
+ if (exit === undefined)
207
+ killed = true;
208
+ };
209
+ }
210
+ const kill = () => {
211
+ if (group)
212
+ this.killGroup(group);
213
+ };
214
+ const timer = setTimeout(() => {
215
+ if (exit === undefined)
216
+ timedOut = true;
217
+ kill();
218
+ }, args.timeoutMs);
219
+ const onAbort = () => kill();
220
+ signal.addEventListener("abort", onAbort, { once: true });
221
+ const cleanup = () => {
222
+ clearTimeout(timer);
223
+ if (grace)
224
+ clearTimeout(grace);
225
+ signal.removeEventListener("abort", onAbort);
226
+ if (group) {
227
+ group.exited = true;
228
+ group.onKill = undefined;
229
+ }
230
+ SandboxManager.unregisterCommandNetworkLists(commandId);
231
+ SandboxManager.cleanupAfterCommand();
232
+ };
233
+ const finish = () => {
234
+ if (settled || exit === undefined)
235
+ return;
236
+ settled = true;
237
+ cleanup();
238
+ child.stdout?.destroy();
239
+ child.stderr?.destroy();
240
+ let exitCode = exit.code;
241
+ if (killed || timedOut)
242
+ exitCode = null;
243
+ else if (exitCode === null && exit.sig !== null) {
244
+ exitCode = 128 + (osConstants.signals[exit.sig] ?? 0);
245
+ }
246
+ resolvePromise({
247
+ exitCode,
248
+ stdout: cap.text("stdout"),
249
+ stderr: cap.text("stderr"),
250
+ truncated: cap.truncated,
251
+ timedOut,
252
+ });
253
+ };
254
+ child.stdout?.on("data", (b) => cap.push("stdout", b));
255
+ child.stderr?.on("data", (b) => cap.push("stderr", b));
256
+ child.once("error", (e) => {
257
+ if (settled)
258
+ return;
259
+ settled = true;
260
+ if (group)
261
+ this.groups.delete(group);
262
+ cleanup();
263
+ reject(e);
264
+ });
265
+ child.once("exit", (code, sig) => {
266
+ exit = { code, sig };
267
+ if (group)
268
+ group.exited = true;
269
+ // A background child may hold the pipes open; do not wait for it past a short grace.
270
+ grace = setTimeout(finish, PIPE_GRACE_MS);
271
+ });
272
+ child.once("close", () => finish());
273
+ });
274
+ }
275
+ /** Runs one file operation in the sandboxed helper; returns its `r`, throws its `e`. */
276
+ async helper(op, path, maxBytes, data) {
277
+ const script = [
278
+ process.execPath,
279
+ "-e",
280
+ FS_HELPER_SCRIPT,
281
+ op,
282
+ path,
283
+ String(maxBytes),
284
+ this.roots.workspace,
285
+ this.roots.tmp,
286
+ ]
287
+ .map(shellQuote)
288
+ .join(" ");
289
+ const { child, commandId } = await this.spawnSandboxed(script, {
290
+ cwd: this.roots.workspace,
291
+ tag: "fs-helper",
292
+ egress: [],
293
+ stdin: data !== undefined,
294
+ });
295
+ const chunks = [];
296
+ const errs = [];
297
+ child.stdout?.on("data", (b) => chunks.push(b));
298
+ child.stderr?.on("data", (b) => errs.push(b));
299
+ if (child.stdin) {
300
+ child.stdin.on("error", () => { });
301
+ child.stdin.end(data !== undefined ? Buffer.from(data) : undefined);
302
+ }
303
+ let timedOut = false;
304
+ const timer = setTimeout(() => {
305
+ timedOut = true;
306
+ if (child.pid !== undefined)
307
+ killGroupId(child.pid);
308
+ }, HELPER_TIMEOUT_MS);
309
+ try {
310
+ await new Promise((res, rej) => {
311
+ child.once("error", rej);
312
+ child.once("close", () => res());
313
+ });
314
+ }
315
+ finally {
316
+ clearTimeout(timer);
317
+ if (child.pid !== undefined)
318
+ killGroupId(child.pid);
319
+ SandboxManager.unregisterCommandNetworkLists(commandId);
320
+ SandboxManager.cleanupAfterCommand();
321
+ }
322
+ if (timedOut)
323
+ throw new DeviceOpError("error", `${op} ${path} timed out`);
324
+ const text = Buffer.concat(chunks).toString("utf8");
325
+ let res;
326
+ try {
327
+ res = JSON.parse(text);
328
+ }
329
+ catch {
330
+ const stderr = Buffer.concat(errs).toString("utf8").trim().slice(0, 500);
331
+ throw new DeviceOpError("error", `${op} ${path} failed in the sandbox${stderr ? `: ${stderr}` : ""}`);
332
+ }
333
+ if (res.e !== undefined)
334
+ throw new DeviceOpError(res.e === "policy" ? "policy" : "error", res.m ?? "failed");
335
+ return res.r ?? null;
336
+ }
337
+ async readFile(path, maxBytes) {
338
+ const p = this.files.lexical(path);
339
+ if (isUnder(p, this.roots.skills))
340
+ return this.files.read(path, maxBytes);
341
+ const r = (await this.helper("read", p, maxBytes));
342
+ return r === null ? null : { data: Buffer.from(r.b64, "base64"), truncated: r.truncated };
343
+ }
344
+ async writeFile(path, data) {
345
+ const p = this.files.lexical(path);
346
+ if (isUnder(p, this.roots.skills))
347
+ return this.files.write(path, data);
348
+ await this.helper("write", p, 0, data);
349
+ }
350
+ async stat(path) {
351
+ const p = this.files.lexical(path);
352
+ if (isUnder(p, this.roots.skills)) {
353
+ return this.files.stat(path);
354
+ }
355
+ return (await this.helper("stat", p, 0));
356
+ }
357
+ async killTagged(tags) {
358
+ const want = new Set(tags);
359
+ for (const g of [...this.groups])
360
+ if (want.has(g.tag))
361
+ this.killGroup(g);
362
+ const values = new Set(tags.map((t) => this.markerOf(t)));
363
+ await killMarked((v) => values.has(v));
364
+ }
365
+ async killAll() {
366
+ for (const g of [...this.groups])
367
+ this.killGroup(g);
368
+ await this.killLeftovers();
369
+ }
370
+ /** Kills every process carrying this environment's marker (also a previous run's). */
371
+ async killLeftovers() {
372
+ const prefix = `${this.dirKey}.`;
373
+ await killMarked((v) => v.startsWith(prefix));
374
+ }
375
+ /** Kills every running command and shuts the sandbox's proxies down. */
376
+ async dispose() {
377
+ await this.killAll();
378
+ if (this.pruneTimer !== undefined)
379
+ clearInterval(this.pruneTimer);
380
+ this.pruneTimer = undefined;
381
+ await SandboxManager.reset();
382
+ }
383
+ }
384
+ /**
385
+ * The OS sandbox executor: checks the platform and dependencies, starts the sandbox's proxies
386
+ * once for this process, and kills what a previous run of this environment left running.
387
+ * Network is denied unless a command's own list allows it.
388
+ */
389
+ export async function createOsExecutor(opts) {
390
+ const available = sandboxAvailability();
391
+ if (!available.ok)
392
+ throw new Error(available.reason);
393
+ const executor = new OsExecutor(opts);
394
+ // No ask callback: a destination outside the lists is refused, never prompted.
395
+ await SandboxManager.initialize(executor.config());
396
+ await executor.killLeftovers();
397
+ return executor;
398
+ }
@@ -0,0 +1,11 @@
1
+ /** The environment variable every sandboxed command (and everything it starts) carries. */
2
+ export declare const EXEC_MARKER = "CAPYBARA_EXEC";
3
+ /**
4
+ * The pids of this user's processes whose environment carries {@link EXEC_MARKER} with a value
5
+ * `match` accepts. Linux reads `/proc/<pid>/environ` (exact). macOS reads `ps -E`, which shows
6
+ * the environment of ordinary programs but not of Apple platform binaries (`/bin/sleep`), so it
7
+ * is best effort there; process groups cover the rest (see the OS executor).
8
+ */
9
+ export declare function findMarked(match: (value: string) => boolean): Promise<number[]>;
10
+ /** SIGKILLs every process {@link findMarked} finds for `match`. */
11
+ export declare function killMarked(match: (value: string) => boolean): Promise<void>;
@@ -0,0 +1,67 @@
1
+ import { execFile } from "node:child_process";
2
+ import { readdir, readFile } from "node:fs/promises";
3
+ /** The environment variable every sandboxed command (and everything it starts) carries. */
4
+ export const EXEC_MARKER = "CAPYBARA_EXEC";
5
+ const MARKER_RE = new RegExp(`(?:^|\\s)${EXEC_MARKER}=(\\S+)`, "g");
6
+ function psLines() {
7
+ return new Promise((resolve) => {
8
+ execFile("ps", ["-E", "-ww", "-U", String(process.getuid?.() ?? ""), "-o", "pid=,command="], { timeout: 5000, maxBuffer: 64 * 1024 * 1024 }, (_err, stdout) => resolve(stdout ?? ""));
9
+ });
10
+ }
11
+ /**
12
+ * The pids of this user's processes whose environment carries {@link EXEC_MARKER} with a value
13
+ * `match` accepts. Linux reads `/proc/<pid>/environ` (exact). macOS reads `ps -E`, which shows
14
+ * the environment of ordinary programs but not of Apple platform binaries (`/bin/sleep`), so it
15
+ * is best effort there; process groups cover the rest (see the OS executor).
16
+ */
17
+ export async function findMarked(match) {
18
+ const found = new Set();
19
+ if (process.platform === "linux") {
20
+ let entries = [];
21
+ try {
22
+ entries = await readdir("/proc");
23
+ }
24
+ catch {
25
+ return [];
26
+ }
27
+ await Promise.all(entries
28
+ .filter((e) => /^\d+$/.test(e))
29
+ .map(async (e) => {
30
+ try {
31
+ const env = await readFile(`/proc/${e}/environ`, "latin1");
32
+ for (const kv of env.split("\0")) {
33
+ if (kv.startsWith(`${EXEC_MARKER}=`) && match(kv.slice(EXEC_MARKER.length + 1))) {
34
+ found.add(Number(e));
35
+ }
36
+ }
37
+ }
38
+ catch {
39
+ // Gone, or not ours.
40
+ }
41
+ }));
42
+ }
43
+ else if (process.platform === "darwin") {
44
+ for (const line of (await psLines()).split("\n")) {
45
+ const m = /^\s*(\d+)\s(.*)$/.exec(line);
46
+ if (!m)
47
+ continue;
48
+ for (const v of m[2].matchAll(MARKER_RE)) {
49
+ if (match(v[1]))
50
+ found.add(Number(m[1]));
51
+ }
52
+ }
53
+ }
54
+ found.delete(process.pid);
55
+ return [...found];
56
+ }
57
+ /** SIGKILLs every process {@link findMarked} finds for `match`. */
58
+ export async function killMarked(match) {
59
+ for (const pid of await findMarked(match)) {
60
+ try {
61
+ process.kill(pid, "SIGKILL");
62
+ }
63
+ catch {
64
+ // Already gone.
65
+ }
66
+ }
67
+ }