@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,356 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { dirname, resolve } from "node:path";
3
+ import { parseImplementationParams } from "./params.js";
4
+ import { checkPlaceholders, substituteValues } from "./values.js";
5
+ import { isAlias, isMap, isNode, isScalar, isSeq, parseDocument } from "yaml";
6
+ import { CASES_KEY, CASE_FIELDS, CASE_FIELD_KEYS, ConfigError, errorMessage, expectCaseConfig, } from "./config.js";
7
+ /**
8
+ * Resolve one YAML authoring document to a single case.
9
+ *
10
+ * `view` and execution both use this function, so they see the same values and
11
+ * field origins. Runtime implementation validation remains a separate step.
12
+ */
13
+ export async function loadCase(path, selection = {}) {
14
+ const document = await readCaseDocument(path);
15
+ return buildCase(document, selectCase(document.cases, selection.caseName, document.file));
16
+ }
17
+ /**
18
+ * Resolve every selected case in declaration order: the named one when a name is
19
+ * given, all entries of a `cases` document when it is not, or the one ordinary case.
20
+ */
21
+ export async function loadCases(path, selection = {}) {
22
+ const document = await readCaseDocument(path);
23
+ const { cases, file } = document;
24
+ if (cases === undefined) {
25
+ return [buildCase(document, selectCase(undefined, selection.caseName, file))];
26
+ }
27
+ if (selection.caseName !== undefined) {
28
+ return [buildCase(document, selectCase(cases, selection.caseName, file))];
29
+ }
30
+ return [...cases.values()].map((entry) => buildCase(document, entry));
31
+ }
32
+ async function readCaseDocument(path) {
33
+ const { file, text, fields } = await readMapping(path);
34
+ const common = [];
35
+ let casesField;
36
+ for (const field of fields) {
37
+ if (field.key === CASES_KEY) {
38
+ casesField = field;
39
+ continue;
40
+ }
41
+ if (!CASE_FIELD_KEYS.has(field.key)) {
42
+ throw new ConfigError(`case configuration ${file} has unknown field: ${field.key}`);
43
+ }
44
+ common.push(field);
45
+ }
46
+ const cases = casesField === undefined ? undefined : parseCases(casesField, file, text);
47
+ return { file, text, common, ...(cases === undefined ? {} : { cases }) };
48
+ }
49
+ function buildCase(document, selected) {
50
+ const { file, text, common } = document;
51
+ const final = {};
52
+ const origins = {};
53
+ for (const field of common) {
54
+ const type = fieldType(field.key);
55
+ final[field.key] = fieldValue(field);
56
+ origins[field.key] = extractFieldOrigin(type, field, { file, line: field.line, kind: "common" }, text);
57
+ }
58
+ if (selected !== undefined) {
59
+ for (const field of selected.fields) {
60
+ const type = fieldType(field.key);
61
+ const nextValue = fieldValue(field);
62
+ const nextOrigin = extractFieldOrigin(type, field, { file, line: field.line, kind: "case", caseName: selected.name }, text);
63
+ if (Object.hasOwn(final, field.key)) {
64
+ final[field.key] = composeFieldValue(type, final[field.key], nextValue);
65
+ origins[field.key] = composeFieldOrigin(type, origins[field.key], nextOrigin);
66
+ }
67
+ else {
68
+ final[field.key] = nextValue;
69
+ origins[field.key] = nextOrigin;
70
+ }
71
+ }
72
+ }
73
+ const label = selected === undefined ? `case configuration ${file}` : `case "${selected.name}"`;
74
+ const config = expectCaseConfig(final, label);
75
+ for (const [index, record] of [config.runner, ...config.checks].entries()) {
76
+ const { $type: _, ...params } = record;
77
+ checkPlaceholders(params, index === 0 ? `${label} runner` : `${label} checks[${index - 1}]`);
78
+ }
79
+ return {
80
+ path: file,
81
+ dir: dirname(file),
82
+ ...(selected === undefined ? {} : { name: selected.name }),
83
+ config,
84
+ origins,
85
+ };
86
+ }
87
+ function fieldType(key) {
88
+ return CASE_FIELDS[key];
89
+ }
90
+ function composeFieldValue(type, commonValue, caseValue) {
91
+ if (typeof type !== "string") {
92
+ if (!isPlainRecord(commonValue) || !isPlainRecord(caseValue)) {
93
+ return isPlainRecord(commonValue) ? caseValue : commonValue;
94
+ }
95
+ const merged = {};
96
+ for (const [entryKey, value] of Object.entries(commonValue)) {
97
+ defineOwn(merged, entryKey, value);
98
+ }
99
+ for (const [entryKey, caseEntry] of Object.entries(caseValue)) {
100
+ defineOwn(merged, entryKey, Object.hasOwn(merged, entryKey) ? composeFieldValue(type.child, merged[entryKey], caseEntry) : caseEntry);
101
+ }
102
+ return merged;
103
+ }
104
+ switch (type) {
105
+ case "value":
106
+ return caseValue;
107
+ case "list":
108
+ if (!Array.isArray(commonValue) || !Array.isArray(caseValue)) {
109
+ return Array.isArray(commonValue) ? caseValue : commonValue;
110
+ }
111
+ return [...commonValue, ...caseValue];
112
+ }
113
+ }
114
+ function extractFieldOrigin(type, field, base, text) {
115
+ if (typeof type !== "string") {
116
+ if (!isMap(field.node))
117
+ return base;
118
+ const entries = {};
119
+ for (const pair of field.node.items) {
120
+ if (!isScalar(pair.key) || typeof pair.key.value !== "string")
121
+ continue;
122
+ const entryBase = {
123
+ ...base,
124
+ line: isNode(pair.key) ? lineAt(pair.key, text) : base.line,
125
+ };
126
+ defineOwn(entries, pair.key.value, extractFieldOrigin(type.child, { node: pair.value }, entryBase, text));
127
+ }
128
+ return { kind: "map", base, entries };
129
+ }
130
+ switch (type) {
131
+ case "value":
132
+ return base;
133
+ case "list": {
134
+ if (!isSeq(field.node))
135
+ return base;
136
+ const items = field.node.items.map((item) => ({
137
+ ...base,
138
+ line: isNode(item) ? lineAt(item, text) : base.line,
139
+ }));
140
+ return { kind: "list", base, items };
141
+ }
142
+ }
143
+ }
144
+ function composeFieldOrigin(type, common, next) {
145
+ if (typeof type !== "string") {
146
+ if (common.kind === "map" && next.kind === "map") {
147
+ const entries = {};
148
+ for (const [entryKey, entryOrigin] of Object.entries(common.entries)) {
149
+ defineOwn(entries, entryKey, entryOrigin);
150
+ }
151
+ for (const [entryKey, entryOrigin] of Object.entries(next.entries)) {
152
+ defineOwn(entries, entryKey, Object.hasOwn(entries, entryKey)
153
+ ? composeFieldOrigin(type.child, entries[entryKey], entryOrigin)
154
+ : entryOrigin);
155
+ }
156
+ return { kind: "map", base: common.base, entries };
157
+ }
158
+ return next;
159
+ }
160
+ switch (type) {
161
+ case "value":
162
+ if ((common.kind === "common" || common.kind === "case") && (next.kind === "common" || next.kind === "case")) {
163
+ return { ...next, overrides: common };
164
+ }
165
+ return next;
166
+ case "list":
167
+ if (common.kind === "list" && next.kind === "list") {
168
+ return { kind: "list", base: common.base, items: [...common.items, ...next.items] };
169
+ }
170
+ return next;
171
+ }
172
+ }
173
+ function defineOwn(target, key, value) {
174
+ Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });
175
+ }
176
+ function isPlainRecord(value) {
177
+ return typeof value === "object" && value !== null && !Array.isArray(value);
178
+ }
179
+ /** Load a standalone implementation object using the same YAML and placeholder rules as cases. */
180
+ export async function loadImplementationParameters(path, schema, source) {
181
+ const { file, fields } = await readMapping(path);
182
+ // Preserve every YAML key as data, including __proto__, for schema validation.
183
+ const raw = Object.fromEntries(fields.map((field) => [field.key, fieldValue(field)]));
184
+ return {
185
+ params: await parseImplementationParams(schema, await substituteValues(raw, file, source), file),
186
+ dir: dirname(file),
187
+ };
188
+ }
189
+ async function readMapping(path) {
190
+ const file = resolve(path);
191
+ const text = await readConfiguration(file);
192
+ const document = parseDocument(text, { merge: false, uniqueKeys: true });
193
+ const issue = document.errors[0] ?? document.warnings[0];
194
+ if (issue !== undefined) {
195
+ const kind = document.errors.length > 0 ? "invalid" : "unsupported";
196
+ throw new ConfigError(`${kind} YAML in configuration ${file}: ${issue.message}`);
197
+ }
198
+ if (document.contents === null || document.contents === undefined) {
199
+ throw new ConfigError(`configuration ${file} must contain a YAML mapping`);
200
+ }
201
+ rejectForbiddenSyntax(document.contents, text, file);
202
+ const root = expectMapNode(document.contents, "configuration", file);
203
+ return { file, text, fields: readFields(root, "configuration", file, text) };
204
+ }
205
+ async function readConfiguration(file) {
206
+ try {
207
+ return await readFile(file, "utf8");
208
+ }
209
+ catch (error) {
210
+ throw new ConfigError(`could not read case configuration ${file}: ${errorMessage(error)}`);
211
+ }
212
+ }
213
+ function parseCases(field, file, text) {
214
+ const node = expectMapNode(field.node, "cases", file);
215
+ if (node.items.length === 0) {
216
+ throw new ConfigError(`case configuration ${file} has an empty cases mapping; add a named case or omit cases`);
217
+ }
218
+ const cases = new Map();
219
+ for (const pair of node.items) {
220
+ const name = fieldKey(pair, "cases entry", file);
221
+ if (name.trim().length === 0) {
222
+ throw new ConfigError(`case configuration ${file} has an empty case name`);
223
+ }
224
+ if (cases.has(name)) {
225
+ throw new ConfigError(`case configuration ${file} repeats case name "${name}"`);
226
+ }
227
+ const entryNode = expectMapNode(pair.value, `case "${name}"`, file);
228
+ const fields = readFields(entryNode, `case "${name}"`, file, text);
229
+ for (const entryField of fields) {
230
+ if (entryField.key === CASES_KEY) {
231
+ throw new ConfigError(`case "${name}" in ${file} contains nested cases; cases may only appear at the document root`);
232
+ }
233
+ if (!CASE_FIELD_KEYS.has(entryField.key)) {
234
+ throw new ConfigError(`case "${name}" in ${file} has unknown field: ${entryField.key}`);
235
+ }
236
+ }
237
+ cases.set(name, { name, fields });
238
+ }
239
+ return cases;
240
+ }
241
+ function selectCase(cases, caseName, file) {
242
+ if (cases === undefined) {
243
+ if (caseName !== undefined) {
244
+ throw new ConfigError(`case configuration ${file} does not define named cases; omit the case selection`);
245
+ }
246
+ return undefined;
247
+ }
248
+ const names = [...cases.keys()].join(", ");
249
+ if (caseName === undefined || caseName.trim().length === 0) {
250
+ throw new ConfigError(`case configuration ${file} defines named cases (${names}); select one with --case <name>`);
251
+ }
252
+ const selected = cases.get(caseName);
253
+ if (selected === undefined) {
254
+ throw new ConfigError(`case configuration ${file} has no case named "${caseName}" (available: ${names})`);
255
+ }
256
+ return selected;
257
+ }
258
+ function readFields(node, label, file, text) {
259
+ const fields = [];
260
+ const seen = new Set();
261
+ for (const pair of node.items) {
262
+ const key = fieldKey(pair, `${label} field`, file);
263
+ if (seen.has(key)) {
264
+ throw new ConfigError(`${label} in ${file} repeats field "${key}"`);
265
+ }
266
+ seen.add(key);
267
+ const keyNode = pair.key;
268
+ fields.push({
269
+ key,
270
+ node: pair.value,
271
+ line: isNode(keyNode) ? lineAt(keyNode, text) : 1,
272
+ });
273
+ }
274
+ return fields;
275
+ }
276
+ function fieldKey(pair, label, file) {
277
+ if (!isScalar(pair.key) || typeof pair.key.value !== "string") {
278
+ throw new ConfigError(`${label} in ${file} must use a string key`);
279
+ }
280
+ return pair.key.value;
281
+ }
282
+ function fieldValue(field) {
283
+ if (field.node === null || field.node === undefined) {
284
+ return null;
285
+ }
286
+ return isNode(field.node) ? field.node.toJSON() : field.node;
287
+ }
288
+ function expectMapNode(node, label, file) {
289
+ if (!isMap(node)) {
290
+ throw new ConfigError(`${label} in ${file} must be a YAML mapping`);
291
+ }
292
+ return node;
293
+ }
294
+ /**
295
+ * Reject syntax that this authoring format does not support. The visitor
296
+ * inspects parsed nodes, so ordinary text values that merely look like YAML
297
+ * reuse syntax remain valid data.
298
+ */
299
+ function rejectForbiddenSyntax(node, text, file) {
300
+ rejectAliases(node, text, file);
301
+ rejectUnsupportedSyntax(node, text, file);
302
+ }
303
+ function rejectAliases(node, text, file) {
304
+ if (isAlias(node)) {
305
+ throw new ConfigError(`YAML aliases are not supported in case configuration ${file} (line ${lineAt(node, text)})`);
306
+ }
307
+ if (isMap(node)) {
308
+ for (const pair of node.items) {
309
+ rejectAliases(pair.key, text, file);
310
+ rejectAliases(pair.value, text, file);
311
+ }
312
+ }
313
+ else if (isSeq(node)) {
314
+ for (const item of node.items) {
315
+ rejectAliases(item, text, file);
316
+ }
317
+ }
318
+ }
319
+ function rejectUnsupportedSyntax(node, text, file) {
320
+ if (isScalar(node)) {
321
+ rejectAnchor(node, text, file);
322
+ return;
323
+ }
324
+ if (isMap(node)) {
325
+ rejectAnchor(node, text, file);
326
+ for (const pair of node.items) {
327
+ if (isScalar(pair.key) && pair.key.value === "<<") {
328
+ throw new ConfigError(`reserved YAML key "<<" is not supported in case configuration ${file} (line ${lineAt(pair.key, text)})`);
329
+ }
330
+ rejectUnsupportedSyntax(pair.key, text, file);
331
+ rejectUnsupportedSyntax(pair.value, text, file);
332
+ }
333
+ return;
334
+ }
335
+ if (isSeq(node)) {
336
+ rejectAnchor(node, text, file);
337
+ for (const item of node.items) {
338
+ rejectUnsupportedSyntax(item, text, file);
339
+ }
340
+ }
341
+ }
342
+ function rejectAnchor(node, text, file) {
343
+ if (node.anchor !== undefined) {
344
+ throw new ConfigError(`YAML anchors are not supported in case configuration ${file} (line ${lineAt(node, text)})`);
345
+ }
346
+ }
347
+ function lineAt(node, text) {
348
+ const offset = node.range?.[0] ?? 0;
349
+ let line = 1;
350
+ for (let index = 0; index < offset && index < text.length; index += 1) {
351
+ if (text.charCodeAt(index) === 10) {
352
+ line += 1;
353
+ }
354
+ }
355
+ return line;
356
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,127 @@
1
+ import { spawn } from "node:child_process";
2
+ import { writeSync } from "node:fs";
3
+ import { copyFile, lstat, mkdir, readdir, unlink } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ const [stagingDir, program, ...args] = process.argv.slice(2);
6
+ let settled = false;
7
+ function report(outcome) {
8
+ if (settled)
9
+ return;
10
+ settled = true;
11
+ try {
12
+ writeSync(5, JSON.stringify(outcome) + "\n");
13
+ }
14
+ catch {
15
+ // Host closed the report pipe (for example on timeout or cancellation).
16
+ }
17
+ }
18
+ function errorMessage(error) {
19
+ return error instanceof Error ? error.message : String(error);
20
+ }
21
+ function errorCode(error) {
22
+ if (typeof error === "object" && error !== null && "code" in error && typeof error.code === "string") {
23
+ return error.code;
24
+ }
25
+ return error instanceof Error ? error.message : String(error);
26
+ }
27
+ function isMissing(error) {
28
+ return (typeof error === "object" &&
29
+ error !== null &&
30
+ "code" in error &&
31
+ (error.code === "ENOENT" || error.code === "ENOTDIR"));
32
+ }
33
+ /** Place the staged tree into the workspace without following any symlink the agent planted. */
34
+ async function placeStaged(staging, workspace) {
35
+ await placeNode(staging, workspace, []);
36
+ }
37
+ async function placeNode(source, root, segments) {
38
+ const info = await lstat(source);
39
+ if (info.isDirectory()) {
40
+ await ensureDirectory(root, segments);
41
+ for (const name of await readdir(source)) {
42
+ await placeNode(join(source, name), root, [...segments, name]);
43
+ }
44
+ return;
45
+ }
46
+ await ensureDirectory(root, segments.slice(0, -1));
47
+ await replaceFile(source, join(root, ...segments), segments.join("/"));
48
+ }
49
+ /** Create or verify every directory component without following a symlink. */
50
+ async function ensureDirectory(root, segments) {
51
+ let current = root;
52
+ for (const [index, segment] of segments.entries()) {
53
+ current = join(current, segment);
54
+ let info;
55
+ try {
56
+ info = await lstat(current);
57
+ }
58
+ catch (error) {
59
+ if (isMissing(error)) {
60
+ await mkdir(current);
61
+ continue;
62
+ }
63
+ throw error;
64
+ }
65
+ const path = segments.slice(0, index + 1).join("/");
66
+ if (info.isSymbolicLink()) {
67
+ throw new Error(`cannot place files through the symlink at ${path}`);
68
+ }
69
+ if (!info.isDirectory()) {
70
+ throw new Error(`needs a directory at ${path}, where a file exists`);
71
+ }
72
+ }
73
+ }
74
+ /** Replace whatever is at a file's destination, so copying never follows a link. */
75
+ async function replaceFile(source, target, destination) {
76
+ let info;
77
+ try {
78
+ info = await lstat(target);
79
+ }
80
+ catch (error) {
81
+ if (isMissing(error)) {
82
+ info = undefined;
83
+ }
84
+ else {
85
+ throw error;
86
+ }
87
+ }
88
+ if (info !== undefined) {
89
+ if (info.isDirectory()) {
90
+ throw new Error(`places a file at ${destination}, where a directory exists`);
91
+ }
92
+ await unlink(target);
93
+ }
94
+ await copyFile(source, target);
95
+ }
96
+ async function main() {
97
+ if (stagingDir !== undefined && stagingDir !== "-") {
98
+ try {
99
+ await placeStaged(stagingDir, process.cwd());
100
+ }
101
+ catch (error) {
102
+ report({ kind: "failed", reason: `could not place files: ${errorMessage(error)}` });
103
+ return;
104
+ }
105
+ }
106
+ if (program === undefined) {
107
+ report({ kind: "failed", reason: "the check named no program" });
108
+ return;
109
+ }
110
+ try {
111
+ const child = spawn(program, args, {
112
+ cwd: process.cwd(),
113
+ env: { PATH: process.env.PATH, HOME: process.env.HOME, TMPDIR: process.env.TMPDIR },
114
+ stdio: ["ignore", "inherit", "inherit"],
115
+ });
116
+ child.on("error", (error) => {
117
+ report({ kind: "failed", reason: `could not start ${program}: ${errorCode(error)}` });
118
+ });
119
+ child.on("close", (code, signal) => {
120
+ report(signal === null ? { kind: "exited", exitCode: code ?? 1 } : { kind: "signalled", signal });
121
+ });
122
+ }
123
+ catch (error) {
124
+ report({ kind: "failed", reason: `could not start ${program}: ${errorCode(error)}` });
125
+ }
126
+ }
127
+ void main();
@@ -0,0 +1,18 @@
1
+ import type { CheckSandbox } from "./registry.js";
2
+ export interface CheckSandboxOptions {
3
+ /** Prepared workspace root; the program starts here and may write in it. */
4
+ readonly workspaceDir: string;
5
+ /** Engine-private directory; the check's own HOME, temporary directory and policy live here. */
6
+ readonly engineDir: string;
7
+ /** Where a checker's `files` sources resolve from, normally the case file's directory. */
8
+ readonly authoringDir: string;
9
+ /** The check's deadline or cancellation. */
10
+ readonly signal: AbortSignal;
11
+ /** The run's own abort signal; when it fired, an aborted check was cancelled, not timed out. */
12
+ readonly cancelled?: AbortSignal;
13
+ }
14
+ /**
15
+ * The engine's check sandbox: the evaluated agent has stopped, so reads are open, while writes
16
+ * stay beneath the workspace and a private HOME and temporary directory and the network is denied.
17
+ */
18
+ export declare function createCheckSandbox(options: CheckSandboxOptions): CheckSandbox;
@@ -0,0 +1,171 @@
1
+ import { mkdir, mkdtemp, rm } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { errorMessage } from "./config.js";
5
+ import { stageCheckFiles } from "./files.js";
6
+ import { siblingRuntimeModule } from "./runtime-assets.js";
7
+ import { SYSTEM_PATH } from "../platform/macos/policy.js";
8
+ import { spawnSupervised } from "../platform/macos/supervise.js";
9
+ /** How much of a program's combined output a check may keep as its reason. */
10
+ const MAX_OUTPUT_LENGTH = 4_096;
11
+ const CHECK_RUNNER = fileURLToPath(siblingRuntimeModule(import.meta.url, "check-runner"));
12
+ /**
13
+ * The engine's check sandbox: the evaluated agent has stopped, so reads are open, while writes
14
+ * stay beneath the workspace and a private HOME and temporary directory and the network is denied.
15
+ */
16
+ export function createCheckSandbox(options) {
17
+ return { run: (command, runOptions) => runProgram(options, command, runOptions?.files) };
18
+ }
19
+ async function runProgram(options, command, files) {
20
+ const [program, ...args] = command;
21
+ if (program === undefined) {
22
+ return { kind: "failed", reason: "the check named no program", output: "" };
23
+ }
24
+ const path = process.env.PATH ?? SYSTEM_PATH.join(":");
25
+ const directory = await mkdtemp(join(options.engineDir, "check-"));
26
+ const homeDir = join(directory, "home");
27
+ const tmpDir = join(directory, "tmp");
28
+ let supervised;
29
+ let stagingDir;
30
+ try {
31
+ await Promise.all([mkdir(homeDir, { mode: 0o700 }), mkdir(tmpDir, { mode: 0o700 })]);
32
+ if (files !== undefined && Object.keys(files).length > 0) {
33
+ if (options.signal.aborted) {
34
+ return { kind: "failed", reason: abortReason(options), output: "" };
35
+ }
36
+ stagingDir = join(directory, "staged");
37
+ try {
38
+ await mkdir(stagingDir);
39
+ await stageCheckFiles(files, options.authoringDir, stagingDir, options.signal, "check files");
40
+ }
41
+ catch (error) {
42
+ if (options.signal.aborted) {
43
+ return { kind: "failed", reason: abortReason(options), output: "" };
44
+ }
45
+ return { kind: "failed", reason: `could not place files: ${errorMessage(error)}`, output: "" };
46
+ }
47
+ }
48
+ if (options.signal.aborted) {
49
+ return { kind: "failed", reason: abortReason(options), output: "" };
50
+ }
51
+ supervised = await spawnSupervised({
52
+ policy: {
53
+ writableRoots: [options.workspaceDir, homeDir, tmpDir],
54
+ readableRoots: [],
55
+ readAll: true,
56
+ allowNetwork: false,
57
+ },
58
+ policyDirectory: directory,
59
+ command: [process.execPath, CHECK_RUNNER, stagingDir ?? "-", program, ...args],
60
+ cwd: options.workspaceDir,
61
+ env: { PATH: path, HOME: homeDir, TMPDIR: tmpDir },
62
+ interactive: false,
63
+ report: true,
64
+ });
65
+ return await supervise(supervised, options);
66
+ }
67
+ catch (error) {
68
+ return { kind: "failed", reason: `the check sandbox failed: ${errorMessage(error)}`, output: "" };
69
+ }
70
+ finally {
71
+ try {
72
+ await supervised?.stop();
73
+ }
74
+ catch {
75
+ // The run root is removed with everything the supervisor could not stop.
76
+ }
77
+ await rm(directory, { recursive: true, force: true, maxRetries: 3 }).catch(() => {
78
+ // The engine removes the containing run root and records any failure there.
79
+ });
80
+ }
81
+ }
82
+ async function supervise(supervised, options) {
83
+ let stdout = "";
84
+ let stderr = "";
85
+ let report = "";
86
+ supervised.child.stdout?.on("data", (chunk) => {
87
+ stdout = keepTail(stdout, chunk);
88
+ });
89
+ supervised.child.stderr?.on("data", (chunk) => {
90
+ stderr = keepTail(stderr, chunk);
91
+ });
92
+ supervised.report?.on("data", (chunk) => {
93
+ if (report.length <= MAX_OUTPUT_LENGTH)
94
+ report += chunk.toString("utf8");
95
+ });
96
+ // The check program reads no standard input, so it does not wait for the engine.
97
+ supervised.child.stdin?.end();
98
+ let aborted = options.signal.aborted;
99
+ const onAbort = () => {
100
+ aborted = true;
101
+ };
102
+ options.signal.addEventListener("abort", onAbort, { once: true });
103
+ const cancelled = new Promise((resolveCancelled) => {
104
+ if (options.signal.aborted) {
105
+ resolveCancelled("cancelled");
106
+ return;
107
+ }
108
+ options.signal.addEventListener("abort", () => resolveCancelled("cancelled"), { once: true });
109
+ });
110
+ const closed = new Promise((resolveClosed) => supervised.child.once("close", () => resolveClosed()));
111
+ try {
112
+ const status = await Promise.race([supervised.completion.catch(() => undefined), cancelled]);
113
+ if (status === "cancelled" || aborted) {
114
+ return { kind: "failed", reason: abortReason(options), output: tail(stdout + stderr) };
115
+ }
116
+ if (status === undefined) {
117
+ return { kind: "failed", reason: "the check sandbox ended without an outcome", output: tail(stdout + stderr) };
118
+ }
119
+ // Completion arrives on its own pipe before the output and report pipes are drained.
120
+ await closed;
121
+ const outcome = readReport(report);
122
+ if (outcome === undefined) {
123
+ return { kind: "failed", reason: "the check program did not report an outcome", output: tail(stdout + stderr) };
124
+ }
125
+ return { ...outcome, output: tail(stdout + stderr) };
126
+ }
127
+ finally {
128
+ options.signal.removeEventListener("abort", onAbort);
129
+ }
130
+ }
131
+ function abortReason(options) {
132
+ return options.cancelled?.aborted === true
133
+ ? "the run was cancelled while this check was running"
134
+ : "the program did not finish before the check deadline";
135
+ }
136
+ /** Read the wrapper's one report line; anything else means the report is missing or corrupt. */
137
+ function readReport(report) {
138
+ const lines = report.split("\n").filter((line) => line.length > 0);
139
+ if (lines.length !== 1)
140
+ return undefined;
141
+ let value;
142
+ try {
143
+ value = JSON.parse(lines[0]);
144
+ }
145
+ catch {
146
+ return undefined;
147
+ }
148
+ return reportedOutcome(value);
149
+ }
150
+ function reportedOutcome(value) {
151
+ if (typeof value !== "object" || value === null)
152
+ return undefined;
153
+ const record = value;
154
+ if (record.kind === "exited" && Number.isSafeInteger(record.exitCode)) {
155
+ return { kind: "exited", exitCode: record.exitCode };
156
+ }
157
+ if (record.kind === "signalled" && typeof record.signal === "string") {
158
+ return { kind: "signalled", signal: record.signal };
159
+ }
160
+ if (record.kind === "failed" && typeof record.reason === "string") {
161
+ return { kind: "failed", reason: record.reason };
162
+ }
163
+ return undefined;
164
+ }
165
+ function keepTail(current, chunk) {
166
+ const next = current + chunk.toString("utf8");
167
+ return next.length > MAX_OUTPUT_LENGTH ? next.slice(-MAX_OUTPUT_LENGTH) : next;
168
+ }
169
+ function tail(value) {
170
+ return value.length > MAX_OUTPUT_LENGTH ? value.slice(-MAX_OUTPUT_LENGTH) : value;
171
+ }