@capybara-hq/device 0.1.0-rc.11 → 0.1.0-rc.12

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.
package/README.md CHANGED
@@ -79,14 +79,17 @@ with `capybara-device mode`):
79
79
  network. It is what a coding agent without an OS sandbox has, and what Claude Code calls auto
80
80
  mode. The deployment reviews every command before it runs and blocks, or asks about, the
81
81
  dangerous ones (deleting outside the workspace, sending a secret away, force-pushing a protected
82
- branch). The platform's file tools reach any absolute path on the machine.
82
+ branch). The platform's file tools reach any absolute path on the machine. The hello reports
83
+ your home directory, and the deployment can list any directory you can read and scan your home
84
+ for projects (directory entries only, never file contents).
83
85
  - **sandbox**: today's strict `@anthropic-ai/sandbox-runtime` profile (macOS Seatbelt, Linux
84
86
  bubblewrap; Linux needs `bwrap` and `socat`). Writes only under `workspace/` and `tmp/`,
85
87
  `skills/` read only, `HOME` = the workspace, `~/.ssh`, cloud CLI credentials, `~/.netrc`,
86
88
  `~/.gnupg`, browser profiles and this program's state directory unreadable, no local binding or
87
89
  unix sockets, and network only to the domains of the local policy that the organization's
88
90
  allowlist also admits (with an empty list, no network at all). Commands keep their package
89
- caches in the workspace like any other file.
91
+ caches in the workspace like any other file. The hello still reports your home directory, but
92
+ the deployment's directory listing and project scan cover the workspace only.
90
93
 
91
94
  If the OS sandbox is unavailable on the machine (an unsupported platform or missing dependencies,
92
95
  such as `bwrap` / `socat` on Linux), the device still starts and serves: auto mode works, and every
@@ -222,6 +225,9 @@ Docker mode has no per-domain network filter, so the mode alone decides:
222
225
  network), and the platform's file tools reach any absolute path in the container.
223
226
  - **sandbox**: the container has no network at all, and file operations stay in the mounted roots.
224
227
 
228
+ In both, the hello reports your home directory, while the deployment's directory listing and
229
+ project scan cover the container's `/workspace` only (directory entries, never file contents).
230
+
225
231
  The network is switched between the two without recreating the container (a container disconnected
226
232
  from every network has no network, the same as `--network none`). Use OS mode's sandbox when you
227
233
  need to allow single domains.
package/dist/client.d.ts CHANGED
@@ -20,6 +20,12 @@ export interface ConnectOptions {
20
20
  random?: () => number;
21
21
  now?: () => number;
22
22
  programVersion?: string;
23
+ /**
24
+ * The owner's home directory, reported in the hello (the base of an auto-mode project path).
25
+ * Defaults to the user's home; left out of the hello when it is not a clean absolute path, and
26
+ * by a docker-mode device (it offers its container's workspace only).
27
+ */
28
+ home?: string;
23
29
  /** A connection must stay up this long before the backoff resets (default 10 s). */
24
30
  stableMs?: number;
25
31
  /** Terminate a socket that heard nothing from the server for this long (default 60 s). */
package/dist/client.js CHANGED
@@ -1,4 +1,5 @@
1
- import { DEVICE_PROTOCOL_VERSION, parseDeviceFrame, } from "@capybara-hq/plugin-sdk";
1
+ import { homedir } from "node:os";
2
+ import { DEVICE_PROTOCOL_VERSION, parseDeviceFrame, validateSandboxPathShape, } from "@capybara-hq/plugin-sdk";
2
3
  import WebSocket from "ws";
3
4
  import { logEntryFor, policySummary, serveOp, summaryFacts, } from "./server-ops.js";
4
5
  import { PROGRAM_VERSION } from "./version.js";
@@ -241,6 +242,11 @@ export function connect(cred, executor, opts = {}) {
241
242
  * policy summary is the store's policy now (the owner's mode, not cut by any ceiling);
242
243
  * then the outcomes of the latest policy ops by op id.
243
244
  */
245
+ // A container device offers only its container's workspace: the host's home is not its base.
246
+ const ownerHome = opts.home ?? homedir();
247
+ const home = executor.mode === "os" && validateSandboxPathShape(ownerHome).length === 0
248
+ ? ownerHome
249
+ : undefined;
244
250
  const hello = () => {
245
251
  const summary = summaryNow();
246
252
  sentPolicy = summary === undefined ? undefined : JSON.stringify(summary);
@@ -251,6 +257,9 @@ export function connect(cred, executor, opts = {}) {
251
257
  if (opts.policy !== undefined)
252
258
  features.push("policyOp", "policyOpId");
253
259
  features.push("mode");
260
+ // `list` and `scan`, read in each request's own mode (they need the owner's policy)
261
+ if (opts.policy !== undefined)
262
+ features.push("projects");
254
263
  return {
255
264
  type: "hello",
256
265
  protocol: DEVICE_PROTOCOL_VERSION,
@@ -261,6 +270,7 @@ export function connect(cred, executor, opts = {}) {
261
270
  roots: executor.roots,
262
271
  sessionIsolation: false,
263
272
  features,
273
+ ...(home !== undefined && { home }),
264
274
  ...(summary !== undefined && { policy: summary }),
265
275
  // what became of the latest policy ops, so an answer lost with a connection is not lost
266
276
  ...(opts.policy !== undefined && { recentOps: opts.policy.ops.recent() }),
@@ -1,5 +1,5 @@
1
- import { type DeviceExecArgs, type ExecResult, type SandboxRoots } from "@capybara-hq/plugin-sdk";
2
- import type { Policy } from "../state.js";
1
+ import { type DeviceExecArgs, type DeviceListResult, type DeviceScanResult, type ExecResult, type SandboxRoots } from "@capybara-hq/plugin-sdk";
2
+ import type { Policy, SandboxMode } from "../state.js";
3
3
  import { type Executor } from "./types.js";
4
4
  /** The version of the published sandbox images this program runs commands in. */
5
5
  export declare const SANDBOX_IMAGE_TAG = "0.1.0-rc.5";
@@ -134,6 +134,28 @@ export declare class DockerExecutor implements Executor {
134
134
  size: number;
135
135
  isDir: boolean;
136
136
  } | null>;
137
+ /**
138
+ * `path` made absolute and normalized, refused unless it lies lexically under the container's
139
+ * workspace: a container device offers its workspace only, in either mode (spec §4.2).
140
+ */
141
+ private workspacePath;
142
+ /**
143
+ * Whether the device directory is marked and holds all three roots. `list` and `scan` only
144
+ * read: a removed root under a marked directory lost its files and is never recreated empty
145
+ * (`ensureContainer` would create it), and an unmarked or vanished directory gets no roots either.
146
+ */
147
+ private rootsIntact;
148
+ /**
149
+ * Runs {@link LIST_SCRIPT} in the container (as the `sandbox` user, like the file operations):
150
+ * links resolve in the container, so whatever a command there does to the workspace, the answer
151
+ * shows only what the container itself can see, never the host behind the bind mount. A stopped
152
+ * container is started first, as for the file operations.
153
+ */
154
+ private listOp;
155
+ /** Lists a container workspace directory, read in the container, in either mode. */
156
+ list(_mode: SandboxMode, path: string, limit: number, signal?: AbortSignal): Promise<DeviceListResult>;
157
+ /** Scans a container workspace directory, read in the container ({@link list}'s rules). */
158
+ scan(_mode: SandboxMode, base: string, signal?: AbortSignal): Promise<DeviceScanResult>;
137
159
  /** Kills the container processes of one marker (exact) or marker prefix. */
138
160
  private killScript;
139
161
  private killMarker;
@@ -2,10 +2,11 @@ import { spawn } from "node:child_process";
2
2
  import { createHash, randomBytes } from "node:crypto";
3
3
  import { existsSync, mkdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
4
  import { join, resolve } from "node:path";
5
- import { DEFAULT_SANDBOX_ROOTS, validateSandboxPathShape, } from "@capybara-hq/plugin-sdk";
5
+ import { DEFAULT_SANDBOX_ROOTS, DEVICE_SCAN_SKIPPED_BASE_DIRS, DEVICE_SCAN_SKIPPED_DIRS, MAX_DEVICE_SCAN_DEPTH, MAX_DEVICE_SCAN_DIRS, validateSandboxPathShape, } from "@capybara-hq/plugin-sdk";
6
6
  import { effectiveMode } from "../policy.js";
7
+ import { finishScan } from "./listing.js";
7
8
  import { EXEC_MARKER } from "./procs.js";
8
- import { ENV_NAME_RE, HostFiles, isUnder, OutputCap, osRoots, PIPE_GRACE_MS, policyError, RootGuard, } from "./shared.js";
9
+ import { ENV_NAME_RE, HostFiles, isUnder, OutputCap, osRoots, PIPE_GRACE_MS, policyError, ROOT_MARKER, RootGuard, } from "./shared.js";
9
10
  import { FILE_OPS_DECISION_TTL_MS } from "./switch.js";
10
11
  import { DeviceOpError } from "./types.js";
11
12
  /** The version of the published sandbox images this program runs commands in. */
@@ -50,14 +51,20 @@ function docker(args, o = {}) {
50
51
  child.stdin.end(Buffer.from(o.input));
51
52
  }
52
53
  const timer = o.timeoutMs !== undefined ? setTimeout(() => child.kill("SIGKILL"), o.timeoutMs) : undefined;
54
+ const onAbort = () => {
55
+ child.kill("SIGKILL");
56
+ };
57
+ o.signal?.addEventListener("abort", onAbort, { once: true });
53
58
  child.once("error", (e) => {
54
59
  if (timer)
55
60
  clearTimeout(timer);
61
+ o.signal?.removeEventListener("abort", onAbort);
56
62
  reject(e);
57
63
  });
58
64
  child.once("close", (code) => {
59
65
  if (timer)
60
66
  clearTimeout(timer);
67
+ o.signal?.removeEventListener("abort", onAbort);
61
68
  resolvePromise({ code, stdout: Buffer.concat(out), stderr: Buffer.concat(err) });
62
69
  });
63
70
  });
@@ -135,6 +142,89 @@ f="$rp/$(basename -- "$p")"
135
142
  if [ -L "$f" ]; then r=$(realpath -e -- "$f" 2>/dev/null) || exit ${E_DANGLING}; allowed "$r" || exit ${E_OUTSIDE}; f=$r; fi
136
143
  if [ -e "$f" ] && [ ! -f "$f" ]; then exit ${E_NOT_FILE}; fi
137
144
  cat > "$f" || exit ${E_FAIL}`;
145
+ /**
146
+ * `list` / `scan` in the container (python3, which the sandbox image carries): argv `<op> <path>
147
+ * <limit>`, the path lexically under /workspace already. The same rules as `listing.ts`'s
148
+ * `listDirectory` / `scanDirectory` with /workspace as the area: realpath containment, a link
149
+ * leaving the workspace is not a directory, null / [] for a missing path, the same breadth-first
150
+ * walk and budget. Names sort by UTF-16 code unit (`utf-16-be` bytes). stdout: `{"r": ...}` or
151
+ * `{"e": "policy" | "error", "m": ...}`; scan answers raw paths (the caller applies `finishScan`).
152
+ */
153
+ const LIST_SCRIPT = `
154
+ import errno, json, os, sys
155
+ op, p, limit = sys.argv[1], sys.argv[2], int(sys.argv[3])
156
+ W = "/workspace"
157
+ def out(o):
158
+ sys.stdout.write(json.dumps(o)); sys.exit(0)
159
+ def key(s):
160
+ return s.encode("utf-16-be", "surrogatepass")
161
+ def under(r):
162
+ return r == W or r.startswith(W + "/")
163
+ def fail(e):
164
+ c = errno.errorcode.get(getattr(e, "errno", None) or 0)
165
+ out({"e": "error", "m": p + " cannot be read" + (" (" + c + ")" if c else "")})
166
+ away = {"e": "policy", "m": p + " is outside the container's workspace (/workspace); this device reads only that"}
167
+ q = os.path.normpath(p)
168
+ if not os.path.isabs(q) or not under(q):
169
+ out(away)
170
+ try:
171
+ r = os.path.realpath(q, strict=True)
172
+ except (FileNotFoundError, NotADirectoryError):
173
+ out({"r": None if op == "list" else []})
174
+ except OSError as e:
175
+ fail(e)
176
+ if not under(r):
177
+ out(away)
178
+ if not os.path.isdir(r):
179
+ out({"e": "error", "m": p + " is not a directory"})
180
+ try:
181
+ with os.scandir(r) as it:
182
+ ents = sorted(it, key=lambda e: key(e.name))
183
+ except OSError as e:
184
+ fail(e)
185
+ def is_dir(d, e):
186
+ try:
187
+ if e.is_dir(follow_symlinks=False):
188
+ return True
189
+ if not e.is_symlink():
190
+ return False
191
+ t = os.path.realpath(os.path.join(d, e.name), strict=True)
192
+ return under(t) and os.path.isdir(t)
193
+ except OSError:
194
+ return False
195
+ if op == "list":
196
+ out({"r": {"entries": [{"name": e.name, "isDir": is_dir(r, e)} for e in ents[:limit]], "truncated": len(ents) > limit}})
197
+ skip_any = ${JSON.stringify(DEVICE_SCAN_SKIPPED_DIRS)}
198
+ skip_base = ${JSON.stringify(DEVICE_SCAN_SKIPPED_BASE_DIRS)}
199
+ found = []
200
+ def below(d, rep, es, depth):
201
+ if any(e.name == ".git" or (e.name == "AGENTS.md" and not e.is_dir(follow_symlinks=False)) for e in es):
202
+ found.append(rep)
203
+ if depth >= ${MAX_DEVICE_SCAN_DEPTH}:
204
+ return []
205
+ return [(os.path.join(d, e.name), os.path.join(rep, e.name)) for e in es
206
+ if e.is_dir(follow_symlinks=False) and not e.name.startswith(".")
207
+ and e.name not in skip_any and not (depth == 0 and e.name in skip_base)]
208
+ visits = 1
209
+ level = below(r, q, ents, 0)
210
+ depth = 1
211
+ while level and visits < ${MAX_DEVICE_SCAN_DIRS}:
212
+ level.sort(key=lambda n: key(n[1]))
213
+ nxt = []
214
+ for d, rep in level:
215
+ if visits >= ${MAX_DEVICE_SCAN_DIRS}:
216
+ break
217
+ visits += 1
218
+ try:
219
+ with os.scandir(d) as it:
220
+ es = list(it)
221
+ except OSError:
222
+ continue
223
+ nxt.extend(below(d, rep, es, depth))
224
+ level = nxt
225
+ depth += 1
226
+ out({"r": found})
227
+ `;
138
228
  /**
139
229
  * Runs every command with `docker exec` in one long-lived container of the published sandbox
140
230
  * image: the device directory's workspace, skills (read only) and tmp are mounted at
@@ -695,6 +785,90 @@ export class DockerExecutor {
695
785
  const [size, kind] = r.stdout.toString("utf8").split(" ");
696
786
  return { size: Number(size), isDir: kind === "d" };
697
787
  }
788
+ /**
789
+ * `path` made absolute and normalized, refused unless it lies lexically under the container's
790
+ * workspace: a container device offers its workspace only, in either mode (spec §4.2).
791
+ */
792
+ workspacePath(path) {
793
+ if (!path.startsWith("/"))
794
+ throw policyError(`${path} is not an absolute path`);
795
+ const p = resolve(path);
796
+ if (!isUnder(p, ROOTS.workspace)) {
797
+ throw policyError(`${path} is outside the container's workspace (${ROOTS.workspace}); this device reads only that`);
798
+ }
799
+ return p;
800
+ }
801
+ /**
802
+ * Whether the device directory is marked and holds all three roots. `list` and `scan` only
803
+ * read: a removed root under a marked directory lost its files and is never recreated empty
804
+ * (`ensureContainer` would create it), and an unmarked or vanished directory gets no roots either.
805
+ */
806
+ rootsIntact() {
807
+ return (existsSync(join(this.dir, ROOT_MARKER)) &&
808
+ Object.values(this.hostRoots).every((r) => existsSync(r)));
809
+ }
810
+ /**
811
+ * Runs {@link LIST_SCRIPT} in the container (as the `sandbox` user, like the file operations):
812
+ * links resolve in the container, so whatever a command there does to the workspace, the answer
813
+ * shows only what the container itself can see, never the host behind the bind mount. A stopped
814
+ * container is started first, as for the file operations.
815
+ */
816
+ async listOp(op, path, limit, signal) {
817
+ signal?.throwIfAborted();
818
+ await this.serial(() => this.ensureContainer({ anySpec: true }));
819
+ signal?.throwIfAborted();
820
+ const r = await docker([
821
+ "exec",
822
+ this.name,
823
+ "timeout",
824
+ "-s",
825
+ "KILL",
826
+ String(FILE_OP_TIMEOUT_S),
827
+ "python3",
828
+ "-I",
829
+ "-c",
830
+ LIST_SCRIPT,
831
+ op,
832
+ path,
833
+ String(limit),
834
+ ], { timeoutMs: (FILE_OP_TIMEOUT_S + 5) * 1000, ...(signal !== undefined && { signal }) });
835
+ signal?.throwIfAborted();
836
+ let res;
837
+ try {
838
+ res = JSON.parse(r.stdout.toString("utf8"));
839
+ }
840
+ catch {
841
+ this.noteFailure(r.stderr.toString("utf8"));
842
+ throw new DeviceOpError("error", `${op} ${path} failed in the container: ${r.stderr.toString("utf8").trim().slice(0, 300)}`);
843
+ }
844
+ if (res.e !== undefined) {
845
+ throw new DeviceOpError(res.e === "policy" ? "policy" : "error", res.m ?? "failed");
846
+ }
847
+ return res.r ?? null;
848
+ }
849
+ /** Lists a container workspace directory, read in the container, in either mode. */
850
+ async list(_mode, path, limit, signal) {
851
+ const p = this.workspacePath(path);
852
+ // nothing under the workspace exists (as the OS reader answers)
853
+ if (!this.rootsIntact())
854
+ return null;
855
+ const r = await this.listOp("list", p, limit, signal);
856
+ if (r !== null && !Array.isArray(r.entries)) {
857
+ throw new DeviceOpError("error", `list ${path} answered an invalid result`);
858
+ }
859
+ return r;
860
+ }
861
+ /** Scans a container workspace directory, read in the container ({@link list}'s rules). */
862
+ async scan(_mode, base, signal) {
863
+ const p = this.workspacePath(base);
864
+ if (!this.rootsIntact())
865
+ return [];
866
+ const r = await this.listOp("scan", p, 0, signal);
867
+ if (!Array.isArray(r) || !r.every((x) => typeof x === "string")) {
868
+ throw new DeviceOpError("error", `scan ${base} answered an invalid result`);
869
+ }
870
+ return finishScan(r);
871
+ }
698
872
  /** Kills the container processes of one marker (exact) or marker prefix. */
699
873
  async killScript(marker, prefix) {
700
874
  try {
@@ -5,13 +5,17 @@
5
5
  * could reach anyway.
6
6
  *
7
7
  * argv: `<mode> <op> <path> <maxBytes> <root>...`, mode `auto` | `sandbox`, op `read` | `stat` |
8
- * `write` (data on stdin). A missing or unknown mode is refused. In sandbox mode the roots are
8
+ * `write` (data on stdin) | `list` (`maxBytes` is the entry limit) | `scan`. A missing or unknown mode is refused. In sandbox mode the roots are
9
9
  * enforced; in auto mode any clean absolute path is accepted (shape checks: absolute, no `..`
10
10
  * segments, no control characters). The `auto` branch is required by this contract but has no
11
11
  * production caller today: the OS executor runs the helper in sandbox mode only, and auto mode
12
12
  * reads and writes directly through `HostExecutor`. stdout: one JSON object, `{ "r": <result> }`
13
13
  * or `{ "e": "policy" | "error", "m": <message> }`. read → `null` | `{ b64, truncated }`; stat →
14
- * `null` | `{ size, isDir }`; write → `null`. Non-regular files (FIFOs, sockets, devices) are
14
+ * `null` | `{ size, isDir }`; write → `null`; list → `null` | `{ entries, truncated }`; scan → the
15
+ * paths of the directories found, unfiltered and unsorted (the caller applies the name rule, the
16
+ * order and the cut: `finishScan`). `list` and `scan` follow `listing.ts`'s `listDirectory` and
17
+ * `scanDirectory` (same traversal, same budget); in sandbox mode their path must also lie lexically
18
+ * under a root, so a missing path outside the roots is refused, never `null`. Non-regular files (FIFOs, sockets, devices) are
15
19
  * refused without blocking (`O_NONBLOCK`).
16
20
  */
17
- export declare const FS_HELPER_SCRIPT = "\n(() => {\n const fs = require(\"fs\");\n const path = require(\"path\");\n const C = fs.constants;\n const [mode, op, p, maxS, ...roots] = process.argv.slice(1);\n const out = (o) => process.stdout.write(JSON.stringify(o));\n const realRoots = roots.map((r) => { try { return fs.realpathSync(r); } catch { return r; } });\n const under = (r) => realRoots.some((x) => r === x || r.startsWith(x + \"/\"));\n const missing = (e) => e && (e.code === \"ENOENT\" || e.code === \"ENOTDIR\");\n const real = (q) => { try { return fs.realpathSync(q); } catch (e) { if (missing(e)) return null; throw e; } };\n const outside = (r) => out({ e: \"policy\", m: p + \" resolves to \" + r + \", outside the device's roots\" });\n // auto mode: any clean absolute path; sandbox mode: one of the roots.\n const shapeOk = () => {\n if (typeof p !== \"string\" || !path.isAbsolute(p)) return false;\n if (/[\\u0000-\\u001f\\u007f]/.test(p)) return false;\n return !p.split(\"/\").some((s) => s === \"..\");\n };\n const allowed = (r) => mode === \"auto\" ? true : under(r);\n try {\n if (mode !== \"auto\" && mode !== \"sandbox\") {\n return out({ e: \"policy\", m: \"missing or unknown mode\" });\n }\n if (mode === \"auto\" && !shapeOk()) {\n return out({ e: \"policy\", m: p + \" is not a clean absolute path\" });\n }\n if (op === \"read\" || op === \"stat\") {\n const r = real(p);\n if (r === null) return out({ r: null });\n if (!allowed(r)) return outside(r);\n const fd = fs.openSync(r, C.O_RDONLY | C.O_NONBLOCK | C.O_NOFOLLOW);\n try {\n const st = fs.fstatSync(fd);\n if (op === \"stat\") return out({ r: { size: st.size, isDir: st.isDirectory() } });\n if (st.isDirectory()) return out({ r: null });\n if (!st.isFile()) return out({ e: \"policy\", m: p + \" is not a regular file\" });\n const max = Number(maxS);\n const want = Math.min(st.size, max);\n const buf = Buffer.alloc(want);\n let off = 0;\n while (off < want) {\n const n = fs.readSync(fd, buf, off, want - off, off);\n if (n === 0) break;\n off += n;\n }\n return out({ r: { b64: buf.subarray(0, off).toString(\"base64\"), truncated: st.size > max } });\n } finally {\n fs.closeSync(fd);\n }\n }\n if (op === \"write\") {\n const data = fs.readFileSync(0);\n const parent = path.dirname(p);\n let anc = parent;\n while (real(anc) === null && anc !== path.dirname(anc)) anc = path.dirname(anc);\n const ra = real(anc);\n if (ra === null || !allowed(ra)) return outside(ra);\n fs.mkdirSync(parent, { recursive: true });\n const rp = real(parent);\n if (rp === null) return out({ e: \"error\", m: \"cannot create \" + parent });\n if (!allowed(rp)) return outside(rp);\n let file = path.join(rp, path.basename(p));\n let st = null;\n try { st = fs.lstatSync(file); } catch (e) { if (!missing(e)) throw e; }\n if (st && st.isSymbolicLink()) {\n const r = real(file);\n if (r === null) return out({ e: \"policy\", m: p + \" is a dangling symbolic link\" });\n if (!allowed(r)) return outside(r);\n file = r;\n }\n const fd = fs.openSync(file, C.O_WRONLY | C.O_CREAT | C.O_NONBLOCK | C.O_NOFOLLOW, 0o644);\n try {\n if (!fs.fstatSync(fd).isFile()) return out({ e: \"policy\", m: p + \" is not a regular file\" });\n fs.ftruncateSync(fd, 0);\n let off = 0;\n while (off < data.length) off += fs.writeSync(fd, data, off, data.length - off, off);\n } finally {\n fs.closeSync(fd);\n }\n return out({ r: null });\n }\n out({ e: \"error\", m: \"unknown helper op \" + op });\n } catch (e) {\n out({ e: \"error\", m: String((e && e.message) || e) });\n }\n})();\n";
21
+ export declare const FS_HELPER_SCRIPT: string;
@@ -1,3 +1,4 @@
1
+ import { DEVICE_SCAN_SKIPPED_BASE_DIRS, DEVICE_SCAN_SKIPPED_DIRS, MAX_DEVICE_SCAN_DEPTH, MAX_DEVICE_SCAN_DIRS, } from "@capybara-hq/plugin-sdk";
1
2
  /**
2
3
  * The file-operation helper the OS executor runs **inside the sandbox** (`node -e`), so a
3
4
  * kernel-side read or write never touches the host file system with the program's own privileges:
@@ -5,13 +6,17 @@
5
6
  * could reach anyway.
6
7
  *
7
8
  * argv: `<mode> <op> <path> <maxBytes> <root>...`, mode `auto` | `sandbox`, op `read` | `stat` |
8
- * `write` (data on stdin). A missing or unknown mode is refused. In sandbox mode the roots are
9
+ * `write` (data on stdin) | `list` (`maxBytes` is the entry limit) | `scan`. A missing or unknown mode is refused. In sandbox mode the roots are
9
10
  * enforced; in auto mode any clean absolute path is accepted (shape checks: absolute, no `..`
10
11
  * segments, no control characters). The `auto` branch is required by this contract but has no
11
12
  * production caller today: the OS executor runs the helper in sandbox mode only, and auto mode
12
13
  * reads and writes directly through `HostExecutor`. stdout: one JSON object, `{ "r": <result> }`
13
14
  * or `{ "e": "policy" | "error", "m": <message> }`. read → `null` | `{ b64, truncated }`; stat →
14
- * `null` | `{ size, isDir }`; write → `null`. Non-regular files (FIFOs, sockets, devices) are
15
+ * `null` | `{ size, isDir }`; write → `null`; list → `null` | `{ entries, truncated }`; scan → the
16
+ * paths of the directories found, unfiltered and unsorted (the caller applies the name rule, the
17
+ * order and the cut: `finishScan`). `list` and `scan` follow `listing.ts`'s `listDirectory` and
18
+ * `scanDirectory` (same traversal, same budget); in sandbox mode their path must also lie lexically
19
+ * under a root, so a missing path outside the roots is refused, never `null`. Non-regular files (FIFOs, sockets, devices) are
15
20
  * refused without blocking (`O_NONBLOCK`).
16
21
  */
17
22
  export const FS_HELPER_SCRIPT = `
@@ -95,6 +100,69 @@ export const FS_HELPER_SCRIPT = `
95
100
  }
96
101
  return out({ r: null });
97
102
  }
103
+ if (op === "list" || op === "scan") {
104
+ const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
105
+ const fail = (e) => {
106
+ const code = e && typeof e.code === "string" && /^[A-Z0-9_]+$/.test(e.code) ? " (" + e.code + ")" : "";
107
+ return out({ e: "error", m: p + " cannot be read" + code });
108
+ };
109
+ const away = () => out({ e: "policy", m: p + " is outside the device's workspace; in this mode the device reads only that" });
110
+ if (typeof p !== "string" || !path.isAbsolute(p)) return out({ e: "policy", m: p + " is not an absolute path" });
111
+ const q = path.resolve(p);
112
+ if (mode === "sandbox" && !roots.some((x) => q === x || q.startsWith(x + "/"))) return away();
113
+ let r;
114
+ try { r = real(q); } catch (e) { return fail(e); }
115
+ if (r === null) return out({ r: op === "list" ? null : [] });
116
+ if (!allowed(r)) return away();
117
+ let st;
118
+ try { st = fs.statSync(r); } catch (e) { return fail(e); }
119
+ if (!st.isDirectory()) return out({ e: "error", m: p + " is not a directory" });
120
+ let ents;
121
+ try { ents = fs.readdirSync(r, { withFileTypes: true }); } catch (e) { return fail(e); }
122
+ ents.sort((a, b) => cmp(a.name, b.name));
123
+ if (op === "list") {
124
+ const limit = Number(maxS);
125
+ // a link counts as a directory only when its target is one inside what the mode reads
126
+ const isDir = (e) => {
127
+ if (e.isDirectory()) return true;
128
+ if (!e.isSymbolicLink()) return false;
129
+ try {
130
+ const t = fs.realpathSync(path.join(r, e.name));
131
+ if (mode !== "auto" && !under(t)) return false;
132
+ return fs.statSync(t).isDirectory();
133
+ } catch { return false; }
134
+ };
135
+ const entries = ents.slice(0, limit).map((e) => ({ name: e.name, isDir: isDir(e) }));
136
+ return out({ r: { entries, truncated: ents.length > limit } });
137
+ }
138
+ const skipAny = ${JSON.stringify(DEVICE_SCAN_SKIPPED_DIRS)};
139
+ const skipBase = ${JSON.stringify(DEVICE_SCAN_SKIPPED_BASE_DIRS)};
140
+ const found = [];
141
+ let visits = 1;
142
+ // a hit is recorded; the directories to visit below are returned
143
+ const below = (node, es, depth) => {
144
+ if (es.some((e) => e.name === ".git" || (e.name === "AGENTS.md" && !e.isDirectory()))) found.push(node.rep);
145
+ if (depth >= ${MAX_DEVICE_SCAN_DEPTH}) return [];
146
+ return es
147
+ .filter((e) => e.isDirectory() && !e.name.startsWith(".") && !skipAny.includes(e.name) && !(depth === 0 && skipBase.includes(e.name)))
148
+ .map((e) => ({ dir: path.join(node.dir, e.name), rep: path.join(node.rep, e.name) }));
149
+ };
150
+ let level = below({ dir: r, rep: q }, ents, 0);
151
+ // breadth-first, each level in code-unit order of path, until the visit budget is spent
152
+ walk: for (let depth = 1; level.length > 0; depth++) {
153
+ level.sort((a, b) => cmp(a.rep, b.rep));
154
+ const next = [];
155
+ for (const node of level) {
156
+ if (visits >= ${MAX_DEVICE_SCAN_DIRS}) break walk;
157
+ visits += 1;
158
+ let es;
159
+ try { es = fs.readdirSync(node.dir, { withFileTypes: true }); } catch { continue; }
160
+ next.push(...below(node, es, depth));
161
+ }
162
+ level = next;
163
+ }
164
+ return out({ r: found });
165
+ }
98
166
  out({ e: "error", m: "unknown helper op " + op });
99
167
  } catch (e) {
100
168
  out({ e: "error", m: String((e && e.message) || e) });
@@ -1,4 +1,5 @@
1
- import type { DeviceExecArgs, ExecResult, SandboxRoots } from "@capybara-hq/plugin-sdk";
1
+ import type { DeviceExecArgs, DeviceListResult, DeviceScanResult, ExecResult, SandboxRoots } from "@capybara-hq/plugin-sdk";
2
+ import type { SandboxMode } from "../state.js";
2
3
  import type { ExecHooks, Executor } from "./types.js";
3
4
  export interface HostExecutorOptions {
4
5
  /** The device directory (from login). */
@@ -44,6 +45,13 @@ export declare class HostExecutor implements Executor {
44
45
  size: number;
45
46
  isDir: boolean;
46
47
  } | null>;
48
+ /**
49
+ * Lists a directory with the owner's rights: auto mode only. This executor has no sandbox, so a
50
+ * request decided as sandbox mode is refused here rather than read unsandboxed.
51
+ */
52
+ list(mode: SandboxMode, path: string, limit: number): Promise<DeviceListResult>;
53
+ /** Scans with the owner's rights: auto mode only ({@link list}). */
54
+ scan(mode: SandboxMode, base: string, signal: AbortSignal): Promise<DeviceScanResult>;
47
55
  killTagged(tags: string[]): Promise<void>;
48
56
  killAll(): Promise<void>;
49
57
  /** Kills every process carrying this device's marker (also a previous run's). */
package/dist/exec/host.js CHANGED
@@ -3,8 +3,11 @@ import { existsSync, realpathSync } from "node:fs";
3
3
  import { constants as osConstants } from "node:os";
4
4
  import { resolve } from "node:path";
5
5
  import { dirKeyOf, GroupTracker } from "./groups.js";
6
+ import { listDirectory, scanDirectory } from "./listing.js";
6
7
  import { EXEC_MARKER, killMarked } from "./procs.js";
7
8
  import { ENV_NAME_RE, HostFiles, OutputCap, osRoots, PIPE_GRACE_MS, policyError, RootGuard, } from "./shared.js";
9
+ /** The refusal of a sandbox-mode read sent to the executor without a sandbox. */
10
+ const UNSANDBOXED_READ = "sandbox mode reads only through the sandbox, and this executor runs without one";
8
11
  /**
9
12
  * Runs commands without a sandbox (spec §4.1): `/bin/bash -c` directly on this machine as the
10
13
  * user, with this program's own environment plus the request's, so commands see the real `HOME`,
@@ -161,6 +164,23 @@ export class HostExecutor {
161
164
  async stat(path) {
162
165
  return this.files.stat(path);
163
166
  }
167
+ /**
168
+ * Lists a directory with the owner's rights: auto mode only. This executor has no sandbox, so a
169
+ * request decided as sandbox mode is refused here rather than read unsandboxed.
170
+ */
171
+ async list(mode, path, limit) {
172
+ this.files.lexical(path);
173
+ if (mode !== "auto")
174
+ throw policyError(UNSANDBOXED_READ);
175
+ return listDirectory(path, limit);
176
+ }
177
+ /** Scans with the owner's rights: auto mode only ({@link list}). */
178
+ async scan(mode, base, signal) {
179
+ this.files.lexical(base);
180
+ if (mode !== "auto")
181
+ throw policyError(UNSANDBOXED_READ);
182
+ return scanDirectory(base, { signal });
183
+ }
164
184
  async killTagged(tags) {
165
185
  this.groups.killTags(tags);
166
186
  const values = new Set(tags.map((t) => this.markerOf(t)));
@@ -0,0 +1,35 @@
1
+ import { type DeviceListResult, type DeviceProjectCandidate, type DeviceScanResult } from "@capybara-hq/plugin-sdk";
2
+ /**
3
+ * `list` and `scan` with this process's rights (auto mode, the owner's machine). Sandbox mode reads
4
+ * through the sandboxed helper (`fs-helper.ts`) and a container device in its container
5
+ * (`docker.ts`'s `LIST_SCRIPT`): each follows the same rules, so every reader answers the same.
6
+ */
7
+ /** `a` before `b` in UTF-16 code-unit order (locale-independent). */
8
+ export declare function byCodeUnit(a: string, b: string): number;
9
+ /**
10
+ * One directory's entries (`SandboxProvider.list`): sorted by code unit, at most `limit`,
11
+ * `truncated` when there are more; `isDir` follows symbolic links. Null when the path does not
12
+ * exist; a file or an unreadable directory throws an error.
13
+ */
14
+ export declare function listDirectory(path: string, limit: number): Promise<DeviceListResult>;
15
+ /** Whether a scan enters a directory named `name` found at `depth` (0: right under the base). */
16
+ export declare function enterable(name: string, depth: number): boolean;
17
+ /**
18
+ * Directories that look like projects under `base` (`SandboxProvider.scan`'s traversal): `base`
19
+ * and the directories at most `MAX_DEVICE_SCAN_DEPTH` levels below it holding a `.git` entry or an
20
+ * `AGENTS.md` file. Symbolic links are never followed below `base`; hidden directories and the
21
+ * SDK's `DEVICE_SCAN_SKIPPED_DIRS` / `DEVICE_SCAN_SKIPPED_BASE_DIRS` are not entered. Directories
22
+ * are visited breadth-first, each level in code-unit order of path, at most `MAX_DEVICE_SCAN_DIRS` visits with
23
+ * `base` the first; a subdirectory that cannot be read is skipped (it counts as visited). Reads are
24
+ * async and `signal` is checked before each visit. A missing base answers `[]`; a file or an
25
+ * unreadable one throws.
26
+ */
27
+ export declare function scanDirectory(base: string, opts?: {
28
+ signal?: AbortSignal;
29
+ }): Promise<DeviceScanResult>;
30
+ /**
31
+ * The answer of a scan: candidates whose basename satisfies the project name rule and whose path
32
+ * the protocol accepts (others are skipped, never renamed), sorted by path in code-unit order, the
33
+ * first {@link MAX_DEVICE_SCAN_RESULTS}.
34
+ */
35
+ export declare function finishScan(found: readonly string[]): DeviceProjectCandidate[];
@@ -0,0 +1,157 @@
1
+ import { readdir, realpath, stat } from "node:fs/promises";
2
+ import { basename, join, resolve } from "node:path";
3
+ import { DEVICE_SCAN_SKIPPED_BASE_DIRS, DEVICE_SCAN_SKIPPED_DIRS, isDeviceProjectName, MAX_DEVICE_SCAN_DEPTH, MAX_DEVICE_SCAN_DIRS, MAX_DEVICE_SCAN_RESULTS, validateSandboxPathShape, } from "@capybara-hq/plugin-sdk";
4
+ import { isMissing } from "./shared.js";
5
+ import { DeviceOpError } from "./types.js";
6
+ /**
7
+ * `list` and `scan` with this process's rights (auto mode, the owner's machine). Sandbox mode reads
8
+ * through the sandboxed helper (`fs-helper.ts`) and a container device in its container
9
+ * (`docker.ts`'s `LIST_SCRIPT`): each follows the same rules, so every reader answers the same.
10
+ */
11
+ /** `a` before `b` in UTF-16 code-unit order (locale-independent). */
12
+ export function byCodeUnit(a, b) {
13
+ return a < b ? -1 : a > b ? 1 : 0;
14
+ }
15
+ /** ` (CODE)` of a file system error, never its message (which may name where a link resolves). */
16
+ function errnoSuffix(e) {
17
+ const code = e?.code;
18
+ return typeof code === "string" && /^[A-Z0-9_]+$/.test(code) ? ` (${code})` : "";
19
+ }
20
+ /** The real path of `path`, null when it does not exist; throws when it cannot be resolved. */
21
+ async function realOf(path) {
22
+ try {
23
+ return await realpath(resolve(path));
24
+ }
25
+ catch (e) {
26
+ if (isMissing(e))
27
+ return null;
28
+ throw new DeviceOpError("error", `${path} cannot be read${errnoSuffix(e)}`);
29
+ }
30
+ }
31
+ /** The entries of the real directory `real` (`path` names it in messages); throws when unreadable. */
32
+ async function entriesOf(real, path) {
33
+ let st;
34
+ try {
35
+ st = await stat(real);
36
+ }
37
+ catch (e) {
38
+ throw new DeviceOpError("error", `${path} cannot be read${errnoSuffix(e)}`);
39
+ }
40
+ if (!st.isDirectory())
41
+ throw new DeviceOpError("error", `${path} is not a directory`);
42
+ try {
43
+ return await readdir(real, { withFileTypes: true });
44
+ }
45
+ catch (e) {
46
+ throw new DeviceOpError("error", `${path} cannot be read${errnoSuffix(e)}`);
47
+ }
48
+ }
49
+ /**
50
+ * Whether the entry of the real directory `dir` is a directory, following a symbolic link (a
51
+ * dangling one is not): the link is resolved, then its real target is checked.
52
+ */
53
+ async function isDirEntry(dir, entry) {
54
+ if (entry.isDirectory())
55
+ return true;
56
+ if (!entry.isSymbolicLink())
57
+ return false;
58
+ try {
59
+ return (await stat(await realpath(join(dir, entry.name)))).isDirectory();
60
+ }
61
+ catch {
62
+ return false;
63
+ }
64
+ }
65
+ /**
66
+ * One directory's entries (`SandboxProvider.list`): sorted by code unit, at most `limit`,
67
+ * `truncated` when there are more; `isDir` follows symbolic links. Null when the path does not
68
+ * exist; a file or an unreadable directory throws an error.
69
+ */
70
+ export async function listDirectory(path, limit) {
71
+ const real = await realOf(path);
72
+ if (real === null)
73
+ return null;
74
+ const all = (await entriesOf(real, path)).sort((a, b) => byCodeUnit(a.name, b.name));
75
+ const entries = await Promise.all(all.slice(0, limit).map(async (e) => ({ name: e.name, isDir: await isDirEntry(real, e) })));
76
+ return { entries, truncated: all.length > limit };
77
+ }
78
+ /** Whether a scan enters a directory named `name` found at `depth` (0: right under the base). */
79
+ export function enterable(name, depth) {
80
+ if (name.startsWith("."))
81
+ return false;
82
+ if (DEVICE_SCAN_SKIPPED_DIRS.includes(name))
83
+ return false;
84
+ return !(depth === 0 && DEVICE_SCAN_SKIPPED_BASE_DIRS.includes(name));
85
+ }
86
+ /**
87
+ * Directories that look like projects under `base` (`SandboxProvider.scan`'s traversal): `base`
88
+ * and the directories at most `MAX_DEVICE_SCAN_DEPTH` levels below it holding a `.git` entry or an
89
+ * `AGENTS.md` file. Symbolic links are never followed below `base`; hidden directories and the
90
+ * SDK's `DEVICE_SCAN_SKIPPED_DIRS` / `DEVICE_SCAN_SKIPPED_BASE_DIRS` are not entered. Directories
91
+ * are visited breadth-first, each level in code-unit order of path, at most `MAX_DEVICE_SCAN_DIRS` visits with
92
+ * `base` the first; a subdirectory that cannot be read is skipped (it counts as visited). Reads are
93
+ * async and `signal` is checked before each visit. A missing base answers `[]`; a file or an
94
+ * unreadable one throws.
95
+ */
96
+ export async function scanDirectory(base, opts = {}) {
97
+ opts.signal?.throwIfAborted();
98
+ const report = resolve(base);
99
+ const real = await realOf(base);
100
+ if (real === null)
101
+ return [];
102
+ const first = await entriesOf(real, base);
103
+ const found = [];
104
+ let visits = 1;
105
+ /** Records a hit and returns the directories to visit below `node`, found at `depth`. */
106
+ const below = (node, entries, depth) => {
107
+ if (entries.some((e) => e.name === ".git" || (e.name === "AGENTS.md" && !e.isDirectory()))) {
108
+ found.push(node.report);
109
+ }
110
+ if (depth >= MAX_DEVICE_SCAN_DEPTH)
111
+ return [];
112
+ return entries
113
+ .filter((e) => e.isDirectory() && enterable(e.name, depth))
114
+ .map((e) => ({ dir: join(node.dir, e.name), report: join(node.report, e.name) }));
115
+ };
116
+ let level = below({ dir: real, report }, first, 0);
117
+ // breadth-first, each level in code-unit order of path, until the visit budget is spent
118
+ for (let depth = 1; level.length > 0; depth++) {
119
+ level.sort((a, b) => byCodeUnit(a.report, b.report));
120
+ const next = [];
121
+ for (const node of level) {
122
+ if (visits >= MAX_DEVICE_SCAN_DIRS)
123
+ return finishScan(found);
124
+ opts.signal?.throwIfAborted();
125
+ visits += 1;
126
+ let entries;
127
+ try {
128
+ entries = await readdir(node.dir, { withFileTypes: true });
129
+ }
130
+ catch {
131
+ continue;
132
+ }
133
+ next.push(...below(node, entries, depth));
134
+ }
135
+ level = next;
136
+ }
137
+ return finishScan(found);
138
+ }
139
+ /**
140
+ * The answer of a scan: candidates whose basename satisfies the project name rule and whose path
141
+ * the protocol accepts (others are skipped, never renamed), sorted by path in code-unit order, the
142
+ * first {@link MAX_DEVICE_SCAN_RESULTS}.
143
+ */
144
+ export function finishScan(found) {
145
+ const out = [];
146
+ const seen = new Set();
147
+ for (const path of found) {
148
+ const name = basename(path);
149
+ if (seen.has(path) || !isDeviceProjectName(name))
150
+ continue;
151
+ if (validateSandboxPathShape(path).length > 0)
152
+ continue;
153
+ seen.add(path);
154
+ out.push({ path, suggestedName: name });
155
+ }
156
+ return out.sort((a, b) => byCodeUnit(a.path, b.path)).slice(0, MAX_DEVICE_SCAN_RESULTS);
157
+ }
package/dist/exec/os.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type SandboxAskCallback, type SandboxRuntimeConfig } from "@anthropic-ai/sandbox-runtime";
2
- import { type DeviceExecArgs, type ExecResult, type SandboxRoots } from "@capybara-hq/plugin-sdk";
3
- import type { Policy } from "../state.js";
2
+ import { type DeviceExecArgs, type DeviceListResult, type DeviceScanResult, type ExecResult, type SandboxRoots } from "@capybara-hq/plugin-sdk";
3
+ import type { Policy, SandboxMode } from "../state.js";
4
4
  import { type ReaperDeps } from "./reap.js";
5
5
  import { type Executor } from "./types.js";
6
6
  export { osRoots, ROOT_MARKER, utf8Prefix } from "./shared.js";
@@ -124,6 +124,18 @@ export declare class OsExecutor implements Executor {
124
124
  size: number;
125
125
  isDir: boolean;
126
126
  } | null>;
127
+ /**
128
+ * The workspace path `path` names, refused unless it lies lexically under the workspace: sandbox
129
+ * mode offers the workspace only (spec §4.2), not the tmp or skills roots.
130
+ */
131
+ private workspacePath;
132
+ /**
133
+ * Lists a workspace directory in the sandboxed helper (sandbox mode whatever `_mode` says: this
134
+ * executor has no other). A path outside the workspace is refused, also after resolving links.
135
+ */
136
+ list(_mode: SandboxMode, path: string, limit: number, signal?: AbortSignal): Promise<DeviceListResult>;
137
+ /** Scans a workspace directory in the sandboxed helper ({@link list}'s rules). */
138
+ scan(_mode: SandboxMode, base: string, signal?: AbortSignal): Promise<DeviceScanResult>;
127
139
  killTagged(tags: string[]): Promise<void>;
128
140
  killAll(): Promise<void>;
129
141
  /** Kills every process carrying this device's marker (also a previous run's). */
package/dist/exec/os.js CHANGED
@@ -2,12 +2,13 @@ import { spawn } from "node:child_process";
2
2
  import { createHash, randomBytes } from "node:crypto";
3
3
  import { existsSync, realpathSync } from "node:fs";
4
4
  import { homedir, constants as osConstants } from "node:os";
5
- import { resolve } from "node:path";
5
+ import { isAbsolute, resolve } from "node:path";
6
6
  import { SandboxManager, } from "@anthropic-ai/sandbox-runtime";
7
7
  import { isBackgroundLaunch, } from "@capybara-hq/plugin-sdk";
8
8
  import { blockedHosts, denyReason, networkTrailer } from "../network.js";
9
9
  import { effectiveEgress, grantedHosts, srtConfig } from "../policy.js";
10
10
  import { FS_HELPER_SCRIPT } from "./fs-helper.js";
11
+ import { finishScan } from "./listing.js";
11
12
  import { EXEC_MARKER, killMarked } from "./procs.js";
12
13
  import { Reaper } from "./reap.js";
13
14
  import { sandboxUnavailableMessage } from "./sandbox-messages.js";
@@ -415,18 +416,10 @@ export class OsExecutor {
415
416
  });
416
417
  }
417
418
  /** Runs one file operation in the sandboxed helper; returns its `r`, throws its `e`. */
418
- async helper(op, path, maxBytes, data) {
419
- const script = [
420
- process.execPath,
421
- "-e",
422
- FS_HELPER_SCRIPT,
423
- "sandbox",
424
- op,
425
- path,
426
- String(maxBytes),
427
- this.roots.workspace,
428
- this.roots.tmp,
429
- ]
419
+ async helper(op, path, maxBytes, data, roots = [this.roots.workspace, this.roots.tmp], signal) {
420
+ signal?.throwIfAborted();
421
+ const script = [process.execPath, "-e", FS_HELPER_SCRIPT, "sandbox", op, path, String(maxBytes)]
422
+ .concat(roots)
430
423
  .map(shellQuote)
431
424
  .join(" ");
432
425
  const { child, commandId } = await this.spawnSandboxed(script, {
@@ -449,6 +442,15 @@ export class OsExecutor {
449
442
  if (child.pid !== undefined)
450
443
  killGroupId(child.pid);
451
444
  }, HELPER_TIMEOUT_MS);
445
+ // the kernel cancelled: the helper's whole process group goes at once
446
+ const onAbort = () => {
447
+ if (child.pid !== undefined)
448
+ killGroupId(child.pid);
449
+ };
450
+ signal?.addEventListener("abort", onAbort, { once: true });
451
+ // a listener added to an already-aborted signal never fires: an abort during the spawn lands here
452
+ if (signal?.aborted)
453
+ onAbort();
452
454
  try {
453
455
  await new Promise((res, rej) => {
454
456
  child.once("error", rej);
@@ -457,11 +459,13 @@ export class OsExecutor {
457
459
  }
458
460
  finally {
459
461
  clearTimeout(timer);
462
+ signal?.removeEventListener("abort", onAbort);
460
463
  if (child.pid !== undefined)
461
464
  killGroupId(child.pid);
462
465
  SandboxManager.unregisterCommandNetworkLists(commandId);
463
466
  SandboxManager.cleanupAfterCommand();
464
467
  }
468
+ signal?.throwIfAborted();
465
469
  if (timedOut)
466
470
  throw new DeviceOpError("error", `${op} ${path} timed out`);
467
471
  const text = Buffer.concat(chunks).toString("utf8");
@@ -500,6 +504,48 @@ export class OsExecutor {
500
504
  }
501
505
  return (await this.helper("stat", p, 0));
502
506
  }
507
+ /**
508
+ * The workspace path `path` names, refused unless it lies lexically under the workspace: sandbox
509
+ * mode offers the workspace only (spec §4.2), not the tmp or skills roots.
510
+ */
511
+ workspacePath(path) {
512
+ if (!isAbsolute(path))
513
+ throw policyError(`${path} is not an absolute path`);
514
+ const p = resolve(path);
515
+ if (!isUnder(p, this.roots.workspace)) {
516
+ throw policyError(`${path} is outside the device's workspace; in sandbox mode the device reads only that`);
517
+ }
518
+ return p;
519
+ }
520
+ /**
521
+ * Lists a workspace directory in the sandboxed helper (sandbox mode whatever `_mode` says: this
522
+ * executor has no other). A path outside the workspace is refused, also after resolving links.
523
+ */
524
+ async list(_mode, path, limit, signal) {
525
+ this.requireSandbox();
526
+ const p = this.workspacePath(path);
527
+ // the device directory is gone: nothing under the workspace exists (and no helper can start
528
+ // there, its working directory being the workspace)
529
+ if (!existsSync(this.roots.workspace))
530
+ return null;
531
+ const r = await this.helper("list", p, limit, undefined, [this.roots.workspace], signal);
532
+ if (r !== null && !Array.isArray(r.entries)) {
533
+ throw new DeviceOpError("error", `list ${path} answered an invalid result`);
534
+ }
535
+ return r;
536
+ }
537
+ /** Scans a workspace directory in the sandboxed helper ({@link list}'s rules). */
538
+ async scan(_mode, base, signal) {
539
+ this.requireSandbox();
540
+ const p = this.workspacePath(base);
541
+ if (!existsSync(this.roots.workspace))
542
+ return [];
543
+ const r = await this.helper("scan", p, 0, undefined, [this.roots.workspace], signal);
544
+ if (!Array.isArray(r) || !r.every((x) => typeof x === "string")) {
545
+ throw new DeviceOpError("error", `scan ${base} answered an invalid result`);
546
+ }
547
+ return finishScan(r);
548
+ }
503
549
  async killTagged(tags) {
504
550
  const want = new Set(tags);
505
551
  for (const g of [...this.groups])
@@ -1,5 +1,5 @@
1
1
  import type { DeviceExecArgs, ExecResult, SandboxLimits, SandboxRoots } from "@capybara-hq/plugin-sdk";
2
- import type { Policy } from "../state.js";
2
+ import type { Policy, SandboxMode } from "../state.js";
3
3
  import { type ExecMode, type Executor } from "./types.js";
4
4
  export type { ExecMode } from "./types.js";
5
5
  /**
@@ -90,6 +90,15 @@ export declare class SwitchingExecutor implements Executor {
90
90
  size: number;
91
91
  isDir: boolean;
92
92
  } | null>;
93
+ /**
94
+ * The executor that reads as a device in `mode` (the request's own effective mode), without the
95
+ * file-operation window: the host with the owner's rights in auto mode, else the sandboxed
96
+ * helper. The policy is reread and wins: a sandbox turned on on the machine reads through the
97
+ * sandboxed helper whatever `mode` says.
98
+ */
99
+ private readerFor;
100
+ list(mode: SandboxMode, path: string, limit: number, signal: AbortSignal): Promise<import("@capybara-hq/plugin-sdk").DeviceListResult>;
101
+ scan(mode: SandboxMode, base: string, signal: AbortSignal): Promise<import("@capybara-hq/plugin-sdk").DeviceScanResult>;
93
102
  killTagged(tags: string[]): Promise<void>;
94
103
  killAll(): Promise<void>;
95
104
  ensureRoot(): Promise<"ok" | "gone">;
@@ -157,6 +157,30 @@ export class SwitchingExecutor {
157
157
  async stat(path) {
158
158
  return (await this.files()).stat(path);
159
159
  }
160
+ /**
161
+ * The executor that reads as a device in `mode` (the request's own effective mode), without the
162
+ * file-operation window: the host with the owner's rights in auto mode, else the sandboxed
163
+ * helper. The policy is reread and wins: a sandbox turned on on the machine reads through the
164
+ * sandboxed helper whatever `mode` says.
165
+ */
166
+ async readerFor(mode) {
167
+ const policy = this.policy();
168
+ await this.sync(policy);
169
+ const auto = mode === "auto" && policy.mode === "auto";
170
+ return auto ? { ex: this.host, mode: "auto" } : { ex: this.sandboxed, mode: "sandbox" };
171
+ }
172
+ async list(mode, path, limit, signal) {
173
+ const r = await this.readerFor(mode);
174
+ if (r.ex.list === undefined)
175
+ throw new DeviceOpError("error", "unsupported operation");
176
+ return r.ex.list(r.mode, path, limit, signal);
177
+ }
178
+ async scan(mode, base, signal) {
179
+ const r = await this.readerFor(mode);
180
+ if (r.ex.scan === undefined)
181
+ throw new DeviceOpError("error", "unsupported operation");
182
+ return r.ex.scan(r.mode, base, signal);
183
+ }
160
184
  async killTagged(tags) {
161
185
  await Promise.all([this.sandboxed.killTagged(tags), this.host.killTagged(tags)]);
162
186
  }
@@ -1,4 +1,4 @@
1
- import type { DeviceErrorKind, DeviceExecArgs, ExecResult, SandboxRoots } from "@capybara-hq/plugin-sdk";
1
+ import type { DeviceErrorKind, DeviceExecArgs, DeviceListResult, DeviceScanResult, ExecResult, SandboxRoots } from "@capybara-hq/plugin-sdk";
2
2
  import type { Policy, SandboxMode } from "../state.js";
3
3
  /** How one command runs: in auto mode (no OS sandbox) or in the sandbox. */
4
4
  export interface ExecMode {
@@ -33,6 +33,18 @@ export interface Executor {
33
33
  size: number;
34
34
  isDir: boolean;
35
35
  } | null>;
36
+ /**
37
+ * Lists one directory as a device in `mode` reads (`SandboxProvider.list`'s semantics): `mode`
38
+ * is the request's own, `effectiveMode(policy, limits)` on the ceiling that came with it, never
39
+ * the latest command's decision. Auto mode reads with the owner's rights; sandbox mode through
40
+ * the sandboxed helper, the workspace only; a container device its workspace only, in either
41
+ * mode. A path the mode cannot reach throws a `policy` refusal. Works without the device
42
+ * directory (it is not called through `ensureRoot`). Optional: without it (and {@link scan})
43
+ * the device answers `list` and `scan` as unsupported.
44
+ */
45
+ list?(mode: SandboxMode, path: string, limit: number, signal: AbortSignal): Promise<DeviceListResult>;
46
+ /** Looks for projects under `base` as a device in `mode` reads ({@link list}'s rules). */
47
+ scan?(mode: SandboxMode, base: string, signal: AbortSignal): Promise<DeviceScanResult>;
36
48
  killTagged(tags: string[]): Promise<void>;
37
49
  killAll(): Promise<void>;
38
50
  /**
@@ -40,7 +40,7 @@ export declare function summaryFacts(executor: Executor, ctx: OpContext): Summar
40
40
  /**
41
41
  * Runs one request and returns the answer plus its local audit line and, for an exec, its mode
42
42
  * (for the local command log). A vanished device directory answers `fs_gone` for every operation
43
- * except `stop`, `policy` and `policyStatus`. Never throws.
43
+ * except `stop`, `policy`, `policyStatus`, `list` and `scan`. Never throws.
44
44
  */
45
45
  export declare function serveOp(executor: Executor, req: KernelReq, signal: AbortSignal, ctx?: OpContext): Promise<{
46
46
  res: DeviceRes;
@@ -1,4 +1,4 @@
1
- import { isPolicyOpId, validateAllowHost, } from "@capybara-hq/plugin-sdk";
1
+ import { isPolicyOpId, MAX_DEVICE_LIST_ENTRIES, validateAllowHost, validateSandboxPathShape, } from "@capybara-hq/plugin-sdk";
2
2
  import { DeviceOpError } from "./exec/types.js";
3
3
  import { effectiveMode, grantedHosts } from "./policy.js";
4
4
  import { publicSuffixWildcard } from "./public-suffix.js";
@@ -192,6 +192,22 @@ function servePolicyOp(req, store, facts) {
192
192
  throw e;
193
193
  }
194
194
  }
195
+ /**
196
+ * Whether `op` is answered from the local policy file: it lives in the state directory, so these
197
+ * work while the device directory is gone, like the `policy` ops.
198
+ */
199
+ function isLocalPolicyOp(op) {
200
+ return op === "policy" || op === "policyStatus";
201
+ }
202
+ /** The answer to an operation this program does not serve (no policy store, or no reader). */
203
+ function unsupported(req) {
204
+ return {
205
+ type: "res",
206
+ id: req.id,
207
+ ok: false,
208
+ error: { kind: "error", message: "unsupported operation" },
209
+ };
210
+ }
195
211
  /** What the log says of an op id, with the summary now. Read-only. */
196
212
  function policyStatus(store, args, facts) {
197
213
  const opId = args?.opId;
@@ -205,6 +221,52 @@ function policyStatus(store, args, facts) {
205
221
  ...(known?.outcome === "refused" && known.message !== undefined && { message: known.message }),
206
222
  };
207
223
  }
224
+ /** A `list` / `scan` field that must be a clean absolute path, checked again here. */
225
+ function requestPath(v, key) {
226
+ const errors = typeof v === "string" ? validateSandboxPathShape(v) : ["path must be a string"];
227
+ if (errors.length > 0) {
228
+ throw new DeviceOpError("error", `invalid request: field "${key}": ${errors.join("; ")}`);
229
+ }
230
+ return v;
231
+ }
232
+ /** A `list` / `scan` request's ceiling (`limits.mode`), checked again here. */
233
+ function requestCeiling(args) {
234
+ const mode = args?.limits?.mode;
235
+ if (mode !== "auto" && mode !== "sandbox") {
236
+ throw new DeviceOpError("error", 'invalid request: field "limits.mode" must be "auto" or "sandbox"');
237
+ }
238
+ return { mode };
239
+ }
240
+ /**
241
+ * A `list` or `scan` request (a trust boundary: the device decides what a web session sees of its
242
+ * machine). Each is read in the mode it would run in now, `effectiveMode` of the owner's policy and
243
+ * the ceiling the request carries, never one an earlier command saw nor the file operations'
244
+ * window. Answered without the device directory: it reads the owner's machine, not that
245
+ * directory. Throws like the executor (a path its mode cannot reach is a `policy` refusal).
246
+ */
247
+ async function serveRead(executor, req, signal, store) {
248
+ const args = req.args;
249
+ const limits = requestCeiling(args);
250
+ if (req.op === "list") {
251
+ const path = requestPath(args?.path, "path");
252
+ const limit = args?.limit;
253
+ if (typeof limit !== "number" ||
254
+ !Number.isInteger(limit) ||
255
+ limit < 1 ||
256
+ limit > MAX_DEVICE_LIST_ENTRIES) {
257
+ throw new DeviceOpError("error", `invalid request: field "limit" must be an integer from 1 to ${MAX_DEVICE_LIST_ENTRIES}`);
258
+ }
259
+ const mode = effectiveMode(store.current(), limits);
260
+ signal.throwIfAborted();
261
+ const result = await executor.list(mode, path, limit, signal);
262
+ return { result, detail: `list ${clean(path, 300)} in ${mode} mode` };
263
+ }
264
+ const base = requestPath(args?.base, "base");
265
+ const mode = effectiveMode(store.current(), limits);
266
+ signal.throwIfAborted();
267
+ const result = await executor.scan(mode, base, signal);
268
+ return { result, detail: `scan ${clean(base, 300)} in ${mode} mode` };
269
+ }
208
270
  /** The audit line of an exec whose grants applied (sandbox mode only: auto mode ignores grants). */
209
271
  function grantsDetail(executor, args, policy) {
210
272
  if (executor.mode !== "os" || args.grants === undefined || policy === undefined) {
@@ -221,7 +283,7 @@ function grantsDetail(executor, args, policy) {
221
283
  /**
222
284
  * Runs one request and returns the answer plus its local audit line and, for an exec, its mode
223
285
  * (for the local command log). A vanished device directory answers `fs_gone` for every operation
224
- * except `stop`, `policy` and `policyStatus`. Never throws.
286
+ * except `stop`, `policy`, `policyStatus`, `list` and `scan`. Never throws.
225
287
  */
226
288
  export async function serveOp(executor, req, signal, ctx = {}) {
227
289
  const ok = (result) => ({ type: "res", id: req.id, ok: true, result });
@@ -229,22 +291,31 @@ export async function serveOp(executor, req, signal, ctx = {}) {
229
291
  if (req.op === "stop")
230
292
  return { res: ok(null) };
231
293
  // The policy lives in the state directory, not the device directory.
232
- if (req.op === "policy" || req.op === "policyStatus") {
233
- if (ctx.policy === undefined) {
234
- return {
235
- res: {
236
- type: "res",
237
- id: req.id,
238
- ok: false,
239
- error: { kind: "error", message: "unsupported operation" },
240
- },
241
- };
242
- }
294
+ if (isLocalPolicyOp(req.op)) {
295
+ if (ctx.policy === undefined)
296
+ return { res: unsupported(req) };
243
297
  const facts = summaryFacts(executor, ctx);
244
298
  if (req.op === "policyStatus")
245
299
  return { res: ok(policyStatus(ctx.policy, req.args, facts)) };
246
300
  return servePolicyOp(req, ctx.policy, facts);
247
301
  }
302
+ // They read the owner's machine in the request's own mode, not the device directory, so they
303
+ // work while that directory is gone. Served only with a policy store (the mode needs the
304
+ // owner's choice) and by an executor that can read in a given mode.
305
+ if (req.op === "list" || req.op === "scan") {
306
+ const can = req.op === "list" ? executor.list : executor.scan;
307
+ if (ctx.policy === undefined || can === undefined)
308
+ return { res: unsupported(req) };
309
+ try {
310
+ const { result, detail } = await serveRead(executor, req, signal, ctx.policy);
311
+ return { res: ok(result), detail };
312
+ }
313
+ catch (e) {
314
+ const { res } = errorAnswer(req, e);
315
+ const message = res.ok ? "" : clean(res.error.message, 300);
316
+ return { res, detail: `${req.op} refused: ${message}` };
317
+ }
318
+ }
248
319
  if ((await executor.ensureRoot()) === "gone") {
249
320
  return {
250
321
  res: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/device",
3
- "version": "0.1.0-rc.11",
3
+ "version": "0.1.0-rc.12",
4
4
  "description": "capybara-device: connects a laptop or server to a Capybara deployment as a device",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -34,7 +34,7 @@
34
34
  "dependencies": {
35
35
  "@anthropic-ai/sandbox-runtime": "0.0.81",
36
36
  "ws": "^8.18.0",
37
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.22"
37
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.24"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@types/ws": "^8.5.13"