@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.
@@ -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,12 +1,12 @@
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
  /**
6
- * How long the latest command's limits decide file operations. The kernel judges the mode at each
7
- * exec, and file operations carry no limits, so a decision older than this no longer counts: file
8
- * operations fall back to the sandboxed helper (the safe default for an organization whose ceiling
9
- * is sandbox), until the next command decides again. A minute covers a turn's file operations
6
+ * How long the latest command's limits decide file writes. The kernel judges the mode at each
7
+ * exec, and file writes carry no limits, so a decision older than this no longer counts: file
8
+ * writes fall back to the sandboxed helper (the safe default for an organization whose ceiling
9
+ * is sandbox), until the next command decides again. A minute covers a turn's file writes
10
10
  * around its commands while bounding how long an organization's change takes to reach a device
11
11
  * that runs no more commands.
12
12
  */
@@ -14,17 +14,17 @@ export declare const FILE_OPS_DECISION_TTL_MS = 60000;
14
14
  /** The refusal of an auto-mode command whose sandbox was turned back on before it started. */
15
15
  export declare const SANDBOX_BACK_ON: string;
16
16
  /**
17
- * The refusal of a file operation on a machine without the OS sandbox when no recent command
18
- * decided the mode: file operations never pass command review, so they cannot exceed a ceiling
17
+ * The refusal of a file write on a machine without the OS sandbox when no recent command
18
+ * decided the mode: file writes never pass command review, so they cannot exceed a ceiling
19
19
  * the deployment has not confirmed.
20
20
  */
21
21
  export declare const NO_FRESH_DECISION: string;
22
22
  /**
23
23
  * The OS-mode executor the program serves: each command runs in the sandbox or, in auto mode,
24
24
  * directly on the machine ({@link effectiveMode}). The policy is read per operation, so a change
25
- * applies at the next command. File operations use the host executor's direct IO (any absolute
25
+ * applies at the next command. File writes use the host executor's direct IO (any absolute
26
26
  * path in auto mode, the roots in the sandbox) only while the latest command's decision is fresh;
27
- * before any command, or once its limits are stale, the sandboxed helper runs (file operations
27
+ * before any command, or once its limits are stale, the sandboxed helper runs (file writes
28
28
  * never pass command review, so the org's ceiling may not be exceeded). When the policy turns the
29
29
  * sandbox back on, every auto-mode command still running (and what it left in the background) is
30
30
  * killed, and one still starting is refused right before its spawn; while auto mode is on, the
@@ -47,7 +47,7 @@ export declare class SwitchingExecutor implements Executor {
47
47
  */
48
48
  private readonly sandboxReady;
49
49
  private watch;
50
- /** The latest command's limits and when they came (file operations follow their decision). */
50
+ /** The latest command's limits and when they came (file writes follow their decision). */
51
51
  private lastLimits;
52
52
  private lastLimitsAt;
53
53
  constructor(sandboxed: Executor,
@@ -59,12 +59,12 @@ export declare class SwitchingExecutor implements Executor {
59
59
  */
60
60
  sync(policy?: Policy): Promise<boolean>;
61
61
  /**
62
- * Records an exec's limits, refused ones included, so file operations follow the latest
62
+ * Records an exec's limits, refused ones included, so file writes follow the latest
63
63
  * decision (see {@link FILE_OPS_DECISION_TTL_MS}).
64
64
  */
65
65
  noteLimits(limits: Pick<SandboxLimits, "mode">): void;
66
66
  /**
67
- * The executor for file operations now. File operations carry no limits and never pass command
67
+ * The executor for file writes now. File writes carry no limits and never pass command
68
68
  * review, so they only follow an exec's decision when it is fresh: the sandboxed helper before
69
69
  * any exec and once those limits are stale (the safe default for an organization whose ceiling
70
70
  * is sandbox), else `effectiveMode(policy, limits)`. On a machine without the OS sandbox there is
@@ -72,7 +72,7 @@ export declare class SwitchingExecutor implements Executor {
72
72
  * run on the host; a fresh auto decision runs them on the host, a sandbox one is refused by the
73
73
  * sandboxed executor with the reason.
74
74
  */
75
- private files;
75
+ private writeFiles;
76
76
  exec(args: DeviceExecArgs, signal: AbortSignal): Promise<ExecResult>;
77
77
  /**
78
78
  * Runs one command as `how` decided (the caller logs the same decision). The policy it was
@@ -81,15 +81,24 @@ export declare class SwitchingExecutor implements Executor {
81
81
  * sandbox came back on while it was starting is refused ({@link SANDBOX_BACK_ON}).
82
82
  */
83
83
  execDecided(args: DeviceExecArgs, signal: AbortSignal, how: ExecMode, policy?: Policy): Promise<ExecResult>;
84
- readFile(path: string, maxBytes: number): Promise<{
84
+ readFile(path: string, maxBytes: number, mode?: SandboxMode): Promise<{
85
85
  data: Uint8Array;
86
86
  truncated: boolean;
87
87
  } | null>;
88
88
  writeFile(path: string, data: Uint8Array): Promise<void>;
89
- stat(path: string): Promise<{
89
+ stat(path: string, mode?: SandboxMode): Promise<{
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">;
@@ -1,10 +1,10 @@
1
1
  import { effectiveMode } from "../policy.js";
2
2
  import { DeviceOpError } from "./types.js";
3
3
  /**
4
- * How long the latest command's limits decide file operations. The kernel judges the mode at each
5
- * exec, and file operations carry no limits, so a decision older than this no longer counts: file
6
- * operations fall back to the sandboxed helper (the safe default for an organization whose ceiling
7
- * is sandbox), until the next command decides again. A minute covers a turn's file operations
4
+ * How long the latest command's limits decide file writes. The kernel judges the mode at each
5
+ * exec, and file writes carry no limits, so a decision older than this no longer counts: file
6
+ * writes fall back to the sandboxed helper (the safe default for an organization whose ceiling
7
+ * is sandbox), until the next command decides again. A minute covers a turn's file writes
8
8
  * around its commands while bounding how long an organization's change takes to reach a device
9
9
  * that runs no more commands.
10
10
  */
@@ -15,19 +15,19 @@ const WATCH_INTERVAL_MS = 1000;
15
15
  export const SANDBOX_BACK_ON = "The sandbox was turned back on on this machine while the command was starting, so it did " +
16
16
  "not run. Run it again: it runs in the sandbox now.";
17
17
  /**
18
- * The refusal of a file operation on a machine without the OS sandbox when no recent command
19
- * decided the mode: file operations never pass command review, so they cannot exceed a ceiling
18
+ * The refusal of a file write on a machine without the OS sandbox when no recent command
19
+ * decided the mode: file writes never pass command review, so they cannot exceed a ceiling
20
20
  * the deployment has not confirmed.
21
21
  */
22
22
  export const NO_FRESH_DECISION = "The OS sandbox is unavailable on this machine and no recent command decided this device's " +
23
- "mode, so file operations are refused until the next command runs (the deployment decides the " +
23
+ "mode, so file writes are refused until the next command runs (the deployment decides the " +
24
24
  "mode at each command).";
25
25
  /**
26
26
  * The OS-mode executor the program serves: each command runs in the sandbox or, in auto mode,
27
27
  * directly on the machine ({@link effectiveMode}). The policy is read per operation, so a change
28
- * applies at the next command. File operations use the host executor's direct IO (any absolute
28
+ * applies at the next command. File writes use the host executor's direct IO (any absolute
29
29
  * path in auto mode, the roots in the sandbox) only while the latest command's decision is fresh;
30
- * before any command, or once its limits are stale, the sandboxed helper runs (file operations
30
+ * before any command, or once its limits are stale, the sandboxed helper runs (file writes
31
31
  * never pass command review, so the org's ceiling may not be exceeded). When the policy turns the
32
32
  * sandbox back on, every auto-mode command still running (and what it left in the background) is
33
33
  * killed, and one still starting is refused right before its spawn; while auto mode is on, the
@@ -49,7 +49,7 @@ export class SwitchingExecutor {
49
49
  */
50
50
  sandboxReady;
51
51
  watch;
52
- /** The latest command's limits and when they came (file operations follow their decision). */
52
+ /** The latest command's limits and when they came (file writes follow their decision). */
53
53
  lastLimits;
54
54
  lastLimitsAt = 0;
55
55
  constructor(sandboxed,
@@ -96,7 +96,7 @@ export class SwitchingExecutor {
96
96
  return auto;
97
97
  }
98
98
  /**
99
- * Records an exec's limits, refused ones included, so file operations follow the latest
99
+ * Records an exec's limits, refused ones included, so file writes follow the latest
100
100
  * decision (see {@link FILE_OPS_DECISION_TTL_MS}).
101
101
  */
102
102
  noteLimits(limits) {
@@ -104,7 +104,7 @@ export class SwitchingExecutor {
104
104
  this.lastLimitsAt = Date.now();
105
105
  }
106
106
  /**
107
- * The executor for file operations now. File operations carry no limits and never pass command
107
+ * The executor for file writes now. File writes carry no limits and never pass command
108
108
  * review, so they only follow an exec's decision when it is fresh: the sandboxed helper before
109
109
  * any exec and once those limits are stale (the safe default for an organization whose ceiling
110
110
  * is sandbox), else `effectiveMode(policy, limits)`. On a machine without the OS sandbox there is
@@ -112,7 +112,7 @@ export class SwitchingExecutor {
112
112
  * run on the host; a fresh auto decision runs them on the host, a sandbox one is refused by the
113
113
  * sandboxed executor with the reason.
114
114
  */
115
- async files() {
115
+ async writeFiles() {
116
116
  const policy = this.policy();
117
117
  await this.sync(policy);
118
118
  if (policy.mode === "sandbox")
@@ -148,14 +148,42 @@ export class SwitchingExecutor {
148
148
  };
149
149
  return this.host.exec(args, signal, { beforeSpawn });
150
150
  }
151
- async readFile(path, maxBytes) {
152
- return (await this.files()).readFile(path, maxBytes);
151
+ async readFile(path, maxBytes, mode = "sandbox") {
152
+ const r = await this.readerFor(mode);
153
+ return r.ex.readFile(path, maxBytes);
153
154
  }
154
155
  async writeFile(path, data) {
155
- return (await this.files()).writeFile(path, data);
156
+ return (await this.writeFiles()).writeFile(path, data);
156
157
  }
157
- async stat(path) {
158
- return (await this.files()).stat(path);
158
+ async stat(path, mode = "sandbox") {
159
+ const r = await this.readerFor(mode);
160
+ return r.ex.stat(path);
161
+ }
162
+ /**
163
+ * The executor that reads as a device in `mode` (the request's own effective mode), without the
164
+ * file-operation window: the host with the owner's rights in auto mode, else the sandboxed
165
+ * helper. The policy is reread and wins: a sandbox turned on on the machine reads through the
166
+ * sandboxed helper whatever `mode` says.
167
+ */
168
+ async readerFor(mode) {
169
+ const policy = this.policy();
170
+ await this.sync(policy);
171
+ const auto = mode === "auto" && policy.mode === "auto";
172
+ if (!auto && !this.sandboxReady)
173
+ throw new DeviceOpError("policy", "The OS sandbox is unavailable; this file request requires sandbox mode.");
174
+ return auto ? { ex: this.host, mode: "auto" } : { ex: this.sandboxed, mode: "sandbox" };
175
+ }
176
+ async list(mode, path, limit, signal) {
177
+ const r = await this.readerFor(mode);
178
+ if (r.ex.list === undefined)
179
+ throw new DeviceOpError("error", "unsupported operation");
180
+ return r.ex.list(r.mode, path, limit, signal);
181
+ }
182
+ async scan(mode, base, signal) {
183
+ const r = await this.readerFor(mode);
184
+ if (r.ex.scan === undefined)
185
+ throw new DeviceOpError("error", "unsupported operation");
186
+ return r.ex.scan(r.mode, base, signal);
159
187
  }
160
188
  async killTagged(tags) {
161
189
  await Promise.all([this.sandboxed.killTagged(tags), this.host.killTagged(tags)]);
@@ -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 {
@@ -22,17 +22,29 @@ export interface Executor {
22
22
  * the executor that runs commands without a sandbox; others may ignore them.
23
23
  */
24
24
  exec(args: DeviceExecArgs, signal: AbortSignal, hooks?: ExecHooks): Promise<ExecResult>;
25
- /** The file's bytes (at most `maxBytes`); null when it does not exist. */
26
- readFile(path: string, maxBytes: number): Promise<{
25
+ /** The file's bytes (at most `maxBytes`); null when it does not exist. The switching executor uses this request's mode, defaulting to sandbox. */
26
+ readFile(path: string, maxBytes: number, mode?: SandboxMode): Promise<{
27
27
  data: Uint8Array;
28
28
  truncated: boolean;
29
29
  } | null>;
30
30
  writeFile(path: string, data: Uint8Array): Promise<void>;
31
31
  /** null when the path does not exist. */
32
- stat(path: string): Promise<{
32
+ stat(path: string, mode?: SandboxMode): Promise<{
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
  /**
@@ -42,7 +54,7 @@ export interface Executor {
42
54
  ensureRoot(): Promise<"ok" | "gone">;
43
55
  /**
44
56
  * OS mode, an executor that can run without a sandbox: records an exec's limits, also of one
45
- * the policy sent to the sandbox, so file operations follow the latest decision.
57
+ * the policy sent to the sandbox, so file writes follow the latest decision.
46
58
  */
47
59
  noteLimits?(limits: DeviceExecArgs["limits"]): void;
48
60
  /**
@@ -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;