@lelouchhe/agent-evals 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/.env.example +27 -0
  2. package/LICENSE +21 -0
  3. package/README.md +121 -2
  4. package/dist/checkers/file/index.d.ts +26 -0
  5. package/dist/checkers/file/index.js +396 -0
  6. package/dist/checkers/judge/index.d.ts +20 -0
  7. package/dist/checkers/judge/index.js +474 -0
  8. package/dist/checkers/judge/prompt.d.ts +19 -0
  9. package/dist/checkers/judge/prompt.js +55 -0
  10. package/dist/checkers/judge/trace.d.ts +6 -0
  11. package/dist/checkers/judge/trace.js +41 -0
  12. package/dist/checkers/mock/index.d.ts +18 -0
  13. package/dist/checkers/mock/index.js +127 -0
  14. package/dist/checkers/shell/index.d.ts +10 -0
  15. package/dist/checkers/shell/index.js +61 -0
  16. package/dist/checkers/trace/index.d.ts +22 -0
  17. package/dist/checkers/trace/index.js +183 -0
  18. package/dist/cli.d.ts +2 -0
  19. package/dist/cli.js +453 -0
  20. package/dist/engine/authoring.d.ts +24 -0
  21. package/dist/engine/authoring.js +356 -0
  22. package/dist/engine/check-runner.d.ts +1 -0
  23. package/dist/engine/check-runner.js +127 -0
  24. package/dist/engine/check-sandbox.d.ts +18 -0
  25. package/dist/engine/check-sandbox.js +171 -0
  26. package/dist/engine/config.d.ts +171 -0
  27. package/dist/engine/config.js +368 -0
  28. package/dist/engine/env-source.d.ts +10 -0
  29. package/dist/engine/env-source.js +114 -0
  30. package/dist/engine/files.d.ts +84 -0
  31. package/dist/engine/files.js +304 -0
  32. package/dist/engine/forwarder.sh +61 -0
  33. package/dist/engine/ignore.d.ts +29 -0
  34. package/dist/engine/ignore.js +67 -0
  35. package/dist/engine/messages.d.ts +8 -0
  36. package/dist/engine/messages.js +9 -0
  37. package/dist/engine/mock-match.d.ts +44 -0
  38. package/dist/engine/mock-match.js +104 -0
  39. package/dist/engine/mocks.d.ts +35 -0
  40. package/dist/engine/mocks.js +336 -0
  41. package/dist/engine/params.d.ts +18 -0
  42. package/dist/engine/params.js +96 -0
  43. package/dist/engine/placement.d.ts +26 -0
  44. package/dist/engine/placement.js +107 -0
  45. package/dist/engine/regex.d.ts +10 -0
  46. package/dist/engine/regex.js +16 -0
  47. package/dist/engine/registry.d.ts +243 -0
  48. package/dist/engine/registry.js +127 -0
  49. package/dist/engine/report.d.ts +17 -0
  50. package/dist/engine/report.js +420 -0
  51. package/dist/engine/results.d.ts +50 -0
  52. package/dist/engine/results.js +42 -0
  53. package/dist/engine/run.d.ts +50 -0
  54. package/dist/engine/run.js +710 -0
  55. package/dist/engine/runtime-assets.d.ts +6 -0
  56. package/dist/engine/runtime-assets.js +11 -0
  57. package/dist/engine/skills.d.ts +49 -0
  58. package/dist/engine/skills.js +270 -0
  59. package/dist/engine/truncate.d.ts +3 -0
  60. package/dist/engine/truncate.js +7 -0
  61. package/dist/engine/values.d.ts +18 -0
  62. package/dist/engine/values.js +75 -0
  63. package/dist/engine/view.d.ts +10 -0
  64. package/dist/engine/view.js +150 -0
  65. package/dist/engine/workspace.d.ts +63 -0
  66. package/dist/engine/workspace.js +305 -0
  67. package/dist/index.d.ts +16 -0
  68. package/dist/index.js +7 -0
  69. package/dist/platform/macos/launch.d.ts +13 -0
  70. package/dist/platform/macos/launch.js +14 -0
  71. package/dist/platform/macos/policy.d.ts +33 -0
  72. package/dist/platform/macos/policy.js +131 -0
  73. package/dist/platform/macos/supervise.d.ts +26 -0
  74. package/dist/platform/macos/supervise.js +98 -0
  75. package/dist/platform/macos/supervisor.sh +13 -0
  76. package/dist/runners/acp/agent.d.ts +17 -0
  77. package/dist/runners/acp/agent.js +38 -0
  78. package/dist/runners/acp/commands.d.ts +2 -0
  79. package/dist/runners/acp/commands.js +112 -0
  80. package/dist/runners/acp/environment.d.ts +71 -0
  81. package/dist/runners/acp/environment.js +280 -0
  82. package/dist/runners/acp/index.d.ts +21 -0
  83. package/dist/runners/acp/index.js +135 -0
  84. package/dist/runners/acp/session.d.ts +7 -0
  85. package/dist/runners/acp/session.js +48 -0
  86. package/dist/runners/acp/trace.d.ts +23 -0
  87. package/dist/runners/acp/trace.js +44 -0
  88. package/dist/runners/acp/usage.d.ts +12 -0
  89. package/dist/runners/acp/usage.js +56 -0
  90. package/dist/runners/noop/index.d.ts +12 -0
  91. package/dist/runners/noop/index.js +22 -0
  92. package/dist/runners/pi/index.d.ts +21 -0
  93. package/dist/runners/pi/index.js +116 -0
  94. package/dist/runners/pi/params.d.ts +10 -0
  95. package/dist/runners/pi/params.js +3 -0
  96. package/dist/runners/pi/rpc.d.ts +30 -0
  97. package/dist/runners/pi/rpc.js +341 -0
  98. package/dist/runners/pi/safe-process-group.d.ts +7 -0
  99. package/dist/runners/pi/safe-process-group.js +13 -0
  100. package/dist/runners/pi/session.d.ts +56 -0
  101. package/dist/runners/pi/session.js +298 -0
  102. package/dist/runners/pi/shell-wrapper.sh +46 -0
  103. package/dist/runners/pi/supervisor.d.ts +1 -0
  104. package/dist/runners/pi/supervisor.js +101 -0
  105. package/package.json +77 -4
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Resolve a sibling runtime module that is executed separately from this module
3
+ * (a worker, or sandbox-resident supervisor). Source runs use `.ts`; built
4
+ * package runs use emitted `.js`.
5
+ */
6
+ export declare function siblingRuntimeModule(moduleUrl: string, name: string): URL;
@@ -0,0 +1,11 @@
1
+ import { extname } from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+ /**
4
+ * Resolve a sibling runtime module that is executed separately from this module
5
+ * (a worker, or sandbox-resident supervisor). Source runs use `.ts`; built
6
+ * package runs use emitted `.js`.
7
+ */
8
+ export function siblingRuntimeModule(moduleUrl, name) {
9
+ const extension = extname(fileURLToPath(moduleUrl)) === ".ts" ? ".ts" : ".js";
10
+ return new URL(`./${name}${extension}`, moduleUrl);
11
+ }
@@ -0,0 +1,49 @@
1
+ import type { TraceEntry } from "./registry.js";
2
+ import { type RunRoot } from "./workspace.js";
3
+ /** One skill a run consulted, as far as its trace and workspace show. */
4
+ export interface SkillConsultation {
5
+ /** The skill's frontmatter `name`, or the parent directory's when no source gives a frontmatter name. */
6
+ readonly name: string;
7
+ /** True when `name` is the parent directory's, because neither the baseline nor the output named it. */
8
+ readonly fromDirectory: boolean;
9
+ }
10
+ /**
11
+ * The run directories the derivation reads: the live workspace and HOME a trace names, and what
12
+ * the case placed in each before the agent started.
13
+ */
14
+ export interface SkillSources {
15
+ /** The workspace as the agent left it; relative trace paths are resolved against it. */
16
+ readonly workspace: RunRoot;
17
+ /** The run HOME as the agent left it; `~/` and absolute paths inside it resolve here. */
18
+ readonly home: RunRoot;
19
+ /** The workspace's initial snapshot, where a placed skill's frontmatter is read. */
20
+ readonly workspaceBaseline: RunRoot;
21
+ /** What the case placed in HOME; agent-file and login content is not part of it. */
22
+ readonly homeBaseline: RunRoot;
23
+ }
24
+ /**
25
+ * The skills one run consulted, derived from its trace and the run's workspace and baseline.
26
+ *
27
+ * ACP has no skill update, so this reads the two forms harnesses report: a completed
28
+ * non-read tool call carrying `rawInput.skill` (Claude Code, GitHub Copilot CLI), and a
29
+ * completed `read` of a `SKILL.md` (Pi). Only completed tool calls count, and a skill is
30
+ * one consultation however many times or chunks it was read.
31
+ *
32
+ * A skill the case placed, in the workspace or in HOME, is named from its frontmatter in that
33
+ * root's baseline. A read outside both roots is named from the text it returned, then from the
34
+ * skill's parent directory.
35
+ */
36
+ export declare function skillConsultations(trace: readonly TraceEntry[], sources: SkillSources): Promise<readonly SkillConsultation[]>;
37
+ /** A skill whose placed `SKILL.md` an executed command's text named, reported but never counted. */
38
+ export interface ShellSkillAccess {
39
+ /** The skill's frontmatter `name` in the baseline, or its parent directory's. */
40
+ readonly name: string;
41
+ }
42
+ /**
43
+ * The placed skills whose `SKILL.md` path an executed command's text named.
44
+ *
45
+ * Whether reading a skill body through a shell is a consultation is ambiguous, so this is
46
+ * reported separately and never counts as one. Only a `SKILL.md` a baseline placed is
47
+ * recognized; a file the agent created is not the skill it started with.
48
+ */
49
+ export declare function shellSkillAccess(trace: readonly TraceEntry[], sources: SkillSources): Promise<readonly ShellSkillAccess[]>;
@@ -0,0 +1,270 @@
1
+ import { realpath } from "node:fs/promises";
2
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
3
+ import { parse } from "yaml";
4
+ import { readRunFile } from "./workspace.js";
5
+ /** The file every harness's skill loader reads when it consults a skill's body. */
6
+ const SKILL_FILE = "SKILL.md";
7
+ const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
8
+ /**
9
+ * The skills one run consulted, derived from its trace and the run's workspace and baseline.
10
+ *
11
+ * ACP has no skill update, so this reads the two forms harnesses report: a completed
12
+ * non-read tool call carrying `rawInput.skill` (Claude Code, GitHub Copilot CLI), and a
13
+ * completed `read` of a `SKILL.md` (Pi). Only completed tool calls count, and a skill is
14
+ * one consultation however many times or chunks it was read.
15
+ *
16
+ * A skill the case placed, in the workspace or in HOME, is named from its frontmatter in that
17
+ * root's baseline. A read outside both roots is named from the text it returned, then from the
18
+ * skill's parent directory.
19
+ */
20
+ export async function skillConsultations(trace, sources) {
21
+ const recognized = [];
22
+ const frontmatterTargets = new Set();
23
+ for (const entry of trace) {
24
+ if (entry.type !== "tool" || entry.status !== "completed")
25
+ continue;
26
+ if (entry.kind !== "read") {
27
+ const name = trimmedField(entry.rawInput, "skill");
28
+ if (name !== undefined)
29
+ recognized.push({ name, fromDirectory: false });
30
+ continue;
31
+ }
32
+ const read = await recognizeRead(entry, sources);
33
+ if (read === undefined)
34
+ continue;
35
+ if (!read.consultation.fromDirectory)
36
+ frontmatterTargets.add(read.key);
37
+ recognized.push({ key: read.key, ...read.consultation });
38
+ }
39
+ const consultations = new Map();
40
+ for (const item of recognized) {
41
+ // A chunk without frontmatter on a file another chunk already named from frontmatter adds nothing.
42
+ if (item.fromDirectory && item.key !== undefined && frontmatterTargets.has(item.key))
43
+ continue;
44
+ const consultation = { name: item.name, fromDirectory: item.fromDirectory };
45
+ const existing = consultations.get(consultation.name);
46
+ if (existing === undefined || (existing.fromDirectory && !consultation.fromDirectory)) {
47
+ consultations.set(consultation.name, consultation);
48
+ }
49
+ }
50
+ return [...consultations.values()];
51
+ }
52
+ /**
53
+ * The placed skills whose `SKILL.md` path an executed command's text named.
54
+ *
55
+ * Whether reading a skill body through a shell is a consultation is ambiguous, so this is
56
+ * reported separately and never counts as one. Only a `SKILL.md` a baseline placed is
57
+ * recognized; a file the agent created is not the skill it started with.
58
+ */
59
+ export async function shellSkillAccess(trace, sources) {
60
+ const found = new Map();
61
+ for (const entry of trace) {
62
+ if (entry.type !== "tool" || entry.status !== "completed" || entry.kind !== "execute")
63
+ continue;
64
+ const command = pathField(entry.rawInput, "command");
65
+ if (command === undefined)
66
+ continue;
67
+ for (const token of commandSkillPaths(command)) {
68
+ const name = await placedSkillName(token, sources);
69
+ if (name !== undefined && !found.has(name))
70
+ found.set(name, { name });
71
+ }
72
+ }
73
+ return [...found.values()];
74
+ }
75
+ /** Path-shaped tokens of a command whose basename is `SKILL.md`, in command order. */
76
+ function commandSkillPaths(command) {
77
+ return command.split(/[\s;|&()<>'"`]+/).filter((token) => token.length > 0 && basename(token) === SKILL_FILE);
78
+ }
79
+ /** The skill a workspace path names, when the baseline placed a `SKILL.md` there. */
80
+ async function placedSkillName(target, sources) {
81
+ const resolved = await resolveTarget(sources, target);
82
+ if (resolved.placed === undefined)
83
+ return undefined;
84
+ let text;
85
+ try {
86
+ text = (await readRunFile(resolved.placed.baseline, resolved.placed.relativePath)).toString("utf8");
87
+ }
88
+ catch {
89
+ // Not placed by the baseline, unreadable, or not a regular file.
90
+ return undefined;
91
+ }
92
+ const name = frontmatterName(text);
93
+ if (name !== undefined)
94
+ return name;
95
+ const directory = basename(dirname(target));
96
+ return directory === "" || directory === "." || directory === "/" ? undefined : directory;
97
+ }
98
+ async function recognizeRead(entry, sources) {
99
+ // A skill loader that reads the body has to name the SKILL.md it read.
100
+ const target = readTarget(entry);
101
+ if (target === undefined)
102
+ return undefined;
103
+ const resolved = await resolveTarget(sources, target);
104
+ if (resolved.placed !== undefined) {
105
+ const fromBaseline = await baselineName(resolved.placed.baseline, resolved.placed.relativePath);
106
+ if (fromBaseline !== undefined) {
107
+ return { key: resolved.key, consultation: { name: fromBaseline, fromDirectory: false } };
108
+ }
109
+ }
110
+ const fromOutput = frontmatterName(returnedText(entry));
111
+ if (fromOutput !== undefined)
112
+ return { key: resolved.key, consultation: { name: fromOutput, fromDirectory: false } };
113
+ const directory = basename(dirname(target));
114
+ if (directory === "" || directory === "." || directory === "/")
115
+ return undefined;
116
+ return { key: resolved.key, consultation: { name: directory, fromDirectory: true } };
117
+ }
118
+ /** The path a completed read targeted, when it names a skill file. */
119
+ function readTarget(entry) {
120
+ const locations = Array.isArray(entry.locations) ? entry.locations : [];
121
+ const location = locations[0];
122
+ const path = pathField(location, "path") ?? pathField(entry.rawInput, "path") ?? pathField(entry.rawInput, "file_path");
123
+ if (path === undefined || path.endsWith("/") || path.endsWith("\\"))
124
+ return undefined;
125
+ return basename(path) === SKILL_FILE ? path : undefined;
126
+ }
127
+ /** The frontmatter name of the same file in the baseline. */
128
+ async function baselineName(baseline, path) {
129
+ try {
130
+ return frontmatterName((await readRunFile(baseline, path)).toString("utf8"));
131
+ }
132
+ catch {
133
+ // A path outside the snapshot, unreadable, or not a regular file names nothing here;
134
+ // the returned text and the parent directory remain.
135
+ return undefined;
136
+ }
137
+ }
138
+ /**
139
+ * Resolve a read target to a stable identity and, when it names a run root, the path inside it
140
+ * and the baseline that recorded the case's placement there. Never follows agent-writable
141
+ * symlinks inside a live root.
142
+ */
143
+ async function resolveTarget(sources, target) {
144
+ if (target.startsWith("~/")) {
145
+ const fullPath = resolve(sources.home.path, target.slice(2));
146
+ const relativePath = await relativeWithin(sources.home.path, fullPath);
147
+ return relativePath === undefined
148
+ ? { key: `outside:${await canonicalExternalPath(fullPath)}` }
149
+ : { key: `home:${relativePath}`, placed: { relativePath, baseline: sources.homeBaseline } };
150
+ }
151
+ const fullPath = isAbsolute(target) ? target : resolve(sources.workspace.path, target);
152
+ const workspacePath = await relativeWithin(sources.workspace.path, fullPath);
153
+ if (workspacePath !== undefined) {
154
+ return {
155
+ key: `workspace:${workspacePath}`,
156
+ placed: { relativePath: workspacePath, baseline: sources.workspaceBaseline },
157
+ };
158
+ }
159
+ const homePath = await relativeWithin(sources.home.path, fullPath);
160
+ if (homePath !== undefined) {
161
+ return { key: `home:${homePath}`, placed: { relativePath: homePath, baseline: sources.homeBaseline } };
162
+ }
163
+ return { key: `outside:${await canonicalExternalPath(fullPath)}` };
164
+ }
165
+ /** Canonicalize existing ancestors of an external path so `/var/…` and `/private/var/…` match. */
166
+ async function canonicalExternalPath(target) {
167
+ const missing = [];
168
+ let probe = resolve(target);
169
+ while (true) {
170
+ try {
171
+ return join(await realpath(probe), ...missing);
172
+ }
173
+ catch {
174
+ const parent = dirname(probe);
175
+ if (parent === probe)
176
+ return resolve(target);
177
+ missing.unshift(basename(probe));
178
+ probe = parent;
179
+ }
180
+ }
181
+ }
182
+ /**
183
+ * Strip the outermost run-root prefix from an absolute trace path (`/var/…` vs `/private/var/…`,
184
+ * or a symlinked temp root) without following agent-writable symlinks inside the live root.
185
+ * Walking from `/` downward finds the host's root before entering any of its children.
186
+ */
187
+ async function relativeWithin(rootPath, target) {
188
+ const segments = resolve(target).split("/").filter(Boolean);
189
+ let probe = "/";
190
+ for (const [index, segment] of segments.entries()) {
191
+ probe = join(probe, segment);
192
+ const rest = segments.slice(index + 1);
193
+ if (probe === rootPath) {
194
+ return rest.length === 0 ? undefined : join(...rest);
195
+ }
196
+ try {
197
+ if ((await realpath(probe)) === rootPath) {
198
+ return rest.length === 0 ? undefined : join(...rest);
199
+ }
200
+ }
201
+ catch {
202
+ // An unreadable or missing prefix outside the root means this path cannot enter it.
203
+ return undefined;
204
+ }
205
+ }
206
+ return undefined;
207
+ }
208
+ /** The text a call returned, from its content blocks or otherwise its raw output. */
209
+ function returnedText(entry) {
210
+ const texts = textBlocks(entry.content);
211
+ if (texts.length > 0)
212
+ return texts.join("\n");
213
+ if (typeof entry.rawOutput === "string")
214
+ return entry.rawOutput;
215
+ const raw = textBlocks(entry.rawOutput);
216
+ return raw.length === 0 ? undefined : raw.join("\n");
217
+ }
218
+ /** Text of plain text blocks, or of `{ type: "content", content: { type: "text" } }` blocks. */
219
+ function textBlocks(value) {
220
+ const container = typeof value === "object" && value !== null ? value : undefined;
221
+ const blocks = Array.isArray(value)
222
+ ? value
223
+ : Array.isArray(container?.content)
224
+ ? container.content
225
+ : [value];
226
+ return blocks.flatMap((block) => {
227
+ if (typeof block === "string")
228
+ return [block];
229
+ if (typeof block !== "object" || block === null)
230
+ return [];
231
+ const item = block;
232
+ if (item.type === "text" && typeof item.text === "string")
233
+ return [item.text];
234
+ if (item.content?.type === "text" && typeof item.content.text === "string")
235
+ return [item.content.text];
236
+ return [];
237
+ });
238
+ }
239
+ /** The `name` a Markdown frontmatter block declares, if it declares a non-empty one. */
240
+ function frontmatterName(text) {
241
+ const block = text === undefined ? undefined : FRONTMATTER.exec(text)?.[1];
242
+ if (block === undefined)
243
+ return undefined;
244
+ let frontmatter;
245
+ try {
246
+ frontmatter = parse(block);
247
+ }
248
+ catch {
249
+ return undefined;
250
+ }
251
+ if (typeof frontmatter !== "object" || frontmatter === null)
252
+ return undefined;
253
+ return trimmedField(frontmatter, "name");
254
+ }
255
+ /** Read a path field verbatim without trimming legal leading or trailing filename spaces. */
256
+ function pathField(value, key) {
257
+ if (typeof value !== "object" || value === null)
258
+ return undefined;
259
+ const field = value[key];
260
+ return typeof field === "string" && field.trim().length > 0 ? field : undefined;
261
+ }
262
+ function trimmedField(value, key) {
263
+ if (typeof value !== "object" || value === null)
264
+ return undefined;
265
+ const field = value[key];
266
+ if (typeof field !== "string")
267
+ return undefined;
268
+ const trimmed = field.trim();
269
+ return trimmed.length > 0 ? trimmed : undefined;
270
+ }
@@ -0,0 +1,3 @@
1
+ /** Truncate a string to a UTF-16 code-unit limit, appending an ellipsis when cut. */
2
+ export declare function truncate(value: string, limit: number): string;
3
+ export declare function truncateNullable(value: string | null, limit: number): string | null;
@@ -0,0 +1,7 @@
1
+ /** Truncate a string to a UTF-16 code-unit limit, appending an ellipsis when cut. */
2
+ export function truncate(value, limit) {
3
+ return value.length <= limit ? value : value.slice(0, limit) + "…";
4
+ }
5
+ export function truncateNullable(value, limit) {
6
+ return value === null ? null : truncate(value, limit);
7
+ }
@@ -0,0 +1,18 @@
1
+ import type { EnvSource } from "./env-source.js";
2
+ /** Built-in variables: the run's directories, known before they are created. */
3
+ export interface RunVariables {
4
+ readonly HOME: string;
5
+ readonly TMPDIR: string;
6
+ }
7
+ /** Everything a `${...}` placeholder can read. */
8
+ export interface ValueSource {
9
+ readonly env: EnvSource;
10
+ readonly run: RunVariables;
11
+ }
12
+ /** Reject malformed placeholders anywhere in a value without reading any source. */
13
+ export declare function checkPlaceholders(value: unknown, where: string): void;
14
+ /**
15
+ * Substitute every placeholder in every string of a parameter value. Substituted
16
+ * text is not scanned again; keys, `$type` and non-string values are unchanged.
17
+ */
18
+ export declare function substituteValues<T>(value: T, where: string, source: ValueSource): Promise<T>;
@@ -0,0 +1,75 @@
1
+ import { ConfigError, ENV_NAME_PATTERN } from "./config.js";
2
+ const BUILT_INS = ["HOME", "TMPDIR"];
3
+ /** `$${` is a literal `${`; `${...}` is a placeholder; any other `${` is unterminated. */
4
+ const TOKEN = /\$\$\{|\$\{([^}]*)\}|\$\{/g;
5
+ /**
6
+ * Replace every token in a string: `${env:NAME}` reads the invocation `.env`,
7
+ * `${NAME}` reads a built-in variable and `$${` is a literal `${`.
8
+ */
9
+ function replace(text, where, resolve) {
10
+ return text.replace(TOKEN, (token, expression) => {
11
+ if (token === "$${")
12
+ return "${";
13
+ if (expression === undefined)
14
+ throw new ConfigError(`unterminated "\${" in ${where}; write "$\${" for a literal`);
15
+ return resolve(placeholder(expression, where));
16
+ });
17
+ }
18
+ function placeholder(expression, where) {
19
+ const colon = expression.indexOf(":");
20
+ const source = colon < 0 ? undefined : expression.slice(0, colon);
21
+ const name = expression.slice(colon + 1);
22
+ if (!ENV_NAME_PATTERN.test(name))
23
+ throw new ConfigError(`invalid placeholder "\${${expression}}" in ${where}`);
24
+ if (source === "env")
25
+ return { env: name };
26
+ if (source !== undefined) {
27
+ throw new ConfigError(`unknown value source "${source}" in "\${${expression}}" in ${where} (available: env)`);
28
+ }
29
+ if (BUILT_INS.includes(name))
30
+ return { run: name };
31
+ throw new ConfigError(`unknown variable "\${${name}}" in ${where} (built-in: ${BUILT_INS.join(", ")}); use "\${env:${name}}" for a .env value`);
32
+ }
33
+ /** Reject malformed placeholders anywhere in a value without reading any source. */
34
+ export function checkPlaceholders(value, where) {
35
+ walk(value, where, (text, at) => replace(text, at, () => ""));
36
+ }
37
+ /**
38
+ * Substitute every placeholder in every string of a parameter value. Substituted
39
+ * text is not scanned again; keys, `$type` and non-string values are unchanged.
40
+ */
41
+ export async function substituteValues(value, where, source) {
42
+ // Collect every .env name first: lookups are asynchronous, replacement is not.
43
+ const names = new Set();
44
+ walk(value, where, (text, at) => replace(text, at, (found) => {
45
+ if ("env" in found)
46
+ names.add(found.env);
47
+ return "";
48
+ }));
49
+ const env = new Map();
50
+ for (const name of names)
51
+ env.set(name, await source.env.require(name));
52
+ return walk(value, where, (text, at) => replace(text, at, (found) => ("env" in found ? env.get(found.env) : source.run[found.run])));
53
+ }
54
+ function walk(value, where, onString) {
55
+ if (typeof value === "string")
56
+ return onString(value, where);
57
+ if (Array.isArray(value))
58
+ return value.map((item, index) => walk(item, `${where}[${index}]`, onString));
59
+ if (typeof value === "object" && value !== null) {
60
+ // defineProperty keeps keys such as __proto__ as data for schema validation.
61
+ const copy = {};
62
+ for (const [key, item] of Object.entries(value)) {
63
+ Object.defineProperty(copy, key, {
64
+ // A `$type` selector names an implementation, so it is a registry key rather than data;
65
+ // a non-string value under that name is ordinary data and is walked like any other.
66
+ value: key === "$type" && typeof item === "string" ? item : walk(item, `${where}.${key}`, onString),
67
+ enumerable: true,
68
+ writable: true,
69
+ configurable: true,
70
+ });
71
+ }
72
+ return copy;
73
+ }
74
+ return value;
75
+ }
@@ -0,0 +1,10 @@
1
+ import type { ResolvedCase } from "./config.js";
2
+ import type { PlacementSummary } from "./placement.js";
3
+ export interface ViewOptions {
4
+ /** What the case would place, computed by the caller (view starts no runtime). */
5
+ readonly placement: readonly PlacementSummary[];
6
+ /** List every placed and excluded path instead of the entry counts. */
7
+ readonly files: boolean;
8
+ }
9
+ /** Render the resolved configuration with inline `# <file>:<line>` origins and placement. */
10
+ export declare function formatResolvedCase(resolved: ResolvedCase, options: ViewOptions): string;
@@ -0,0 +1,150 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { basename } from "node:path";
3
+ import { Document, isMap, isNode, isScalar, isSeq } from "yaml";
4
+ /** Render the resolved configuration with inline `# <file>:<line>` origins and placement. */
5
+ export function formatResolvedCase(resolved, options) {
6
+ const lines = [
7
+ `configuration: ${resolved.path}`,
8
+ `case: ${resolved.name === undefined ? "(ordinary)" : JSON.stringify(resolved.name)}`,
9
+ "resolved configuration:",
10
+ ];
11
+ for (const line of formatAnnotatedConfig(resolved).trimEnd().split("\n")) {
12
+ lines.push(` ${line}`);
13
+ }
14
+ lines.push("placement:");
15
+ if (options.placement.length === 0) {
16
+ lines.push(" none");
17
+ }
18
+ for (const summary of options.placement) {
19
+ lines.push(` ${summary.label}: ${count(summary.placed.length, "placed")}, ${count(summary.excluded.length, "excluded")}`);
20
+ if (!options.files) {
21
+ continue;
22
+ }
23
+ for (const placed of summary.placed) {
24
+ lines.push(` place ${placed.path} <- ${placed.source}`);
25
+ }
26
+ for (const excluded of summary.excluded) {
27
+ const kind = excluded.directory ? " (directory)" : "";
28
+ lines.push(` exclude ${excluded.path}${kind} <- .agentevalsignore at ${excluded.ignoreDir}`);
29
+ }
30
+ }
31
+ return lines.join("\n") + "\n";
32
+ }
33
+ const MAX_ALIGN_COLUMN = 44;
34
+ function formatAnnotatedConfig(resolved) {
35
+ const marker = `__AE_ORIGIN_${randomBytes(6).toString("hex")}__`;
36
+ const doc = new Document(resolved.config);
37
+ if (isMap(doc.contents)) {
38
+ for (const pair of doc.contents.items) {
39
+ if (!isScalar(pair.key) || typeof pair.key.value !== "string")
40
+ continue;
41
+ const origin = resolved.origins[pair.key.value];
42
+ if (origin === undefined)
43
+ continue;
44
+ applyOrigin(pair, origin, marker);
45
+ }
46
+ }
47
+ return alignOriginComments(doc.toString(), marker);
48
+ }
49
+ /**
50
+ * Align only the origin comments emitted by this function (tagged with `marker`), so literal
51
+ * `# ...` text inside user scalars is never altered. Capped so one long scalar does not push
52
+ * every other line's comment far to the right.
53
+ */
54
+ function alignOriginComments(yamlText, marker) {
55
+ const token = ` #${marker}`;
56
+ const lines = yamlText.trimEnd().split("\n");
57
+ const parsed = lines.map((line) => {
58
+ const index = line.lastIndexOf(token);
59
+ if (index === -1)
60
+ return { line };
61
+ return { body: line.slice(0, index), comment: `#${line.slice(index + token.length)}` };
62
+ });
63
+ let column = 0;
64
+ for (const entry of parsed) {
65
+ if ("comment" in entry && entry.body.length + 2 <= MAX_ALIGN_COLUMN) {
66
+ column = Math.max(column, entry.body.length + 2);
67
+ }
68
+ }
69
+ return parsed
70
+ .map((entry) => {
71
+ if (!("comment" in entry))
72
+ return entry.line;
73
+ const pad = Math.max(2, column - entry.body.length);
74
+ return `${entry.body}${" ".repeat(pad)}${entry.comment}`;
75
+ })
76
+ .join("\n");
77
+ }
78
+ function applyOrigin(pair, origin, marker) {
79
+ const uniform = uniformSource(origin);
80
+ if (uniform !== undefined) {
81
+ annotatePair(pair, formatSource(uniform, marker));
82
+ return;
83
+ }
84
+ if (origin.kind === "list") {
85
+ if (!isSeq(pair.value))
86
+ return;
87
+ for (const [index, item] of pair.value.items.entries()) {
88
+ const entryOrigin = origin.items[index];
89
+ if (entryOrigin === undefined)
90
+ continue;
91
+ const comment = formatSource(entryOrigin, marker);
92
+ if (isMap(item) && item.items[0] !== undefined) {
93
+ annotatePair(item.items[0], comment);
94
+ }
95
+ else if (isNode(item)) {
96
+ item.comment = comment;
97
+ }
98
+ }
99
+ return;
100
+ }
101
+ if (origin.kind === "map") {
102
+ if (!isMap(pair.value))
103
+ return;
104
+ for (const entryPair of pair.value.items) {
105
+ if (!isScalar(entryPair.key) || typeof entryPair.key.value !== "string")
106
+ continue;
107
+ const childOrigin = origin.entries[entryPair.key.value];
108
+ if (childOrigin !== undefined) {
109
+ applyOrigin(entryPair, childOrigin, marker);
110
+ }
111
+ }
112
+ }
113
+ }
114
+ /**
115
+ * If an entire field or subtree originates from one block (`common` or `case`) with no overrides,
116
+ * return that single source so `view` annotates only the highest node instead of every entry.
117
+ */
118
+ function uniformSource(origin) {
119
+ if (origin.kind === "common" || origin.kind === "case") {
120
+ return origin;
121
+ }
122
+ if (origin.kind === "list") {
123
+ const allSame = origin.items.every((item) => item.kind === origin.base.kind && item.overrides === undefined);
124
+ return allSame ? origin.base : undefined;
125
+ }
126
+ const children = Object.values(origin.entries);
127
+ const allSame = children.every((child) => {
128
+ const sub = uniformSource(child);
129
+ return sub !== undefined && sub.kind === origin.base.kind && sub.overrides === undefined;
130
+ });
131
+ return allSame ? origin.base : undefined;
132
+ }
133
+ function annotatePair(pair, comment) {
134
+ if (isScalar(pair.value)) {
135
+ pair.value.comment = comment;
136
+ }
137
+ else if (isNode(pair.key)) {
138
+ pair.key.comment = comment;
139
+ }
140
+ }
141
+ function formatSource(origin, marker) {
142
+ const self = `${basename(origin.file)}:${origin.line}`;
143
+ if (origin.overrides === undefined)
144
+ return `${marker} ${self}`;
145
+ const prev = `${basename(origin.overrides.file)}:${origin.overrides.line}`;
146
+ return `${marker} ${self} (overrides ${prev})`;
147
+ }
148
+ function count(value, label) {
149
+ return `${value} ${label}`;
150
+ }
@@ -0,0 +1,63 @@
1
+ /** Largest file a check will read. Checks stay bounded and predictable. */
2
+ export declare const MAX_CHECK_BYTES: number;
3
+ export declare class WorkspacePathError extends Error {
4
+ constructor(message: string);
5
+ }
6
+ /**
7
+ * An opened run directory. The recorded device/inode pair lets later operations
8
+ * reject replacement of the directory path instead of trusting a new target.
9
+ */
10
+ export interface RunRoot {
11
+ readonly path: string;
12
+ readonly dev: bigint;
13
+ readonly ino: bigint;
14
+ }
15
+ export declare function openRunRoot(path: string): Promise<RunRoot>;
16
+ /**
17
+ * Verify the directory path still refers to the prepared directory. A path
18
+ * replaced by a symlink or a different directory is rejected.
19
+ */
20
+ export declare function assertRunRoot(root: RunRoot): Promise<void>;
21
+ /**
22
+ * Resolve a run-relative path without allowing it to leave the prepared run
23
+ * root. The root identity is verified first, and symlinks (including ancestor
24
+ * symlinks) are rejected when they escape. A broken symlink is rejected rather
25
+ * than treated as a missing file.
26
+ */
27
+ export declare function resolveWorkspacePath(root: RunRoot, requestedPath: string): Promise<string>;
28
+ /**
29
+ * Read a regular run file. Non-regular evidence is rejected without opening it,
30
+ * so a FIFO or device cannot block the engine or checks.
31
+ */
32
+ export declare function readRunFile(root: RunRoot, requestedPath: string): Promise<Buffer>;
33
+ /** The kind of one node in a run tree. Non-regular entries are recorded, never opened. */
34
+ export type RunEntryKind = "file" | "directory" | "symlink" | "other";
35
+ /** One node of a run tree. `size` is the byte size of a regular file within the check limit. */
36
+ export interface RunTreeEntry {
37
+ readonly kind: RunEntryKind;
38
+ readonly size?: number;
39
+ }
40
+ /**
41
+ * A run path's contents keyed by path relative to it, with `""` for the path itself.
42
+ * Symlinks and special files are recorded by kind and never followed, so a link the
43
+ * agent wrote is visible as a change instead of hiding the evidence behind an error.
44
+ */
45
+ export type RunTree = ReadonlyMap<string, RunTreeEntry>;
46
+ /**
47
+ * Snapshot a run path for comparison. `undefined` means the path itself does not
48
+ * exist; an existing path is one entry per node beneath it, listed and opened
49
+ * without following links.
50
+ */
51
+ export declare function readRunTree(root: RunRoot, requestedPath: string): Promise<RunTree | undefined>;
52
+ /** True when the run-relative path is a regular file or a directory; special files are errors. */
53
+ export declare function runPathExists(root: RunRoot, requestedPath: string): Promise<boolean>;
54
+ export declare function requireConfigurationPath(declaringDir: string, relativePath: string, label: string): string;
55
+ export declare function isWithin(root: string, target: string): boolean;
56
+ export declare function isMissing(error: unknown): boolean;
57
+ /** The identity a filesystem uses for one file, independent of the spelling that reached it. */
58
+ export declare function fileIdentity(info: {
59
+ readonly dev: bigint;
60
+ readonly ino: bigint;
61
+ }): string;
62
+ /** True when `relativePath` is or lies under any protected HOME-relative path. */
63
+ export declare function isProtectedHomePath(relativePath: string, protectedPaths: readonly string[]): boolean;