@buildanagent/harness 0.1.0-alpha.28 → 0.1.0-alpha.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +111 -5
  2. package/dist/context/file-spill.d.ts +11 -1
  3. package/dist/context/file-spill.js +23 -8
  4. package/dist/context/file-spill.js.map +1 -1
  5. package/dist/context/spill.d.ts +5 -1
  6. package/dist/context/spill.js +6 -2
  7. package/dist/context/spill.js.map +1 -1
  8. package/dist/credentials/allowlist.d.ts +22 -2
  9. package/dist/credentials/allowlist.js +74 -17
  10. package/dist/credentials/allowlist.js.map +1 -1
  11. package/dist/credentials/egress-policy.d.ts +69 -0
  12. package/dist/credentials/egress-policy.js +170 -0
  13. package/dist/credentials/egress-policy.js.map +1 -0
  14. package/dist/credentials/egress-proxy.d.ts +13 -1
  15. package/dist/credentials/egress-proxy.js +179 -11
  16. package/dist/credentials/egress-proxy.js.map +1 -1
  17. package/dist/credentials/git-route.d.ts +68 -0
  18. package/dist/credentials/git-route.js +288 -0
  19. package/dist/credentials/git-route.js.map +1 -0
  20. package/dist/credentials/index.d.ts +5 -1
  21. package/dist/credentials/index.js +5 -1
  22. package/dist/credentials/index.js.map +1 -1
  23. package/dist/credentials/scrub.d.ts +7 -0
  24. package/dist/credentials/scrub.js +22 -0
  25. package/dist/credentials/scrub.js.map +1 -1
  26. package/dist/errors.d.ts +9 -5
  27. package/dist/errors.js +8 -4
  28. package/dist/errors.js.map +1 -1
  29. package/dist/sandbox/base.d.ts +11 -1
  30. package/dist/sandbox/base.js +14 -0
  31. package/dist/sandbox/base.js.map +1 -1
  32. package/dist/sandbox/docker/index.d.ts +8 -2
  33. package/dist/sandbox/docker/index.js +63 -14
  34. package/dist/sandbox/docker/index.js.map +1 -1
  35. package/dist/sandbox/errors.d.ts +30 -2
  36. package/dist/sandbox/errors.js +36 -1
  37. package/dist/sandbox/errors.js.map +1 -1
  38. package/dist/sandbox/host-files.d.ts +2 -0
  39. package/dist/sandbox/host-files.js +10 -0
  40. package/dist/sandbox/host-files.js.map +1 -1
  41. package/dist/sandbox/index.d.ts +6 -4
  42. package/dist/sandbox/index.js +5 -3
  43. package/dist/sandbox/index.js.map +1 -1
  44. package/dist/sandbox/policy.d.ts +49 -0
  45. package/dist/sandbox/policy.js +149 -0
  46. package/dist/sandbox/policy.js.map +1 -0
  47. package/dist/sandbox/process.js +1 -1
  48. package/dist/sandbox/process.js.map +1 -1
  49. package/dist/sandbox/srt/index.d.ts +5 -2
  50. package/dist/sandbox/srt/index.js +27 -8
  51. package/dist/sandbox/srt/index.js.map +1 -1
  52. package/dist/sandbox/srt/settings.d.ts +17 -5
  53. package/dist/sandbox/srt/settings.js +53 -0
  54. package/dist/sandbox/srt/settings.js.map +1 -1
  55. package/dist/sandbox/types.d.ts +41 -4
  56. package/dist/sandbox/types.js.map +1 -1
  57. package/dist/testing/fake-sandbox.d.ts +21 -3
  58. package/dist/testing/fake-sandbox.js +157 -8
  59. package/dist/testing/fake-sandbox.js.map +1 -1
  60. package/dist/testing/sandbox-conformance.js +108 -1
  61. package/dist/testing/sandbox-conformance.js.map +1 -1
  62. package/dist/tools/builtins/bash.d.ts +9 -0
  63. package/dist/tools/builtins/bash.js +75 -0
  64. package/dist/tools/builtins/bash.js.map +1 -0
  65. package/dist/tools/builtins/builtins.d.ts +38 -0
  66. package/dist/tools/builtins/builtins.js +48 -0
  67. package/dist/tools/builtins/builtins.js.map +1 -0
  68. package/dist/tools/builtins/descriptions.d.ts +69 -0
  69. package/dist/tools/builtins/descriptions.js +94 -0
  70. package/dist/tools/builtins/descriptions.js.map +1 -0
  71. package/dist/tools/builtins/fetch.d.ts +12 -0
  72. package/dist/tools/builtins/fetch.js +157 -0
  73. package/dist/tools/builtins/fetch.js.map +1 -0
  74. package/dist/tools/builtins/files.d.ts +27 -0
  75. package/dist/tools/builtins/files.js +274 -0
  76. package/dist/tools/builtins/files.js.map +1 -0
  77. package/dist/tools/builtins/paths.d.ts +30 -0
  78. package/dist/tools/builtins/paths.js +62 -0
  79. package/dist/tools/builtins/paths.js.map +1 -0
  80. package/dist/tools/builtins/results.d.ts +15 -0
  81. package/dist/tools/builtins/results.js +31 -0
  82. package/dist/tools/builtins/results.js.map +1 -0
  83. package/dist/tools/builtins/search.d.ts +18 -0
  84. package/dist/tools/builtins/search.js +217 -0
  85. package/dist/tools/builtins/search.js.map +1 -0
  86. package/dist/tools/index.d.ts +6 -2
  87. package/dist/tools/index.js +5 -2
  88. package/dist/tools/index.js.map +1 -1
  89. package/llms.txt +34 -0
  90. package/package.json +5 -5
@@ -1,3 +1,9 @@
1
+ /**
2
+ * The `srt` settings file for a sandbox policy. It is a pure function of the policy, so a test can read the file a
3
+ * backend would write without starting `srt`. `srt` is a pre-1.0 beta whose settings format may change (as of
4
+ * November 2026), so this is the one place that knows the format.
5
+ */
6
+ import { SandboxPolicyMismatchError } from "../errors.js";
1
7
  const literal = (path) => ({ path, literal: true });
2
8
  /** Removes repeats, keeping the first of each. */
3
9
  const unique = (paths) => [...new Set(paths)];
@@ -28,4 +34,51 @@ export function srtSettings(input) {
28
34
  },
29
35
  };
30
36
  }
37
+ const isRecord = (value) => typeof value === "object" && value !== null;
38
+ /** The strings of a list, or a mismatch naming `field` when it is anything else. */
39
+ function strings(value, field) {
40
+ if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) {
41
+ throw new SandboxPolicyMismatchError(field);
42
+ }
43
+ return value;
44
+ }
45
+ /** The paths of a list of literal entries. An entry `srt` would read as a pattern is a mismatch naming `field`. */
46
+ function literalPaths(value, field) {
47
+ if (!Array.isArray(value))
48
+ throw new SandboxPolicyMismatchError(field);
49
+ return value.map((entry) => {
50
+ if (!isRecord(entry) || typeof entry.path !== "string" || entry.literal !== true) {
51
+ throw new SandboxPolicyMismatchError(field);
52
+ }
53
+ return entry.path;
54
+ });
55
+ }
56
+ /**
57
+ * The policy a settings file applies, in the spelling of the request. A write root maps back through `names.write`,
58
+ * and a readable folder through `names.read`. A folder the backend adds itself, and a write root, which is readable
59
+ * anyway, are left out, so any other folder in the file shows up as a read root the request didn't ask for. A file
60
+ * that doesn't deny every read first reads back as the read root `/`. A file that isn't in the shape `srtSettings()`
61
+ * writes throws `SandboxPolicyMismatchError`.
62
+ */
63
+ export function srtPolicyFromSettings(settings, names) {
64
+ const network = isRecord(settings) && isRecord(settings.network) ? settings.network : undefined;
65
+ const filesystem = isRecord(settings) && isRecord(settings.filesystem) ? settings.filesystem : undefined;
66
+ if (network === undefined || filesystem === undefined)
67
+ throw new SandboxPolicyMismatchError("settings");
68
+ const writeReal = literalPaths(filesystem.allowWrite, "writeRoots");
69
+ const denyRead = literalPaths(filesystem.denyRead, "readRoots");
70
+ const allowRead = literalPaths(filesystem.allowRead, "readRoots");
71
+ const implied = new Set([...writeReal, ...names.implicitReads]);
72
+ const readRoots = denyRead.length === 1 && denyRead[0] === "/"
73
+ ? allowRead.flatMap((path) => names.read.get(path) ?? (implied.has(path) ? [] : [path]))
74
+ : ["/"];
75
+ return {
76
+ readRoots,
77
+ writeRoots: writeReal.flatMap((path) => names.write.get(path) ?? [path]),
78
+ network: {
79
+ allow: strings(network.allowedDomains, "network.allow"),
80
+ deny: strings(network.deniedDomains, "network.deny"),
81
+ },
82
+ };
83
+ }
31
84
  //# sourceMappingURL=settings.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"settings.js","sourceRoot":"","sources":["../../../src/sandbox/srt/settings.ts"],"names":[],"mappings":"AAwCA,MAAM,OAAO,GAAG,CAAC,IAAY,EAAgB,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;AAE1E,kDAAkD;AAClD,MAAM,MAAM,GAAG,CAAC,KAAwB,EAAY,EAAE,CAAC,CAAC,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;AAE3E;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAC,KAAuB;IACjD,MAAM,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IACzB,MAAM,QAAQ,GAAG,MAAM,CAAC;QACtB,GAAG,MAAM,CAAC,SAAS;QACnB,GAAG,MAAM,CAAC,UAAU;QACpB,GAAG,KAAK,CAAC,eAAe;QACxB,GAAG,KAAK,CAAC,eAAe;KACzB,CAAC,CAAC;IACH,OAAO;QACL,OAAO,EAAE;YACP,cAAc,EAAE,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC;YACzC,aAAa,EAAE,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC;YACvC,GAAG,CAAC,KAAK,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,KAAK,CAAC,WAAW,EAAE,CAAC;SAC/E;QACD,UAAU,EAAE;YACV,QAAQ,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;YACxB,SAAS,EAAE,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC;YAChC,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC;YAClD,SAAS,EAAE,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC;SAChD;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The `srt` settings file for a sandbox policy. It is a pure function of the policy, so a test can read the file a\n * backend would write without starting `srt`. `srt` is a pre-1.0 beta whose settings format may change (as of\n * November 2026), so this is the one place that knows the format.\n */\nimport type { SandboxPolicy } from \"../types.js\";\n\n/** A path that `srt` must read as written. Without `literal`, `srt` reads a spelling such as `*.ts` as a pattern. */\nexport interface SrtPathEntry {\n readonly path: string;\n readonly literal: true;\n}\n\n/** The settings `srt` reads from its `--settings` file. */\nexport interface SrtSettings {\n readonly network: {\n readonly allowedDomains: readonly string[];\n readonly deniedDomains: readonly string[];\n readonly parentProxy?: { readonly http?: string; readonly https?: string };\n };\n readonly filesystem: {\n readonly denyRead: readonly SrtPathEntry[];\n readonly allowRead: readonly SrtPathEntry[];\n readonly allowWrite: readonly SrtPathEntry[];\n readonly denyWrite: readonly SrtPathEntry[];\n };\n}\n\n/** What the settings are built from, beyond the policy. Every path is absolute with its symlinks resolved. */\nexport interface SrtSettingsInput {\n readonly policy: SandboxPolicy;\n /** The system folders every program needs to start, which the policy does not list. */\n readonly systemReadRoots: readonly string[];\n /** The folders `srt` itself needs to read, such as its own helper and its private socket folder. */\n readonly helperReadRoots: readonly string[];\n /** Folders to keep read-only inside a write root, such as the session's own log folder. */\n readonly denyWrite: readonly string[];\n readonly parentProxy?: { readonly http?: string; readonly https?: string };\n}\n\nconst literal = (path: string): SrtPathEntry => ({ path, literal: true });\n\n/** Removes repeats, keeping the first of each. */\nconst unique = (paths: readonly string[]): string[] => [...new Set(paths)];\n\n/**\n * Denies every read and then allows the policy's read and write roots, the system folders and the helper folders back.\n * Writes are allowed only under the write roots, and `denyWrite` takes precedence over them. The network allows only the\n * policy's hosts. Each path is `literal`, so a folder named `*` is never read as a pattern.\n */\nexport function srtSettings(input: SrtSettingsInput): SrtSettings {\n const { policy } = input;\n const readable = unique([\n ...policy.readRoots,\n ...policy.writeRoots,\n ...input.systemReadRoots,\n ...input.helperReadRoots,\n ]);\n return {\n network: {\n allowedDomains: [...policy.network.allow],\n deniedDomains: [...policy.network.deny],\n ...(input.parentProxy === undefined ? {} : { parentProxy: input.parentProxy }),\n },\n filesystem: {\n denyRead: [literal(\"/\")],\n allowRead: readable.map(literal),\n allowWrite: unique(policy.writeRoots).map(literal),\n denyWrite: unique(input.denyWrite).map(literal),\n },\n };\n}\n"]}
1
+ {"version":3,"file":"settings.js","sourceRoot":"","sources":["../../../src/sandbox/srt/settings.ts"],"names":[],"mappings":"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","sourcesContent":["/**\n * The `srt` settings file for a sandbox policy. It is a pure function of the policy, so a test can read the file a\n * backend would write without starting `srt`. `srt` is a pre-1.0 beta whose settings format may change (as of\n * November 2026), so this is the one place that knows the format.\n */\nimport { SandboxPolicyMismatchError } from \"../errors.js\";\nimport type { SandboxPolicy } from \"../types.js\";\n\n/** A path that `srt` must read as written. Without `literal`, `srt` reads a spelling such as `*.ts` as a pattern. */\nexport interface SrtPathEntry {\n readonly path: string;\n readonly literal: true;\n}\n\n/** The settings `srt` reads from its `--settings` file. */\nexport interface SrtSettings {\n readonly network: {\n readonly allowedDomains: readonly string[];\n readonly deniedDomains: readonly string[];\n readonly parentProxy?: { readonly http?: string; readonly https?: string };\n };\n readonly filesystem: {\n readonly denyRead: readonly SrtPathEntry[];\n readonly allowRead: readonly SrtPathEntry[];\n readonly allowWrite: readonly SrtPathEntry[];\n readonly denyWrite: readonly SrtPathEntry[];\n };\n}\n\n/** What the settings are built from, beyond the policy. Every path is absolute with its symlinks resolved. */\nexport interface SrtSettingsInput {\n readonly policy: SandboxPolicy;\n /** The system folders every program needs to start, which the policy does not list. */\n readonly systemReadRoots: readonly string[];\n /** The folders `srt` itself needs to read, such as its own helper and its private socket folder. */\n readonly helperReadRoots: readonly string[];\n /** Folders to keep read-only inside a write root, such as the session's own log folder. */\n readonly denyWrite: readonly string[];\n readonly parentProxy?: { readonly http?: string; readonly https?: string };\n}\n\nconst literal = (path: string): SrtPathEntry => ({ path, literal: true });\n\n/** Removes repeats, keeping the first of each. */\nconst unique = (paths: readonly string[]): string[] => [...new Set(paths)];\n\n/**\n * Denies every read and then allows the policy's read and write roots, the system folders and the helper folders back.\n * Writes are allowed only under the write roots, and `denyWrite` takes precedence over them. The network allows only the\n * policy's hosts. Each path is `literal`, so a folder named `*` is never read as a pattern.\n */\nexport function srtSettings(input: SrtSettingsInput): SrtSettings {\n const { policy } = input;\n const readable = unique([\n ...policy.readRoots,\n ...policy.writeRoots,\n ...input.systemReadRoots,\n ...input.helperReadRoots,\n ]);\n return {\n network: {\n allowedDomains: [...policy.network.allow],\n deniedDomains: [...policy.network.deny],\n ...(input.parentProxy === undefined ? {} : { parentProxy: input.parentProxy }),\n },\n filesystem: {\n denyRead: [literal(\"/\")],\n allowRead: readable.map(literal),\n allowWrite: unique(policy.writeRoots).map(literal),\n denyWrite: unique(input.denyWrite).map(literal),\n },\n };\n}\n\n/** How a settings file's real paths map back to the spelling of the request, for `srtPolicyFromSettings()`. */\nexport interface SrtPolicyNames {\n /** For each real read root, the request's spellings that resolved to it. */\n readonly read: ReadonlyMap<string, readonly string[]>;\n /** For each real write root, the request's spellings that resolved to it. */\n readonly write: ReadonlyMap<string, readonly string[]>;\n /** The readable folders the backend adds itself: the system's, `srt`'s own and the caller's extra read roots. */\n readonly implicitReads: readonly string[];\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null;\n\n/** The strings of a list, or a mismatch naming `field` when it is anything else. */\nfunction strings(value: unknown, field: string): string[] {\n if (!Array.isArray(value) || !value.every((item) => typeof item === \"string\")) {\n throw new SandboxPolicyMismatchError(field);\n }\n return value;\n}\n\n/** The paths of a list of literal entries. An entry `srt` would read as a pattern is a mismatch naming `field`. */\nfunction literalPaths(value: unknown, field: string): string[] {\n if (!Array.isArray(value)) throw new SandboxPolicyMismatchError(field);\n return value.map((entry: unknown) => {\n if (!isRecord(entry) || typeof entry.path !== \"string\" || entry.literal !== true) {\n throw new SandboxPolicyMismatchError(field);\n }\n return entry.path;\n });\n}\n\n/**\n * The policy a settings file applies, in the spelling of the request. A write root maps back through `names.write`,\n * and a readable folder through `names.read`. A folder the backend adds itself, and a write root, which is readable\n * anyway, are left out, so any other folder in the file shows up as a read root the request didn't ask for. A file\n * that doesn't deny every read first reads back as the read root `/`. A file that isn't in the shape `srtSettings()`\n * writes throws `SandboxPolicyMismatchError`.\n */\nexport function srtPolicyFromSettings(settings: unknown, names: SrtPolicyNames): SandboxPolicy {\n const network = isRecord(settings) && isRecord(settings.network) ? settings.network : undefined;\n const filesystem = isRecord(settings) && isRecord(settings.filesystem) ? settings.filesystem : undefined;\n if (network === undefined || filesystem === undefined) throw new SandboxPolicyMismatchError(\"settings\");\n const writeReal = literalPaths(filesystem.allowWrite, \"writeRoots\");\n const denyRead = literalPaths(filesystem.denyRead, \"readRoots\");\n const allowRead = literalPaths(filesystem.allowRead, \"readRoots\");\n const implied = new Set([...writeReal, ...names.implicitReads]);\n const readRoots =\n denyRead.length === 1 && denyRead[0] === \"/\"\n ? allowRead.flatMap((path) => names.read.get(path) ?? (implied.has(path) ? [] : [path]))\n : [\"/\"];\n return {\n readRoots,\n writeRoots: writeReal.flatMap((path) => names.write.get(path) ?? [path]),\n network: {\n allow: strings(network.allowedDomains, \"network.allow\"),\n deny: strings(network.deniedDomains, \"network.deny\"),\n },\n };\n}\n"]}
@@ -24,7 +24,8 @@ export type SandboxTier = "none" | "os" | "container" | "gvisor" | "microvm";
24
24
  /**
25
25
  * What a backend claims to stop. `mistakes`: the agent's own errors, such as a write outside the workspace.
26
26
  * `exfiltration`: sending data to a host that is not allowed. `hostile_process`: a process that is trying to escape.
27
- * A backend lists a stop only when its tier and its setup deliver it, and no tier here claims `hostile_process` yet.
27
+ * A backend lists a stop only when its tier and its applied policy deliver it, which `stopsFor()` computes: only a
28
+ * `microvm` stops a `hostile_process`, and none of the backends in this package is one.
28
29
  */
29
30
  export type SandboxStop = "mistakes" | "exfiltration" | "hostile_process";
30
31
  /** The workspace a sandbox is provisioned for: its root directory and the files to put there first. */
@@ -43,14 +44,16 @@ export interface SandboxDenial {
43
44
  /**
44
45
  * What a command did: its exit status and output, or the denial that stopped it. A failing command is a result.
45
46
  * `exitCode` is 124 for a timeout, 127 for a program that can't be found, and 128 plus the signal's number for a
46
- * command that a signal killed, with `signal` naming it. `truncated` is `true` when the output passed the cap and the
47
- * rest was dropped.
47
+ * command that a signal killed, with `signal` naming it. `timedOut` is `true` only when the sandbox stopped the command
48
+ * at its timeout, so a command that exits with 124 itself can be told apart. `truncated` is `true` when the output
49
+ * passed the cap and the rest was dropped.
48
50
  */
49
51
  export type ExecResult = {
50
52
  exitCode: number;
51
53
  stdout: string;
52
54
  stderr: string;
53
55
  signal?: string;
56
+ timedOut?: boolean;
54
57
  truncated?: boolean;
55
58
  } | {
56
59
  denied: SandboxDenial;
@@ -68,6 +71,12 @@ export interface ExecOptions {
68
71
  /** The most bytes of each of standard output and standard error to keep. Defaults to 8 MiB; the rest is dropped. */
69
72
  readonly maxOutputBytes?: number;
70
73
  }
74
+ /**
75
+ * What a backend can do besides provisioning. `resume`: reattach to a sandbox by its id, such as after `pause` or a lost
76
+ * connection, or start one from a snapshot's id. `snapshot`: save a sandbox's state under an id that `resume` takes.
77
+ * `pause`: suspend a sandbox, keeping its state, until `resume`. A local backend has none of them.
78
+ */
79
+ export type SandboxCapability = "resume" | "snapshot" | "pause";
71
80
  /** A provisioned sandbox. */
72
81
  export interface Sandbox {
73
82
  /** Runs `command`, an executable and its arguments with no shell, and resolves with what it did. */
@@ -78,11 +87,39 @@ export interface Sandbox {
78
87
  writeFile(path: string, data: Uint8Array): Promise<void>;
79
88
  /** Stops what is still running, and releases the sandbox. Calling it again does nothing, and any other call afterwards rejects. */
80
89
  dispose(): Promise<void>;
90
+ /** The id `SandboxClient.resume()` takes. Only a sandbox from a backend with the `resume` capability has one. */
91
+ readonly id?: string;
92
+ /**
93
+ * The stops the applied policy delivers, as `stopsFor()` computes them from the read-back. A backend that reads its
94
+ * policy back sets it when it provisions, and one that enforces nothing leaves it out.
95
+ */
96
+ readonly stops?: readonly SandboxStop[];
97
+ /**
98
+ * Reads back the policy the backend applied, from the backend's own record of it, such as the settings file it wrote
99
+ * or the policy a hosted provider reports. A backend that claims any stop has it, and `provision()` compares its
100
+ * answer with the request and throws `SandboxPolicyMismatchError` when they differ.
101
+ */
102
+ readBack?(): Promise<SandboxPolicy>;
103
+ /** Saves the sandbox's state and resolves with an id that `resume()` starts a sandbox from. Needs `snapshot`. */
104
+ snapshot?(): Promise<string>;
105
+ /** Suspends the sandbox until `resume()` with its `id`. Needs `pause`. */
106
+ pause?(): Promise<void>;
81
107
  }
82
108
  /** A sandbox backend. */
83
109
  export interface SandboxClient {
84
110
  readonly tier: SandboxTier;
111
+ /** The stops the backend claims for every policy it accepts. `provision()` checks them against the applied policy. */
85
112
  readonly stops: readonly SandboxStop[];
86
- /** Provisions a sandbox, or throws `SandboxUnavailableError` when the backend can't start. It never falls back. */
113
+ /** What the backend can do besides provisioning. Leaving it out means none; call each one through its helper. */
114
+ readonly capabilities?: readonly SandboxCapability[];
115
+ /**
116
+ * Provisions a sandbox, or throws `SandboxUnavailableError` when the backend can't start. It never falls back. A
117
+ * backend that claims a stop reads its policy back first, and throws `SandboxPolicyMismatchError` on a difference.
118
+ */
87
119
  provision(manifest: WorkspaceManifest, policy: SandboxPolicy): Promise<Sandbox>;
120
+ /**
121
+ * Reattaches to the sandbox with this id, or starts one from the snapshot with this id. `policy` is the policy it must
122
+ * still apply. Needs `resume`; call it through `resumeSandbox()`, which checks the read-back.
123
+ */
124
+ resume?(id: string, policy: SandboxPolicy): Promise<Sandbox>;
88
125
  }
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/sandbox/types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * The sandbox interface: a pluggable client with honest tiers. The host owns the policy and the approval, never the\n * model, and a backend that can't start throws instead of running unconfined (harness guide section 6, ADR 0020).\n */\n\n/** What a sandbox may touch. Roots are absolute directories; a backend that enforces them denies the rest. */\nexport interface SandboxPolicy {\n /** Directories the sandbox may read. The write roots are readable too. */\n readonly readRoots: readonly string[];\n /** Directories the sandbox may write. */\n readonly writeRoots: readonly string[];\n /** The hosts the sandbox may reach: `allow` names them, and `deny` names the ones that stay closed inside `allow`. */\n readonly network: { readonly allow: readonly string[]; readonly deny: readonly string[] };\n}\n\n/** When a denied action may be asked for again, which is the host's decision and never the sandbox's. */\nexport type ApprovalPolicy = \"on-request\" | \"granular\" | \"never\";\n\n/**\n * How strongly a backend confines a process. `none`: not at all. `os`: an operating-system sandbox that shares the\n * host's kernel. `container`: a container. `gvisor`: a user-space kernel. `microvm`: a virtual machine.\n */\nexport type SandboxTier = \"none\" | \"os\" | \"container\" | \"gvisor\" | \"microvm\";\n\n/**\n * What a backend claims to stop. `mistakes`: the agent's own errors, such as a write outside the workspace.\n * `exfiltration`: sending data to a host that is not allowed. `hostile_process`: a process that is trying to escape.\n * A backend lists a stop only when its tier and its setup deliver it, and no tier here claims `hostile_process` yet.\n */\nexport type SandboxStop = \"mistakes\" | \"exfiltration\" | \"hostile_process\";\n\n/** The workspace a sandbox is provisioned for: its root directory and the files to put there first. */\nexport interface WorkspaceManifest {\n /** The workspace's absolute root. Relative paths and working directories resolve against it. */\n readonly root: string;\n /** Files to write under the root before the first command, by path relative to it. */\n readonly files?: Readonly<Record<string, string | Uint8Array>>;\n}\n\n/** What the policy refused. `target` names the path or host, and `reason` says which rule. */\nexport interface SandboxDenial {\n readonly kind: \"filesystem_read\" | \"filesystem_write\" | \"network\";\n readonly target: string;\n readonly reason: string;\n}\n\n/**\n * What a command did: its exit status and output, or the denial that stopped it. A failing command is a result.\n * `exitCode` is 124 for a timeout, 127 for a program that can't be found, and 128 plus the signal's number for a\n * command that a signal killed, with `signal` naming it. `truncated` is `true` when the output passed the cap and the\n * rest was dropped.\n */\nexport type ExecResult =\n | { exitCode: number; stdout: string; stderr: string; signal?: string; truncated?: boolean }\n | { denied: SandboxDenial };\n\n/** The options of `Sandbox.exec()`. */\nexport interface ExecOptions {\n /** The working directory, relative to the workspace root. Defaults to the root. */\n readonly cwd?: string;\n /** The command's whole environment. Build it with `spawnEnv()`: nothing else is added. */\n readonly env: Readonly<Record<string, string>>;\n /** Aborts the command and every process it started. An already aborted signal rejects before the command runs. */\n readonly signal: AbortSignal;\n /** Stops a command, and every process it started, that runs longer than this, with exit code 124. */\n readonly timeoutMs?: number;\n /** The most bytes of each of standard output and standard error to keep. Defaults to 8 MiB; the rest is dropped. */\n readonly maxOutputBytes?: number;\n}\n\n/** A provisioned sandbox. */\nexport interface Sandbox {\n /** Runs `command`, an executable and its arguments with no shell, and resolves with what it did. */\n exec(command: readonly string[], options: ExecOptions): Promise<ExecResult>;\n /** Reads a file by path relative to the workspace root, or absolute. A missing file rejects with `sandbox_not_found`. */\n readFile(path: string): Promise<Uint8Array>;\n /** Writes a file by path relative to the workspace root, or absolute, making its folders. */\n writeFile(path: string, data: Uint8Array): Promise<void>;\n /** Stops what is still running, and releases the sandbox. Calling it again does nothing, and any other call afterwards rejects. */\n dispose(): Promise<void>;\n}\n\n/** A sandbox backend. */\nexport interface SandboxClient {\n readonly tier: SandboxTier;\n readonly stops: readonly SandboxStop[];\n /** Provisions a sandbox, or throws `SandboxUnavailableError` when the backend can't start. It never falls back. */\n provision(manifest: WorkspaceManifest, policy: SandboxPolicy): Promise<Sandbox>;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/sandbox/types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * The sandbox interface: a pluggable client with honest tiers. The host owns the policy and the approval, never the\n * model, and a backend that can't start throws instead of running unconfined (harness guide section 6, ADR 0020).\n */\n\n/** What a sandbox may touch. Roots are absolute directories; a backend that enforces them denies the rest. */\nexport interface SandboxPolicy {\n /** Directories the sandbox may read. The write roots are readable too. */\n readonly readRoots: readonly string[];\n /** Directories the sandbox may write. */\n readonly writeRoots: readonly string[];\n /** The hosts the sandbox may reach: `allow` names them, and `deny` names the ones that stay closed inside `allow`. */\n readonly network: { readonly allow: readonly string[]; readonly deny: readonly string[] };\n}\n\n/** When a denied action may be asked for again, which is the host's decision and never the sandbox's. */\nexport type ApprovalPolicy = \"on-request\" | \"granular\" | \"never\";\n\n/**\n * How strongly a backend confines a process. `none`: not at all. `os`: an operating-system sandbox that shares the\n * host's kernel. `container`: a container. `gvisor`: a user-space kernel. `microvm`: a virtual machine.\n */\nexport type SandboxTier = \"none\" | \"os\" | \"container\" | \"gvisor\" | \"microvm\";\n\n/**\n * What a backend claims to stop. `mistakes`: the agent's own errors, such as a write outside the workspace.\n * `exfiltration`: sending data to a host that is not allowed. `hostile_process`: a process that is trying to escape.\n * A backend lists a stop only when its tier and its applied policy deliver it, which `stopsFor()` computes: only a\n * `microvm` stops a `hostile_process`, and none of the backends in this package is one.\n */\nexport type SandboxStop = \"mistakes\" | \"exfiltration\" | \"hostile_process\";\n\n/** The workspace a sandbox is provisioned for: its root directory and the files to put there first. */\nexport interface WorkspaceManifest {\n /** The workspace's absolute root. Relative paths and working directories resolve against it. */\n readonly root: string;\n /** Files to write under the root before the first command, by path relative to it. */\n readonly files?: Readonly<Record<string, string | Uint8Array>>;\n}\n\n/** What the policy refused. `target` names the path or host, and `reason` says which rule. */\nexport interface SandboxDenial {\n readonly kind: \"filesystem_read\" | \"filesystem_write\" | \"network\";\n readonly target: string;\n readonly reason: string;\n}\n\n/**\n * What a command did: its exit status and output, or the denial that stopped it. A failing command is a result.\n * `exitCode` is 124 for a timeout, 127 for a program that can't be found, and 128 plus the signal's number for a\n * command that a signal killed, with `signal` naming it. `timedOut` is `true` only when the sandbox stopped the command\n * at its timeout, so a command that exits with 124 itself can be told apart. `truncated` is `true` when the output\n * passed the cap and the rest was dropped.\n */\nexport type ExecResult =\n | { exitCode: number; stdout: string; stderr: string; signal?: string; timedOut?: boolean; truncated?: boolean }\n | { denied: SandboxDenial };\n\n/** The options of `Sandbox.exec()`. */\nexport interface ExecOptions {\n /** The working directory, relative to the workspace root. Defaults to the root. */\n readonly cwd?: string;\n /** The command's whole environment. Build it with `spawnEnv()`: nothing else is added. */\n readonly env: Readonly<Record<string, string>>;\n /** Aborts the command and every process it started. An already aborted signal rejects before the command runs. */\n readonly signal: AbortSignal;\n /** Stops a command, and every process it started, that runs longer than this, with exit code 124. */\n readonly timeoutMs?: number;\n /** The most bytes of each of standard output and standard error to keep. Defaults to 8 MiB; the rest is dropped. */\n readonly maxOutputBytes?: number;\n}\n\n/**\n * What a backend can do besides provisioning. `resume`: reattach to a sandbox by its id, such as after `pause` or a lost\n * connection, or start one from a snapshot's id. `snapshot`: save a sandbox's state under an id that `resume` takes.\n * `pause`: suspend a sandbox, keeping its state, until `resume`. A local backend has none of them.\n */\nexport type SandboxCapability = \"resume\" | \"snapshot\" | \"pause\";\n\n/** A provisioned sandbox. */\nexport interface Sandbox {\n /** Runs `command`, an executable and its arguments with no shell, and resolves with what it did. */\n exec(command: readonly string[], options: ExecOptions): Promise<ExecResult>;\n /** Reads a file by path relative to the workspace root, or absolute. A missing file rejects with `sandbox_not_found`. */\n readFile(path: string): Promise<Uint8Array>;\n /** Writes a file by path relative to the workspace root, or absolute, making its folders. */\n writeFile(path: string, data: Uint8Array): Promise<void>;\n /** Stops what is still running, and releases the sandbox. Calling it again does nothing, and any other call afterwards rejects. */\n dispose(): Promise<void>;\n /** The id `SandboxClient.resume()` takes. Only a sandbox from a backend with the `resume` capability has one. */\n readonly id?: string;\n /**\n * The stops the applied policy delivers, as `stopsFor()` computes them from the read-back. A backend that reads its\n * policy back sets it when it provisions, and one that enforces nothing leaves it out.\n */\n readonly stops?: readonly SandboxStop[];\n /**\n * Reads back the policy the backend applied, from the backend's own record of it, such as the settings file it wrote\n * or the policy a hosted provider reports. A backend that claims any stop has it, and `provision()` compares its\n * answer with the request and throws `SandboxPolicyMismatchError` when they differ.\n */\n readBack?(): Promise<SandboxPolicy>;\n /** Saves the sandbox's state and resolves with an id that `resume()` starts a sandbox from. Needs `snapshot`. */\n snapshot?(): Promise<string>;\n /** Suspends the sandbox until `resume()` with its `id`. Needs `pause`. */\n pause?(): Promise<void>;\n}\n\n/** A sandbox backend. */\nexport interface SandboxClient {\n readonly tier: SandboxTier;\n /** The stops the backend claims for every policy it accepts. `provision()` checks them against the applied policy. */\n readonly stops: readonly SandboxStop[];\n /** What the backend can do besides provisioning. Leaving it out means none; call each one through its helper. */\n readonly capabilities?: readonly SandboxCapability[];\n /**\n * Provisions a sandbox, or throws `SandboxUnavailableError` when the backend can't start. It never falls back. A\n * backend that claims a stop reads its policy back first, and throws `SandboxPolicyMismatchError` on a difference.\n */\n provision(manifest: WorkspaceManifest, policy: SandboxPolicy): Promise<Sandbox>;\n /**\n * Reattaches to the sandbox with this id, or starts one from the snapshot with this id. `policy` is the policy it must\n * still apply. Needs `resume`; call it through `resumeSandbox()`, which checks the read-back.\n */\n resume?(id: string, policy: SandboxPolicy): Promise<Sandbox>;\n}\n"]}
@@ -1,8 +1,15 @@
1
- import type { SandboxClient } from "../sandbox/types.js";
1
+ import type { SandboxClient, SandboxPolicy, SandboxStop } from "../sandbox/types.js";
2
2
  /** The options of `fakeSandbox()`. */
3
3
  export interface FakeSandboxOptions {
4
4
  /** Makes `provision()` throw `SandboxUnavailableError` with this reason, as a backend that can't start does. */
5
5
  readonly unavailable?: string;
6
+ /**
7
+ * The policy the fake applies and reads back instead of the requested one, as a hosted provider's account-wide
8
+ * override would. `provision()` then throws `SandboxPolicyMismatchError` when the two differ.
9
+ */
10
+ readonly applied?: (requested: SandboxPolicy) => SandboxPolicy;
11
+ /** The stops the fake claims. Defaults to `mistakes` and `exfiltration`, which its in-memory checks deliver. */
12
+ readonly stops?: readonly SandboxStop[];
6
13
  }
7
14
  /** One command the fake received, with what the caller passed. */
8
15
  export interface RecordedExec {
@@ -24,11 +31,22 @@ export interface FakeSandboxClient extends SandboxClient {
24
31
  * The commands the fake runs, in the form `[name, ...arguments]`: `echo` prints its arguments, `env` prints the
25
32
  * environment it was given as `NAME=value` lines, `cat <path>` prints a file, `write <path> <text>` writes one,
26
33
  * `true` and `false` exit with 0 and 1, `sleep <seconds>` waits and honours the timeout and the signal, and
27
- * `net-probe <host>` reaches a host only if the policy allows it. Any other command exits with 127.
34
+ * `net-probe <host>` reaches a host only if the policy allows it. `find <dir>` lists the files under a folder, one per
35
+ * line or ending in NUL with `-print0`. When the command has `-prune`, it leaves out every folder named by a `-name`,
36
+ * the starting folder included. A `! -path <start>` exempts the starting folder. It exits with 0 and prints nothing for a folder
37
+ * with no files, and with 1 for a path that does not exist. `grep [-i] -e <pattern> -- <file>...` prints each
38
+ * matching line as `file:line:text`, reading the pattern as a JavaScript regular expression and skipping a file that
39
+ * holds a NUL byte. It exits with 1 when nothing matches, and with 2 after a missing file or a pattern it can't read,
40
+ * as grep does. A command that runs past its timeout exits with 124 and `timedOut: true`, and each stream keeps at
41
+ * most `maxOutputBytes`, with `truncated: true` when more was dropped.
42
+ * `bash -c <script>` and `sh -c <script>` split the script on whitespace and run its words as one of these commands,
43
+ * with no shell syntax. Any other command exits with 127.
28
44
  */
29
45
  export declare const FAKE_COMMANDS: readonly string[];
30
46
  /**
31
47
  * Builds a fake backend with the tier `os` and the stops `mistakes` and `exfiltration`, because it enforces the
32
- * policy's file roots and network allowlist in memory. That says nothing about a real process: it runs none.
48
+ * policy's file roots and network allowlist in memory. That says nothing about a real process: it runs none. It reads
49
+ * its policy back as a real backend does, so `provision()` throws `SandboxPolicyMismatchError` when `applied` changes
50
+ * the policy.
33
51
  */
34
52
  export declare function fakeSandbox(options?: FakeSandboxOptions): FakeSandboxClient;
@@ -5,15 +5,40 @@
5
5
  */
6
6
  import { HarnessError } from "../errors.js";
7
7
  import { SandboxDeniedError, SandboxUnavailableError } from "../sandbox/errors.js";
8
+ import { confirmPolicy } from "../sandbox/policy.js";
8
9
  /**
9
10
  * The commands the fake runs, in the form `[name, ...arguments]`: `echo` prints its arguments, `env` prints the
10
11
  * environment it was given as `NAME=value` lines, `cat <path>` prints a file, `write <path> <text>` writes one,
11
12
  * `true` and `false` exit with 0 and 1, `sleep <seconds>` waits and honours the timeout and the signal, and
12
- * `net-probe <host>` reaches a host only if the policy allows it. Any other command exits with 127.
13
+ * `net-probe <host>` reaches a host only if the policy allows it. `find <dir>` lists the files under a folder, one per
14
+ * line or ending in NUL with `-print0`. When the command has `-prune`, it leaves out every folder named by a `-name`,
15
+ * the starting folder included. A `! -path <start>` exempts the starting folder. It exits with 0 and prints nothing for a folder
16
+ * with no files, and with 1 for a path that does not exist. `grep [-i] -e <pattern> -- <file>...` prints each
17
+ * matching line as `file:line:text`, reading the pattern as a JavaScript regular expression and skipping a file that
18
+ * holds a NUL byte. It exits with 1 when nothing matches, and with 2 after a missing file or a pattern it can't read,
19
+ * as grep does. A command that runs past its timeout exits with 124 and `timedOut: true`, and each stream keeps at
20
+ * most `maxOutputBytes`, with `truncated: true` when more was dropped.
21
+ * `bash -c <script>` and `sh -c <script>` split the script on whitespace and run its words as one of these commands,
22
+ * with no shell syntax. Any other command exits with 127.
13
23
  */
14
- export const FAKE_COMMANDS = ["echo", "env", "cat", "write", "true", "false", "sleep", "net-probe"];
24
+ export const FAKE_COMMANDS = [
25
+ "echo",
26
+ "env",
27
+ "cat",
28
+ "write",
29
+ "true",
30
+ "false",
31
+ "sleep",
32
+ "net-probe",
33
+ "find",
34
+ "grep",
35
+ "bash",
36
+ "sh",
37
+ ];
15
38
  const ENCODER = new TextEncoder();
16
39
  const DECODER = new TextDecoder();
40
+ // What a real backend keeps of each stream when the caller names no cap.
41
+ const DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
17
42
  function normalize(path) {
18
43
  const parts = [];
19
44
  for (const part of path.split("/")) {
@@ -26,12 +51,41 @@ function normalize(path) {
26
51
  }
27
52
  return `/${parts.join("/")}`;
28
53
  }
54
+ /** The lines of `text` that match, as `grep -n -H` prints them. */
55
+ function matchingLines(file, text, pattern) {
56
+ const lines = text.endsWith("\n") ? text.slice(0, -1).split("\n") : text.split("\n");
57
+ return lines.map((line, index) => (pattern.test(line) ? `${file}:${index + 1}:${line}\n` : "")).join("");
58
+ }
59
+ /** A `find -path` pattern with its backslash escapes removed, as the literal path it names. */
60
+ const literalOf = (pattern) => pattern?.replace(/\\(.)/g, "$1");
61
+ /** `text` cut to its first `bytes` UTF-8 bytes, never splitting a character, and whether anything was cut. */
62
+ function capped(text, bytes) {
63
+ const encoded = ENCODER.encode(text);
64
+ if (encoded.length <= bytes)
65
+ return { text, cut: false };
66
+ let end = bytes;
67
+ while (end > 0 && (encoded[end] & 0b1100_0000) === 0b1000_0000)
68
+ end -= 1;
69
+ return { text: DECODER.decode(encoded.subarray(0, end)), cut: true };
70
+ }
71
+ /** The pattern of a `grep` command's flags, or the result grep gives for a pattern it can't read. */
72
+ function patternOf(flags) {
73
+ const at = flags.indexOf("-e");
74
+ try {
75
+ return new RegExp(at < 0 ? "" : (flags[at + 1] ?? ""), flags.includes("-i") ? "i" : "");
76
+ }
77
+ catch (error) {
78
+ // grep reports a pattern it can't read on standard error and exits with 2, before it reads any file.
79
+ return { exitCode: 2, stdout: "", stderr: `grep: ${error.message}\n` };
80
+ }
81
+ }
29
82
  const within = (path, root) => {
30
83
  const base = normalize(root);
31
84
  return base === "/" || path === base || path.startsWith(`${base}/`);
32
85
  };
33
86
  class FakeSandbox {
34
87
  disposed = false;
88
+ stops = [];
35
89
  // What ends each command still running, so `dispose()` can reject them as a real backend does.
36
90
  running = new Set();
37
91
  store = new Map();
@@ -48,6 +102,16 @@ class FakeSandbox {
48
102
  if (this.disposed)
49
103
  throw new HarnessError("sandbox_disposed", "the sandbox was disposed");
50
104
  }
105
+ /** The policy the fake enforces, as a copy. */
106
+ async readBack() {
107
+ this.live();
108
+ const { readRoots, writeRoots, network } = this.policy;
109
+ return {
110
+ readRoots: [...readRoots],
111
+ writeRoots: [...writeRoots],
112
+ network: { allow: [...network.allow], deny: [...network.deny] },
113
+ };
114
+ }
51
115
  /** The absolute path a name stands for: joined to the root, tidied of `.` and `..`, then followed through links. */
52
116
  resolve(path, base = this.root) {
53
117
  const tidy = normalize(path.startsWith("/") ? path : `${base}/${path}`);
@@ -109,7 +173,16 @@ class FakeSandbox {
109
173
  return { denied: denial };
110
174
  this.log.push({ command: [...command], cwd: options.cwd, env: { ...options.env }, timeoutMs: options.timeoutMs });
111
175
  const [name = "", ...args] = command;
112
- return this.run(name, args, options);
176
+ const result = await this.run(name, args, options);
177
+ if ("denied" in result)
178
+ return result;
179
+ // Each stream keeps at most `maxOutputBytes`, as a real backend's does.
180
+ const limit = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
181
+ const stdout = capped(result.stdout, limit);
182
+ const stderr = capped(result.stderr, limit);
183
+ if (!stdout.cut && !stderr.cut)
184
+ return result;
185
+ return { ...result, stdout: stdout.text, stderr: stderr.text, truncated: true };
113
186
  }
114
187
  async run(name, args, options) {
115
188
  const ok = (stdout = "") => ({ exitCode: 0, stdout, stderr: "" });
@@ -135,6 +208,13 @@ class FakeSandbox {
135
208
  }
136
209
  case "sleep":
137
210
  return this.sleep(Number(args[0] ?? 0) * 1000, options);
211
+ case "find":
212
+ return this.find(args);
213
+ case "grep":
214
+ return this.grep(args);
215
+ case "bash":
216
+ case "sh":
217
+ return this.shell(args, options);
138
218
  default:
139
219
  return { exitCode: 127, stdout: "", stderr: `command not found: ${name}\n` };
140
220
  }
@@ -149,6 +229,69 @@ class FakeSandbox {
149
229
  ? { exitCode: 1, stdout: "", stderr: `no such file: ${target}\n` }
150
230
  : { exitCode: 0, stdout: DECODER.decode(data), stderr: "" };
151
231
  }
232
+ /** The script's words as one command, so a test can drive a shell tool without a shell. */
233
+ shell(args, options) {
234
+ if (args[0] !== "-c")
235
+ return Promise.resolve({ exitCode: 2, stdout: "", stderr: "the fake shell runs only -c\n" });
236
+ const [name = "", ...rest] = (args[1] ?? "").trim().split(/\s+/);
237
+ return this.run(name, rest, options);
238
+ }
239
+ /** Whether `path` is a folder: the root, a folder above it, or a folder that holds a file. */
240
+ isFolder(path) {
241
+ if (within(this.root, path))
242
+ return true;
243
+ const prefix = path === "/" ? "/" : `${path}/`;
244
+ return [...this.store.keys()].some((file) => file.startsWith(prefix));
245
+ }
246
+ find(args) {
247
+ const start = this.resolve(args[0] ?? ".");
248
+ const denial = this.readDenial(start);
249
+ if (denial)
250
+ return { denied: denial };
251
+ if (!this.store.has(start) && !this.isFolder(start)) {
252
+ return { exitCode: 1, stdout: "", stderr: `find: '${args[0] ?? "."}': No such file or directory\n` };
253
+ }
254
+ const named = args.flatMap((arg, index) => (arg === "-name" ? [args[index + 1] ?? ""] : []));
255
+ const pruned = new Set(args.includes("-prune") ? named : []);
256
+ // `! -path <start>` exempts the starting point from the prune, as it does for find; without it the prune tests
257
+ // the starting point's own name too, so a search that starts in a pruned folder finds nothing.
258
+ const exempt = args.some((arg, index) => arg === "!" && args[index + 1] === "-path" && literalOf(args[index + 2]) === start);
259
+ const ownName = start.split("/").at(-1) ?? "";
260
+ if (!exempt && ownName !== "" && pruned.has(ownName))
261
+ return { exitCode: 0, stdout: "", stderr: "" };
262
+ const files = [...this.store.keys()]
263
+ .filter((path) => path === start || path.startsWith(`${start === "/" ? "" : start}/`))
264
+ .filter((path) => !path
265
+ .slice(start.length)
266
+ .split("/")
267
+ .some((part) => pruned.has(part)))
268
+ .sort();
269
+ const end = args.includes("-print0") ? "\0" : "\n";
270
+ return { exitCode: 0, stdout: files.map((path) => `${path}${end}`).join(""), stderr: "" };
271
+ }
272
+ grep(args) {
273
+ const split = args.indexOf("--");
274
+ const flags = split < 0 ? args : args.slice(0, split);
275
+ const files = split < 0 ? [] : args.slice(split + 1);
276
+ const pattern = patternOf(flags);
277
+ if (!(pattern instanceof RegExp))
278
+ return pattern;
279
+ let stdout = "";
280
+ let stderr = "";
281
+ for (const file of files) {
282
+ const target = this.resolve(file);
283
+ const denial = this.readDenial(target);
284
+ if (denial)
285
+ return { denied: denial };
286
+ const data = this.store.get(target);
287
+ if (data === undefined)
288
+ stderr += `grep: ${file}: No such file or directory\n`;
289
+ else if (!data.includes(0))
290
+ stdout += matchingLines(file, DECODER.decode(data), pattern);
291
+ }
292
+ // grep exits with 2 after any error, even when other files matched.
293
+ return { exitCode: stderr !== "" ? 2 : stdout === "" ? 1 : 0, stdout, stderr };
294
+ }
152
295
  writeCommand(path, text) {
153
296
  const target = this.resolve(path);
154
297
  const denial = this.writeDenial(target);
@@ -179,7 +322,9 @@ class FakeSandbox {
179
322
  const stopAt = options.timeoutMs !== undefined && options.timeoutMs < ms ? options.timeoutMs : ms;
180
323
  const timer = setTimeout(() => {
181
324
  const timedOut = stopAt < ms;
182
- done({ exitCode: timedOut ? 124 : 0, stdout: "", stderr: timedOut ? `timed out after ${stopAt} ms\n` : "" });
325
+ done(timedOut
326
+ ? { exitCode: 124, stdout: "", stderr: `timed out after ${stopAt} ms\n`, timedOut: true }
327
+ : { exitCode: 0, stdout: "", stderr: "" });
183
328
  }, stopAt);
184
329
  options.signal.addEventListener("abort", aborted, { once: true });
185
330
  });
@@ -193,14 +338,16 @@ class FakeSandbox {
193
338
  }
194
339
  /**
195
340
  * Builds a fake backend with the tier `os` and the stops `mistakes` and `exfiltration`, because it enforces the
196
- * policy's file roots and network allowlist in memory. That says nothing about a real process: it runs none.
341
+ * policy's file roots and network allowlist in memory. That says nothing about a real process: it runs none. It reads
342
+ * its policy back as a real backend does, so `provision()` throws `SandboxPolicyMismatchError` when `applied` changes
343
+ * the policy.
197
344
  */
198
345
  export function fakeSandbox(options = {}) {
199
346
  const execs = [];
200
347
  let latest;
201
- return {
348
+ const client = {
202
349
  tier: "os",
203
- stops: ["mistakes", "exfiltration"],
350
+ stops: options.stops ?? ["mistakes", "exfiltration"],
204
351
  execs,
205
352
  files: () => latest?.store ?? new Map(),
206
353
  symlink(link, target) {
@@ -209,7 +356,8 @@ export function fakeSandbox(options = {}) {
209
356
  async provision(manifest, policy) {
210
357
  if (options.unavailable !== undefined)
211
358
  throw new SandboxUnavailableError("fake", options.unavailable);
212
- const sandbox = new FakeSandbox(manifest.root, policy, execs);
359
+ const sandbox = new FakeSandbox(manifest.root, options.applied?.(policy) ?? policy, execs);
360
+ sandbox.stops = await confirmPolicy(client, sandbox, policy);
213
361
  for (const [path, data] of Object.entries(manifest.files ?? {})) {
214
362
  sandbox.seed(path, typeof data === "string" ? ENCODER.encode(data) : data);
215
363
  }
@@ -217,5 +365,6 @@ export function fakeSandbox(options = {}) {
217
365
  return sandbox;
218
366
  },
219
367
  };
368
+ return client;
220
369
  }
221
370
  //# sourceMappingURL=fake-sandbox.js.map