@lelouchhe/agent-evals 0.0.0-stage → 0.1.1

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 +117 -2
  4. package/dist/checkers/file/index.d.ts +26 -0
  5. package/dist/checkers/file/index.js +228 -0
  6. package/dist/checkers/judge/index.d.ts +20 -0
  7. package/dist/checkers/judge/index.js +262 -0
  8. package/dist/checkers/judge/prompt.d.ts +18 -0
  9. package/dist/checkers/judge/prompt.js +36 -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 +352 -0
  20. package/dist/engine/authoring.d.ts +24 -0
  21. package/dist/engine/authoring.js +261 -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 +142 -0
  27. package/dist/engine/config.js +362 -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 +87 -0
  31. package/dist/engine/files.js +307 -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 +16 -0
  42. package/dist/engine/params.js +86 -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 +234 -0
  48. package/dist/engine/registry.js +127 -0
  49. package/dist/engine/report.d.ts +17 -0
  50. package/dist/engine/report.js +385 -0
  51. package/dist/engine/results.d.ts +43 -0
  52. package/dist/engine/results.js +39 -0
  53. package/dist/engine/run.d.ts +47 -0
  54. package/dist/engine/run.js +566 -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 +38 -0
  65. package/dist/engine/workspace.d.ts +56 -0
  66. package/dist/engine/workspace.js +280 -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 +131 -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,104 @@
1
+ import { workspaceTargetPath, } from "./config.js";
2
+ import { compilePattern } from "./regex.js";
3
+ /** Compile every pattern once, when the host starts. Invalid patterns already failed at load. */
4
+ export function compileShellMocks(shell) {
5
+ const path = new Map();
6
+ const workspace = new Map();
7
+ for (const [target, rules] of Object.entries(shell)) {
8
+ const compiled = compileRules(rules);
9
+ if (target.includes("/")) {
10
+ workspace.set(workspaceTargetPath(target), { target, rules: compiled });
11
+ }
12
+ else {
13
+ path.set(target, compiled);
14
+ }
15
+ }
16
+ return { path, workspace };
17
+ }
18
+ /**
19
+ * Compile one argument specification into a predicate over a call's argv. A checker asks whether a
20
+ * recorded call matches; ordered dispatch and actions belong to the host, not to the check.
21
+ */
22
+ export function compileMockArgs(args) {
23
+ const positional = args.positional.map(compilePatternOf);
24
+ const options = args.options.map(compileArgument);
25
+ return (argv) => argsMatch(positional, options, argv);
26
+ }
27
+ /** Compile one target's ordered rules; the same path serves the host and a mock check. */
28
+ export function compileRules(rules) {
29
+ return rules.map(compileRule);
30
+ }
31
+ function compileRule(rule) {
32
+ if (rule.args === undefined) {
33
+ return { positional: undefined, options: undefined, action: rule.action };
34
+ }
35
+ return {
36
+ positional: rule.args.positional.map(compilePatternOf),
37
+ options: rule.args.options.map(compileArgument),
38
+ action: rule.action,
39
+ };
40
+ }
41
+ function compileArgument(option) {
42
+ const key = compilePatternOf(option.key);
43
+ if (option.kind === "value") {
44
+ return { key, kind: "value", value: compilePatternOf(option.value) };
45
+ }
46
+ return { key, kind: option.kind };
47
+ }
48
+ function compilePatternOf(pattern) {
49
+ return pattern.regex
50
+ ? { literal: undefined, re: compilePattern(pattern.source) }
51
+ : { literal: pattern.source, re: undefined };
52
+ }
53
+ function tokenMatches(pattern, token) {
54
+ return pattern.re !== undefined ? pattern.re.matcher(token).matches() : pattern.literal === token;
55
+ }
56
+ /** The option name is the whole token, or the part before `=` in `--name=value`. */
57
+ function nameMatches(pattern, token) {
58
+ if (tokenMatches(pattern, token))
59
+ return true;
60
+ const separator = token.indexOf("=");
61
+ return separator > 0 && tokenMatches(pattern, token.slice(0, separator));
62
+ }
63
+ /** First matching rule wins; a rule without conditions is the fallback. */
64
+ export function matchCall(rules, argv) {
65
+ for (const rule of rules) {
66
+ if (rule.positional === undefined || argsMatch(rule.positional, rule.options ?? [], argv)) {
67
+ return rule.action;
68
+ }
69
+ }
70
+ return undefined;
71
+ }
72
+ function argsMatch(positional, options, argv) {
73
+ if (argv.length < positional.length)
74
+ return false;
75
+ for (const [index, pattern] of positional.entries()) {
76
+ if (!tokenMatches(pattern, argv[index]))
77
+ return false;
78
+ }
79
+ const rest = argv.slice(positional.length);
80
+ return options.every((option) => optionMatches(option, rest));
81
+ }
82
+ function optionMatches(option, tokens) {
83
+ if (option.kind === "value") {
84
+ const { key, value } = option;
85
+ return tokens.some((token, index) => {
86
+ // Both promised spellings: `--name=value` first, then `--name value`. A regex name may
87
+ // match the whole `--name=value` token, so splitting cannot depend on that check.
88
+ const separator = token.indexOf("=");
89
+ if (separator > 0 &&
90
+ tokenMatches(key, token.slice(0, separator)) &&
91
+ tokenMatches(value, token.slice(separator + 1))) {
92
+ return true;
93
+ }
94
+ if (!tokenMatches(key, token))
95
+ return false;
96
+ const next = tokens[index + 1];
97
+ return next !== undefined && tokenMatches(value, next);
98
+ });
99
+ }
100
+ if (option.kind === "required") {
101
+ return tokens.some((token) => nameMatches(option.key, token));
102
+ }
103
+ return !tokens.some((token) => nameMatches(option.key, token));
104
+ }
@@ -0,0 +1,35 @@
1
+ import { type ShellMocks } from "./config.js";
2
+ import type { MockRecord, MockWiring } from "./registry.js";
3
+ export interface MockOutcome {
4
+ /** Every recorded call, in arrival order. */
5
+ readonly records: readonly MockRecord[];
6
+ /** Infrastructure faults, such as a run program that could not start. */
7
+ readonly faults: readonly string[];
8
+ }
9
+ export interface MockHost {
10
+ /** What the runner places in its environment. */
11
+ readonly wiring: MockWiring;
12
+ /** Stop answering calls, then return every recorded call and fault. Safe to call again. */
13
+ readonly close: () => Promise<MockOutcome>;
14
+ }
15
+ export interface MockHostOptions {
16
+ readonly runRootDir: string;
17
+ /** Engine-private state; the replaced workspace scripts move here, out of the agent's reach. */
18
+ readonly engineDir: string;
19
+ /** Read-only forwarder directory the runner puts first on `PATH`. */
20
+ readonly mocksDir: string;
21
+ /** Prepared workspace root; its real path, as the runner's sandbox sees it. */
22
+ readonly workspaceDir: string;
23
+ /** Temporary directory; a forwarder that cannot reach the host reports there. */
24
+ readonly tmpDir: string;
25
+ /** Directory of the case file, the working directory of `run` programs. */
26
+ readonly authoringDir: string;
27
+ readonly shell: ShellMocks;
28
+ readonly timeoutMs: number;
29
+ readonly signal: AbortSignal;
30
+ }
31
+ /**
32
+ * Write every forwarder, workspace scripts included, and start answering calls. The caller
33
+ * runs this before the baseline snapshot, so the snapshot already holds the forwarders.
34
+ */
35
+ export declare function startMockHost(options: MockHostOptions): Promise<MockHost>;
@@ -0,0 +1,336 @@
1
+ import { spawn } from "node:child_process";
2
+ import { link, mkdir, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
3
+ import { createServer } from "node:net";
4
+ import { basename, dirname, join, relative, sep } from "node:path";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { tmpdir } from "node:os";
7
+ import { ConfigError, errorMessage } from "./config.js";
8
+ import { compileShellMocks, matchCall } from "./mock-match.js";
9
+ import { isMissing, isWithin, openRunRoot, resolveWorkspacePath } from "./workspace.js";
10
+ /** How long closing waits for already connected callers before dropping them. */
11
+ const CLOSE_GRACE_MS = 5_000;
12
+ /** Any sandboxed process can connect and send; argv itself is limited to about 256 KiB. */
13
+ const MAX_CALL_BYTES = 1_000_000;
14
+ /** The complete stdout of a `run` program that hands the call to the real command. */
15
+ const PASS_MARKER = Buffer.from("agent-evals:pass");
16
+ const PASS_MARKER_LINE = Buffer.from("agent-evals:pass\n");
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
+ /**
24
+ * Write every forwarder, workspace scripts included, and start answering calls. The caller
25
+ * runs this before the baseline snapshot, so the snapshot already holds the forwarders.
26
+ */
27
+ export async function startMockHost(options) {
28
+ 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
+ const faultPath = join(options.tmpDir, ".forward-fault");
32
+ // The template lives in engine-private state; only its hard links are runnable in mocks/.
33
+ const scriptPath = join(options.engineDir, "forward");
34
+ const rules = compileShellMocks(options.shell);
35
+ const workspaceRoot = await openRunRoot(options.workspaceDir);
36
+ await mkdir(forwarderDir, { recursive: true, mode: 0o700 });
37
+ // The forwarder canonicalises its own path, so identity comparisons use the real directory.
38
+ 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) };
53
+ const records = [];
54
+ const faults = [];
55
+ /** Process-group leaders still owning descendants we must not leave behind. */
56
+ const groups = new Set();
57
+ const sockets = new Set();
58
+ // The forwarder half-closes after sending, then reads the reply: keep the writable side open
59
+ // until the answer (which may await a run program) has been written.
60
+ const server = createServer({ allowHalfOpen: true }, (socket) => {
61
+ sockets.add(socket);
62
+ socket.on("close", () => sockets.delete(socket));
63
+ socket.on("error", () => { });
64
+ const chunks = [];
65
+ let size = 0;
66
+ socket.on("data", (chunk) => {
67
+ size += chunk.length;
68
+ if (size > MAX_CALL_BYTES) {
69
+ socket.destroy();
70
+ return;
71
+ }
72
+ chunks.push(chunk);
73
+ });
74
+ socket.on("end", () => {
75
+ void answer(socket, Buffer.concat(chunks)).catch((error) => {
76
+ faults.push(`failed to answer a call: ${errorMessage(error)}`);
77
+ socket.end(denied(""));
78
+ });
79
+ });
80
+ });
81
+ await listen(server, socketPath);
82
+ async function answer(socket, message) {
83
+ const lines = message.toString("utf8").split("\n");
84
+ if (lines.pop() !== "" || lines.length === 0) {
85
+ socket.end(denied("call"));
86
+ return;
87
+ }
88
+ const call = resolveCall(decode(lines[0]), forwarderRoot, workspaceRoot.path, rules);
89
+ if (call === undefined) {
90
+ socket.end(denied("call"));
91
+ return;
92
+ }
93
+ const argv = lines.slice(1).map(decode);
94
+ records.push({ target: call.target, arguments: argv });
95
+ const action = matchCall(call.rules, argv);
96
+ socket.end(action === undefined ? denied(call.target) : await reply(action, call.target, argv));
97
+ }
98
+ async function reply(action, target, argv) {
99
+ if (action.kind === "pass")
100
+ return passReply();
101
+ // An explicit refusal is a decision, like an unmatched call: recorded, never a fault.
102
+ if (action.kind === "refuse")
103
+ return denied(target);
104
+ if (action.kind === "return") {
105
+ return resultReply(action.result.exitCode, Buffer.from(action.result.stdout, "utf8"), Buffer.from(action.result.stderr, "utf8"));
106
+ }
107
+ const program = await runProgram(target, action, argv, groups, options);
108
+ if (program.fault !== undefined) {
109
+ faults.push(program.fault);
110
+ return denied(target);
111
+ }
112
+ if (program.stdout.equals(PASS_MARKER) || program.stdout.equals(PASS_MARKER_LINE)) {
113
+ if (!action.pass) {
114
+ faults.push(`run program for "${target}" printed the pass marker but the rule has no pass`);
115
+ return denied(target);
116
+ }
117
+ if (program.exitCode !== 0) {
118
+ faults.push(`run program for "${target}" printed the pass marker with exit code ${program.exitCode}`);
119
+ return denied(target);
120
+ }
121
+ return passReply();
122
+ }
123
+ // Any other bytes, the marker included, are the program's response: data, not a control.
124
+ return resultReply(program.exitCode, program.stdout, program.stderr);
125
+ }
126
+ let closing;
127
+ const close = () => (closing ??= shutdown());
128
+ async function shutdown() {
129
+ for (const pid of groups)
130
+ killGroupPid(pid);
131
+ groups.clear();
132
+ const closed = new Promise((resolve) => server.close(() => resolve()));
133
+ const grace = new AbortController();
134
+ try {
135
+ await Promise.race([closed, delay(CLOSE_GRACE_MS, undefined, { signal: grace.signal })]);
136
+ }
137
+ finally {
138
+ grace.abort();
139
+ }
140
+ for (const socket of sockets)
141
+ socket.destroy();
142
+ await closed;
143
+ await rm(socketPath, { force: true });
144
+ faults.push(...(await transportFaults(faultPath)));
145
+ return { records: [...records], faults: [...faults] };
146
+ }
147
+ return { wiring, close };
148
+ }
149
+ /** PATH targets without any `pass` rule, whose real binaries the runner must deny. */
150
+ function denyTargetsOf(shell) {
151
+ return Object.entries(shell)
152
+ .filter(([target, rules]) => !target.includes("/") &&
153
+ !rules.some((rule) => rule.action.kind === "pass" || (rule.action.kind === "run" && rule.action.pass)))
154
+ .map(([target]) => target)
155
+ .sort();
156
+ }
157
+ /**
158
+ * A call is identified by where its forwarder lives: directly in the run's forwarder directory,
159
+ * or at its workspace-relative path. A bare name and `./name` are different targets: a `PATH`
160
+ * command and a workspace-root script.
161
+ */
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 };
167
+ }
168
+ if (isWithin(workspaceDir, self)) {
169
+ const path = relative(workspaceDir, self).split(sep).join("/");
170
+ const target = rules.workspace.get(path);
171
+ return target === undefined ? undefined : { target: target.target, rules: target.rules };
172
+ }
173
+ return undefined;
174
+ }
175
+ /**
176
+ * Place one workspace forwarder before the baseline snapshot. A target with a `pass` rule keeps
177
+ * its real script beside it under a dot-prefixed name; without `pass` the real script leaves the
178
+ * sandbox entirely, so only the forwarder is runnable.
179
+ */
180
+ async function placeWorkspaceForwarder(workspaceDir, options, target, forwarder) {
181
+ const root = await openRunRoot(workspaceDir);
182
+ const targetPath = await resolveWorkspacePath(root, target);
183
+ const folder = dirname(targetPath);
184
+ const real = await stat(targetPath).catch((error) => {
185
+ if (isMissing(error))
186
+ return undefined;
187
+ throw error;
188
+ });
189
+ if (real?.isDirectory() === true) {
190
+ throw new ConfigError(`mocked workspace script ${target} is a directory`);
191
+ }
192
+ const usesPass = options.shell[target]?.some((rule) => rule.action.kind === "pass" || (rule.action.kind === "run" && rule.action.pass));
193
+ if (usesPass) {
194
+ if (real === undefined) {
195
+ throw new ConfigError(`mocked workspace script ${target} needs a real script for its pass rule`);
196
+ }
197
+ const beside = join(folder, `.${basename(targetPath)}`);
198
+ try {
199
+ await stat(beside);
200
+ throw new ConfigError(`mocked workspace script ${target} already has ${basename(beside)} beside it`);
201
+ }
202
+ catch (error) {
203
+ if (!isMissing(error))
204
+ throw error;
205
+ }
206
+ await rename(targetPath, beside);
207
+ }
208
+ else if (real !== undefined) {
209
+ const stash = join(options.engineDir, "replaced", ...target.split("/").filter((segment) => segment.length > 0));
210
+ await mkdir(dirname(stash), { recursive: true, mode: 0o700 });
211
+ await rename(targetPath, stash);
212
+ }
213
+ await mkdir(folder, { recursive: true, mode: 0o700 });
214
+ await writeFile(targetPath, forwarder, { mode: 0o500, flag: "wx" });
215
+ }
216
+ /**
217
+ * Start the author's program with the call's arguments appended, without a shell, in the case
218
+ * directory and with empty stdin. A program that cannot start, dies from a signal or exceeds the
219
+ * run's deadline is an infrastructure fault; an ordinary nonzero exit is just a response.
220
+ * Stdout and stderr stay opaque bytes.
221
+ */
222
+ async function runProgram(target, action, argv, groups, options) {
223
+ const [program, ...prefix] = action.command;
224
+ const child = spawn(program, [...prefix, ...argv], {
225
+ cwd: options.authoringDir,
226
+ stdio: ["ignore", "pipe", "pipe"],
227
+ detached: true,
228
+ });
229
+ const pid = child.pid;
230
+ if (pid !== undefined)
231
+ groups.add(pid);
232
+ const stdout = [];
233
+ const stderr = [];
234
+ child.stdout?.on("data", (chunk) => stdout.push(chunk));
235
+ child.stderr?.on("data", (chunk) => stderr.push(chunk));
236
+ let timedOut = false;
237
+ let aborted = false;
238
+ const timer = setTimeout(() => {
239
+ timedOut = true;
240
+ killGroup(child);
241
+ }, options.timeoutMs);
242
+ const onAbort = () => {
243
+ aborted = true;
244
+ killGroup(child);
245
+ };
246
+ options.signal.addEventListener("abort", onAbort, { once: true });
247
+ try {
248
+ const outcome = await new Promise((resolve) => {
249
+ child.once("error", (error) => resolve({ error }));
250
+ child.once("close", (code, signal) => resolve({ code, signal }));
251
+ });
252
+ const failed = (fault) => ({ exitCode: 126, stdout: EMPTY, stderr: EMPTY, fault });
253
+ if ("error" in outcome)
254
+ return failed(`could not start ${program} for "${target}": ${outcome.error.message}`);
255
+ if (timedOut)
256
+ return failed(`run program for "${target}" exceeded ${options.timeoutMs}ms`);
257
+ if (aborted)
258
+ return failed(`run program for "${target}" was stopped by cancellation`);
259
+ if (outcome.signal !== null)
260
+ return failed(`run program for "${target}" was killed by ${outcome.signal}`);
261
+ return {
262
+ exitCode: outcome.code ?? 126,
263
+ stdout: Buffer.concat(stdout),
264
+ stderr: Buffer.concat(stderr),
265
+ };
266
+ }
267
+ finally {
268
+ clearTimeout(timer);
269
+ options.signal.removeEventListener("abort", onAbort);
270
+ // The leader can exit while descendants live on in its process group; leave none behind.
271
+ killGroup(child);
272
+ if (pid !== undefined)
273
+ groups.delete(pid);
274
+ }
275
+ }
276
+ /** Kill a run program's process group, including descendants that outlived its leader. */
277
+ function killGroupPid(pid) {
278
+ try {
279
+ process.kill(-pid, "SIGKILL");
280
+ }
281
+ catch {
282
+ // Already gone.
283
+ }
284
+ }
285
+ function killGroup(child) {
286
+ try {
287
+ child.kill("SIGKILL");
288
+ }
289
+ catch {
290
+ // Already gone.
291
+ }
292
+ if (child.pid !== undefined)
293
+ killGroupPid(child.pid);
294
+ }
295
+ /** Faults a forwarder wrote when it could not reach the call socket. */
296
+ async function transportFaults(path) {
297
+ try {
298
+ const text = await readFile(path, "utf8");
299
+ return text
300
+ .split("\n")
301
+ .filter((line) => line.length > 0)
302
+ .map((line) => `a forwarder for "${line}" could not reach the mock host`);
303
+ }
304
+ catch {
305
+ return [];
306
+ }
307
+ }
308
+ function resultReply(exitCode, stdout, stderr) {
309
+ return `result ${exitCode} ${field(stdout)} ${field(stderr)}\n`;
310
+ }
311
+ function passReply() {
312
+ return "pass 0 - -\n";
313
+ }
314
+ function denied(target) {
315
+ return resultReply(126, EMPTY, Buffer.from(`${target}: Operation not permitted\n`, "utf8"));
316
+ }
317
+ /** A reply field is never empty, so a stripped trailing newline cannot merge two fields. */
318
+ function field(bytes) {
319
+ return bytes.length === 0 ? "-" : bytes.toString("base64");
320
+ }
321
+ /** Quote a value as one POSIX shell word. */
322
+ function quote(value) {
323
+ return `'${value.replaceAll("'", "'\\''")}'`;
324
+ }
325
+ function decode(line) {
326
+ return Buffer.from(line, "base64").toString("utf8");
327
+ }
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
+ }
@@ -0,0 +1,16 @@
1
+ import { z, type ZodType } from "zod";
2
+ import { type ImplementationParams, type PatternSyntax } from "./config.js";
3
+ /**
4
+ * One literal or /…/ pattern. A YAML number is compared as its text; a boolean or a mapping is
5
+ * rejected, because an unquoted `state: failed` in a list is a mapping rather than the string
6
+ * the author meant.
7
+ */
8
+ export declare const patternSyntaxSchema: z.ZodPipe<z.ZodUnknown, z.ZodTransform<PatternSyntax, unknown>>;
9
+ /** One pattern or a non-empty list of them, normalized to a list in declaration order. */
10
+ export declare const patternListSchema: z.ZodPipe<z.ZodUnknown, z.ZodTransform<readonly PatternSyntax[], unknown>>;
11
+ /** A declared string that must carry content once surrounding whitespace is ignored. */
12
+ export declare const nonEmptyTrimmedString: z.ZodString;
13
+ /** Shared schema rule for check targets relative to the evaluated workspace. */
14
+ export declare const runRelativePathSchema: z.ZodString;
15
+ /** Parse raw declared parameters exactly once with the implementation's Zod schema. */
16
+ export declare function parseImplementationParams<P>(schema: ZodType<P>, raw: ImplementationParams, label: string): Promise<P>;
@@ -0,0 +1,86 @@
1
+ import { z } from "zod";
2
+ import { ConfigError, parsePatternScalar, } from "./config.js";
3
+ /**
4
+ * One literal or /…/ pattern. A YAML number is compared as its text; a boolean or a mapping is
5
+ * rejected, because an unquoted `state: failed` in a list is a mapping rather than the string
6
+ * the author meant.
7
+ */
8
+ export const patternSyntaxSchema = z.unknown().transform((value, context) => {
9
+ const parsed = parsePatternScalar(value);
10
+ if (parsed.kind === "pattern") {
11
+ if (parsed.pattern.regex && parsed.pattern.source.length === 0) {
12
+ context.addIssue({ code: "custom", message: "must name a pattern inside /…/" });
13
+ return z.NEVER;
14
+ }
15
+ return parsed.pattern;
16
+ }
17
+ context.addIssue({ code: "custom", message: patternIssue(value, parsed) });
18
+ return z.NEVER;
19
+ });
20
+ const MAX_PATTERNS = 100;
21
+ /** One pattern or a non-empty list of them, normalized to a list in declaration order. */
22
+ export const patternListSchema = z.unknown().transform((value, context) => {
23
+ if (Array.isArray(value) && value.length === 0) {
24
+ context.addIssue({ code: "custom", message: "must hold at least one pattern" });
25
+ return [];
26
+ }
27
+ const entries = Array.isArray(value) ? value : [value];
28
+ if (entries.length > MAX_PATTERNS) {
29
+ context.addIssue({ code: "custom", message: `must hold at most ${MAX_PATTERNS} patterns` });
30
+ return [];
31
+ }
32
+ const listed = Array.isArray(value);
33
+ return entries.flatMap((entry, index) => {
34
+ const parsed = patternSyntaxSchema.safeParse(entry);
35
+ if (parsed.success) {
36
+ return [parsed.data];
37
+ }
38
+ // A scalar names the field itself; only a list entry needs its position.
39
+ const path = listed ? [index] : [];
40
+ for (const issue of parsed.error.issues) {
41
+ context.addIssue({ code: "custom", path: [...path, ...issue.path], message: issue.message });
42
+ }
43
+ return [];
44
+ });
45
+ });
46
+ /** The field-level message for a scalar that is not a pattern; each caller names its own mistake. */
47
+ function patternIssue(value, parsed) {
48
+ if (parsed.reason === "regex") {
49
+ return `is not a valid RE2 pattern: ${parsed.message}`;
50
+ }
51
+ if (typeof value === "object" && value !== null) {
52
+ return 'must be a string, number or /…/ RE2 pattern; quote a string containing ": ", as in "state: failed"';
53
+ }
54
+ if (typeof value === "boolean") {
55
+ return "must be a string, number or /…/ RE2 pattern; quote a boolean literal";
56
+ }
57
+ return "must be a non-empty string, number or /…/ RE2 pattern";
58
+ }
59
+ /** A declared string that must carry content once surrounding whitespace is ignored. */
60
+ export const nonEmptyTrimmedString = z
61
+ .string()
62
+ .refine((value) => value.trim().length > 0, { message: "must be a non-empty string" });
63
+ /** Shared schema rule for check targets relative to the evaluated workspace. */
64
+ export const runRelativePathSchema = z
65
+ .string()
66
+ .min(1, "must be a non-empty run-relative path")
67
+ .refine((value) => !value.startsWith("/") && !value.split(/[\\/]+/).includes(".."), {
68
+ message: "must be relative to the run workspace without '..' segments",
69
+ });
70
+ /** Parse raw declared parameters exactly once with the implementation's Zod schema. */
71
+ export async function parseImplementationParams(schema, raw, label) {
72
+ const result = await schema.safeParseAsync(raw);
73
+ if (result.success) {
74
+ return result.data;
75
+ }
76
+ throw new ConfigError(formatSchemaError(label, result.error));
77
+ }
78
+ function formatSchemaError(label, error) {
79
+ return error.issues
80
+ .map((issue) => {
81
+ const path = issue.path.map(String).join(".");
82
+ const location = path.length === 0 ? `${label} parameters` : `${label} parameter ${path}`;
83
+ return `${location}: ${issue.message}`;
84
+ })
85
+ .join("; ");
86
+ }
@@ -0,0 +1,26 @@
1
+ import { type ResolvedCase } from "./config.js";
2
+ /** One placed file: its destination and the authoring source it came from. */
3
+ export interface PlacedPath {
4
+ readonly path: string;
5
+ readonly source: string;
6
+ }
7
+ /** One excluded path: what the ignore file removed, and which file decided it. */
8
+ export interface ExcludedPath {
9
+ readonly path: string;
10
+ readonly directory: boolean;
11
+ /** The directory holding the deciding `.agentevalsignore`, relative to the case file. */
12
+ readonly ignoreDir: string;
13
+ }
14
+ /** What one case-level entry places, without running anything. */
15
+ export interface PlacementSummary {
16
+ /** The declaration this entry comes from, such as `files ".agents/skills"` or `home "~/notes"`. */
17
+ readonly label: string;
18
+ readonly placed: readonly PlacedPath[];
19
+ readonly excluded: readonly ExcludedPath[];
20
+ }
21
+ /**
22
+ * Describe what the case's `fixture` and `files` entries would place, using the same traversal
23
+ * and ignore rules as the run. Only the case is described: the agent file's HOME content is the
24
+ * runner's, and check-time `files` are not part of the initial environment.
25
+ */
26
+ export declare function describePlacement(loadedCase: ResolvedCase): Promise<readonly PlacementSummary[]>;