@lelouchhe/agent-evals 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/.env.example +27 -0
  2. package/LICENSE +21 -0
  3. package/README.md +121 -2
  4. package/dist/checkers/file/index.d.ts +26 -0
  5. package/dist/checkers/file/index.js +396 -0
  6. package/dist/checkers/judge/index.d.ts +20 -0
  7. package/dist/checkers/judge/index.js +474 -0
  8. package/dist/checkers/judge/prompt.d.ts +19 -0
  9. package/dist/checkers/judge/prompt.js +55 -0
  10. package/dist/checkers/judge/trace.d.ts +6 -0
  11. package/dist/checkers/judge/trace.js +41 -0
  12. package/dist/checkers/mock/index.d.ts +18 -0
  13. package/dist/checkers/mock/index.js +127 -0
  14. package/dist/checkers/shell/index.d.ts +10 -0
  15. package/dist/checkers/shell/index.js +61 -0
  16. package/dist/checkers/trace/index.d.ts +22 -0
  17. package/dist/checkers/trace/index.js +183 -0
  18. package/dist/cli.d.ts +2 -0
  19. package/dist/cli.js +453 -0
  20. package/dist/engine/authoring.d.ts +24 -0
  21. package/dist/engine/authoring.js +356 -0
  22. package/dist/engine/check-runner.d.ts +1 -0
  23. package/dist/engine/check-runner.js +127 -0
  24. package/dist/engine/check-sandbox.d.ts +18 -0
  25. package/dist/engine/check-sandbox.js +171 -0
  26. package/dist/engine/config.d.ts +171 -0
  27. package/dist/engine/config.js +368 -0
  28. package/dist/engine/env-source.d.ts +10 -0
  29. package/dist/engine/env-source.js +114 -0
  30. package/dist/engine/files.d.ts +84 -0
  31. package/dist/engine/files.js +304 -0
  32. package/dist/engine/forwarder.sh +61 -0
  33. package/dist/engine/ignore.d.ts +29 -0
  34. package/dist/engine/ignore.js +67 -0
  35. package/dist/engine/messages.d.ts +8 -0
  36. package/dist/engine/messages.js +9 -0
  37. package/dist/engine/mock-match.d.ts +44 -0
  38. package/dist/engine/mock-match.js +104 -0
  39. package/dist/engine/mocks.d.ts +35 -0
  40. package/dist/engine/mocks.js +336 -0
  41. package/dist/engine/params.d.ts +18 -0
  42. package/dist/engine/params.js +96 -0
  43. package/dist/engine/placement.d.ts +26 -0
  44. package/dist/engine/placement.js +107 -0
  45. package/dist/engine/regex.d.ts +10 -0
  46. package/dist/engine/regex.js +16 -0
  47. package/dist/engine/registry.d.ts +243 -0
  48. package/dist/engine/registry.js +127 -0
  49. package/dist/engine/report.d.ts +17 -0
  50. package/dist/engine/report.js +420 -0
  51. package/dist/engine/results.d.ts +50 -0
  52. package/dist/engine/results.js +42 -0
  53. package/dist/engine/run.d.ts +50 -0
  54. package/dist/engine/run.js +710 -0
  55. package/dist/engine/runtime-assets.d.ts +6 -0
  56. package/dist/engine/runtime-assets.js +11 -0
  57. package/dist/engine/skills.d.ts +49 -0
  58. package/dist/engine/skills.js +270 -0
  59. package/dist/engine/truncate.d.ts +3 -0
  60. package/dist/engine/truncate.js +7 -0
  61. package/dist/engine/values.d.ts +18 -0
  62. package/dist/engine/values.js +75 -0
  63. package/dist/engine/view.d.ts +10 -0
  64. package/dist/engine/view.js +150 -0
  65. package/dist/engine/workspace.d.ts +63 -0
  66. package/dist/engine/workspace.js +305 -0
  67. package/dist/index.d.ts +16 -0
  68. package/dist/index.js +7 -0
  69. package/dist/platform/macos/launch.d.ts +13 -0
  70. package/dist/platform/macos/launch.js +14 -0
  71. package/dist/platform/macos/policy.d.ts +33 -0
  72. package/dist/platform/macos/policy.js +131 -0
  73. package/dist/platform/macos/supervise.d.ts +26 -0
  74. package/dist/platform/macos/supervise.js +98 -0
  75. package/dist/platform/macos/supervisor.sh +13 -0
  76. package/dist/runners/acp/agent.d.ts +17 -0
  77. package/dist/runners/acp/agent.js +38 -0
  78. package/dist/runners/acp/commands.d.ts +2 -0
  79. package/dist/runners/acp/commands.js +112 -0
  80. package/dist/runners/acp/environment.d.ts +71 -0
  81. package/dist/runners/acp/environment.js +280 -0
  82. package/dist/runners/acp/index.d.ts +21 -0
  83. package/dist/runners/acp/index.js +135 -0
  84. package/dist/runners/acp/session.d.ts +7 -0
  85. package/dist/runners/acp/session.js +48 -0
  86. package/dist/runners/acp/trace.d.ts +23 -0
  87. package/dist/runners/acp/trace.js +44 -0
  88. package/dist/runners/acp/usage.d.ts +12 -0
  89. package/dist/runners/acp/usage.js +56 -0
  90. package/dist/runners/noop/index.d.ts +12 -0
  91. package/dist/runners/noop/index.js +22 -0
  92. package/dist/runners/pi/index.d.ts +21 -0
  93. package/dist/runners/pi/index.js +116 -0
  94. package/dist/runners/pi/params.d.ts +10 -0
  95. package/dist/runners/pi/params.js +3 -0
  96. package/dist/runners/pi/rpc.d.ts +30 -0
  97. package/dist/runners/pi/rpc.js +341 -0
  98. package/dist/runners/pi/safe-process-group.d.ts +7 -0
  99. package/dist/runners/pi/safe-process-group.js +13 -0
  100. package/dist/runners/pi/session.d.ts +56 -0
  101. package/dist/runners/pi/session.js +298 -0
  102. package/dist/runners/pi/shell-wrapper.sh +46 -0
  103. package/dist/runners/pi/supervisor.d.ts +1 -0
  104. package/dist/runners/pi/supervisor.js +101 -0
  105. package/package.json +77 -4
@@ -0,0 +1,305 @@
1
+ import { constants } from "node:fs";
2
+ import { lstat, open, readdir, realpath } from "node:fs/promises";
3
+ import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
4
+ import { ConfigError, errorMessage } from "./config.js";
5
+ /** Largest file a check will read. Checks stay bounded and predictable. */
6
+ export const MAX_CHECK_BYTES = 1024 * 1024;
7
+ export class WorkspacePathError extends Error {
8
+ constructor(message) {
9
+ super(message);
10
+ this.name = "WorkspacePathError";
11
+ }
12
+ }
13
+ export async function openRunRoot(path) {
14
+ const canonical = await realpath(path);
15
+ let handle;
16
+ try {
17
+ handle = await open(canonical, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
18
+ }
19
+ catch (error) {
20
+ throw new WorkspacePathError(`could not open run directory ${path}: ${errorMessage(error)}`);
21
+ }
22
+ try {
23
+ const stats = await handle.stat({ bigint: true });
24
+ if (!stats.isDirectory()) {
25
+ throw new WorkspacePathError(`run path is not a directory: ${path}`);
26
+ }
27
+ return { path: canonical, dev: stats.dev, ino: stats.ino };
28
+ }
29
+ finally {
30
+ await handle.close();
31
+ }
32
+ }
33
+ /**
34
+ * Verify the directory path still refers to the prepared directory. A path
35
+ * replaced by a symlink or a different directory is rejected.
36
+ */
37
+ export async function assertRunRoot(root) {
38
+ let entry;
39
+ try {
40
+ entry = await lstat(root.path, { bigint: true });
41
+ }
42
+ catch (error) {
43
+ throw new WorkspacePathError(`run directory is no longer accessible: ${root.path}: ${errorMessage(error)}`);
44
+ }
45
+ if (entry.isSymbolicLink() || !entry.isDirectory() || entry.dev !== root.dev || entry.ino !== root.ino) {
46
+ throw new WorkspacePathError(`run directory was replaced after preparation: ${root.path}`);
47
+ }
48
+ let handle;
49
+ try {
50
+ handle = await open(root.path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
51
+ }
52
+ catch (error) {
53
+ throw new WorkspacePathError(`run directory can no longer be opened safely: ${root.path}: ${errorMessage(error)}`);
54
+ }
55
+ try {
56
+ const stats = await handle.stat({ bigint: true });
57
+ if (!stats.isDirectory() || stats.dev !== root.dev || stats.ino !== root.ino) {
58
+ throw new WorkspacePathError(`run directory was replaced while opening it: ${root.path}`);
59
+ }
60
+ }
61
+ finally {
62
+ await handle.close();
63
+ }
64
+ }
65
+ /**
66
+ * Resolve a run-relative path without allowing it to leave the prepared run
67
+ * root. The root identity is verified first, and symlinks (including ancestor
68
+ * symlinks) are rejected when they escape. A broken symlink is rejected rather
69
+ * than treated as a missing file.
70
+ */
71
+ export async function resolveWorkspacePath(root, requestedPath) {
72
+ if (typeof requestedPath !== "string" || requestedPath.length === 0) {
73
+ throw new WorkspacePathError("path must be a non-empty string");
74
+ }
75
+ if (requestedPath.includes("\0")) {
76
+ throw new WorkspacePathError("path contains a NUL byte");
77
+ }
78
+ if (isAbsolute(requestedPath)) {
79
+ throw new WorkspacePathError(`path must be relative to the run workspace: ${requestedPath}`);
80
+ }
81
+ const segments = requestedPath.split(/[\\/]+/);
82
+ if (segments.some((segment) => segment === "..")) {
83
+ throw new WorkspacePathError(`path must not contain "..": ${requestedPath}`);
84
+ }
85
+ await assertRunRoot(root);
86
+ const target = resolve(root.path, requestedPath);
87
+ if (!isWithin(root.path, target)) {
88
+ throw new WorkspacePathError(`path escapes the run workspace: ${requestedPath}`);
89
+ }
90
+ let probe = target;
91
+ const missing = [];
92
+ while (true) {
93
+ try {
94
+ const resolvedProbe = await realpath(probe);
95
+ const resolvedTarget = missing.length === 0 ? resolvedProbe : join(resolvedProbe, ...missing);
96
+ if (!isWithin(root.path, resolvedTarget)) {
97
+ throw new WorkspacePathError(`path resolves outside the run workspace through a symlink: ${requestedPath}`);
98
+ }
99
+ return resolvedTarget;
100
+ }
101
+ catch (error) {
102
+ if (!isMissing(error)) {
103
+ throw error;
104
+ }
105
+ // Distinguish a genuinely missing component from a broken symlink, which
106
+ // realpath also reports as ENOENT but must not be silently treated as absent.
107
+ let entry;
108
+ try {
109
+ entry = await lstat(probe);
110
+ }
111
+ catch {
112
+ entry = undefined;
113
+ }
114
+ if (entry !== undefined) {
115
+ throw new WorkspacePathError(`path contains a broken symlink: ${requestedPath}`);
116
+ }
117
+ if (probe === root.path) {
118
+ throw new WorkspacePathError(`path escapes the run workspace: ${requestedPath}`);
119
+ }
120
+ missing.unshift(basename(probe));
121
+ probe = dirname(probe);
122
+ }
123
+ }
124
+ }
125
+ /**
126
+ * Read a regular run file. Non-regular evidence is rejected without opening it,
127
+ * so a FIFO or device cannot block the engine or checks.
128
+ */
129
+ export async function readRunFile(root, requestedPath) {
130
+ const resolved = await resolveWorkspacePath(root, requestedPath);
131
+ let entry;
132
+ try {
133
+ entry = await lstat(resolved);
134
+ }
135
+ catch (error) {
136
+ if (isMissing(error)) {
137
+ throw error;
138
+ }
139
+ throw new WorkspacePathError(`could not inspect ${requestedPath}: ${errorMessage(error)}`);
140
+ }
141
+ if (!entry.isFile()) {
142
+ throw new WorkspacePathError(`not a regular file: ${requestedPath}`);
143
+ }
144
+ return readBoundedFile(resolved, requestedPath);
145
+ }
146
+ /**
147
+ * Snapshot a run path for comparison. `undefined` means the path itself does not
148
+ * exist; an existing path is one entry per node beneath it, listed and opened
149
+ * without following links.
150
+ */
151
+ export async function readRunTree(root, requestedPath) {
152
+ const resolved = await resolveWorkspacePath(root, requestedPath);
153
+ let entry;
154
+ try {
155
+ // Inspect the named node itself rather than its canonical target: a directory replaced by
156
+ // an in-root link must read as a link, or a twin tree would make the comparison pass.
157
+ entry = await lstat(resolve(root.path, requestedPath));
158
+ }
159
+ catch (error) {
160
+ if (isMissing(error)) {
161
+ return undefined;
162
+ }
163
+ throw new WorkspacePathError(`could not inspect ${requestedPath}: ${errorMessage(error)}`);
164
+ }
165
+ if (entry.isSymbolicLink()) {
166
+ return new Map([["", { kind: "symlink" }]]);
167
+ }
168
+ const entries = new Map();
169
+ const visit = async (absolute, relative, stats) => {
170
+ if (stats.isSymbolicLink()) {
171
+ entries.set(relative, { kind: "symlink" });
172
+ return;
173
+ }
174
+ if (stats.isDirectory()) {
175
+ entries.set(relative, { kind: "directory" });
176
+ let names;
177
+ try {
178
+ names = await readdir(absolute);
179
+ }
180
+ catch (error) {
181
+ throw new WorkspacePathError(`could not list ${requestedPath}: ${errorMessage(error)}`);
182
+ }
183
+ for (const name of [...names].sort()) {
184
+ const child = join(absolute, name);
185
+ const childRelative = relative === "" ? name : `${relative}/${name}`;
186
+ let childStats;
187
+ try {
188
+ childStats = await lstat(child);
189
+ }
190
+ catch (error) {
191
+ throw new WorkspacePathError(`could not inspect ${childRelative}: ${errorMessage(error)}`);
192
+ }
193
+ await visit(child, childRelative, childStats);
194
+ }
195
+ return;
196
+ }
197
+ if (stats.isFile()) {
198
+ if (stats.size > MAX_CHECK_BYTES) {
199
+ throw new WorkspacePathError(`file exceeds the ${MAX_CHECK_BYTES}-byte check limit: ${relative || requestedPath} (${stats.size} bytes)`);
200
+ }
201
+ entries.set(relative, { kind: "file", size: stats.size });
202
+ return;
203
+ }
204
+ entries.set(relative, { kind: "other" });
205
+ };
206
+ await visit(resolved, "", entry);
207
+ return entries;
208
+ }
209
+ /** Read one regular file with the size ceiling and the same no-follow open as `readRunFile`. */
210
+ async function readBoundedFile(absolute, requestedPath) {
211
+ let handle;
212
+ try {
213
+ handle = await open(absolute, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
214
+ }
215
+ catch (error) {
216
+ if (isMissing(error)) {
217
+ throw error;
218
+ }
219
+ throw new WorkspacePathError(`could not open ${requestedPath}: ${errorMessage(error)}`);
220
+ }
221
+ try {
222
+ const stats = await handle.stat();
223
+ if (!stats.isFile()) {
224
+ throw new WorkspacePathError(`not a regular file: ${requestedPath}`);
225
+ }
226
+ if (stats.size > MAX_CHECK_BYTES) {
227
+ throw new WorkspacePathError(`file exceeds the ${MAX_CHECK_BYTES}-byte check limit: ${requestedPath} (${stats.size} bytes)`);
228
+ }
229
+ // Read at most one byte past the ceiling: a file that grows between the size check and the
230
+ // read would otherwise let readFile allocate without a bound.
231
+ const buffer = Buffer.allocUnsafe(MAX_CHECK_BYTES + 1);
232
+ let offset = 0;
233
+ while (offset < buffer.length) {
234
+ const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, null);
235
+ if (bytesRead === 0)
236
+ break;
237
+ offset += bytesRead;
238
+ }
239
+ if (offset > MAX_CHECK_BYTES) {
240
+ throw new WorkspacePathError(`file exceeds the ${MAX_CHECK_BYTES}-byte check limit: ${requestedPath}`);
241
+ }
242
+ return buffer.subarray(0, offset);
243
+ }
244
+ finally {
245
+ await handle.close();
246
+ }
247
+ }
248
+ /** True when the run-relative path is a regular file or a directory; special files are errors. */
249
+ export async function runPathExists(root, requestedPath) {
250
+ const resolved = await resolveWorkspacePath(root, requestedPath);
251
+ try {
252
+ const stats = await lstat(resolved);
253
+ if (stats.isFile() || stats.isDirectory()) {
254
+ return true;
255
+ }
256
+ throw new WorkspacePathError(`not a regular file or directory: ${requestedPath}`);
257
+ }
258
+ catch (error) {
259
+ if (isMissing(error)) {
260
+ return false;
261
+ }
262
+ throw error;
263
+ }
264
+ }
265
+ export function requireConfigurationPath(declaringDir, relativePath, label) {
266
+ if (relativePath.startsWith("/") || relativePath.includes("\0")) {
267
+ throw new ConfigError(`${label} must be a relative path`);
268
+ }
269
+ return resolve(declaringDir, relativePath);
270
+ }
271
+ export function isWithin(root, target) {
272
+ const path = relative(root, target);
273
+ return path === "" || (!path.startsWith(".." + sep) && path !== ".." && !path.startsWith(sep));
274
+ }
275
+ export function isMissing(error) {
276
+ return (typeof error === "object" &&
277
+ error !== null &&
278
+ "code" in error &&
279
+ (error.code === "ENOENT" || error.code === "ENOTDIR"));
280
+ }
281
+ /** The identity a filesystem uses for one file, independent of the spelling that reached it. */
282
+ export function fileIdentity(info) {
283
+ return `${info.dev}:${info.ino}`;
284
+ }
285
+ /** True when `relativePath` is or lies under any protected HOME-relative path. */
286
+ export function isProtectedHomePath(relativePath, protectedPaths) {
287
+ if (protectedPaths.length === 0)
288
+ return false;
289
+ const candidate = normalizeProtectedPath(relativePath);
290
+ if (candidate.length === 0)
291
+ return false;
292
+ return protectedPaths.some((entry) => {
293
+ const excluded = normalizeProtectedPath(entry);
294
+ return excluded.length > 0 && (candidate === excluded || candidate.startsWith(`${excluded}/`));
295
+ });
296
+ }
297
+ function normalizeProtectedPath(path) {
298
+ const cleaned = path.replace(/^\/+/u, "").replace(/\/+$/u, "");
299
+ if (cleaned.length === 0)
300
+ return "";
301
+ const normalized = posix.normalize(cleaned).replace(/\/+$/u, "");
302
+ if (normalized === ".")
303
+ return "";
304
+ return process.platform === "darwin" ? normalized.toLowerCase() : normalized;
305
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The package's public surface: the contracts a runner or checker implements, the evidence types
3
+ * they exchange with the engine, the trace derivations a checker can reuse, and the evidence
4
+ * access a built-in checker uses. Everything not exported here is internal; a built-in that
5
+ * needs something absent from this file is a missing capability, not a private exception.
6
+ */
7
+ export type { Checker, CheckerContext, CheckerDefinition, CheckResult, CheckSandbox, CheckSandboxOutcome, CheckStatus, HomeProtection, ImplementationContext, MockRecord, MockWiring, PreparedRunner, Runner, RunnerContext, RunnerDefinition, RunnerOutcome, RunnerTokens, RunnerUsage, TraceEntry, } from "./engine/registry.js";
8
+ export type { EnvSource } from "./engine/env-source.js";
9
+ export type { RunVariables, ValueSource } from "./engine/values.js";
10
+ export { ConfigError, expectMockArgs, expectMockTarget, mockTargetIdentity, type ImplementationRecord, type MockArgs, type MockArgument, type MockPattern, type PatternSyntax, } from "./engine/config.js";
11
+ export { compileMockArgs } from "./engine/mock-match.js";
12
+ export { patternListSchema, patternSyntaxSchema, runFilePathSchema, runRelativePathSchema } from "./engine/params.js";
13
+ export { searches } from "./engine/regex.js";
14
+ export { MAX_CHECK_BYTES, WorkspacePathError, assertRunRoot, fileIdentity, isMissing, isProtectedHomePath, readRunFile, readRunTree, resolveWorkspacePath, runPathExists, type RunEntryKind, type RunRoot, type RunTree, type RunTreeEntry, } from "./engine/workspace.js";
15
+ export { messageText } from "./engine/messages.js";
16
+ export { shellSkillAccess, skillConsultations, type ShellSkillAccess, type SkillConsultation, type SkillSources, } from "./engine/skills.js";
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { ConfigError, expectMockArgs, expectMockTarget, mockTargetIdentity, } from "./engine/config.js";
2
+ export { compileMockArgs } from "./engine/mock-match.js";
3
+ export { patternListSchema, patternSyntaxSchema, runFilePathSchema, runRelativePathSchema } from "./engine/params.js";
4
+ export { searches } from "./engine/regex.js";
5
+ export { MAX_CHECK_BYTES, WorkspacePathError, assertRunRoot, fileIdentity, isMissing, isProtectedHomePath, readRunFile, readRunTree, resolveWorkspacePath, runPathExists, } from "./engine/workspace.js";
6
+ export { messageText } from "./engine/messages.js";
7
+ export { shellSkillAccess, skillConsultations, } from "./engine/skills.js";
@@ -0,0 +1,13 @@
1
+ import { type ChildProcessWithoutNullStreams } from "node:child_process";
2
+ export interface SandboxSpawnOptions {
3
+ readonly policyPath: string;
4
+ readonly command: string;
5
+ readonly args: readonly string[];
6
+ readonly cwd: string;
7
+ readonly env: NodeJS.ProcessEnv;
8
+ }
9
+ /**
10
+ * Launch a command inside the Seatbelt sandbox as its own process group.
11
+ * The process group lets the owner terminate the harness and its children.
12
+ */
13
+ export declare function spawnSandboxed(options: SandboxSpawnOptions): ChildProcessWithoutNullStreams;
@@ -0,0 +1,14 @@
1
+ import { spawn } from "node:child_process";
2
+ import { sandboxExecutablePath, sandboxLaunchCommand } from "./policy.js";
3
+ /**
4
+ * Launch a command inside the Seatbelt sandbox as its own process group.
5
+ * The process group lets the owner terminate the harness and its children.
6
+ */
7
+ export function spawnSandboxed(options) {
8
+ return spawn(sandboxExecutablePath(), sandboxLaunchCommand(options.policyPath, options.command, options.args), {
9
+ cwd: options.cwd,
10
+ env: options.env,
11
+ stdio: ["pipe", "pipe", "pipe"],
12
+ detached: true,
13
+ });
14
+ }
@@ -0,0 +1,33 @@
1
+ export declare const SYSTEM_PATH: readonly ["/usr/bin", "/bin", "/usr/sbin", "/sbin"];
2
+ export interface SandboxPolicy {
3
+ /** Read and write access. */
4
+ readonly writableRoots: readonly string[];
5
+ /** Read-only access. */
6
+ readonly readableRoots: readonly string[];
7
+ /**
8
+ * Read everything the host user can read, as the check sandbox does after the evaluated agent
9
+ * stopped. It replaces `readableRoots` for the read clauses.
10
+ */
11
+ readonly readAll?: boolean;
12
+ /** Read-only single files, such as a launcher script. */
13
+ readonly readableFiles?: readonly string[];
14
+ /** Executables the sandbox may not start, such as the real binary behind a mocked command. */
15
+ readonly denyExecutables?: readonly string[];
16
+ /** Interactive terminal device; allow termios mode changes, not arbitrary ioctl operations. */
17
+ readonly terminal?: string;
18
+ readonly allowNetwork: boolean;
19
+ }
20
+ /** Add macOS system access and current-terminal handling to caller-owned roots. */
21
+ export declare function createSandboxPolicy(options: Pick<SandboxPolicy, "writableRoots" | "readableRoots" | "allowNetwork" | "denyExecutables"> & {
22
+ readonly interactive: boolean;
23
+ }): SandboxPolicy;
24
+ /**
25
+ * Render a deny-default macOS Seatbelt profile. Reads are limited to explicit
26
+ * system/toolchain roots and run directories; writes are limited to run state.
27
+ */
28
+ export declare function renderSeatbeltPolicy(policy: SandboxPolicy): string;
29
+ /** Write a profile outside the evaluated workspace, then return its path. */
30
+ export declare function writeSeatbeltPolicy(directory: string, policy: SandboxPolicy): Promise<string>;
31
+ export declare function assertSeatbeltAvailable(): void;
32
+ export declare function sandboxExecutablePath(): string;
33
+ export declare function sandboxLaunchCommand(policyPath: string, command: string, args: readonly string[]): string[];
@@ -0,0 +1,131 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { realpathSync } from "node:fs";
3
+ import { open } from "node:fs/promises";
4
+ import { dirname, join, resolve } from "node:path";
5
+ export const SYSTEM_PATH = ["/usr/bin", "/bin", "/usr/sbin", "/sbin"];
6
+ /** Add macOS system access and current-terminal handling to caller-owned roots. */
7
+ export function createSandboxPolicy(options) {
8
+ const terminal = options.interactive && process.stdin.isTTY
9
+ ? execFileSync("/usr/bin/tty", { stdio: ["inherit", "pipe", "ignore"], encoding: "utf8" }).trim()
10
+ : undefined;
11
+ return {
12
+ writableRoots: options.writableRoots,
13
+ readableRoots: [
14
+ "/System",
15
+ "/usr",
16
+ "/bin",
17
+ "/sbin",
18
+ "/private/etc",
19
+ "/Library",
20
+ "/dev",
21
+ "/private/var/select",
22
+ "/private/var/db/timezone",
23
+ ...(options.allowNetwork ? ["/private/var/db/mds"] : []),
24
+ ...options.readableRoots,
25
+ ],
26
+ readableFiles: ["/var", "/etc"],
27
+ ...(options.denyExecutables === undefined ? {} : { denyExecutables: options.denyExecutables }),
28
+ allowNetwork: options.allowNetwork,
29
+ ...(terminal === undefined ? {} : { terminal }),
30
+ };
31
+ }
32
+ /**
33
+ * Render a deny-default macOS Seatbelt profile. Reads are limited to explicit
34
+ * system/toolchain roots and run directories; writes are limited to run state.
35
+ */
36
+ export function renderSeatbeltPolicy(policy) {
37
+ const writable = normalize(policy.writableRoots);
38
+ const readable = normalize([...policy.readableRoots, ...policy.writableRoots]);
39
+ const terminals = policy.terminal === undefined ? [] : normalize([policy.terminal, "/dev/tty"]);
40
+ const files = normalize([...(policy.readableFiles ?? []), ...terminals]);
41
+ const readClauses = [
42
+ '(literal "/")',
43
+ ...readable.map((path) => `(subpath ${quote(path)})`),
44
+ ...files.map((path) => `(literal ${quote(path)})`),
45
+ ];
46
+ const metadata = new Set();
47
+ for (const path of [...readable, ...files]) {
48
+ let current = dirname(path);
49
+ while (current !== "/" && !metadata.has(current)) {
50
+ metadata.add(current);
51
+ current = dirname(current);
52
+ }
53
+ metadata.add("/");
54
+ }
55
+ const denied = normalize(policy.denyExecutables ?? []);
56
+ const lines = [
57
+ "(version 1)",
58
+ "(deny default)",
59
+ "(allow process-exec*)",
60
+ ...(denied.length === 0
61
+ ? []
62
+ : [`(deny process-exec ${denied.map((path) => `(literal ${quote(path)})`).join(" ")})`]),
63
+ "(allow process-fork)",
64
+ "(allow signal (target same-sandbox))",
65
+ "(allow sysctl-read)",
66
+ policy.readAll === true ? "(allow file-read*)" : `(allow file-read* ${readClauses.join(" ")})`,
67
+ ];
68
+ if (policy.readAll !== true && metadata.size > 0) {
69
+ lines.push(`(allow file-read-metadata ${[...metadata]
70
+ .sort()
71
+ .map((path) => `(literal ${quote(path)})`)
72
+ .join(" ")})`);
73
+ }
74
+ const terminalClauses = terminals.map((path) => `(literal ${quote(path)})`);
75
+ const writeClauses = [
76
+ ...writable.map((path) => `(subpath ${quote(path)})`),
77
+ ...terminalClauses,
78
+ '(literal "/dev/null")',
79
+ ];
80
+ lines.push(`(allow file-write* ${writeClauses.join(" ")})`);
81
+ if (terminals.length > 0) {
82
+ lines.push(`(allow file-ioctl (require-all (require-any ${terminalClauses.join(" ")}) (ioctl-command TIOCSETA TIOCSETAW TIOCSETAF)))`);
83
+ }
84
+ if (policy.allowNetwork) {
85
+ lines.push("(allow network-outbound)",
86
+ // System TLS trust evaluation and directory membership for native HTTPS stacks (e.g. Rust/Security.framework).
87
+ '(allow mach-lookup (global-name "com.apple.SecurityServer" "com.apple.trustd.agent" "com.apple.system.opendirectoryd.membership"))');
88
+ }
89
+ return lines.join("\n") + "\n";
90
+ }
91
+ /** Write a profile outside the evaluated workspace, then return its path. */
92
+ export async function writeSeatbeltPolicy(directory, policy) {
93
+ const path = join(directory, "sandbox.sb");
94
+ const handle = await open(path, "w", 0o600);
95
+ try {
96
+ await handle.writeFile(renderSeatbeltPolicy(policy), "utf8");
97
+ }
98
+ finally {
99
+ await handle.close();
100
+ }
101
+ return resolve(path);
102
+ }
103
+ export function assertSeatbeltAvailable() {
104
+ if (process.platform !== "darwin") {
105
+ throw new Error("the macOS Seatbelt backend requires darwin");
106
+ }
107
+ }
108
+ export function sandboxExecutablePath() {
109
+ assertSeatbeltAvailable();
110
+ return "/usr/bin/sandbox-exec";
111
+ }
112
+ export function sandboxLaunchCommand(policyPath, command, args) {
113
+ return ["-f", policyPath, "--", command, ...args];
114
+ }
115
+ function normalize(paths) {
116
+ const values = new Set();
117
+ for (const path of paths) {
118
+ const resolved = resolve(path);
119
+ values.add(resolved);
120
+ try {
121
+ values.add(realpathSync(resolved));
122
+ }
123
+ catch {
124
+ // The path may not exist yet; the resolved form still scopes it.
125
+ }
126
+ }
127
+ return [...values].sort();
128
+ }
129
+ function quote(value) {
130
+ return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
131
+ }
@@ -0,0 +1,26 @@
1
+ import { type ChildProcess } from "node:child_process";
2
+ import type { Readable } from "node:stream";
3
+ import { type SandboxPolicy } from "./policy.js";
4
+ export interface SupervisedProcess {
5
+ readonly child: ChildProcess;
6
+ /** Native workload result, not the supervisor's intentional SIGKILL exit. */
7
+ readonly completion: Promise<number>;
8
+ readonly stop: () => Promise<void>;
9
+ /**
10
+ * The workload's private report pipe at FD 5, present only when requested. FD 5 is not a
11
+ * standard stream, so it stays out of the workload's own output; `spawn` closes it for the
12
+ * workload's children, so untrusted descendants cannot write it.
13
+ */
14
+ readonly report?: Readable;
15
+ }
16
+ /** Start a sandbox-wide-cleanup supervisor; never execute its program on the host. */
17
+ export declare function spawnSupervised(options: {
18
+ readonly policy: SandboxPolicy;
19
+ readonly policyDirectory: string;
20
+ readonly command: readonly [string, ...string[]];
21
+ readonly cwd: string;
22
+ readonly env: NodeJS.ProcessEnv;
23
+ readonly interactive: boolean;
24
+ /** Add a private report pipe at FD 5 for the workload, exposed as `report`. */
25
+ readonly report?: boolean;
26
+ }): Promise<SupervisedProcess>;
@@ -0,0 +1,98 @@
1
+ import { spawn } from "node:child_process";
2
+ import { readFile } from "node:fs/promises";
3
+ import { setTimeout as delay } from "node:timers/promises";
4
+ import { sandboxExecutablePath, sandboxLaunchCommand, writeSeatbeltPolicy } from "./policy.js";
5
+ const SUPERVISOR_ASSET = new URL("./supervisor.sh", import.meta.url);
6
+ /** Start a sandbox-wide-cleanup supervisor; never execute its program on the host. */
7
+ export async function spawnSupervised(options) {
8
+ const executable = sandboxExecutablePath();
9
+ const [policyPath, supervisor] = await Promise.all([
10
+ writeSeatbeltPolicy(options.policyDirectory, options.policy),
11
+ readFile(SUPERVISOR_ASSET, "utf8"),
12
+ ]);
13
+ const mode = options.interactive ? "inherit" : "pipe";
14
+ const stdio = [mode, mode, mode, "pipe"];
15
+ // FD 4 is the supervisor's saved stdin; the optional report pipe is FD 5.
16
+ if (options.report === true)
17
+ stdio.push("ignore", "pipe");
18
+ const child = spawn(executable, sandboxLaunchCommand(policyPath, "/bin/sh", ["-c", supervisor, "agent-evals", ...options.command]), {
19
+ cwd: options.cwd,
20
+ env: options.env,
21
+ stdio,
22
+ });
23
+ // stdio[3] is explicitly a pipe above; Node's general stdio type does not
24
+ // distinguish its read direction from other possible descriptor kinds.
25
+ const control = child.stdio[3];
26
+ // Node's type fixes `stdio` at five entries; a longer array is still honoured at runtime.
27
+ const report = options.report === true
28
+ ? child.stdio[5]
29
+ : undefined;
30
+ let status = "";
31
+ const controlEnded = new Promise((resolve, reject) => {
32
+ control.on("data", (chunk) => {
33
+ status += chunk.toString("utf8");
34
+ if (status.length > 16) {
35
+ reject(new Error("invalid sandbox supervisor completion record"));
36
+ control.destroy();
37
+ }
38
+ });
39
+ control.once("end", resolve);
40
+ control.once("error", reject);
41
+ });
42
+ let exited = false;
43
+ const exit = new Promise((resolve, reject) => {
44
+ child.once("exit", () => {
45
+ exited = true;
46
+ resolve();
47
+ });
48
+ child.once("error", (error) => {
49
+ exited = true;
50
+ reject(error);
51
+ });
52
+ });
53
+ const completion = Promise.all([exit, controlEnded]).then(() => {
54
+ if (!/^(?:0|[1-9][0-9]{0,2})\n$/.test(status) || Number(status) > 255) {
55
+ throw new Error("sandbox supervisor exited without a workload completion record");
56
+ }
57
+ return Number(status);
58
+ });
59
+ // Query operations intentionally stop a still-running ACP server, so they
60
+ // need not await its native exit result. Rejections remain observable to login.
61
+ completion.catch(() => { });
62
+ const waitForExit = async () => {
63
+ const deadline = new AbortController();
64
+ try {
65
+ return await Promise.race([exit.then(() => true), delay(1000, false, { signal: deadline.signal })]);
66
+ }
67
+ finally {
68
+ deadline.abort();
69
+ }
70
+ };
71
+ let stopping;
72
+ const stop = () => (stopping ??= (async () => {
73
+ try {
74
+ if (!exited) {
75
+ child.kill("SIGCONT");
76
+ child.kill("SIGTERM");
77
+ if (!(await waitForExit())) {
78
+ child.kill("SIGKILL");
79
+ const reaped = await waitForExit();
80
+ throw new Error(reaped
81
+ ? "sandbox supervisor did not perform cleanup before forced termination"
82
+ : "sandbox supervisor did not exit after SIGKILL");
83
+ }
84
+ }
85
+ else {
86
+ await exit;
87
+ }
88
+ }
89
+ finally {
90
+ child.stdin?.destroy();
91
+ child.stdout?.destroy();
92
+ child.stderr?.destroy();
93
+ control.destroy();
94
+ report?.destroy();
95
+ }
96
+ })());
97
+ return { child, completion, stop, ...(report === undefined ? {} : { report }) };
98
+ }
@@ -0,0 +1,13 @@
1
+ # Deliberately not a standalone executable: only passed to /bin/sh -c inside
2
+ # sandbox-exec with our generated same-sandbox signal policy. FD 3 is the
3
+ # private completion channel; the workload never inherits it. Save stdin on
4
+ # FD 4 because asynchronous shell commands otherwise receive /dev/null.
5
+ trap 'kill -KILL -- -1' TERM INT HUP
6
+ exec 4<&0
7
+ "$@" <&4 3>&- 4<&- &
8
+ child=$!
9
+ exec 4<&-
10
+ wait "$child"
11
+ status=$?
12
+ printf '%s\n' "$status" >&3
13
+ kill -KILL -- -1