@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,183 @@
1
+ import { z } from "zod";
2
+ import { messageText } from "../../engine/messages.js";
3
+ import { patternListSchema, patternSyntaxSchema } from "../../engine/params.js";
4
+ import { searches } from "../../engine/regex.js";
5
+ import { skillConsultations, shellSkillAccess } from "../../engine/skills.js";
6
+ import { truncate } from "../../engine/truncate.js";
7
+ const MAX_REASON = 800;
8
+ const MAX_LISTED_SKILLS = 10;
9
+ /** Report an unexpected parameter by name: each event accepts only the fields it asserts on. */
10
+ function acceptsOnly(accepted) {
11
+ return (issue) => issue.code === "unrecognized_keys" ? `accepts only ${accepted}; unexpected: ${issue.keys?.join(", ")}` : undefined;
12
+ }
13
+ /** `event: skill` asserts on the skills the run consulted, derived from completed tool calls. */
14
+ const skillEventSchema = z
15
+ .strictObject({
16
+ event: z.literal("skill"),
17
+ /** The skill's name: a literal for one exact name, or a /…/ RE2 pattern searched within it. */
18
+ name: patternSyntaxSchema,
19
+ /** The exact number of matching consultations; omitted means at least one. */
20
+ times: z.number().int().min(0, "must be a non-negative integer").optional(),
21
+ }, { error: acceptsOnly("event, name and times for a skill event") })
22
+ .superRefine((params, context) => {
23
+ if (!params.name.regex && params.times !== undefined && params.times > 1) {
24
+ context.addIssue({
25
+ code: "custom",
26
+ path: ["times"],
27
+ message: "must be 0 or 1 with a literal name, which matches at most one skill",
28
+ });
29
+ }
30
+ });
31
+ /** `event: message` asserts on the text the agent produced, joined from every `message` entry. */
32
+ const messageEventSchema = z
33
+ .strictObject({
34
+ event: z.literal("message"),
35
+ /** Text the artifact must hold: a literal substring, or a /…/ RE2 pattern searched within it. */
36
+ matches: patternListSchema.optional(),
37
+ /** Text the artifact must not hold, in the same grammar. */
38
+ notMatches: patternListSchema.optional(),
39
+ }, { error: acceptsOnly("event, matches and notMatches for a message event") })
40
+ .superRefine((params, context) => {
41
+ if (params.matches === undefined && params.notMatches === undefined) {
42
+ context.addIssue({ code: "custom", message: "needs at least one of matches or notMatches" });
43
+ }
44
+ });
45
+ const traceCheckParamsSchema = z
46
+ .discriminatedUnion("event", [skillEventSchema, messageEventSchema], {
47
+ error: (issue) => issue.code === "invalid_union" ? 'must be "skill" or "message" (accepted events: skill, message)' : undefined,
48
+ })
49
+ .transform((params) => params.event === "message"
50
+ ? {
51
+ event: "message",
52
+ patterns: [
53
+ ...(params.matches ?? []).map((pattern) => ({ kind: "matches", pattern })),
54
+ ...(params.notMatches ?? []).map((pattern) => ({ kind: "notMatches", pattern })),
55
+ ],
56
+ }
57
+ : params);
58
+ /** Assert on derived trace events: the skills a run consulted, or the text it produced. */
59
+ export const traceChecker = {
60
+ type: "trace",
61
+ params: traceCheckParamsSchema,
62
+ create(params) {
63
+ return new TraceChecker(params);
64
+ },
65
+ };
66
+ class TraceChecker {
67
+ #params;
68
+ constructor(params) {
69
+ this.#params = params;
70
+ }
71
+ check = async (context) => {
72
+ const params = this.#params;
73
+ return params.event === "message" ? messages(context, params.patterns) : skills(context, params);
74
+ };
75
+ }
76
+ async function skills(context, params) {
77
+ const { name, times } = params;
78
+ const subject = `skill ${display(name)}`;
79
+ if (context.trace === undefined) {
80
+ return [
81
+ {
82
+ checker: "trace",
83
+ subject,
84
+ status: "error",
85
+ reason: "this runner records no trace, so no skill consultation can be derived",
86
+ },
87
+ ];
88
+ }
89
+ const sources = {
90
+ workspace: context.workspace,
91
+ home: context.home,
92
+ workspaceBaseline: context.baseline,
93
+ homeBaseline: context.homeBaseline,
94
+ };
95
+ const consultations = await skillConsultations(context.trace, sources);
96
+ const shell = await shellSkillAccess(context.trace, sources);
97
+ const matching = consultations.filter((consultation) => matches(name, consultation.name));
98
+ const satisfied = times === undefined ? matching.length >= 1 : matching.length === times;
99
+ return [
100
+ {
101
+ checker: "trace",
102
+ subject,
103
+ status: satisfied ? "pass" : "fail",
104
+ reason: truncate((satisfied ? found(matching, consultations) : expected(name, times, consultations, matching)) +
105
+ shellNote(shell), MAX_REASON),
106
+ },
107
+ ];
108
+ }
109
+ /** Assert on the joined agent text; a run that produced none is an error, never a vacuous pass. */
110
+ function messages(context, patterns) {
111
+ const text = context.trace === undefined ? undefined : messageText(context.trace);
112
+ if (text === undefined) {
113
+ return [
114
+ {
115
+ checker: "trace",
116
+ subject: "message",
117
+ status: "error",
118
+ reason: "this runner records no trace, so no message text can be derived",
119
+ },
120
+ ];
121
+ }
122
+ if (text === "") {
123
+ return [
124
+ {
125
+ checker: "trace",
126
+ subject: "message",
127
+ status: "error",
128
+ reason: "the trace holds no message text, so there is nothing to assert on",
129
+ },
130
+ ];
131
+ }
132
+ return patterns.map(({ kind, pattern }) => {
133
+ const found = pattern.regex ? searches(pattern.source, text) : text.includes(pattern.source);
134
+ return {
135
+ checker: "trace",
136
+ subject: `message ${kind === "matches" ? "matches" : "does not match"} ${quoted(pattern)}`,
137
+ status: found === (kind === "matches") ? "pass" : "fail",
138
+ reason: found ? "pattern found" : "pattern not found",
139
+ };
140
+ });
141
+ }
142
+ /** A literal names one exact skill; a /…/ pattern is searched within the name. */
143
+ function matches(pattern, name) {
144
+ return pattern.regex ? searches(pattern.source, name) : name === pattern.source;
145
+ }
146
+ function expected(name, times, consultations, matching) {
147
+ const wanted = times === undefined ? `expected ${display(name)}` : `expected exactly ${count(times)} of ${display(name)}`;
148
+ return `${wanted}, consulted: ${listed(consultations)}${fallbackNote(matching)}`;
149
+ }
150
+ /** A pass still names what the run consulted, so a reader sees why the check held. */
151
+ function found(matching, consultations) {
152
+ return `found ${count(matching.length)}, consulted: ${listed(consultations)}${fallbackNote(matching)}`;
153
+ }
154
+ function listed(consultations) {
155
+ return consultations.length === 0
156
+ ? "none"
157
+ : consultations
158
+ .slice(0, MAX_LISTED_SKILLS)
159
+ .map((consultation) => consultation.name)
160
+ .join(", ") + (consultations.length > MAX_LISTED_SKILLS ? ", …" : "");
161
+ }
162
+ /** Shell access is reported, never counted: it does not change the status or the count. */
163
+ function shellNote(shell) {
164
+ return shell.length === 0 ? "" : `; touched via shell: ${listed(shell)}`;
165
+ }
166
+ /** Say when a matched name is only the skill's parent directory. */
167
+ function fallbackNote(matching) {
168
+ const unnamed = matching
169
+ .filter((consultation) => consultation.fromDirectory)
170
+ .map((consultation) => consultation.name);
171
+ return unnamed.length === 0 ? "" : ` (named from the parent directory, not frontmatter: ${unnamed.join(", ")})`;
172
+ }
173
+ /** A skill name as written; its pattern slashes already show that it is a pattern. */
174
+ function display(pattern) {
175
+ return pattern.regex ? `/${truncate(pattern.source, 120)}/` : truncate(pattern.source, 120);
176
+ }
177
+ /** A literal in quotes, or a regex between slashes, so the subject says which pattern was used. */
178
+ function quoted(pattern) {
179
+ return pattern.regex ? `/${truncate(pattern.source, 120)}/` : `"${truncate(pattern.source, 120)}"`;
180
+ }
181
+ function count(value) {
182
+ return `${value} consultation${value === 1 ? "" : "s"}`;
183
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,352 @@
1
+ #!/usr/bin/env node
2
+ import { readdir, readFile, stat } from "node:fs/promises";
3
+ import { join, resolve } from "node:path";
4
+ import { parseArgs } from "node:util";
5
+ import { fileChecker } from "./checkers/file/index.js";
6
+ import { judgeChecker } from "./checkers/judge/index.js";
7
+ import { mockChecker } from "./checkers/mock/index.js";
8
+ import { shellChecker } from "./checkers/shell/index.js";
9
+ import { traceChecker } from "./checkers/trace/index.js";
10
+ import { loadCase, loadCases } from "./engine/authoring.js";
11
+ import { ConfigError, errorMessage } from "./engine/config.js";
12
+ import { addChecker, addRunner, createRegistry, loadTrustedImplementations } from "./engine/registry.js";
13
+ import { executeEvaluation, prepareEvaluation } from "./engine/run.js";
14
+ import { formatMatrix, formatReport } from "./engine/report.js";
15
+ import { runOutcome } from "./engine/results.js";
16
+ import { describePlacement } from "./engine/placement.js";
17
+ import { formatResolvedCase } from "./engine/view.js";
18
+ import { piRunner } from "./runners/pi/index.js";
19
+ import { noopRunner } from "./runners/noop/index.js";
20
+ import { runAgentCommand } from "./runners/acp/commands.js";
21
+ import { acpRunner } from "./runners/acp/index.js";
22
+ const USAGE = `Usage: agent-evals <command> <config.yml> [options]
23
+
24
+ Commands:
25
+ run <config.yml> Execute the selected case, or every case when --case is omitted
26
+ view <config.yml> Show the resolved case, its field origins and its placement
27
+ report <results-dir>... Print a session report from retained run records
28
+ config <agent.yml> Query ACP configuration values without prompting
29
+ login <agent.yml> Run the declared native command and save login files
30
+
31
+ Options:
32
+ --case <name> Named case to select (required by view for files with cases)
33
+ --reps <n> Repeat each selected case n times, serially (default: 1)
34
+ --results-dir <path> Where run records are written (default: .agent-evals)
35
+ --extension-dir <path> Trusted extension root, one implementation per subdirectory (repeatable)
36
+ --files With view: list every placed and excluded path
37
+ --matrix With report: one table of checks by case instead of the session report
38
+ --help Show this help
39
+
40
+ Configuration errors exit with code 2 before any run resource is created.
41
+ `;
42
+ async function main(argv) {
43
+ const major = Number(process.versions.node.split(".")[0] ?? "0");
44
+ if (major < 24) {
45
+ process.stderr.write(`error: Node.js 24 or newer is required (running ${process.versions.node})\n`);
46
+ return 2;
47
+ }
48
+ let options;
49
+ try {
50
+ options = parseArguments(argv);
51
+ }
52
+ catch (error) {
53
+ if (error instanceof HelpRequested) {
54
+ process.stdout.write(USAGE);
55
+ return 0;
56
+ }
57
+ process.stderr.write(`error: ${errorMessage(error)}\n\n${USAGE}`);
58
+ return 2;
59
+ }
60
+ try {
61
+ if (options.command === "view") {
62
+ const resolved = await loadCase(options.configPath, {
63
+ ...(options.caseName === undefined ? {} : { caseName: options.caseName }),
64
+ });
65
+ const placement = await describePlacement(resolved);
66
+ process.stdout.write(formatResolvedCase(resolved, { placement, files: options.showFiles }));
67
+ return 0;
68
+ }
69
+ if (options.command === "report") {
70
+ const records = await readRecords(options.configPath, ...options.extraPaths);
71
+ process.stdout.write(options.matrix ? formatMatrix(records) : formatReport(records));
72
+ return 0;
73
+ }
74
+ if (options.command === "config" || options.command === "login") {
75
+ const abort = new AbortController();
76
+ const onSignal = () => abort.abort();
77
+ process.on("SIGINT", onSignal);
78
+ process.on("SIGTERM", onSignal);
79
+ try {
80
+ process.stdout.write(await runAgentCommand(options.command, options.configPath, abort.signal));
81
+ return 0;
82
+ }
83
+ finally {
84
+ process.off("SIGINT", onSignal);
85
+ process.off("SIGTERM", onSignal);
86
+ }
87
+ }
88
+ return await runCommand(options);
89
+ }
90
+ catch (error) {
91
+ if (error instanceof ConfigError) {
92
+ process.stderr.write(`configuration error: ${error.message}\n`);
93
+ }
94
+ else {
95
+ process.stderr.write(`error: ${errorMessage(error)}\n`);
96
+ }
97
+ return 2;
98
+ }
99
+ }
100
+ async function runCommand(options) {
101
+ const registry = createRegistry();
102
+ addRunner(registry, piRunner, "built-in");
103
+ addRunner(registry, acpRunner, "built-in");
104
+ addRunner(registry, noopRunner, "built-in");
105
+ addChecker(registry, fileChecker, "built-in");
106
+ addChecker(registry, judgeChecker, "built-in");
107
+ addChecker(registry, mockChecker, "built-in");
108
+ addChecker(registry, shellChecker, "built-in");
109
+ addChecker(registry, traceChecker, "built-in");
110
+ const abort = new AbortController();
111
+ let interrupted = false;
112
+ const onSignal = () => {
113
+ if (interrupted) {
114
+ process.exit(130);
115
+ }
116
+ interrupted = true;
117
+ abort.abort();
118
+ };
119
+ process.on("SIGINT", onSignal);
120
+ process.on("SIGTERM", onSignal);
121
+ try {
122
+ // Resolve and validate every selected case before the first one runs, so a configuration
123
+ // error in any of them runs none.
124
+ const cases = await loadCases(options.configPath, {
125
+ ...(options.caseName === undefined ? {} : { caseName: options.caseName }),
126
+ });
127
+ await loadTrustedImplementations(registry, { extensionDirs: options.extensionDirs });
128
+ const resultsDir = options.resultsDir ?? resolve(".agent-evals");
129
+ const prepared = [];
130
+ for (let rep = 0; rep < options.reps; rep += 1) {
131
+ for (const entry of cases) {
132
+ prepared.push(await prepareEvaluation({ case: entry, registry, resultsDir, signal: abort.signal }));
133
+ }
134
+ }
135
+ // One repetition of one case keeps the single-run output; so does an ordinary document.
136
+ if (options.reps === 1 && (options.caseName !== undefined || !cases.some((entry) => entry.name !== undefined))) {
137
+ const record = await executeEvaluation(prepared[0]);
138
+ printRecord(record, resultsDir);
139
+ process.stdout.write(`\n${formatReport([record])}`);
140
+ return exitCode(record);
141
+ }
142
+ const records = [];
143
+ for (const entry of prepared) {
144
+ // Cancellation stops the rest; an error or a failed check does not.
145
+ if (abort.signal.aborted)
146
+ break;
147
+ records.push(await executeEvaluation(entry));
148
+ }
149
+ const casesPerRep = cases.length;
150
+ for (const [index, record] of records.entries()) {
151
+ const repLabel = options.reps === 1 ? "" : `rep ${Math.floor(index / casesPerRep) + 1}/${options.reps} `;
152
+ printCaseLine(record, resultsDir, repLabel);
153
+ }
154
+ const notRunCases = prepared.length - records.length;
155
+ if (notRunCases > 0) {
156
+ process.stdout.write(`cancelled: ${notRunCases} run${notRunCases === 1 ? "" : "s"} not run\n`);
157
+ // The retained runs still get their report; the exit code carries the shortfall.
158
+ if (records.length > 0)
159
+ process.stdout.write(`\n${formatReport(records)}`);
160
+ return 2;
161
+ }
162
+ // Every invocation ends with a session report, one run or many; nothing is written to disk.
163
+ process.stdout.write(`\n${formatReport(records)}`);
164
+ return aggregateExit(records);
165
+ }
166
+ finally {
167
+ process.off("SIGINT", onSignal);
168
+ process.off("SIGTERM", onSignal);
169
+ }
170
+ }
171
+ function parseArguments(argv) {
172
+ let parsed;
173
+ try {
174
+ parsed = parseArgs({
175
+ args: argv,
176
+ allowPositionals: true,
177
+ strict: true,
178
+ options: {
179
+ case: { type: "string" },
180
+ "results-dir": { type: "string" },
181
+ "extension-dir": { type: "string", multiple: true },
182
+ files: { type: "boolean" },
183
+ matrix: { type: "boolean" },
184
+ reps: { type: "string" },
185
+ help: { type: "boolean", short: "h" },
186
+ },
187
+ });
188
+ }
189
+ catch (error) {
190
+ throw new ConfigError(errorMessage(error));
191
+ }
192
+ const { values, positionals } = parsed;
193
+ if (values.help === true) {
194
+ throw new HelpRequested();
195
+ }
196
+ const [command, rawConfigPath, ...unexpected] = positionals;
197
+ if (command !== "run" && command !== "view" && command !== "report" && command !== "config" && command !== "login") {
198
+ throw new ConfigError(command === undefined ? "a command is required" : `unknown command: ${command}`);
199
+ }
200
+ if (rawConfigPath === undefined) {
201
+ throw new ConfigError(command === "report" ? "a results directory is required" : "a configuration file is required");
202
+ }
203
+ if (command !== "report" && unexpected.length > 0) {
204
+ throw new ConfigError(`unexpected argument: ${unexpected[0]}`);
205
+ }
206
+ if ((command === "config" || command === "login") &&
207
+ (values.case !== undefined ||
208
+ values["results-dir"] !== undefined ||
209
+ values["extension-dir"] !== undefined ||
210
+ values.reps !== undefined)) {
211
+ throw new ConfigError(`${command} accepts only an agent configuration file, not case or run options`);
212
+ }
213
+ const extensionDirs = (values["extension-dir"] ?? []).map((directory) => resolve(directory));
214
+ if (command === "view" &&
215
+ (values["results-dir"] !== undefined || extensionDirs.length > 0 || values.reps !== undefined)) {
216
+ throw new ConfigError("view does not accept --results-dir, --extension-dir or --reps");
217
+ }
218
+ if (command !== "view" && values.files === true) {
219
+ throw new ConfigError("--files applies only to view");
220
+ }
221
+ if (command !== "report" && values.matrix === true) {
222
+ throw new ConfigError("--matrix applies only to report");
223
+ }
224
+ if (command === "report" &&
225
+ (values.case !== undefined ||
226
+ values["results-dir"] !== undefined ||
227
+ values["extension-dir"] !== undefined ||
228
+ values.reps !== undefined)) {
229
+ throw new ConfigError("report accepts only results directories");
230
+ }
231
+ const reps = values.reps === undefined ? 1 : expectReps(values.reps);
232
+ return {
233
+ command,
234
+ configPath: resolve(rawConfigPath),
235
+ ...(values.case === undefined ? {} : { caseName: values.case }),
236
+ ...(values["results-dir"] === undefined ? {} : { resultsDir: resolve(values["results-dir"]) }),
237
+ extensionDirs,
238
+ showFiles: values.files === true,
239
+ matrix: values.matrix === true,
240
+ reps,
241
+ extraPaths: unexpected.map((path) => resolve(path)),
242
+ };
243
+ }
244
+ /** A repetition count is a positive integer written in decimal that a loop can count to. */
245
+ function expectReps(value) {
246
+ const count = Number(value);
247
+ if (!/^[0-9]+$/.test(value) || !Number.isSafeInteger(count) || count < 1) {
248
+ throw new ConfigError(`--reps must be a positive integer, got ${JSON.stringify(value)}`);
249
+ }
250
+ return count;
251
+ }
252
+ /**
253
+ * Read every retained run record under the given paths. A path may be a results directory (walked
254
+ * recursively), a single run directory or a `result.json` file.
255
+ */
256
+ async function readRecords(...paths) {
257
+ const files = [];
258
+ for (const path of paths) {
259
+ for (const file of await findResultFiles(path))
260
+ files.push(file);
261
+ }
262
+ if (files.length === 0) {
263
+ throw new ConfigError(`no result.json found under ${paths.join(", ")}`);
264
+ }
265
+ const records = [];
266
+ const seen = new Set();
267
+ for (const file of files) {
268
+ let parsed;
269
+ try {
270
+ parsed = JSON.parse(await readFile(file, "utf8"));
271
+ }
272
+ catch (error) {
273
+ throw new ConfigError(`cannot read ${file}: ${errorMessage(error)}`);
274
+ }
275
+ if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.checks)) {
276
+ throw new ConfigError(`${file} is not an agent-evals result record`);
277
+ }
278
+ const record = parsed;
279
+ // Overlapping arguments can name one record twice; a record is one run however it is reached.
280
+ if (seen.has(record.runId))
281
+ continue;
282
+ seen.add(record.runId);
283
+ records.push(record);
284
+ }
285
+ return records;
286
+ }
287
+ async function findResultFiles(path) {
288
+ let info;
289
+ try {
290
+ info = await stat(path);
291
+ }
292
+ catch (error) {
293
+ throw new ConfigError(`cannot read ${path}: ${errorMessage(error)}`);
294
+ }
295
+ if (info.isFile()) {
296
+ return [path];
297
+ }
298
+ const found = [];
299
+ for (const entry of await readdir(path, { withFileTypes: true })) {
300
+ const child = join(path, entry.name);
301
+ if (entry.isDirectory()) {
302
+ for (const file of await findResultFiles(child))
303
+ found.push(file);
304
+ }
305
+ else if (entry.name === "result.json") {
306
+ found.push(child);
307
+ }
308
+ }
309
+ return found.sort();
310
+ }
311
+ function printRecord(record, resultsDir) {
312
+ const caseLabel = record.case.name === undefined ? record.case.path : `${record.case.name} (${record.case.path})`;
313
+ const lines = [`run ${record.runId}: ${runOutcome(record)}`, ` case: ${caseLabel}`];
314
+ lines.push(` runner ${record.runner.type}: ${record.runner.status} (${record.runner.durationMs}ms)`);
315
+ for (const check of record.checks) {
316
+ lines.push(` ${check.status.toUpperCase().padEnd(5)} ${check.checker} ${check.subject}${check.reason.length > 0 ? ` — ${check.reason}` : ""}`);
317
+ }
318
+ if (record.error !== undefined) {
319
+ lines.push(` error: ${record.error}`);
320
+ }
321
+ lines.push(` results: ${join(resultsDir, record.runId, "result.json")}`);
322
+ process.stdout.write(lines.join("\n") + "\n");
323
+ }
324
+ /** The outcome a reader sees, with the case's `expect` applied; an error is still an error. */
325
+ function exitCode(record) {
326
+ switch (runOutcome(record)) {
327
+ case "pass":
328
+ case "expected-fail":
329
+ return 0;
330
+ case "fail":
331
+ case "unexpected-pass":
332
+ return 1;
333
+ default:
334
+ return 2;
335
+ }
336
+ }
337
+ /** One summary line per executed case: name, status and the retained result record. */
338
+ function printCaseLine(record, resultsDir, prefix = "") {
339
+ const name = record.case.name ?? record.case.path;
340
+ process.stdout.write(`${prefix}${name}: ${runOutcome(record)} ${join(resultsDir, record.runId, "result.json")}\n`);
341
+ }
342
+ /** Zero only when every case passed, 1 for failed checks, 2 for anything that could not be judged. */
343
+ function aggregateExit(records) {
344
+ if (records.every((record) => exitCode(record) === 0)) {
345
+ return 0;
346
+ }
347
+ return records.some((record) => exitCode(record) === 2) ? 2 : 1;
348
+ }
349
+ class HelpRequested extends Error {
350
+ }
351
+ const code = await main(process.argv.slice(2));
352
+ process.exitCode = code;
@@ -0,0 +1,24 @@
1
+ import type { ZodType } from "zod";
2
+ import { type ValueSource } from "./values.js";
3
+ import { type ResolvedCase } from "./config.js";
4
+ export interface CaseSelection {
5
+ /** The named case to select. Required when the document defines `cases`. */
6
+ readonly caseName?: string;
7
+ }
8
+ /**
9
+ * Resolve one YAML authoring document to a single case.
10
+ *
11
+ * `view` and execution both use this function, so they see the same values and
12
+ * field origins. Runtime implementation validation remains a separate step.
13
+ */
14
+ export declare function loadCase(path: string, selection?: CaseSelection): Promise<ResolvedCase>;
15
+ /**
16
+ * Resolve every selected case in declaration order: the named one when a name is
17
+ * given, all entries of a `cases` document when it is not, or the one ordinary case.
18
+ */
19
+ export declare function loadCases(path: string, selection?: CaseSelection): Promise<readonly ResolvedCase[]>;
20
+ /** Load a standalone implementation object using the same YAML and placeholder rules as cases. */
21
+ export declare function loadImplementationParameters<P>(path: string, schema: ZodType<P>, source: ValueSource): Promise<{
22
+ params: P;
23
+ dir: string;
24
+ }>;