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

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[];