@lelouchhe/agent-evals 0.2.0 → 0.3.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 (60) hide show
  1. package/README.md +25 -20
  2. package/dist/cli.js +39 -4
  3. package/dist/engine/check-runner.js +18 -3
  4. package/dist/engine/check-sandbox.js +9 -6
  5. package/dist/engine/env-source.js +82 -14
  6. package/dist/engine/files.js +2 -1
  7. package/dist/engine/mocks.js +72 -46
  8. package/dist/engine/registry.d.ts +2 -0
  9. package/dist/engine/run.js +3 -4
  10. package/dist/engine/skills.js +12 -5
  11. package/dist/engine/view.js +6 -3
  12. package/dist/engine/workspace.js +13 -28
  13. package/dist/platform/index.d.ts +31 -0
  14. package/dist/platform/index.js +88 -0
  15. package/dist/platform/linux/index.d.ts +2 -0
  16. package/dist/platform/linux/index.js +40 -0
  17. package/dist/platform/linux/launch.d.ts +8 -0
  18. package/dist/platform/linux/launch.js +25 -0
  19. package/dist/platform/linux/policy.d.ts +46 -0
  20. package/dist/platform/linux/policy.js +388 -0
  21. package/dist/platform/linux/supervise.d.ts +8 -0
  22. package/dist/platform/linux/supervise.js +124 -0
  23. package/dist/platform/macos/index.d.ts +2 -0
  24. package/dist/platform/macos/index.js +59 -0
  25. package/dist/platform/macos/launch.d.ts +2 -8
  26. package/dist/platform/macos/launch.js +5 -3
  27. package/dist/platform/macos/policy.d.ts +3 -21
  28. package/dist/platform/macos/policy.js +5 -2
  29. package/dist/platform/macos/supervise.d.ts +3 -25
  30. package/dist/platform/posix-forwarder-client.mjs +129 -0
  31. package/dist/platform/posix-forwarder.sh +9 -0
  32. package/dist/platform/posix-helpers.d.ts +22 -0
  33. package/dist/platform/posix-helpers.js +97 -0
  34. package/dist/platform/types.d.ts +118 -0
  35. package/dist/platform/types.js +1 -0
  36. package/dist/platform/windows/forwarder-client.mjs +165 -0
  37. package/dist/platform/windows/forwarder.cmd +3 -0
  38. package/dist/platform/windows/forwarder.ps1 +2 -0
  39. package/dist/platform/windows/forwarder.sh +2 -0
  40. package/dist/platform/windows/index.d.ts +2 -0
  41. package/dist/platform/windows/index.js +225 -0
  42. package/dist/platform/windows/launch.d.ts +3 -0
  43. package/dist/platform/windows/launch.js +30 -0
  44. package/dist/platform/windows/policy.d.ts +17 -0
  45. package/dist/platform/windows/policy.js +155 -0
  46. package/dist/platform/windows/setup.ps1 +112 -0
  47. package/dist/platform/windows/supervise.d.ts +2 -0
  48. package/dist/platform/windows/supervise.js +142 -0
  49. package/dist/platform/windows/win-sandbox.exe +0 -0
  50. package/dist/runners/acp/commands.js +2 -3
  51. package/dist/runners/acp/environment.d.ts +1 -7
  52. package/dist/runners/acp/environment.js +18 -48
  53. package/dist/runners/acp/index.js +1 -1
  54. package/dist/runners/acp/session.d.ts +1 -1
  55. package/dist/runners/pi/index.js +2 -2
  56. package/dist/runners/pi/session.d.ts +1 -1
  57. package/dist/runners/pi/session.js +27 -44
  58. package/dist/runners/pi/supervisor.js +1 -0
  59. package/package.json +5 -3
  60. package/dist/engine/forwarder.sh +0 -61
package/README.md CHANGED
@@ -5,19 +5,19 @@
5
5
 
6
6
  A toolkit for evaluating AI agent systems on the real CLI and harness layer.
7
7
 
8
- Requirements: macOS with `sandbox-exec` and Node.js 24+. The package declares `os: darwin`, so npm refuses to install it on another platform; the CLI is published as `@lelouchhe/agent-evals`, and a run additionally needs an invocation `.env` and prepared harness directories, per [Setup](https://github.com/LelouchHe/agent-evals/blob/main/docs/setup.md). Version 0.1.1 is the first published state — the toolkit, not a finished instrument; [Roadmap](https://github.com/LelouchHe/agent-evals/blob/main/docs/roadmap.md) lists what is still open.
8
+ Requirements: Node.js 24+ on macOS (`sandbox-exec`), Linux, WSL2 (`bubblewrap` / `bwrap` with unprivileged user namespaces), or native Windows (`win-sandbox.exe`; WSL1 is not supported). See [Platforms](https://github.com/LelouchHe/agent-evals/blob/main/docs/platforms.md) for backend details and [Setup](https://github.com/LelouchHe/agent-evals/blob/main/docs/setup.md) for `.env` and harness directories. [Roadmap](https://github.com/LelouchHe/agent-evals/blob/main/docs/roadmap.md) lists what is still open.
9
9
 
10
10
  > **Status: pre-1.0.** Breaking changes ship in a minor release until 1.0.
11
11
 
12
12
  ## Why Agent Evals
13
13
 
14
14
  - **Evaluate the whole agent system, not a bare model API.** Outcomes depend on the model _plus_ its harness, skills, instructions and tool loop. One generic [ACP runner](https://github.com/LelouchHe/agent-evals/blob/main/docs/configuration.md#acp-runner-type-acp) drives unmodified [Pi](https://github.com/LelouchHe/agent-evals/blob/main/examples/agents/pi.yml), [Claude Code](https://github.com/LelouchHe/agent-evals/blob/main/examples/agents/claude.yml) and [GitHub Copilot CLI](https://github.com/LelouchHe/agent-evals/blob/main/examples/agents/copilot.yml) side by side, so changing a skill, instruction, flag or harness is a controlled experiment.
15
- - **Host-native OS sandboxing, not Linux containers.** Each run executes on the host under macOS Seatbelt in its own run root with a private `HOME` and workspace ([layout](https://github.com/LelouchHe/agent-evals/blob/main/docs/setup.md#how-isolated-harness-homes-work)). Host toolchains and platform behavior stay real, while operator dotfiles, login keychains, rubrics and check-time acceptance tests stay unreachable to the agent.
15
+ - **Host-native OS sandboxing, not Linux containers.** Each run executes on the host under macOS Seatbelt, Linux `bubblewrap`, or Windows sandbox users (`win-sandbox.exe`) in its own run root with a private `HOME` and workspace ([layout](https://github.com/LelouchHe/agent-evals/blob/main/docs/setup.md#how-isolated-harness-homes-work)). Host toolchains and platform behavior stay real, while operator dotfiles, login keychains, rubrics and check-time acceptance tests stay unreachable to the agent.
16
16
  - **Three evidence sources, deterministic first.** Checks read workspace side effects (`file`, sandboxed `shell`), host-recorded calls to [mocked commands](https://github.com/LelouchHe/agent-evals/blob/main/docs/mocks.md) (`mock`) and the run's trace (`trace`), with an LLM `judge` only where qualitative judgment is needed. A `noop` baseline runner catches checks that pass without an agent.
17
17
 
18
18
  ## What a Case Looks Like
19
19
 
20
- A case is one YAML file: a task, a prepared environment, and the checks that judge what the run left behind. Abridged from the [worked example](https://github.com/LelouchHe/agent-evals/blob/main/examples/cases/deploy-runbook/case.yml):
20
+ A case is one YAML file: a task, a prepared environment, and the checks that judge what the run left behind. Abridged from the [worked example](https://github.com/LelouchHe/agent-evals/blob/main/examples/cases/deploy-runbook-posix/case.yml):
21
21
 
22
22
  ```yaml
23
23
  input: Our deploy failed. Read deploy.log, confirm the release state with `deployctl status`, then write the cause and the commands to fix it into diagnosis.md.
@@ -71,36 +71,39 @@ npm install -g @lelouchhe/agent-evals # or: npx @lelouchhe/agent-evals
71
71
  agent-evals --help
72
72
  ```
73
73
 
74
- Running a case is macOS-only and needs an invocation `.env` plus a prepared harness directory ([Setup](https://github.com/LelouchHe/agent-evals/blob/main/docs/setup.md)). The worked example below runs from a checkout, because its fixtures and agent files live in the repository.
74
+ > **Note on the bundled Windows binary:** Published npm packages include a small prebuilt Windows helper (`dist/platform/windows/win-sandbox.exe`, ~400 KB), compiled from [`native/win-sandbox/`](https://github.com/LelouchHe/agent-evals/tree/main/native/win-sandbox) in CI with npm provenance so native Windows installs work without Rust. It is **only used on native Windows** (`win32`) and is never executed on macOS or Linux.
75
75
 
76
- Follow [Setup](https://github.com/LelouchHe/agent-evals/blob/main/docs/setup.md) once to configure `.env` and prepare the harness directories you want to run, then inspect and run the worked example ([`examples/cases/deploy-runbook`](https://github.com/LelouchHe/agent-evals/blob/main/examples/cases/deploy-runbook/case.yml) — seven named cases across Pi, Claude Code, Copilot CLI and `noop`, exercising project skills, every `mocks.shell` action, hidden check-time `shell` acceptance scripts and all five checkers):
76
+ Running a case supports macOS, Linux, WSL2, and native Windows ([Platforms](https://github.com/LelouchHe/agent-evals/blob/main/docs/platforms.md)) and needs an invocation `.env` plus a prepared harness directory ([Setup](https://github.com/LelouchHe/agent-evals/blob/main/docs/setup.md)). On native Windows, run `agent-evals setup sandbox` once from an Administrator prompt before your first evaluation. The worked example below runs from a checkout, because its fixtures and agent files live in the repository.
77
+
78
+ Follow [Setup](https://github.com/LelouchHe/agent-evals/blob/main/docs/setup.md) once to configure `.env` and prepare the harness directories you want to run, then inspect and run the worked example ([`examples/cases/deploy-runbook-posix`](https://github.com/LelouchHe/agent-evals/blob/main/examples/cases/deploy-runbook-posix/case.yml) — seven named cases across Pi, Claude Code, Copilot CLI and `noop`, exercising project skills, `~/` HOME placement, every `mocks.shell` action, hidden check-time `shell` acceptance scripts and all five checkers):
77
79
 
78
80
  ```sh
79
81
  npm ci
80
82
  cp .env.example .env # fill in harness paths and keys (see docs/setup.md)
81
- npm run eval -- view examples/cases/deploy-runbook/case.yml --case pi-with-skill
83
+ npm run eval -- view examples/cases/deploy-runbook-posix/case.yml --case pi-with-skill
82
84
  npm run eval -- config examples/agents/pi.yml
83
- npm run eval -- run examples/cases/deploy-runbook/case.yml --case pi-with-skill
84
- npm run eval -- run examples/cases/deploy-runbook/case.yml --reps 3 --jobs 3 --retain on-failure --results-dir /tmp/deploy-runbook
85
+ npm run eval -- run examples/cases/deploy-runbook-posix/case.yml --case pi-with-skill
86
+ npm run eval -- run examples/cases/deploy-runbook-posix/case.yml --reps 3 --jobs 3 --retain on-failure --results-dir /tmp/deploy-runbook
85
87
  npm run eval -- report --matrix /tmp/deploy-runbook # after a sweep: one row per check
86
88
  ```
87
89
 
88
90
  Additional examples showcase other angles of the toolkit:
89
91
 
90
- - [`deploy-runbook-native`](https://github.com/LelouchHe/agent-evals/blob/main/examples/cases/deploy-runbook-native/case.yml) runs the same task through the native Pi runner using an installed `pi` CLI and provider key alone, with `judge` inheriting the case's runner.
91
- - [`notes-home`](https://github.com/LelouchHe/agent-evals/blob/main/examples/cases/notes-home/case.yml) demonstrates `~/` HOME placement, disjoint top-level and case `files` merging, directory-level `changed: false` restraints, and glob `path` checks (`{decisions,changelog}.md`).
92
+ - [`deploy-runbook-windows`](https://github.com/LelouchHe/agent-evals/blob/main/examples/cases/deploy-runbook-windows/case.yml) runs the same ACP evaluation natively on Windows with PowerShell checks, `.cmd` mocks, and `~/` HOME placement.
93
+ - [`deploy-runbook-native-pi`](https://github.com/LelouchHe/agent-evals/blob/main/examples/cases/deploy-runbook-native-pi/case.yml) runs the same task through the native Pi runner using an installed `pi` CLI and provider key alone, with `judge` inheriting the case's runner.
92
94
 
93
95
  ## Documentation
94
96
 
95
- | Document | Question it answers |
96
- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
97
- | [Setup](https://github.com/LelouchHe/agent-evals/blob/main/docs/setup.md) | How do I install the CLI, configure `.env`, and prepare Pi, Claude Code and Copilot? |
98
- | [Writing Cases](https://github.com/LelouchHe/agent-evals/blob/main/docs/cases.md) | How should tasks, fixtures, baselines and assertions be designed? |
99
- | [Configuration Reference](https://github.com/LelouchHe/agent-evals/blob/main/docs/configuration.md) | How do YAML files, placeholders, runners, checkers and result records work? |
100
- | [Mocks](https://github.com/LelouchHe/agent-evals/blob/main/docs/mocks.md) | How do I substitute or spy on shell commands, and what does `mocks.json` contain? |
101
- | [Extensions](https://github.com/LelouchHe/agent-evals/blob/main/docs/extensions.md) | How do I write and load a custom runner or checker? |
102
- | [Architecture](https://github.com/LelouchHe/agent-evals/blob/main/docs/architecture.md) | How do the modules cooperate, and what runtime/development limits apply today? |
103
- | [Roadmap](https://github.com/LelouchHe/agent-evals/blob/main/docs/roadmap.md) | What is planned next (M6 sandbox config, M7 MCP mocks), and where are past archives? |
97
+ | Document | Question it answers |
98
+ | --------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
99
+ | [Setup](https://github.com/LelouchHe/agent-evals/blob/main/docs/setup.md) | How do I install the CLI, configure `.env`, and prepare Pi, Claude Code and Copilot? |
100
+ | [Writing Cases](https://github.com/LelouchHe/agent-evals/blob/main/docs/cases.md) | How should tasks, fixtures, baselines and assertions be designed? |
101
+ | [Configuration Reference](https://github.com/LelouchHe/agent-evals/blob/main/docs/configuration.md) | How do YAML files, placeholders, runners, checkers and result records work? |
102
+ | [Mocks](https://github.com/LelouchHe/agent-evals/blob/main/docs/mocks.md) | How do I substitute or spy on shell commands, and what does `mocks.json` contain? |
103
+ | [Extensions](https://github.com/LelouchHe/agent-evals/blob/main/docs/extensions.md) | How do I write and load a custom runner or checker? |
104
+ | [Platforms](https://github.com/LelouchHe/agent-evals/blob/main/docs/platforms.md) | Which host OSes are supported (macOS, Linux, WSL2, native Windows) and how each sandbox works? |
105
+ | [Architecture](https://github.com/LelouchHe/agent-evals/blob/main/docs/architecture.md) | How do the modules cooperate, and what runtime/development limits apply today? |
106
+ | [Roadmap](https://github.com/LelouchHe/agent-evals/blob/main/docs/roadmap.md) | What is planned next (M6 sandbox config, M7 MCP mocks), and where are past archives? |
104
107
 
105
108
  Delivered milestone records (`M1`–`M5`) are preserved under [`docs/archive/`](https://github.com/LelouchHe/agent-evals/blob/main/docs/archive/).
106
109
 
@@ -115,7 +118,9 @@ Serialize checkout build/test/eval commands because `npm run build` replaces `di
115
118
 
116
119
  ## Releasing
117
120
 
118
- [CI](https://github.com/LelouchHe/agent-evals/blob/main/.github/workflows/ci.yml) runs the gate on macOS for every pull request and push to `main`. A release is a tag: push `vX.Y.Z` matching `package.json`'s version, and [publish](https://github.com/LelouchHe/agent-evals/blob/main/.github/workflows/publish.yml) re-runs that gate on macOS, publishes `@lelouchhe/agent-evals` to npm with provenance, and creates the GitHub release. The workflow needs the `NPM_TOKEN` repository secret: an npm token with publish rights for the `@lelouchhe` scope. A scoped package defaults to restricted, so the publish command passes `--access public`.
121
+ [CI](https://github.com/LelouchHe/agent-evals/blob/main/.github/workflows/ci.yml) runs the deterministic `check` gate on macOS, Linux, and Windows for every pull request and push to `main`. It also defines an optional 3-OS live ACP `smoke` job (`pi-acp` running `deploy-runbook-posix` on macOS/Linux and `deploy-runbook-windows` on Windows): set the `OPENCODE_API_KEY` repository secret (`gh secret set OPENCODE_API_KEY`) to enable it on CI / `workflow_dispatch`, and remove the secret (`gh secret remove OPENCODE_API_KEY`) when you want `smoke` skipped automatically.
122
+
123
+ A release is a tag: push `vX.Y.Z` matching `package.json`'s version, and [publish](https://github.com/LelouchHe/agent-evals/blob/main/.github/workflows/publish.yml) re-runs that gate, publishes `@lelouchhe/agent-evals` to npm with provenance, and creates the GitHub release. The workflow needs the `NPM_TOKEN` repository secret: an npm token with publish rights for the `@lelouchhe` scope. A scoped package defaults to restricted, so the publish command passes `--access public`.
119
124
 
120
125
  ## License
121
126
 
package/dist/cli.js CHANGED
@@ -16,11 +16,12 @@ import { formatMatrix, formatReport } from "./engine/report.js";
16
16
  import { runOutcome } from "./engine/results.js";
17
17
  import { describePlacement } from "./engine/placement.js";
18
18
  import { formatResolvedCase } from "./engine/view.js";
19
+ import { setupSandbox } from "./platform/index.js";
19
20
  import { piRunner } from "./runners/pi/index.js";
20
21
  import { noopRunner } from "./runners/noop/index.js";
21
22
  import { runAgentCommand } from "./runners/acp/commands.js";
22
23
  import { acpRunner } from "./runners/acp/index.js";
23
- const USAGE = `Usage: agent-evals <command> <config.yml> [options]
24
+ const USAGE = `Usage: agent-evals <command> [arguments] [options]
24
25
 
25
26
  Commands:
26
27
  run <config.yml> Execute the selected case, or every case when --case is omitted
@@ -28,6 +29,7 @@ Commands:
28
29
  report <results-dir>... Print a session report from retained run records
29
30
  config <agent.yml> Query ACP configuration values without prompting
30
31
  login <agent.yml> Run the declared native command and save login files
32
+ setup <target> Prepare host prerequisites (sandbox)
31
33
 
32
34
  Options:
33
35
  --case <name> Named case to select (omitting selects every case in a cases document)
@@ -38,6 +40,7 @@ Options:
38
40
  --extension-dir <path> Trusted extension root, one implementation per subdirectory (repeatable)
39
41
  --files With view: list every placed and excluded path
40
42
  --matrix With report: one table of checks by case instead of the session report
43
+ --teardown With setup: remove host sandbox setup instead of provisioning it
41
44
  --version, -V Show version
42
45
  --help Show this help
43
46
 
@@ -98,6 +101,12 @@ async function main(argv) {
98
101
  process.off("SIGTERM", onSignal);
99
102
  }
100
103
  }
104
+ if (options.command === "setup") {
105
+ const output = await setupSandbox({ teardown: options.teardown });
106
+ if (output.length > 0)
107
+ process.stdout.write(output);
108
+ return 0;
109
+ }
101
110
  return await runCommand(options);
102
111
  }
103
112
  catch (error) {
@@ -245,6 +254,7 @@ function parseArguments(argv) {
245
254
  "extension-dir": { type: "string", multiple: true },
246
255
  files: { type: "boolean" },
247
256
  matrix: { type: "boolean" },
257
+ teardown: { type: "boolean" },
248
258
  reps: { type: "string" },
249
259
  jobs: { type: "string" },
250
260
  retain: { type: "string" },
@@ -264,15 +274,27 @@ function parseArguments(argv) {
264
274
  throw new VersionRequested();
265
275
  }
266
276
  const [command, rawConfigPath, ...unexpected] = positionals;
267
- if (command !== "run" && command !== "view" && command !== "report" && command !== "config" && command !== "login") {
277
+ if (command !== "run" &&
278
+ command !== "view" &&
279
+ command !== "report" &&
280
+ command !== "config" &&
281
+ command !== "login" &&
282
+ command !== "setup") {
268
283
  throw new ConfigError(command === undefined ? "a command is required" : `unknown command: ${command}`);
269
284
  }
270
285
  if (rawConfigPath === undefined) {
271
- throw new ConfigError(command === "report" ? "a results directory is required" : "a configuration file is required");
286
+ throw new ConfigError(command === "report"
287
+ ? "a results directory is required"
288
+ : command === "setup"
289
+ ? "a setup target is required (supported: sandbox)"
290
+ : "a configuration file is required");
272
291
  }
273
292
  if (command !== "report" && unexpected.length > 0) {
274
293
  throw new ConfigError(`unexpected argument: ${unexpected[0]}`);
275
294
  }
295
+ if (command === "setup" && rawConfigPath !== "sandbox") {
296
+ throw new ConfigError(`unknown setup target: ${rawConfigPath} (supported: sandbox)`);
297
+ }
276
298
  if ((command === "config" || command === "login") &&
277
299
  (values.case !== undefined ||
278
300
  values["results-dir"] !== undefined ||
@@ -297,6 +319,18 @@ function parseArguments(argv) {
297
319
  if (command !== "report" && values.matrix === true) {
298
320
  throw new ConfigError("--matrix applies only to report");
299
321
  }
322
+ if (command !== "setup" && values.teardown === true) {
323
+ throw new ConfigError("--teardown applies only to setup");
324
+ }
325
+ if (command === "setup" &&
326
+ (values.case !== undefined ||
327
+ values["results-dir"] !== undefined ||
328
+ extensionDirs.length > 0 ||
329
+ values.reps !== undefined ||
330
+ values.jobs !== undefined ||
331
+ values.retain !== undefined)) {
332
+ throw new ConfigError("setup accepts only a target and optional --teardown");
333
+ }
300
334
  if (command === "report" &&
301
335
  (values.case !== undefined ||
302
336
  values["results-dir"] !== undefined ||
@@ -311,12 +345,13 @@ function parseArguments(argv) {
311
345
  const retain = values.retain === undefined ? "none" : expectRetain(values.retain);
312
346
  return {
313
347
  command,
314
- configPath: resolve(rawConfigPath),
348
+ configPath: command === "setup" ? rawConfigPath : resolve(rawConfigPath),
315
349
  ...(values.case === undefined ? {} : { caseName: values.case }),
316
350
  ...(values["results-dir"] === undefined ? {} : { resultsDir: resolve(values["results-dir"]) }),
317
351
  extensionDirs,
318
352
  showFiles: values.files === true,
319
353
  matrix: values.matrix === true,
354
+ teardown: values.teardown === true,
320
355
  reps,
321
356
  jobs,
322
357
  retain,
@@ -1,15 +1,29 @@
1
1
  import { spawn } from "node:child_process";
2
- import { writeSync } from "node:fs";
2
+ import { closeSync, openSync, writeSync } from "node:fs";
3
3
  import { copyFile, lstat, mkdir, readdir, unlink } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
+ import { checkChildEnv } from "../platform/index.js";
5
6
  const [stagingDir, program, ...args] = process.argv.slice(2);
7
+ const REPORT_PIPE = process.env.AGENT_EVALS_REPORT_PIPE;
6
8
  let settled = false;
7
9
  function report(outcome) {
8
10
  if (settled)
9
11
  return;
10
12
  settled = true;
13
+ const line = JSON.stringify(outcome) + "\n";
11
14
  try {
12
- writeSync(5, JSON.stringify(outcome) + "\n");
15
+ if (typeof REPORT_PIPE === "string" && REPORT_PIPE.length > 0) {
16
+ const fd = openSync(REPORT_PIPE, "w");
17
+ try {
18
+ writeSync(fd, line);
19
+ }
20
+ finally {
21
+ closeSync(fd);
22
+ }
23
+ }
24
+ else {
25
+ writeSync(5, line);
26
+ }
13
27
  }
14
28
  catch {
15
29
  // Host closed the report pipe (for example on timeout or cancellation).
@@ -110,8 +124,9 @@ async function main() {
110
124
  try {
111
125
  const child = spawn(program, args, {
112
126
  cwd: process.cwd(),
113
- env: { PATH: process.env.PATH, HOME: process.env.HOME, TMPDIR: process.env.TMPDIR },
127
+ env: checkChildEnv(process.env),
114
128
  stdio: ["ignore", "inherit", "inherit"],
129
+ windowsHide: true,
115
130
  });
116
131
  child.on("error", (error) => {
117
132
  report({ kind: "failed", reason: `could not start ${program}: ${errorCode(error)}` });
@@ -1,11 +1,10 @@
1
1
  import { mkdir, mkdtemp, rm } from "node:fs/promises";
2
- import { join } from "node:path";
2
+ import { delimiter, join } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { errorMessage } from "./config.js";
5
5
  import { stageCheckFiles } from "./files.js";
6
6
  import { siblingRuntimeModule } from "./runtime-assets.js";
7
- import { SYSTEM_PATH } from "../platform/macos/policy.js";
8
- import { spawnSupervised } from "../platform/macos/supervise.js";
7
+ import { dirEnv, SYSTEM_PATH, spawnSupervised } from "../platform/index.js";
9
8
  /** How much of a program's combined output a check may keep as its reason. */
10
9
  const MAX_OUTPUT_LENGTH = 4_096;
11
10
  const CHECK_RUNNER = fileURLToPath(siblingRuntimeModule(import.meta.url, "check-runner"));
@@ -21,7 +20,7 @@ async function runProgram(options, command, files) {
21
20
  if (program === undefined) {
22
21
  return { kind: "failed", reason: "the check named no program", output: "" };
23
22
  }
24
- const path = process.env.PATH ?? SYSTEM_PATH.join(":");
23
+ const path = process.env.PATH ?? SYSTEM_PATH.join(delimiter);
25
24
  const directory = await mkdtemp(join(options.engineDir, "check-"));
26
25
  const homeDir = join(directory, "home");
27
26
  const tmpDir = join(directory, "tmp");
@@ -51,14 +50,18 @@ async function runProgram(options, command, files) {
51
50
  supervised = await spawnSupervised({
52
51
  policy: {
53
52
  writableRoots: [options.workspaceDir, homeDir, tmpDir],
54
- readableRoots: [],
53
+ readableRoots: stagingDir === undefined ? [] : [stagingDir],
54
+ readableFiles: [process.execPath, CHECK_RUNNER],
55
55
  readAll: true,
56
56
  allowNetwork: false,
57
57
  },
58
58
  policyDirectory: directory,
59
59
  command: [process.execPath, CHECK_RUNNER, stagingDir ?? "-", program, ...args],
60
60
  cwd: options.workspaceDir,
61
- env: { PATH: path, HOME: homeDir, TMPDIR: tmpDir },
61
+ env: {
62
+ PATH: path,
63
+ ...dirEnv({ home: homeDir, tmp: tmpDir }),
64
+ },
62
65
  interactive: false,
63
66
  report: true,
64
67
  });
@@ -1,7 +1,7 @@
1
- import { execFile } from "node:child_process";
2
1
  import { readFile } from "node:fs/promises";
3
2
  import { join } from "node:path";
4
3
  import { parseEnv } from "node:util";
4
+ import { spawnShellLookup } from "../platform/index.js";
5
5
  import { ConfigError, errorMessage } from "./config.js";
6
6
  const COMMAND_TIMEOUT_MS = 5_000;
7
7
  const COMMAND_MAX_OUTPUT_BYTES = 64 * 1024;
@@ -66,22 +66,90 @@ async function runLookupCommand(name, command, cwd, signal) {
66
66
  let stdout;
67
67
  try {
68
68
  stdout = await new Promise((resolve, reject) => {
69
- execFile("/bin/sh", ["-c", command], {
70
- cwd,
71
- env: process.env,
72
- encoding: "utf8",
73
- timeout: COMMAND_TIMEOUT_MS,
74
- maxBuffer: COMMAND_MAX_OUTPUT_BYTES,
75
- signal,
76
- killSignal: "SIGKILL",
77
- }, (error, output) => {
78
- if (error === null) {
79
- resolve(output);
69
+ const lookup = spawnShellLookup(command, cwd);
70
+ const { child } = lookup;
71
+ const chunks = [];
72
+ let bytes = 0;
73
+ let settled = false;
74
+ let terminating;
75
+ let reapTimer;
76
+ const finish = (fn) => {
77
+ if (settled)
78
+ return;
79
+ settled = true;
80
+ clearTimeout(timer);
81
+ if (reapTimer !== undefined)
82
+ clearTimeout(reapTimer);
83
+ signal?.removeEventListener("abort", onAbort);
84
+ fn();
85
+ };
86
+ const terminate = (reason) => {
87
+ if (terminating !== undefined)
88
+ return;
89
+ terminating = reason;
90
+ clearTimeout(timer);
91
+ signal?.removeEventListener("abort", onAbort);
92
+ child.stdout.destroy();
93
+ child.stderr.destroy();
94
+ lookup.terminate();
95
+ // Wait briefly for the direct child to be reaped, without hanging on detached
96
+ // descendants that may still hold inherited file descriptors.
97
+ reapTimer = setTimeout(() => finish(() => reject(reason)), 200);
98
+ reapTimer.unref();
99
+ };
100
+ const onAbort = () => {
101
+ terminate(Object.assign(new Error("aborted"), { code: "ABORT_ERR" }));
102
+ };
103
+ const timer = setTimeout(() => {
104
+ terminate(Object.assign(new Error("timed out"), { killed: true }));
105
+ }, COMMAND_TIMEOUT_MS);
106
+ signal?.addEventListener("abort", onAbort, { once: true });
107
+ const onData = (chunk, collect) => {
108
+ if (terminating !== undefined)
109
+ return;
110
+ bytes += chunk.length;
111
+ if (bytes > COMMAND_MAX_OUTPUT_BYTES) {
112
+ terminate(Object.assign(new Error("maxBuffer exceeded"), { code: "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" }));
113
+ return;
80
114
  }
81
- else {
82
- reject(error);
115
+ if (collect)
116
+ chunks.push(chunk);
117
+ };
118
+ child.stdout.on("data", (chunk) => onData(chunk, true));
119
+ child.stderr.on("data", (chunk) => onData(chunk, false));
120
+ child.on("error", (error) => {
121
+ finish(() => reject(terminating ?? error));
122
+ });
123
+ child.on("exit", (code, exitSignal) => {
124
+ if (terminating !== undefined) {
125
+ const reason = terminating;
126
+ finish(() => reject(reason));
127
+ return;
128
+ }
129
+ if (code !== 0) {
130
+ const reason = code !== null
131
+ ? Object.assign(new Error("non-zero exit"), { code })
132
+ : Object.assign(new Error("signalled"), { signal: exitSignal ?? "SIGKILL" });
133
+ terminate(reason);
134
+ finish(() => reject(reason));
83
135
  }
84
136
  });
137
+ child.on("close", (code, exitSignal) => {
138
+ finish(() => {
139
+ if (terminating !== undefined) {
140
+ reject(terminating);
141
+ }
142
+ else if (code === 0) {
143
+ resolve(Buffer.concat(chunks).toString("utf8"));
144
+ }
145
+ else if (code !== null) {
146
+ reject(Object.assign(new Error("non-zero exit"), { code }));
147
+ }
148
+ else {
149
+ reject(Object.assign(new Error("signalled"), { signal: exitSignal ?? "SIGKILL" }));
150
+ }
151
+ });
152
+ });
85
153
  });
86
154
  }
87
155
  catch (error) {
@@ -74,7 +74,8 @@ export async function placedPaths(entries, authoringDir, label, signal) {
74
74
  return;
75
75
  }
76
76
  for (const name of await readdir(source)) {
77
- await walk(join(source, name), join(target, name), join(destination, name), [...segments, name], root);
77
+ const childTarget = target === "" ? name : `${target}/${name}`;
78
+ await walk(join(source, name), childTarget, `${destination}/${name}`, [...segments, name], root);
78
79
  }
79
80
  };
80
81
  for (const entry of entries) {
@@ -1,9 +1,9 @@
1
1
  import { spawn } from "node:child_process";
2
- import { link, mkdir, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
2
+ import { link, mkdir, readFile, realpath, rename, stat, writeFile } from "node:fs/promises";
3
3
  import { createServer } from "node:net";
4
4
  import { basename, dirname, join, relative, sep } from "node:path";
5
5
  import { setTimeout as delay } from "node:timers/promises";
6
- import { tmpdir } from "node:os";
6
+ import { listenMockServer, mockForwarderSpec, } from "../platform/index.js";
7
7
  import { ConfigError, errorMessage } from "./config.js";
8
8
  import { compileShellMocks, matchCall } from "./mock-match.js";
9
9
  import { isMissing, isWithin, openRunRoot, resolveWorkspacePath } from "./workspace.js";
@@ -15,41 +15,23 @@ const MAX_CALL_BYTES = 1_000_000;
15
15
  const PASS_MARKER = Buffer.from("agent-evals:pass");
16
16
  const PASS_MARKER_LINE = Buffer.from("agent-evals:pass\n");
17
17
  const EMPTY = Buffer.alloc(0);
18
- // The forwarder is a POSIX shell asset beside this module, copied unchanged by the build, so
19
- // source and built runs read one text. It reports the call over the run's socket and reads the
20
- // reply from a single line: capturing the reply would strip the trailing newlines that make an
21
- // empty stdout or stderr distinguishable. The name it is executed under selects the target.
22
- const FORWARDER_ASSET = new URL("./forwarder.sh", import.meta.url);
23
18
  /**
24
19
  * Write every forwarder, workspace scripts included, and start answering calls. The caller
25
20
  * runs this before the baseline snapshot, so the snapshot already holds the forwarders.
26
21
  */
27
22
  export async function startMockHost(options) {
23
+ const spec = mockForwarderSpec();
28
24
  const forwarderDir = options.mocksDir;
29
- // A Unix socket path is limited to about 100 bytes, so it cannot live under the run root.
30
- const socketPath = join(tmpdir(), `${basename(options.runRootDir)}.sock`);
31
25
  const faultPath = join(options.tmpDir, ".forward-fault");
32
26
  // The template lives in engine-private state; only its hard links are runnable in mocks/.
33
- const scriptPath = join(options.engineDir, "forward");
27
+ const scriptPath = join(options.engineDir, spec.templateName);
34
28
  const rules = compileShellMocks(options.shell);
35
29
  const workspaceRoot = await openRunRoot(options.workspaceDir);
36
30
  await mkdir(forwarderDir, { recursive: true, mode: 0o700 });
37
31
  // The forwarder canonicalises its own path, so identity comparisons use the real directory.
38
32
  const forwarderRoot = await realpath(forwarderDir);
39
- const forwarder = (await readFile(FORWARDER_ASSET, "utf8"))
40
- .replace("__BINDIR__", quote(forwarderRoot))
41
- .replace("__SOCKET__", quote(socketPath))
42
- .replace("__FAULT__", quote(faultPath));
43
- await writeFile(scriptPath, forwarder, { mode: 0o500, flag: "wx" });
44
- for (const target of Object.keys(options.shell).sort()) {
45
- if (target.includes("/")) {
46
- await placeWorkspaceForwarder(workspaceRoot.path, options, target, forwarder);
47
- }
48
- else {
49
- await link(scriptPath, join(forwarderDir, target));
50
- }
51
- }
52
- const wiring = { forwarderDir, socketPath, denyTargets: denyTargetsOf(options.shell) };
33
+ const nodeExecutable = await realpath(process.execPath);
34
+ const clientPath = await realpath(spec.clientPath);
53
35
  const records = [];
54
36
  const faults = [];
55
37
  /** Process-group leaders still owning descendants we must not leave behind. */
@@ -78,19 +60,76 @@ export async function startMockHost(options) {
78
60
  });
79
61
  });
80
62
  });
81
- await listen(server, socketPath);
63
+ const endpoint = await listenMockServer(server, options.runRootDir);
64
+ const { socketPath, expectedNonce } = endpoint;
65
+ const renderForwarder = async (template) => {
66
+ const replacements = {
67
+ __NODE__: template.quote(nodeExecutable),
68
+ __CLIENT__: template.quote(clientPath),
69
+ __BINDIR__: template.quote(forwarderRoot),
70
+ __SOCKET__: template.quote(socketPath),
71
+ __FAULT__: template.quote(faultPath),
72
+ };
73
+ return (await readFile(template.assetPath, "utf8")).replace(/__NODE__|__CLIENT__|__BINDIR__|__SOCKET__|__FAULT__/g, (token) => replacements[token]);
74
+ };
75
+ const forwarder = await renderForwarder(spec);
76
+ const extraPathTemplates = await Promise.all((spec.extraPathForwarders ?? []).map(async (extra) => ({
77
+ extra,
78
+ scriptPath: join(options.engineDir, extra.templateName),
79
+ content: await renderForwarder(extra),
80
+ })));
81
+ try {
82
+ await writeFile(scriptPath, forwarder, { mode: 0o500, flag: "wx" });
83
+ for (const entry of extraPathTemplates) {
84
+ await writeFile(entry.scriptPath, entry.content, { mode: 0o500, flag: "wx" });
85
+ }
86
+ for (const target of Object.keys(options.shell).sort()) {
87
+ if (target.includes("/")) {
88
+ const wsTemplate = spec.workspaceForwarder?.(target);
89
+ const wsForwarder = wsTemplate === undefined || wsTemplate.assetPath === spec.assetPath
90
+ ? forwarder
91
+ : await renderForwarder(wsTemplate);
92
+ await placeWorkspaceForwarder(workspaceRoot.path, options, target, wsForwarder);
93
+ }
94
+ else {
95
+ await link(scriptPath, join(forwarderDir, spec.targetFileName(target)));
96
+ for (const entry of extraPathTemplates) {
97
+ await link(entry.scriptPath, join(forwarderDir, entry.extra.targetFileName(target)));
98
+ }
99
+ }
100
+ }
101
+ }
102
+ catch (error) {
103
+ server.close();
104
+ await endpoint.cleanup().catch(() => { });
105
+ throw error;
106
+ }
107
+ const wiring = {
108
+ forwarderDir,
109
+ socketPath,
110
+ denyTargets: denyTargetsOf(options.shell),
111
+ readableFiles: [nodeExecutable, clientPath],
112
+ };
82
113
  async function answer(socket, message) {
83
114
  const lines = message.toString("utf8").split("\n");
84
115
  if (lines.pop() !== "" || lines.length === 0) {
85
116
  socket.end(denied("call"));
86
117
  return;
87
118
  }
88
- const call = resolveCall(decode(lines[0]), forwarderRoot, workspaceRoot.path, rules);
119
+ let startIndex = 0;
120
+ if (expectedNonce !== undefined) {
121
+ if (decode(lines[0]) !== `nonce:${expectedNonce}` || lines.length < 2) {
122
+ socket.end(denied("call"));
123
+ return;
124
+ }
125
+ startIndex = 1;
126
+ }
127
+ const call = resolveCall(decode(lines[startIndex]), forwarderRoot, workspaceRoot.path, rules, spec);
89
128
  if (call === undefined) {
90
129
  socket.end(denied("call"));
91
130
  return;
92
131
  }
93
- const argv = lines.slice(1).map(decode);
132
+ const argv = lines.slice(startIndex + 1).map(decode);
94
133
  records.push({ target: call.target, arguments: argv });
95
134
  const action = matchCall(call.rules, argv);
96
135
  socket.end(action === undefined ? denied(call.target) : await reply(action, call.target, argv));
@@ -140,7 +179,7 @@ export async function startMockHost(options) {
140
179
  for (const socket of sockets)
141
180
  socket.destroy();
142
181
  await closed;
143
- await rm(socketPath, { force: true });
182
+ await endpoint.cleanup();
144
183
  faults.push(...(await transportFaults(faultPath)));
145
184
  return { records: [...records], faults: [...faults] };
146
185
  }
@@ -159,11 +198,11 @@ function denyTargetsOf(shell) {
159
198
  * or at its workspace-relative path. A bare name and `./name` are different targets: a `PATH`
160
199
  * command and a workspace-root script.
161
200
  */
162
- function resolveCall(self, forwarderRoot, workspaceDir, rules) {
163
- if (dirname(self) === forwarderRoot) {
164
- const name = basename(self);
165
- const targetRules = rules.path.get(name);
166
- return targetRules === undefined ? undefined : { target: name, rules: targetRules };
201
+ function resolveCall(self, forwarderRoot, workspaceDir, rules, spec) {
202
+ const pathTarget = spec.resolvePathTargetName(self, forwarderRoot);
203
+ if (pathTarget !== undefined) {
204
+ const targetRules = rules.path.get(pathTarget);
205
+ return targetRules === undefined ? undefined : { target: pathTarget, rules: targetRules };
167
206
  }
168
207
  if (isWithin(workspaceDir, self)) {
169
208
  const path = relative(workspaceDir, self).split(sep).join("/");
@@ -318,19 +357,6 @@ function denied(target) {
318
357
  function field(bytes) {
319
358
  return bytes.length === 0 ? "-" : bytes.toString("base64");
320
359
  }
321
- /** Quote a value as one POSIX shell word. */
322
- function quote(value) {
323
- return `'${value.replaceAll("'", "'\\''")}'`;
324
- }
325
360
  function decode(line) {
326
361
  return Buffer.from(line, "base64").toString("utf8");
327
362
  }
328
- function listen(server, path) {
329
- return new Promise((resolve, reject) => {
330
- server.once("error", reject);
331
- server.listen(path, () => {
332
- server.off("error", reject);
333
- resolve();
334
- });
335
- });
336
- }
@@ -27,6 +27,8 @@ export interface MockWiring {
27
27
  readonly socketPath: string;
28
28
  /** `PATH` targets no rule can pass to the real command; their binaries stay denied. */
29
29
  readonly denyTargets: readonly string[];
30
+ /** Additional read-only files the forwarders need inside a deny-default sandbox (e.g. Node). */
31
+ readonly readableFiles?: readonly string[];
30
32
  }
31
33
  export interface RunnerOutcome {
32
34
  readonly finalText: string | null;