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

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,71 @@
1
+ import type { SandboxRoots } from "@capybara-hq/plugin-sdk";
2
+ import { DeviceOpError } from "./types.js";
3
+ /** The file that marks a directory as an environment directory this program has used. */
4
+ export declare const ROOT_MARKER = ".capybara-device";
5
+ /** How long a finished command's output pipes may stay open (held by a background child). */
6
+ export declare const PIPE_GRACE_MS = 200;
7
+ export declare const ENV_NAME_RE: RegExp;
8
+ /** The roots of an environment directory: `<dir>/workspace`, `<dir>/skills`, `<dir>/tmp`. */
9
+ export declare function osRoots(dir: string): SandboxRoots;
10
+ /**
11
+ * The longest prefix of `b` that does not end inside a UTF-8 sequence (a cut buffer's tail is
12
+ * dropped instead of decoding to U+FFFD).
13
+ */
14
+ export declare function utf8Prefix(b: Buffer): Buffer;
15
+ export declare function shellQuote(s: string): string;
16
+ export declare function isUnder(p: string, root: string): boolean;
17
+ export declare function policyError(message: string): DeviceOpError;
18
+ export declare function isMissing(e: unknown): boolean;
19
+ /** Captures stdout and stderr up to a combined byte budget; the rest is drained and dropped. */
20
+ export declare class OutputCap {
21
+ private readonly max;
22
+ private readonly chunks;
23
+ private readonly cut;
24
+ private used;
25
+ truncated: boolean;
26
+ constructor(max: number);
27
+ push(stream: "stdout" | "stderr", buf: Buffer): void;
28
+ text(stream: "stdout" | "stderr"): string;
29
+ }
30
+ /**
31
+ * Creates (or completes) an environment directory: the marker and the three roots. Only `login`
32
+ * calls it, so logging in again after the files were lost starts the environment afresh.
33
+ */
34
+ export declare function prepareEnvironmentDir(dir: string): void;
35
+ /**
36
+ * The environment directory's marker and roots. Once the marker exists, the directory, the marker
37
+ * or any root vanishing is "gone": nothing is recreated silently (log in again to start afresh).
38
+ */
39
+ export declare class RootGuard {
40
+ private readonly dir;
41
+ private readonly roots;
42
+ /** The marker was seen in this process: its vanishing means the directory was removed. */
43
+ private seen;
44
+ constructor(dir: string, roots: SandboxRoots);
45
+ ensure(): "ok" | "gone";
46
+ }
47
+ /**
48
+ * Host-side file access under the three roots (real paths, symlinks resolved, refused when they
49
+ * leave a root). Used for the skills root, which commands can only read, so nothing can race it.
50
+ */
51
+ export declare class HostFiles {
52
+ private readonly roots;
53
+ constructor(roots: SandboxRoots);
54
+ /** `path` made absolute and normalized; refused unless it is lexically under a root. */
55
+ lexical(path: string): string;
56
+ /** The real path of an existing `path`, refused unless under a root after resolving links; null when missing. */
57
+ existing(path: string): Promise<string | null>;
58
+ /** The real path of an existing `path` under a root (symlinks resolved); refused otherwise. */
59
+ inside(path: string, what: string): Promise<string>;
60
+ private checkReal;
61
+ private rootList;
62
+ read(path: string, maxBytes: number): Promise<{
63
+ data: Uint8Array;
64
+ truncated: boolean;
65
+ } | null>;
66
+ stat(path: string): Promise<{
67
+ size: number;
68
+ isDir: boolean;
69
+ } | null>;
70
+ write(path: string, data: Uint8Array): Promise<void>;
71
+ }
@@ -0,0 +1,240 @@
1
+ import { constants, existsSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { lstat, mkdir, open, realpath } from "node:fs/promises";
3
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
4
+ import { DeviceOpError } from "./types.js";
5
+ /** The file that marks a directory as an environment directory this program has used. */
6
+ export const ROOT_MARKER = ".capybara-device";
7
+ /** How long a finished command's output pipes may stay open (held by a background child). */
8
+ export const PIPE_GRACE_MS = 200;
9
+ export const ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
10
+ /** The roots of an environment directory: `<dir>/workspace`, `<dir>/skills`, `<dir>/tmp`. */
11
+ export function osRoots(dir) {
12
+ return { workspace: join(dir, "workspace"), skills: join(dir, "skills"), tmp: join(dir, "tmp") };
13
+ }
14
+ /**
15
+ * The longest prefix of `b` that does not end inside a UTF-8 sequence (a cut buffer's tail is
16
+ * dropped instead of decoding to U+FFFD).
17
+ */
18
+ export function utf8Prefix(b) {
19
+ let i = b.length - 1;
20
+ let cont = 0;
21
+ while (i >= 0 && cont < 3 && (b[i] & 0xc0) === 0x80) {
22
+ i--;
23
+ cont++;
24
+ }
25
+ if (i < 0)
26
+ return b;
27
+ const lead = b[i];
28
+ const need = lead >= 0xf0 ? 4 : lead >= 0xe0 ? 3 : lead >= 0xc0 ? 2 : 1;
29
+ return b.length - i >= need ? b : b.subarray(0, i);
30
+ }
31
+ export function shellQuote(s) {
32
+ return `'${s.replaceAll("'", "'\\''")}'`;
33
+ }
34
+ export function isUnder(p, root) {
35
+ return p === root || p.startsWith(`${root}/`);
36
+ }
37
+ export function policyError(message) {
38
+ return new DeviceOpError("policy", message);
39
+ }
40
+ export function isMissing(e) {
41
+ const code = e.code;
42
+ return code === "ENOENT" || code === "ENOTDIR";
43
+ }
44
+ /** Captures stdout and stderr up to a combined byte budget; the rest is drained and dropped. */
45
+ export class OutputCap {
46
+ max;
47
+ chunks = { stdout: [], stderr: [] };
48
+ cut = { stdout: false, stderr: false };
49
+ used = 0;
50
+ truncated = false;
51
+ constructor(max) {
52
+ this.max = max;
53
+ }
54
+ push(stream, buf) {
55
+ const room = this.max - this.used;
56
+ if (buf.length <= room) {
57
+ this.chunks[stream].push(buf);
58
+ this.used += buf.length;
59
+ return;
60
+ }
61
+ if (room > 0)
62
+ this.chunks[stream].push(buf.subarray(0, room));
63
+ this.used = this.max;
64
+ this.truncated = true;
65
+ this.cut[stream] = true;
66
+ }
67
+ text(stream) {
68
+ const all = Buffer.concat(this.chunks[stream]);
69
+ return (this.cut[stream] ? utf8Prefix(all) : all).toString("utf8");
70
+ }
71
+ }
72
+ const MARKER_TEXT = "This directory is a capybara-device environment.\n";
73
+ /**
74
+ * Creates (or completes) an environment directory: the marker and the three roots. Only `login`
75
+ * calls it, so logging in again after the files were lost starts the environment afresh.
76
+ */
77
+ export function prepareEnvironmentDir(dir) {
78
+ for (const r of Object.values(osRoots(dir)))
79
+ mkdirSync(r, { recursive: true });
80
+ const marker = join(dir, ROOT_MARKER);
81
+ if (!existsSync(marker))
82
+ writeFileSync(marker, MARKER_TEXT);
83
+ }
84
+ /**
85
+ * The environment directory's marker and roots. Once the marker exists, the directory, the marker
86
+ * or any root vanishing is "gone": nothing is recreated silently (log in again to start afresh).
87
+ */
88
+ export class RootGuard {
89
+ dir;
90
+ roots;
91
+ /** The marker was seen in this process: its vanishing means the directory was removed. */
92
+ seen = false;
93
+ constructor(dir, roots) {
94
+ this.dir = dir;
95
+ this.roots = roots;
96
+ }
97
+ ensure() {
98
+ const marker = join(this.dir, ROOT_MARKER);
99
+ const rootList = [this.roots.workspace, this.roots.skills, this.roots.tmp];
100
+ if (existsSync(marker)) {
101
+ this.seen = true;
102
+ // A root removed under a marked directory lost its files: never recreate it empty.
103
+ return rootList.every((r) => existsSync(r)) ? "ok" : "gone";
104
+ }
105
+ // login creates the directory, so a missing one was removed after login.
106
+ if (this.seen || !existsSync(this.dir))
107
+ return "gone";
108
+ writeFileSync(marker, MARKER_TEXT);
109
+ this.seen = true;
110
+ for (const r of rootList)
111
+ mkdirSync(r, { recursive: true });
112
+ return "ok";
113
+ }
114
+ }
115
+ /**
116
+ * Host-side file access under the three roots (real paths, symlinks resolved, refused when they
117
+ * leave a root). Used for the skills root, which commands can only read, so nothing can race it.
118
+ */
119
+ export class HostFiles {
120
+ roots;
121
+ constructor(roots) {
122
+ this.roots = roots;
123
+ }
124
+ /** `path` made absolute and normalized; refused unless it is lexically under a root. */
125
+ lexical(path) {
126
+ if (!isAbsolute(path))
127
+ throw policyError(`${path} is not an absolute path`);
128
+ const p = resolve(path);
129
+ if (!this.rootList().some((r) => isUnder(p, r))) {
130
+ throw policyError(`${path} is outside the environment's roots (${this.rootList().join(", ")})`);
131
+ }
132
+ return p;
133
+ }
134
+ /** The real path of an existing `path`, refused unless under a root after resolving links; null when missing. */
135
+ async existing(path) {
136
+ const p = this.lexical(path);
137
+ let real;
138
+ try {
139
+ real = await realpath(p);
140
+ }
141
+ catch (e) {
142
+ if (isMissing(e))
143
+ return null;
144
+ throw e;
145
+ }
146
+ return this.checkReal(path, real);
147
+ }
148
+ /** The real path of an existing `path` under a root (symlinks resolved); refused otherwise. */
149
+ async inside(path, what) {
150
+ const p = this.lexical(path);
151
+ let real;
152
+ try {
153
+ real = await realpath(p);
154
+ }
155
+ catch (e) {
156
+ if (isMissing(e))
157
+ throw new DeviceOpError("error", `${what} ${path} does not exist`);
158
+ throw e;
159
+ }
160
+ return this.checkReal(path, real);
161
+ }
162
+ async checkReal(path, real) {
163
+ const roots = await Promise.all(this.rootList().map((r) => realpath(r).catch(() => r)));
164
+ if (!roots.some((r) => isUnder(real, r))) {
165
+ throw policyError(`${path} resolves to ${real}, outside the environment's roots`);
166
+ }
167
+ return real;
168
+ }
169
+ rootList() {
170
+ return [this.roots.workspace, this.roots.skills, this.roots.tmp];
171
+ }
172
+ async read(path, maxBytes) {
173
+ const real = await this.existing(path);
174
+ if (real === null)
175
+ return null;
176
+ const fh = await open(real, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
177
+ try {
178
+ const st = await fh.stat();
179
+ if (st.isDirectory())
180
+ return null;
181
+ if (!st.isFile())
182
+ throw policyError(`${path} is not a regular file`);
183
+ const want = Math.min(st.size, maxBytes);
184
+ const buf = Buffer.alloc(want);
185
+ let off = 0;
186
+ while (off < want) {
187
+ const { bytesRead } = await fh.read(buf, off, want - off, off);
188
+ if (bytesRead === 0)
189
+ break;
190
+ off += bytesRead;
191
+ }
192
+ return { data: buf.subarray(0, off), truncated: st.size > maxBytes };
193
+ }
194
+ finally {
195
+ await fh.close();
196
+ }
197
+ }
198
+ async stat(path) {
199
+ const real = await this.existing(path);
200
+ if (real === null)
201
+ return null;
202
+ const st = await lstat(real);
203
+ return { size: st.size, isDir: st.isDirectory() };
204
+ }
205
+ async write(path, data) {
206
+ const target = this.lexical(path);
207
+ const parent = dirname(target);
208
+ // Check the nearest existing ancestor before creating anything beneath it.
209
+ let ancestor = parent;
210
+ while (!existsSync(ancestor))
211
+ ancestor = dirname(ancestor);
212
+ await this.inside(ancestor, "path");
213
+ await mkdir(parent, { recursive: true });
214
+ const realParent = await this.inside(parent, "path");
215
+ let file = join(realParent, basename(target));
216
+ const st = await lstat(file).catch((e) => {
217
+ if (isMissing(e))
218
+ return null;
219
+ throw e;
220
+ });
221
+ if (st?.isSymbolicLink()) {
222
+ const real = await realpath(file).catch((e) => {
223
+ if (isMissing(e))
224
+ throw policyError(`${path} is a dangling symbolic link`);
225
+ throw e;
226
+ });
227
+ file = await this.inside(real, "path");
228
+ }
229
+ const fh = await open(file, constants.O_WRONLY | constants.O_CREAT | constants.O_NONBLOCK | constants.O_NOFOLLOW, 0o644);
230
+ try {
231
+ if (!(await fh.stat()).isFile())
232
+ throw policyError(`${path} is not a regular file`);
233
+ await fh.truncate(0);
234
+ await fh.writeFile(data);
235
+ }
236
+ finally {
237
+ await fh.close();
238
+ }
239
+ }
240
+ }
@@ -0,0 +1,34 @@
1
+ import type { DeviceErrorKind, DeviceExecArgs, ExecResult, SandboxRoots } from "@capybara-hq/plugin-sdk";
2
+ /** What runs the operations on this machine: the OS sandbox (os) or a container (docker). */
3
+ export interface Executor {
4
+ readonly mode: "os" | "docker";
5
+ readonly roots: SandboxRoots;
6
+ /**
7
+ * Runs one command; `signal` aborting kills its whole process tree. An executor must not start
8
+ * work on an already-aborted signal (the kernel cancelled the request).
9
+ */
10
+ exec(args: DeviceExecArgs, signal: AbortSignal): Promise<ExecResult>;
11
+ /** The file's bytes (at most `maxBytes`); null when it does not exist. */
12
+ readFile(path: string, maxBytes: number): Promise<{
13
+ data: Uint8Array;
14
+ truncated: boolean;
15
+ } | null>;
16
+ writeFile(path: string, data: Uint8Array): Promise<void>;
17
+ /** null when the path does not exist. */
18
+ stat(path: string): Promise<{
19
+ size: number;
20
+ isDir: boolean;
21
+ } | null>;
22
+ killTagged(tags: string[]): Promise<void>;
23
+ killAll(): Promise<void>;
24
+ /**
25
+ * Creates the environment directory (and its marker file) on first use. "gone" when it existed
26
+ * before and has vanished; it is never recreated silently.
27
+ */
28
+ ensureRoot(): Promise<"ok" | "gone">;
29
+ }
30
+ /** An executor failure with a protocol error kind (default `error`). */
31
+ export declare class DeviceOpError extends Error {
32
+ readonly kind: DeviceErrorKind;
33
+ constructor(kind: DeviceErrorKind, message: string);
34
+ }
@@ -0,0 +1,9 @@
1
+ /** An executor failure with a protocol error kind (default `error`). */
2
+ export class DeviceOpError extends Error {
3
+ kind;
4
+ constructor(kind, message) {
5
+ super(message);
6
+ this.kind = kind;
7
+ this.name = "DeviceOpError";
8
+ }
9
+ }
@@ -0,0 +1,3 @@
1
+ export { type Command, parseCommandLine } from "./args.js";
2
+ export { runCli } from "./cli.js";
3
+ export { type Credential, type Policy, stateDir } from "./state.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { parseCommandLine } from "./args.js";
2
+ export { runCli } from "./cli.js";
3
+ export { stateDir } from "./state.js";
package/dist/pid.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ export declare function pidPath(dir: string): string;
2
+ export declare function isAlive(pid: number, kill?: typeof process.kill): boolean;
3
+ /** The pid of the running program, or undefined (no file, or a stale one). */
4
+ export declare function readRunningPid(dir: string, kill?: typeof process.kill): number | undefined;
5
+ export declare function writePid(dir: string, pid: number): void;
6
+ export declare function removePid(dir: string, pid: number): void;
package/dist/pid.js ADDED
@@ -0,0 +1,36 @@
1
+ import { existsSync, readFileSync, rmSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { writePrivate } from "./state.js";
4
+ export function pidPath(dir) {
5
+ return join(dir, "capybara-device.pid");
6
+ }
7
+ export function isAlive(pid, kill = process.kill) {
8
+ try {
9
+ kill(pid, 0);
10
+ return true;
11
+ }
12
+ catch (e) {
13
+ return e.code === "EPERM";
14
+ }
15
+ }
16
+ /** The pid of the running program, or undefined (no file, or a stale one). */
17
+ export function readRunningPid(dir, kill = process.kill) {
18
+ const file = pidPath(dir);
19
+ if (!existsSync(file))
20
+ return undefined;
21
+ const pid = Number.parseInt(readFileSync(file, "utf8").trim(), 10);
22
+ return Number.isInteger(pid) && pid > 0 && isAlive(pid, kill) ? pid : undefined;
23
+ }
24
+ export function writePid(dir, pid) {
25
+ writePrivate(pidPath(dir), `${pid}\n`);
26
+ }
27
+ export function removePid(dir, pid) {
28
+ const file = pidPath(dir);
29
+ try {
30
+ if (Number.parseInt(readFileSync(file, "utf8").trim(), 10) === pid)
31
+ rmSync(file, { force: true });
32
+ }
33
+ catch {
34
+ // already gone
35
+ }
36
+ }
@@ -0,0 +1,42 @@
1
+ import type { SandboxLimits, SandboxRoots } from "@capybara-hq/plugin-sdk";
2
+ import type { Policy } from "./state.js";
3
+ /**
4
+ * Paths no command may read (spec §13.6, extended by ruling R19): SSH keys, cloud CLI
5
+ * credentials, container and Kubernetes credentials, netrc, GnuPG, git / npm / PyPI tokens, the
6
+ * macOS keychains, and the browser profile directories (Chrome, Firefox, Chromium, Safari, Brave,
7
+ * Edge, Arc). Relative to `~`.
8
+ */
9
+ export declare const DENIED_SECRET_PATHS: readonly string[];
10
+ /** {@link DENIED_SECRET_PATHS} with `~` expanded to `home`. */
11
+ export declare function deniedSecretPaths(home?: string): string[];
12
+ /**
13
+ * Paths sandbox-runtime makes writable without being asked (its own temp directory and two home
14
+ * convenience directories). They lie outside the environment directory, so they are denied.
15
+ */
16
+ export declare function implicitWritePaths(home?: string): string[];
17
+ /**
18
+ * The domains one command may reach: what the environment's egress allows, cut to the local
19
+ * policy. The cloud can only narrow it: an empty policy allows nothing, whatever the egress.
20
+ */
21
+ export declare function effectiveEgress(policy: Pick<Policy, "allowedDomains">, limits: Pick<SandboxLimits, "egress" | "allowHosts">): string[];
22
+ /** The sandbox-runtime configuration of one environment. */
23
+ export interface SrtConfig {
24
+ filesystem: {
25
+ denyRead: string[];
26
+ allowWrite: string[];
27
+ denyWrite: string[];
28
+ };
29
+ network: {
30
+ allowedDomains: string[];
31
+ deniedDomains: string[];
32
+ };
33
+ }
34
+ /**
35
+ * The sandbox-runtime configuration: writes only under the workspace and tmp roots (the runtime's
36
+ * implicit write paths denied), skills read only, the secret paths (plus `opts.denyRead`, such as this program's own state directory)
37
+ * unreadable, and network limited to `egress`.
38
+ */
39
+ export declare function srtConfig(_policy: Policy, roots: SandboxRoots, egress: string[], opts?: {
40
+ home?: string;
41
+ denyRead?: string[];
42
+ }): SrtConfig;
package/dist/policy.js ADDED
@@ -0,0 +1,97 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ /**
4
+ * Paths no command may read (spec §13.6, extended by ruling R19): SSH keys, cloud CLI
5
+ * credentials, container and Kubernetes credentials, netrc, GnuPG, git / npm / PyPI tokens, the
6
+ * macOS keychains, and the browser profile directories (Chrome, Firefox, Chromium, Safari, Brave,
7
+ * Edge, Arc). Relative to `~`.
8
+ */
9
+ export const DENIED_SECRET_PATHS = Object.freeze([
10
+ "~/.ssh",
11
+ "~/.aws",
12
+ "~/.config/gcloud",
13
+ "~/.azure",
14
+ "~/.kube",
15
+ "~/.docker/config.json",
16
+ "~/.netrc",
17
+ "~/.gnupg",
18
+ "~/Library/Application Support/Google/Chrome",
19
+ "~/Library/Application Support/Firefox",
20
+ "~/.mozilla",
21
+ "~/.config/google-chrome",
22
+ "~/.config/chromium",
23
+ // Ruling R19: more credential stores and browser data.
24
+ "~/.config/gh",
25
+ "~/.git-credentials",
26
+ "~/.npmrc",
27
+ "~/.pypirc",
28
+ "~/Library/Keychains",
29
+ "~/Library/Cookies",
30
+ "~/Library/Safari",
31
+ "~/Library/Application Support/BraveSoftware",
32
+ "~/Library/Application Support/Microsoft Edge",
33
+ "~/Library/Application Support/Arc",
34
+ "~/.config/BraveSoftware",
35
+ "~/.config/microsoft-edge",
36
+ ]);
37
+ /** {@link DENIED_SECRET_PATHS} with `~` expanded to `home`. */
38
+ export function deniedSecretPaths(home = homedir()) {
39
+ return DENIED_SECRET_PATHS.map((p) => join(home, p.slice(2)));
40
+ }
41
+ /**
42
+ * Paths sandbox-runtime makes writable without being asked (its own temp directory and two home
43
+ * convenience directories). They lie outside the environment directory, so they are denied.
44
+ */
45
+ export function implicitWritePaths(home = homedir()) {
46
+ return [
47
+ "/tmp/claude",
48
+ "/private/tmp/claude",
49
+ join(home, ".npm/_logs"),
50
+ join(home, ".claude/debug"),
51
+ ];
52
+ }
53
+ /** True when the allowlist entry `pattern` admits every host `host` names (`host` may be a wildcard). */
54
+ function covers(pattern, host) {
55
+ if (pattern === host)
56
+ return true;
57
+ // `*.x.com` admits `a.x.com` and `*.a.x.com`, never the apex `x.com`.
58
+ return pattern.startsWith("*.") && host.endsWith(pattern.slice(1));
59
+ }
60
+ /**
61
+ * The domains one command may reach: what the environment's egress allows, cut to the local
62
+ * policy. The cloud can only narrow it: an empty policy allows nothing, whatever the egress.
63
+ */
64
+ export function effectiveEgress(policy, limits) {
65
+ const local = policy.allowedDomains.map((d) => d.toLowerCase());
66
+ if (limits.egress === "none")
67
+ return [];
68
+ if (limits.egress === "open")
69
+ return [...new Set(local)];
70
+ const out = new Set();
71
+ for (const raw of limits.allowHosts) {
72
+ const host = raw.toLowerCase();
73
+ for (const p of local) {
74
+ // The intersection of two entries is the narrower one, if either contains the other.
75
+ if (covers(p, host))
76
+ out.add(host);
77
+ else if (covers(host, p))
78
+ out.add(p);
79
+ }
80
+ }
81
+ return [...out];
82
+ }
83
+ /**
84
+ * The sandbox-runtime configuration: writes only under the workspace and tmp roots (the runtime's
85
+ * implicit write paths denied), skills read only, the secret paths (plus `opts.denyRead`, such as this program's own state directory)
86
+ * unreadable, and network limited to `egress`.
87
+ */
88
+ export function srtConfig(_policy, roots, egress, opts = {}) {
89
+ return {
90
+ filesystem: {
91
+ denyRead: [...deniedSecretPaths(opts.home), ...(opts.denyRead ?? [])],
92
+ allowWrite: [roots.workspace, roots.tmp],
93
+ denyWrite: [roots.skills, ...implicitWritePaths()],
94
+ },
95
+ network: { allowedDomains: [...egress], deniedDomains: [] },
96
+ };
97
+ }
@@ -0,0 +1,10 @@
1
+ import type { DeviceRes, KernelReq } from "@capybara-hq/plugin-sdk";
2
+ import type { CommandLogEntry } from "./command-log.js";
3
+ import { type Executor } from "./exec/types.js";
4
+ /** The local-log line for a finished request. */
5
+ export declare function logEntryFor(req: KernelReq, res: DeviceRes, now: Date): CommandLogEntry;
6
+ /**
7
+ * Runs one request on the executor and returns the answer. A vanished environment directory
8
+ * answers `fs_gone` for every operation except `stop`. Never throws.
9
+ */
10
+ export declare function runOp(executor: Executor, req: KernelReq, signal: AbortSignal): Promise<DeviceRes>;
@@ -0,0 +1,74 @@
1
+ import { DeviceOpError } from "./exec/types.js";
2
+ /** The local-log line for a finished request. */
3
+ export function logEntryFor(req, res, now) {
4
+ const exec = req.op === "exec" ? req.args : undefined;
5
+ const exitCode = res.ok && req.op === "exec"
6
+ ? (res.result.exitCode ?? null)
7
+ : null;
8
+ return {
9
+ time: now.toISOString(),
10
+ op: req.op,
11
+ tag: exec ? exec.tag : null,
12
+ actor: exec ? { accountId: exec.actor.accountId } : null,
13
+ exitCode,
14
+ };
15
+ }
16
+ /**
17
+ * Runs one request on the executor and returns the answer. A vanished environment directory
18
+ * answers `fs_gone` for every operation except `stop`. Never throws.
19
+ */
20
+ export async function runOp(executor, req, signal) {
21
+ const ok = (result) => ({ type: "res", id: req.id, ok: true, result });
22
+ try {
23
+ if (req.op === "stop")
24
+ return ok(null);
25
+ if ((await executor.ensureRoot()) === "gone") {
26
+ return {
27
+ type: "res",
28
+ id: req.id,
29
+ ok: false,
30
+ error: {
31
+ kind: "fs_gone",
32
+ message: "The environment directory on this machine existed and is gone. It is not recreated automatically.",
33
+ },
34
+ };
35
+ }
36
+ // The kernel may have cancelled while ensureRoot ran: never start the work then.
37
+ signal.throwIfAborted();
38
+ switch (req.op) {
39
+ case "create":
40
+ return ok({ roots: executor.roots });
41
+ case "exec":
42
+ return ok(await executor.exec(req.args, signal));
43
+ case "readFile": {
44
+ const a = req.args;
45
+ const r = await executor.readFile(a.path, a.maxBytes);
46
+ return ok(r === null
47
+ ? null
48
+ : { dataB64: Buffer.from(r.data).toString("base64"), truncated: r.truncated });
49
+ }
50
+ case "writeFile": {
51
+ const a = req.args;
52
+ await executor.writeFile(a.path, Buffer.from(a.dataB64, "base64"));
53
+ return ok(null);
54
+ }
55
+ case "stat":
56
+ return ok(await executor.stat(req.args.path));
57
+ case "killTagged":
58
+ await executor.killTagged(req.args.tags);
59
+ return ok(null);
60
+ case "killAll":
61
+ await executor.killAll();
62
+ return ok(null);
63
+ }
64
+ }
65
+ catch (e) {
66
+ const kind = e instanceof DeviceOpError ? e.kind : "error";
67
+ return {
68
+ type: "res",
69
+ id: req.id,
70
+ ok: false,
71
+ error: { kind, message: e instanceof Error ? e.message : String(e) },
72
+ };
73
+ }
74
+ }
@@ -0,0 +1,17 @@
1
+ export declare const LAUNCHD_LABEL = "top.capybara.device";
2
+ export interface ServiceSpec {
3
+ /** Absolute path of the node binary that runs the program. */
4
+ nodePath: string;
5
+ /** Absolute path of the `capybara-device` bin script. */
6
+ binPath: string;
7
+ /** The state directory: logs go there. */
8
+ stateDir: string;
9
+ /** Environment the service needs: PATH (for docker) and XDG_CONFIG_HOME when set. */
10
+ env: Record<string, string>;
11
+ }
12
+ export declare function plistPath(home: string): string;
13
+ /** The launchd agent: `node <bin> start`, at login, restarted when it exits with a failure (a clean stop stays stopped). */
14
+ export declare function plistContent(spec: ServiceSpec): string;
15
+ export declare const SERVICE_LOG_MAX_BYTES: number;
16
+ /** Keeps `service.log` from growing without bound: past 10 MiB it is copied to `.1` and emptied. */
17
+ export declare function rotateServiceLog(stateDir: string, maxBytes?: number): void;