openmerit 0.1.6 → 0.1.7-preview.2
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.
- package/CHANGELOG.md +10 -4
- package/README.md +61 -40
- package/dist/eval/src/adapters.mjs +112 -0
- package/dist/eval/src/cli.mjs +151 -0
- package/dist/eval/src/config.mjs +108 -0
- package/dist/eval/src/process.mjs +44 -0
- package/dist/eval/src/report.mjs +59 -0
- package/dist/eval/src/runner.mjs +123 -0
- package/dist/eval/src/scout.mjs +37 -0
- package/dist/terminal/public/app.js +36 -36
- package/dist/terminal/public/flow.css +1 -1
- package/dist/terminal/public/flow.js +26 -26
- package/dist/terminal/public/index.html +3 -2
- package/dist/terminal/public/styles.css +320 -91
- package/dist/terminal/src/cli.mjs +2 -0
- package/dist/terminal/src/demo-policy.mjs +205 -0
- package/dist/terminal/src/enterprise-sample.mjs +151 -0
- package/docs/adapter-guide.md +2 -2
- package/docs/agent-evaluations.md +145 -0
- package/docs/architecture.md +3 -3
- package/docs/automation.md +5 -5
- package/docs/budgets.md +2 -2
- package/docs/commands.md +9 -5
- package/docs/demo-backfill.md +3 -1
- package/docs/demo-fieldkit.md +3 -1
- package/docs/demo-placement.md +3 -1
- package/docs/demo-spam.md +3 -1
- package/docs/demo-support.md +3 -1
- package/docs/demo.md +22 -5
- package/docs/first-trial.md +2 -2
- package/docs/getting-started.md +23 -12
- package/docs/index.md +18 -29
- package/docs/inference-terminal.md +90 -54
- package/docs/interactive-demo.md +118 -0
- package/docs/lifecycle.md +4 -4
- package/docs/metrics-and-evidence.md +3 -3
- package/docs/operations.md +3 -5
- package/docs/pi-extension.md +6 -6
- package/docs/roadmap.md +17 -17
- package/docs/scout.md +206 -0
- package/docs/security.md +8 -4
- package/docs/site-demo.md +4 -0
- package/docs/site-design.md +7 -1
- package/docs/site-documentation.md +9 -3
- package/docs/site-domain-migration.md +57 -0
- package/docs/site-dynamic-og.md +2 -2
- package/docs/site-faq-maintenance.md +133 -6
- package/docs/site-hero-resolution.md +2 -0
- package/docs/site-illustration-sequences.md +3 -1
- package/docs/site-illustration-transparency.md +80 -0
- package/docs/site-memo.md +6 -0
- package/docs/site-og-image.md +1 -1
- package/docs/site-publication-2026-10-14.md +29 -0
- package/docs/site-scout-decisions-experiment.md +87 -0
- package/docs/site-scout.md +254 -0
- package/docs/site-terminal-preview.md +96 -3
- package/docs/site-themes.md +30 -0
- package/docs/testing.md +46 -68
- package/docs/troubleshooting.md +3 -3
- package/package.json +9 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,10 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
## 0.1.
|
|
3
|
+
## 0.1.7-preview.2 — 2026-10-15
|
|
4
4
|
|
|
5
|
-
-
|
|
6
|
-
-
|
|
7
|
-
-
|
|
5
|
+
- Ask for a $10, custom or no-fixed-cap evaluation budget after model scope; save the explicit choice, handle reservations internally, and preserve cumulative usage across reruns and budget changes. Add `eval plan --budget <USD|unlimited>` for coding agents and noninteractive setup.
|
|
6
|
+
- Separate native budget and environment blocks from task scores in agent evaluations; probe the Codex Linux sandbox before making model requests.
|
|
7
|
+
- Recover partial Claude usage, retain partial cost estimates, keep missing native pricing unknown, and preserve budget reservations independently of estimated charges. Report version 2 separates these accounting rules from earlier comparisons.
|
|
8
|
+
|
|
9
|
+
## 0.1.7-preview.1 — 2026-10-15
|
|
10
|
+
|
|
11
|
+
- Add `openmerit eval init/doctor/plan/run/watch/report`: Scout shortlists, explicit model scope, Claude Code/Codex/OpenCode adapters, fresh task attempts, local graders, balanced adaptive 3–10 repetitions, revision comparisons and cumulative budget accounting.
|
|
12
|
+
- Bundle project agent instructions without install-time hooks. Missing usage/cost remains unknown and partial comparisons are disclosed. Terminal/Pi behavior is unchanged.
|
|
13
|
+
- Use the hosted Scout HTTP/MCP `modelIds` filter to select eligible candidates before ranking. This API change was deployed separately on 15 October 2026.
|
|
8
14
|
|
|
9
15
|
## 0.1.6-preview.5 — 2026-10-10
|
|
10
16
|
|
package/README.md
CHANGED
|
@@ -1,76 +1,97 @@
|
|
|
1
1
|
# OpenMerit
|
|
2
2
|
|
|
3
|
-
OpenMerit
|
|
3
|
+
OpenMerit provides a local Inference Terminal for understanding an application's models, services, recorded activity, and compute, plus a Pi integration for evidence-driven model comparisons.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
The terminal reads existing evidence. The Pi integration asks a coding harness to build evaluations, measure candidates, and carry out authorized changes. OpenMerit coordinates that workflow and validates its structured results; the terminal does not route requests, run evaluations, or swap models.
|
|
6
6
|
|
|
7
|
-
##
|
|
7
|
+
## Open the terminal
|
|
8
8
|
|
|
9
|
-
Requires
|
|
9
|
+
Requires Node.js 22.19 or newer and npm:
|
|
10
10
|
|
|
11
11
|
```sh
|
|
12
12
|
npm install -g openmerit
|
|
13
|
+
cd /path/to/your/application
|
|
13
14
|
openmerit dash
|
|
14
15
|
```
|
|
15
16
|
|
|
16
|
-
|
|
17
|
+
Stable `openmerit@0.1.6` includes the terminal. No Pi installation or provider API key is needed. It opens a browser connected to a read-only loopback service. Supported source/configuration declarations establish inventory; existing application logs or exports supply request history. Prompts, responses, and credentials are not retained. Unsupported or missing evidence remains unknown.
|
|
17
18
|
|
|
18
|
-
|
|
19
|
+
The source interface and hosted dashboard follow the device's light/dark preference without a theme control. This appearance change is not included in npm 0.1.6.
|
|
20
|
+
|
|
21
|
+
Explore the [hosted sample](https://dash.openmerit.ai/) or [before/after dashboard demo](https://dash.openmerit.ai/demo). Both use fictional data and make no inference calls. See [the terminal guide](docs/inference-terminal.md) for configuration, discovery, diagnostics, history limits, and agent access.
|
|
22
|
+
|
|
23
|
+
## Compare models with Pi
|
|
24
|
+
|
|
25
|
+
The **npm preview `0.1.7-preview.2`** provides `openmerit eval` for evaluating Claude Code, Codex and OpenCode with your CLI. Choose model scope and a $10, custom or no-fixed-cap budget, freeze Scout's shortlist, and compare 3–10 fresh attempts after source changes. Budget and sandbox blocks stay separate from task scores; unknown costs stay unknown. Install with `npm install -g openmerit@preview`. See [agent evaluations](https://unpkg.com/openmerit@0.1.7-preview.2/docs/agent-evaluations.md) for setup, graders, budgets and availability. This is separate from the Pi workflow below.
|
|
26
|
+
|
|
27
|
+
With Pi 0.87 and a model provider configured:
|
|
19
28
|
|
|
20
29
|
```sh
|
|
21
|
-
|
|
30
|
+
pi install npm:openmerit
|
|
31
|
+
pi list
|
|
22
32
|
```
|
|
23
33
|
|
|
24
|
-
|
|
34
|
+
Open the product repository in interactive Pi. An unconfigured project is checked for an application LLM call at session start and after settled build turns. Pi confirms the application target and incumbent model, proposes task-specific metrics and sampling, explains estimated evaluation cost, and requests confirmation of the plan, budget, and permissions. `/openmerit setup` can recover or rerun setup. Pi's own model is never the application target.
|
|
25
35
|
|
|
26
|
-
|
|
36
|
+
Core checks stored baseline windows against the confirmed requirements. When ready, it asks Pi to discover candidates, run controlled comparisons, and calculate a frontier. Core validates the returned evidence contracts and Pareto conformance. The harness must execute the work and provide honest evidence.
|
|
27
37
|
|
|
28
|
-
-
|
|
29
|
-
- **Inference activity:** requests, tokens, latency, costs, and agent/task identifiers where supported application logs or explicit exports provide them.
|
|
30
|
-
- **Code and configuration evidence:** file-and-line references, indexing progress, unresolved references, and source coverage.
|
|
31
|
-
- **Compute and deployments:** explicitly linked hosts, model residency, and supplied hardware or capacity measurements, with their freshness and scope shown.
|
|
38
|
+
Model changes normally require approval. Explicit automatic-swap opt-in can allow changes once the configured verified-swap threshold is reached, including a threshold of zero. Post-swap evaluation and conditional rollback depend on the harness performing and reporting them.
|
|
32
39
|
|
|
33
|
-
|
|
40
|
+
Read [getting started](docs/getting-started.md) and [your first supervised trial](docs/first-trial.md).
|
|
34
41
|
|
|
35
|
-
##
|
|
42
|
+
## Implemented orchestration
|
|
36
43
|
|
|
37
|
-
|
|
44
|
+
- Task profiles with confirmed metrics, sampling plans, constraints, budgets, and permissions.
|
|
45
|
+
- Preliminary model research, incumbent identity, durable candidate handoffs, and controlled challenger experiments.
|
|
46
|
+
- Deterministic baseline checks and uncertainty-aware frontier validation.
|
|
47
|
+
- Versioned result schemas for all ten intents and a reusable harness adapter boundary.
|
|
48
|
+
- Challenger-spend accounting, bounded intent admission, approval, verification, and rollback requests.
|
|
49
|
+
- Project-local state, redacted audit events, evidence manifests, and optional event exporters.
|
|
50
|
+
- Task-count, elapsed-time, catalogue-change, regression, and post-swap signals.
|
|
51
|
+
- Durable pause and authorized macOS user LaunchAgents; other platforms require an external scheduler.
|
|
38
52
|
|
|
39
|
-
|
|
53
|
+
These implementations have automated coverage. They do not establish application-quality improvements or reliable unattended model changes. See [current limitations](docs/roadmap.md).
|
|
40
54
|
|
|
41
|
-
##
|
|
55
|
+
## Pi commands
|
|
42
56
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
openmerit
|
|
46
|
-
openmerit
|
|
47
|
-
openmerit
|
|
48
|
-
openmerit
|
|
49
|
-
|
|
57
|
+
- `/openmerit` or `/openmerit status` — inspect readiness, active work, and lifecycle state.
|
|
58
|
+
- `/openmerit setup` — request or recover setup.
|
|
59
|
+
- `/openmerit assess` — check stored baseline windows; discover candidates only when ready.
|
|
60
|
+
- `/openmerit frontier` — request a harness-calculated comparison for validation.
|
|
61
|
+
- `/openmerit approve` — approve the current verified proposal.
|
|
62
|
+
- `/openmerit pause` / `/openmerit resume` — persist or clear the automatic-work pause and reconcile authorized scheduling; active work is not cancelled.
|
|
63
|
+
- `/openmerit cancel` — record abandonment of an interrupted intent; it does not terminate a provider request.
|
|
64
|
+
- `/openmerit logs` — locate local state, audit, and evidence files.
|
|
65
|
+
- `/openmerit doctor` — inspect adapter and scheduler diagnostics.
|
|
50
66
|
|
|
51
|
-
|
|
67
|
+
## Documentation
|
|
52
68
|
|
|
53
|
-
|
|
69
|
+
The [documentation overview](docs/index.md) links all current guides. The website at [openmerit.ai/docs](https://openmerit.ai/docs/) is deployed separately from the package and this checkout.
|
|
54
70
|
|
|
55
|
-
|
|
71
|
+
- [Inference Terminal](docs/inference-terminal.md)
|
|
72
|
+
- [Metrics and evidence](docs/metrics-and-evidence.md)
|
|
73
|
+
- [Lifecycle](docs/lifecycle.md), [automation](docs/automation.md), and [budgets](docs/budgets.md)
|
|
74
|
+
- [Commands](docs/commands.md), [operations](docs/operations.md), and [troubleshooting](docs/troubleshooting.md)
|
|
75
|
+
- [Security and data handling](docs/security.md)
|
|
76
|
+
- [Architecture](docs/architecture.md), [Pi adapter](docs/pi-extension.md), and [adapter development](docs/adapter-guide.md)
|
|
77
|
+
- [Pareto specification](docs/pareto-spec.md) and [testing](docs/testing.md)
|
|
56
78
|
|
|
57
|
-
|
|
79
|
+
## Development
|
|
58
80
|
|
|
59
81
|
```sh
|
|
60
|
-
|
|
82
|
+
npm ci
|
|
83
|
+
npm run verify
|
|
84
|
+
npm run dash -- /path/to/application
|
|
61
85
|
```
|
|
62
86
|
|
|
63
|
-
|
|
87
|
+
For Pi extension development:
|
|
64
88
|
|
|
65
|
-
|
|
89
|
+
```sh
|
|
90
|
+
./node_modules/.bin/pi --no-extensions -e ./packages/pi/src/index.ts
|
|
91
|
+
```
|
|
66
92
|
|
|
67
|
-
|
|
93
|
+
`--no-extensions` avoids registering an installed npm copy alongside the source extension. Credentials belong to the harness or its environment and must never be committed. Jev, if configured, is invoked by the harness; OpenMerit provides no Jev client.
|
|
68
94
|
|
|
69
|
-
|
|
70
|
-
- [Security and data handling](docs/security.md)
|
|
71
|
-
- [Project files and logs](docs/operations.md)
|
|
72
|
-
- [Architecture and integrations](docs/architecture.md)
|
|
73
|
-
- [Testing and validation](docs/testing.md)
|
|
74
|
-
- [Changelog](CHANGELOG.md)
|
|
95
|
+
`packages/terminal` contains the CLI, collectors, hosted sample, and browser interface. `packages/protocol`, `packages/core`, and `packages/pi` provide the protocol, coordinator, and Pi adapter. The package exports `openmerit/core`, `openmerit/protocol`, and `openmerit/pi`.
|
|
75
96
|
|
|
76
|
-
|
|
97
|
+
Edit documentation in `docs/`, then run `npm run check:docs`. The website is generated from those Markdown files. See [documentation maintenance](docs/site-documentation.md) and the [production-source reconciliation note](docs/site-domain-migration.md) before deployment; a local build does not publish changes.
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { execute, agentEnvironment } from './process.mjs';
|
|
2
|
+
|
|
3
|
+
const number = value => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
|
|
4
|
+
const sum = values => values.length && values.every(v => v !== null) ? values.reduce((a, b) => a + b, 0) : null;
|
|
5
|
+
const maximum = values => values.some(v => v !== null) ? Math.max(...values.filter(v => v !== null)) : null;
|
|
6
|
+
export const agents = ['claude', 'codex', 'opencode'];
|
|
7
|
+
|
|
8
|
+
export function connectionFailure(text) {
|
|
9
|
+
if (/budget_exhausted|error_max_budget_usd|(?:maximum|exceeded|exhausted|insufficient).{0,25}(?:budget|credits)|(?:budget|credits).{0,25}(?:exceeded|exhausted)/i.test(text)) return 'budget_exhausted';
|
|
10
|
+
if (/(?:bwrap|bubblewrap|sandbox|landlock|seccomp|unshare|user namespace|uid_map).{0,160}(?:failed|not permitted|unavailable|denied)|failed to (?:start|initialize|create).{0,40}sandbox/i.test(text)) return 'sandbox_unavailable';
|
|
11
|
+
if (/\b(?:HTTP\s*)?401\b.{0,30}(?:unauthorized|authentication)|unauthorized|authentication[_ -]?(?:error|required)|invalid api key|not logged in|please log in/i.test(text)) return 'authentication';
|
|
12
|
+
if (/model.{0,100}(?:not supported|not found|not available|does not exist)|(?:unknown|invalid|unsupported) model|ProviderModelNotFoundError/i.test(text)) return 'model_unavailable';
|
|
13
|
+
if (/rejected permission|permission.{0,30}(?:denied|rejected)|not allowed to use.{0,30}tool/i.test(text)) return 'permission_denied';
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function toolFailure(text) {
|
|
18
|
+
const reason = connectionFailure(text);
|
|
19
|
+
// A task's own HTTP/auth/budget errors are task outcomes, not evidence that
|
|
20
|
+
// the coding agent's provider connection failed.
|
|
21
|
+
return ['sandbox_unavailable', 'permission_denied'].includes(reason) ? reason : null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function invocation(connection, reservationUsd, unlimitedBudget = false) {
|
|
25
|
+
const model = connection.model;
|
|
26
|
+
if (connection.agent === 'claude') return ['-p', '--output-format', 'json', '--model', model, '--no-session-persistence', '--permission-mode', 'dontAsk', '--allowedTools', 'Read,Glob,Grep,Bash,Edit,Write', '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}', '--setting-sources', '', ...(unlimitedBudget ? [] : ['--max-budget-usd', String(reservationUsd)])];
|
|
27
|
+
if (connection.agent === 'codex') return ['exec', '--json', '--model', model, '--sandbox', 'workspace-write', '--skip-git-repo-check', '--ephemeral', '-'];
|
|
28
|
+
if (connection.agent === 'opencode') return ['run', '--format', 'json', '--model', model, '--auto'];
|
|
29
|
+
throw new Error('Unknown agent. Use claude, codex or opencode.');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function parseOutput(agent, stdout) {
|
|
33
|
+
let events;
|
|
34
|
+
try { const parsed = JSON.parse(stdout); events = Array.isArray(parsed) ? parsed : [parsed]; }
|
|
35
|
+
catch { events = stdout.split('\n').flatMap(line => { try { return [JSON.parse(line)]; } catch { return []; } }); }
|
|
36
|
+
let output = '', usage = null, costUsd = null, partialCostUsd = null, completed = false, failed = false, failureReason = null;
|
|
37
|
+
// Only native failure fields are evidence of a blocked execution. Task text,
|
|
38
|
+
// successful tool output and model commentary can legitimately discuss errors.
|
|
39
|
+
const errors = events.filter(e => ['error', 'turn.failed'].includes(e.type));
|
|
40
|
+
for (const event of errors) failureReason ??= connectionFailure(JSON.stringify(event));
|
|
41
|
+
const observedModels = new Set();
|
|
42
|
+
if (agent === 'claude') {
|
|
43
|
+
const result = events.findLast(e => e.type === 'result');
|
|
44
|
+
if (result) {
|
|
45
|
+
completed = result.subtype === 'success' && !result.is_error;
|
|
46
|
+
failed = !completed; output = result.result ?? '';
|
|
47
|
+
const u = result.usage;
|
|
48
|
+
if (u) usage = { input: sum([number(u.input_tokens), number(u.cache_read_input_tokens ?? 0), number(u.cache_creation_input_tokens ?? 0)]), output: number(u.output_tokens), cached: number(u.cache_read_input_tokens ?? 0) };
|
|
49
|
+
const models = Object.values(result.modelUsage ?? {});
|
|
50
|
+
if (models.length) {
|
|
51
|
+
const modelUsage = { input: sum(models.map(m => sum([number(m.inputTokens), number(m.cacheReadInputTokens ?? 0), number(m.cacheCreationInputTokens ?? 0)]))), output: sum(models.map(m => number(m.outputTokens))), cached: sum(models.map(m => number(m.cacheReadInputTokens ?? 0))) };
|
|
52
|
+
// A budget stop can emit zero aggregate usage but nonzero per-model usage.
|
|
53
|
+
usage = Object.fromEntries(Object.keys(modelUsage).map(k => [k, maximum([usage?.[k] ?? null, modelUsage[k]])]));
|
|
54
|
+
}
|
|
55
|
+
costUsd = maximum([number(result.total_cost_usd), sum(models.map(m => number(m.costUSD)))]);
|
|
56
|
+
for (const model of Object.keys(result.modelUsage ?? {})) observedModels.add(model);
|
|
57
|
+
if (failed) failureReason ??= connectionFailure(JSON.stringify({ subtype: result.subtype, terminal_reason: result.terminal_reason, errors: result.errors }));
|
|
58
|
+
if (result.permission_denials?.length) failureReason ??= 'permission_denied';
|
|
59
|
+
}
|
|
60
|
+
} else if (agent === 'codex') {
|
|
61
|
+
const turns = events.filter(e => e.type === 'turn.completed');
|
|
62
|
+
completed = turns.length > 0;
|
|
63
|
+
failed = events.some(e => ['turn.failed', 'error'].includes(e.type));
|
|
64
|
+
output = events.findLast(e => e.type === 'item.completed' && e.item?.type === 'agent_message')?.item.text ?? '';
|
|
65
|
+
if (turns.length) usage = { input: sum(turns.map(e => number(e.usage?.input_tokens))), output: sum(turns.map(e => number(e.usage?.output_tokens))), cached: sum(turns.map(e => number(e.usage?.cached_input_tokens))) };
|
|
66
|
+
for (const event of events.filter(e => e.type === 'item.completed' && e.item?.type === 'command_execution' && (e.item.exit_code > 0 || e.item.status === 'failed'))) {
|
|
67
|
+
failureReason ??= toolFailure(event.item.aggregated_output ?? '');
|
|
68
|
+
}
|
|
69
|
+
} else if (agent === 'opencode') {
|
|
70
|
+
const steps = events.filter(e => e.type === 'step_finish');
|
|
71
|
+
const finalStep = steps.findLast(e => ['stop', 'end_turn'].includes(e.part?.reason));
|
|
72
|
+
completed = !!finalStep;
|
|
73
|
+
failed = events.some(e => e.type === 'error');
|
|
74
|
+
const texts = events.filter(e => e.type === 'text');
|
|
75
|
+
output = finalStep?.part?.messageID ? texts.filter(e => e.part?.messageID === finalStep.part.messageID).map(e => e.part?.text ?? '').join('\n') : texts.at(-1)?.part?.text ?? '';
|
|
76
|
+
if (steps.length) {
|
|
77
|
+
usage = { input: sum(steps.map(e => sum([number(e.part?.tokens?.input), number(e.part?.tokens?.cache?.read ?? 0), number(e.part?.tokens?.cache?.write ?? 0)]))), output: sum(steps.map(e => sum([number(e.part?.tokens?.output), number(e.part?.tokens?.reasoning ?? 0)]))), cached: sum(steps.map(e => number(e.part?.tokens?.cache?.read ?? 0))) };
|
|
78
|
+
const costs = steps.map(e => number(e.part?.cost));
|
|
79
|
+
costUsd = costs.every(c => c !== null && c > 0) ? sum(costs) : null;
|
|
80
|
+
if (costUsd === null) partialCostUsd = sum(costs.filter(c => c !== null && c > 0));
|
|
81
|
+
}
|
|
82
|
+
for (const event of events.filter(e => e.type === 'tool_use' && e.part?.state?.status === 'error')) failureReason ??= toolFailure(event.part.state.error ?? '');
|
|
83
|
+
}
|
|
84
|
+
// Native zero prices can mean missing pricing metadata, not free inference.
|
|
85
|
+
return { output, usage, costUsd: costUsd > 0 ? costUsd : null, partialCostUsd, completed: completed && !failed, failureReason, observedModels: [...observedModels] };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export async function preflight(connection, { cwd, executeCommand = execute, platform = process.platform } = {}) {
|
|
89
|
+
const command = connection.command ?? connection.agent;
|
|
90
|
+
const options = { cwd, timeoutMs: 10_000, env: agentEnvironment(connection.env) };
|
|
91
|
+
const version = await executeCommand(command, ['--version'], options);
|
|
92
|
+
const help = await executeCommand(command, connection.agent === 'codex' ? ['exec', '--help'] : connection.agent === 'opencode' ? ['run', '--help'] : ['--help'], options);
|
|
93
|
+
const flags = connection.agent === 'codex' ? ['--json', '--ephemeral', '--sandbox'] : connection.agent === 'claude' ? ['--output-format', '--no-session-persistence', '--max-budget-usd'] : ['--format', '--model', '--auto'];
|
|
94
|
+
if (version.code !== 0 || help.code !== 0 || !flags.every(f => (help.stdout + help.stderr).includes(f))) throw new Error(`${connection.agent} lacks the required non-interactive JSON interface. Update it or set this connection's command to a compatible executable.`);
|
|
95
|
+
if (connection.agent === 'codex' && platform === 'linux') {
|
|
96
|
+
const sandboxHelp = await executeCommand(command, ['sandbox', '--help'], options);
|
|
97
|
+
const legacy = /^\s+linux\s/m.test(sandboxHelp.stdout);
|
|
98
|
+
const probe = await executeCommand(command, ['-c', 'sandbox_mode="workspace-write"', 'sandbox', ...(legacy ? ['linux'] : []), '--', process.execPath, '-e', 'process.stdout.write("openmerit-sandbox-ok")'], options);
|
|
99
|
+
if (probe.code !== 0 || probe.reason || probe.stdout !== 'openmerit-sandbox-ok') {
|
|
100
|
+
throw Object.assign(new Error('Codex sandbox could not run a local probe. Fix host sandbox support before evaluating; no model request was made.'), { failureReason: 'sandbox_unavailable' });
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return version.stdout.trim().slice(0, 160);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export async function runAgent(connection, prompt, options) {
|
|
107
|
+
const result = await execute(connection.command ?? connection.agent, invocation(connection, options.reservationUsd, options.unlimitedBudget), { ...options, input: prompt, env: agentEnvironment(connection.env) });
|
|
108
|
+
const parsed = parseOutput(connection.agent, result.stdout);
|
|
109
|
+
const failureReason = parsed.failureReason ?? (result.code !== 0 ? connectionFailure(result.stderr) : null) ?? (['spawn_failed', 'cancelled', 'output_limit'].includes(result.reason) ? result.reason : null);
|
|
110
|
+
const status = failureReason === 'budget_exhausted' ? 'budget_exhausted' : ['sandbox_unavailable', 'permission_denied', 'spawn_failed'].includes(failureReason) ? 'environment_error' : result.reason ?? (failureReason || result.code !== 0 || !parsed.completed ? 'agent_error' : 'ok');
|
|
111
|
+
return { ...parsed, costUsd: status === 'ok' ? parsed.costUsd : null, partialCostUsd: status === 'ok' ? parsed.partialCostUsd : maximum([parsed.costUsd, parsed.partialCostUsd]), costBasis: parsed.costUsd === null && parsed.partialCostUsd === null ? 'unknown' : 'agent_estimate', seconds: result.seconds, status, failureReason };
|
|
112
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { join, resolve } from 'node:path';
|
|
3
|
+
import { createInterface } from 'node:readline/promises';
|
|
4
|
+
import { agents, preflight } from './adapters.mjs';
|
|
5
|
+
import { configPath, statePath, starter, loadConfig, readJSON, saveJSON } from './config.mjs';
|
|
6
|
+
import { makePlan, savePlan } from './scout.mjs';
|
|
7
|
+
import { acquireLock, evaluate, watch } from './runner.mjs';
|
|
8
|
+
import { formatReport } from './report.mjs';
|
|
9
|
+
|
|
10
|
+
export const help = `OpenMerit · Agent evaluations (source preview)
|
|
11
|
+
|
|
12
|
+
openmerit eval init Add a starter suite and project agent instructions
|
|
13
|
+
openmerit eval doctor Check installed Claude Code, Codex and OpenCode CLIs
|
|
14
|
+
openmerit eval plan [--scope existing|all] [--budget <USD|unlimited>]
|
|
15
|
+
Choose scope and budget, then freeze Scout's shortlist
|
|
16
|
+
openmerit eval run [--json] Evaluate the frozen shortlist in fresh workspaces
|
|
17
|
+
openmerit eval watch [--json] Repeat after selected CLI/docs/fixture files change
|
|
18
|
+
openmerit eval report [--json] Read the latest result without running models
|
|
19
|
+
|
|
20
|
+
--path <directory> Project directory (default: current directory)
|
|
21
|
+
|
|
22
|
+
Configure .openmerit/eval.json: explicit agent connections, task fixtures, local
|
|
23
|
+
graders, CLI variants, 3–10 repeats, and a cumulative budget. Init starts at $0.
|
|
24
|
+
Plan asks for $10, a custom amount, or no fixed cap; nothing is preselected.
|
|
25
|
+
Saved choices and prior budget usage persist across reruns. --budget changes
|
|
26
|
+
the total allowance, not the amount remaining. Reservations are automatic.
|
|
27
|
+
Scout receives task descriptions and, for existing scope, model IDs only.
|
|
28
|
+
Run/watch execute local agents and may incur charges. No background daemon.
|
|
29
|
+
`;
|
|
30
|
+
|
|
31
|
+
const instructions = `<!-- openmerit-eval:start -->
|
|
32
|
+
## OpenMerit agent evaluations
|
|
33
|
+
|
|
34
|
+
When building or changing this project's CLI, tools or harness documentation, use
|
|
35
|
+
\`openmerit eval\` to compare task performance. Skip this workflow when
|
|
36
|
+
\`OPENMERIT_EVAL=1\` to avoid recursive evaluations.
|
|
37
|
+
|
|
38
|
+
- Read .openmerit/eval.json and run \`openmerit eval doctor\`.
|
|
39
|
+
- Ask once: "Models available through this project's existing connections, or all models Scout indexes?" Use \`eval plan --scope existing\` or \`--scope all\`. Reuse the saved choice. Never infer endpoint access from a model name or expose credentials.
|
|
40
|
+
- Then ask once: "What budget should OpenMerit use for this project's evaluations? 1. $10; 2. Custom amount (how much?); 3. No fixed cap." Pass the explicit answer as \`eval plan --budget 10\`, \`--budget <amount>\` or \`--budget unlimited\`, together with scope on first setup. Never choose a default or infer unlimited spending. Reuse an existing positive or unlimited budget unless the user changes it. The allowance is cumulative across reruns, not reset by edits or replanning. Reservations are internal; do not ask the user to calculate them. No fixed cap still has bounded tasks, 3–10 repetitions, timeouts and user-controlled watch; subsequent watched edits can incur further charges until stopped.
|
|
41
|
+
- Declare real connections with Scout model IDs, agent-native model IDs, and environment variable NAMES. Existing scope uses this project-declared inventory. All scope may require new authenticated connections before execution.
|
|
42
|
+
- Replace starter cases with representative tasks, fresh fixtures and deterministic standalone Node graders. A grader reads {workspace, output} JSON on stdin and returns {quality: 0..1}. Keep answer keys outside agent workspaces. Include a bare variant and a CLI/docs variant where useful.
|
|
43
|
+
- Confirm the suite and variants before enabling paid runs, using the budget already selected above. Do not ask again for an unchanged authorized budget. Then plan once, run a baseline, make the requested CLI changes, and run again. Use \`eval watch\` only when the user wants continuous local reruns; it exits with the terminal and retains budget usage across restarts.
|
|
44
|
+
- Report quality, failures, tokens, reported costs and elapsed time per task/model/variant. A shortlist is a prior, not measured success. Do not claim missing costs are zero or that 3–10 repeats prove an exact ordering. Keep fresh holdouts for final validation.
|
|
45
|
+
- If a compatible watcher is already active, let it run; never start overlapping loops. Do not overwrite the frozen plan merely because the CLI changed.
|
|
46
|
+
<!-- openmerit-eval:end -->`;
|
|
47
|
+
|
|
48
|
+
export async function initialize(root) {
|
|
49
|
+
// Refuse partial overwrite of an existing suite or someone's fixtures.
|
|
50
|
+
const files = {
|
|
51
|
+
[configPath]: JSON.stringify(starter, null, 2) + '\n',
|
|
52
|
+
'eval/fixtures/json/request.txt': 'Customer: Mira Chen\nItems: 7\n',
|
|
53
|
+
'eval/tool.mjs': `import {readFileSync} from 'node:fs';\nconst s=readFileSync(process.argv[2],'utf8');\nconsole.log(JSON.stringify({name:s.match(/Customer: (.*)/)?.[1],count:Number(s.match(/Items: (\\d+)/)?.[1])}));\n`,
|
|
54
|
+
'eval/grade.mjs': `let input=''; for await (const chunk of process.stdin) input+=chunk;\nconst {output}=JSON.parse(input); let quality=0;\ntry {const v=JSON.parse(output); quality=(Number(v.name==='Mira Chen')+Number(v.count===7)+Number(Object.keys(v).sort().join(',')==='count,name'))/3;} catch {}\nconsole.log(JSON.stringify({quality}));\n`,
|
|
55
|
+
};
|
|
56
|
+
for (const file of Object.keys(files)) {
|
|
57
|
+
try { await readFile(join(root, file)); throw new Error(`Already exists: ${file}. Init does not overwrite a suite.`); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
58
|
+
}
|
|
59
|
+
for (const [file, body] of Object.entries(files)) { await mkdir(join(root, file, '..'), { recursive: true }); await writeFile(join(root, file), body, { flag: 'wx' }); }
|
|
60
|
+
for (const name of ['AGENTS.md', 'CLAUDE.md']) {
|
|
61
|
+
let body = ''; try { body = await readFile(join(root, name), 'utf8'); } catch (e) { if (e.code !== 'ENOENT') throw e; }
|
|
62
|
+
if (!body.includes('<!-- openmerit-eval:start -->')) await writeFile(join(root, name), `${body}${body ? '\n\n' : ''}${instructions}\n`);
|
|
63
|
+
}
|
|
64
|
+
let ignore = ''; try { ignore = await readFile(join(root, '.gitignore'), 'utf8'); } catch (e) { if (e.code !== 'ENOENT') throw e; }
|
|
65
|
+
if (!ignore.split('\n').includes('/.openmerit/eval/')) await writeFile(join(root, '.gitignore'), `${ignore}${ignore.endsWith('\n') || !ignore ? '' : '\n'}/.openmerit/eval/\n`);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function parseBudget(value) {
|
|
69
|
+
const input = value.trim();
|
|
70
|
+
if (input === 'unlimited') return input;
|
|
71
|
+
const amount = input.replace(/^\$/, '');
|
|
72
|
+
if (!/^(?:\d+(?:\.\d{1,2})?|\.\d{1,2})$/.test(amount) || Number(amount) <= 0 || Number(amount) > Number.MAX_SAFE_INTEGER / 100) throw new Error('Enter a positive USD amount with at most two decimal places, or "unlimited" for no fixed cap.');
|
|
73
|
+
return Number(amount);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// ask is supplied only for an interactive terminal. Coding agents pass explicit
|
|
77
|
+
// flags after asking the user; EOF, blank input and missing flags never consent.
|
|
78
|
+
export async function choosePlanOptions(config, { scope, budget, ask, tell = () => {} } = {}) {
|
|
79
|
+
const next = structuredClone(config);
|
|
80
|
+
if (scope) next.scope = scope;
|
|
81
|
+
while (!['existing', 'all'].includes(next.scope)) {
|
|
82
|
+
if (!ask) throw new Error('Choose a scope with eval plan --scope existing or --scope all, then choose --budget <USD|unlimited>.');
|
|
83
|
+
const answer = (await ask('Use existing project connections or all models Scout indexes? [existing/all] ')).trim();
|
|
84
|
+
if (['existing', 'all'].includes(answer)) next.scope = answer;
|
|
85
|
+
else tell('Choose existing or all.');
|
|
86
|
+
}
|
|
87
|
+
if (budget !== undefined) next.budget = { maxUsd: parseBudget(budget), reservationUsd: 'auto' };
|
|
88
|
+
while (next.budget.maxUsd === 0) {
|
|
89
|
+
if (!ask) throw new Error('Choose an evaluation budget after model scope: --budget 10, --budget <USD>, or --budget unlimited. No amount is selected automatically.');
|
|
90
|
+
const choice = (await ask('What budget should OpenMerit use for this project’s evaluations?\n 1. $10\n 2. Custom amount\n 3. No fixed cap (watched changes can incur further charges until stopped)\nChoose [1/2/3]: ')).trim();
|
|
91
|
+
if (choice === '1') next.budget = { maxUsd: 10, reservationUsd: 'auto' };
|
|
92
|
+
else if (choice === '3') next.budget = { maxUsd: 'unlimited', reservationUsd: 'auto' };
|
|
93
|
+
else if (choice === '2') {
|
|
94
|
+
while (next.budget.maxUsd === 0) {
|
|
95
|
+
const amount = await ask('How much in USD? ');
|
|
96
|
+
try {
|
|
97
|
+
const parsed = parseBudget(amount);
|
|
98
|
+
if (parsed === 'unlimited') throw new Error('Enter a custom USD amount.');
|
|
99
|
+
next.budget = { maxUsd: parsed, reservationUsd: 'auto' };
|
|
100
|
+
} catch { tell('Enter a positive USD amount with at most two decimal places.'); }
|
|
101
|
+
}
|
|
102
|
+
} else tell('Choose 1, 2 or 3. Nothing is selected automatically.');
|
|
103
|
+
}
|
|
104
|
+
return next;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export async function main(args) {
|
|
108
|
+
if (!args.length || args.includes('--help') || args.includes('-h')) { console.log(help); return; }
|
|
109
|
+
const action = args.shift(); let root = process.cwd(), scope, budget, json = false;
|
|
110
|
+
for (let i = 0; i < args.length; i++) {
|
|
111
|
+
if (args[i] === '--path' && args[i + 1]) root = resolve(args[++i]);
|
|
112
|
+
else if (args[i] === '--scope' && ['existing', 'all'].includes(args[i + 1])) scope = args[++i];
|
|
113
|
+
else if (args[i] === '--budget' && args[i + 1] && budget === undefined) { budget = args[++i]; parseBudget(budget); }
|
|
114
|
+
else if (args[i] === '--json') json = true;
|
|
115
|
+
else throw new Error(`Unknown eval argument: ${args[i]}`);
|
|
116
|
+
}
|
|
117
|
+
if (scope && action !== 'plan') throw new Error('--scope belongs to eval plan.');
|
|
118
|
+
if (budget !== undefined && action !== 'plan') throw new Error('--budget belongs to eval plan.');
|
|
119
|
+
if (action === 'init') { await initialize(root); console.log('Created .openmerit/eval.json, starter fixtures, and AGENTS.md / CLAUDE.md instructions. Declare connections, replace the starter task, and set an approved budget before running.'); return; }
|
|
120
|
+
if (action === 'doctor') {
|
|
121
|
+
const results = [];
|
|
122
|
+
for (const agent of agents) { try { results.push({ agent, version: await preflight({ agent }), ready: true }); } catch (error) { results.push({ agent, ready: false, reason: error.message }); } }
|
|
123
|
+
console.log(JSON.stringify(results, null, 2)); return;
|
|
124
|
+
}
|
|
125
|
+
if (action === 'report') { const report = await readJSON(join(root, statePath, 'latest.json')); console.log(json ? JSON.stringify(report, null, 2) : formatReport(report)); return; }
|
|
126
|
+
if (!['plan', 'run', 'watch'].includes(action)) throw new Error('Unknown eval command. Run openmerit eval --help.');
|
|
127
|
+
const unlock = await acquireLock(root);
|
|
128
|
+
const controller = new AbortController(), stop = () => controller.abort();
|
|
129
|
+
process.once('SIGINT', stop); process.once('SIGTERM', stop);
|
|
130
|
+
try {
|
|
131
|
+
if (action === 'plan') {
|
|
132
|
+
const saved = await loadConfig(root);
|
|
133
|
+
const rl = process.stdin.isTTY && !json ? createInterface({ input: process.stdin, output: process.stdout }) : null;
|
|
134
|
+
const inputClosed = new AbortController();
|
|
135
|
+
rl?.once('close', () => inputClosed.abort());
|
|
136
|
+
let config;
|
|
137
|
+
try { config = await choosePlanOptions(saved, { scope, budget, ask: rl ? question => rl.question(question, { signal: AbortSignal.any([controller.signal, inputClosed.signal]) }) : undefined, tell: message => console.log(message) }); }
|
|
138
|
+
finally { rl?.close(); }
|
|
139
|
+
// Preserve explicit choices even if Scout is temporarily unavailable.
|
|
140
|
+
await saveJSON(join(root, configPath), config);
|
|
141
|
+
const plan = await makePlan(config);
|
|
142
|
+
await savePlan(root, plan);
|
|
143
|
+
console.log(JSON.stringify(plan, null, 2));
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
const onReport = report => { console.log(json ? JSON.stringify(report) : formatReport(report)); if (report.status !== 'complete') process.exitCode = 1; };
|
|
147
|
+
const onProgress = json ? () => {} : row => process.stderr.write(`${row.task} · ${row.connection} · ${row.variant} · ${row.round}: ${row.status}\n`);
|
|
148
|
+
if (action === 'run') onReport(await evaluate(root, { signal: controller.signal, onProgress }));
|
|
149
|
+
else { if (!json) console.log('Watching selected files. Ctrl+C stops; budget usage persists.'); await watch(root, { signal: controller.signal, onReport, onProgress }); }
|
|
150
|
+
} finally { process.removeListener('SIGINT', stop); process.removeListener('SIGTERM', stop); await unlock(); }
|
|
151
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { readFile, writeFile, mkdir, rename, readdir, lstat, realpath } from 'node:fs/promises';
|
|
2
|
+
import { resolve, relative, join, dirname, isAbsolute } from 'node:path';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { agents } from './adapters.mjs';
|
|
5
|
+
|
|
6
|
+
export const configPath = '.openmerit/eval.json';
|
|
7
|
+
export const statePath = '.openmerit/eval';
|
|
8
|
+
export const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
9
|
+
export async function readJSON(path) { return JSON.parse(await readFile(path, 'utf8')); }
|
|
10
|
+
export async function saveJSON(path, data) {
|
|
11
|
+
await mkdir(dirname(path), { recursive: true });
|
|
12
|
+
const temp = `${path}.${process.pid}.tmp`;
|
|
13
|
+
await writeFile(temp, JSON.stringify(data, null, 2) + '\n', { mode: 0o600 }); await rename(temp, path);
|
|
14
|
+
}
|
|
15
|
+
const text = v => typeof v === 'string' && v.trim().length > 0;
|
|
16
|
+
const id = v => text(v) && /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,79}$/.test(v);
|
|
17
|
+
function requireThat(ok, message) { if (!ok) throw new Error(`Eval config: ${message}`); }
|
|
18
|
+
export function safePath(path) {
|
|
19
|
+
requireThat(text(path) && !isAbsolute(path) && !path.split(/[\\/]/).some(p => ['..', '.', '.git', '.openmerit', 'node_modules'].includes(p) || p.startsWith('.env')), `unsafe file path ${path}. Use explicit project-relative source/fixture paths, without secrets or symlinks.`);
|
|
20
|
+
return path;
|
|
21
|
+
}
|
|
22
|
+
export function validateConfig(config) {
|
|
23
|
+
requireThat(config.version === 1, 'version must be 1.');
|
|
24
|
+
requireThat([null, 'existing', 'all'].includes(config.scope), 'scope must be null, existing or all.');
|
|
25
|
+
requireThat(Array.isArray(config.connections) && config.connections.length <= 100, 'connections must be a list of up to 100 routes.');
|
|
26
|
+
requireThat(new Set(config.connections.map(c => c.id)).size === config.connections.length, 'connection IDs must be unique.');
|
|
27
|
+
for (const c of config.connections) {
|
|
28
|
+
requireThat(id(c.id) && agents.includes(c.agent) && text(c.scoutId) && text(c.model), 'each connection needs id, scoutId, agent and native model.');
|
|
29
|
+
requireThat(!c.model.startsWith('-') && c.model.length <= 200, 'invalid native model.');
|
|
30
|
+
requireThat(c.env === undefined || Array.isArray(c.env) && c.env.every(k => /^[A-Z][A-Z0-9_]*$/.test(k)), 'env contains variable names, never credential values.');
|
|
31
|
+
requireThat(c.command === undefined || text(c.command), 'command must be an executable path.');
|
|
32
|
+
}
|
|
33
|
+
requireThat(Array.isArray(config.tasks) && config.tasks.length > 0 && config.tasks.length <= 30, 'provide 1–30 tasks.');
|
|
34
|
+
requireThat(new Set(config.tasks.map(t => t.id)).size === config.tasks.length, 'task IDs must be unique.');
|
|
35
|
+
for (const t of config.tasks) {
|
|
36
|
+
requireThat(id(t.id) && text(t.description) && t.description.length <= 4000 && text(t.prompt), 'each task needs id, description for Scout and a local execution prompt.');
|
|
37
|
+
safePath(t.fixture); safePath(t.grader);
|
|
38
|
+
}
|
|
39
|
+
requireThat(Array.isArray(config.variants) && config.variants.length > 0 && config.variants.length <= 5, 'provide 1–5 variants.');
|
|
40
|
+
requireThat(new Set(config.variants.map(v => v.id)).size === config.variants.length, 'variant IDs must be unique.');
|
|
41
|
+
for (const v of config.variants) {
|
|
42
|
+
requireThat(id(v.id) && Array.isArray(v.files) && typeof v.instructions === 'string', 'each variant needs id, files and instructions.');
|
|
43
|
+
v.files.forEach(safePath);
|
|
44
|
+
}
|
|
45
|
+
requireThat(Number.isInteger(config.repeats?.min) && Number.isInteger(config.repeats?.max) && config.repeats.min >= 3 && config.repeats.max <= 10 && config.repeats.min <= config.repeats.max, 'repeats must be between 3 and 10.');
|
|
46
|
+
requireThat((config.budget?.maxUsd === 'unlimited' || Number.isFinite(config.budget?.maxUsd) && config.budget.maxUsd >= 0) && (config.budget.reservationUsd === 'auto' || Number.isFinite(config.budget.reservationUsd) && config.budget.reservationUsd > 0), 'set nonnegative maxUsd or explicit "unlimited", and reservationUsd to "auto" or a positive amount.');
|
|
47
|
+
requireThat(Number.isInteger(config.timeoutSeconds) && config.timeoutSeconds >= 1 && config.timeoutSeconds <= 1800, 'timeoutSeconds must be 1–1800.');
|
|
48
|
+
if (config.scoutURL !== undefined) {
|
|
49
|
+
const url = new URL(config.scoutURL);
|
|
50
|
+
requireThat(!url.username && !url.password && (url.protocol === 'https:' || url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)), 'scoutURL requires HTTPS, or HTTP on loopback for development.');
|
|
51
|
+
}
|
|
52
|
+
return config;
|
|
53
|
+
}
|
|
54
|
+
export async function loadConfig(root) { return validateConfig(await readJSON(join(root, configPath))); }
|
|
55
|
+
|
|
56
|
+
export function reservationFor(config, plan) {
|
|
57
|
+
if (config.budget.reservationUsd !== 'auto') return config.budget.reservationUsd;
|
|
58
|
+
const attempts = plan.tasks.reduce((total, task) => total + task.candidates.reduce((n, model) => n + model.connections.length, 0), 0) * config.variants.length * config.repeats.min;
|
|
59
|
+
return config.budget.maxUsd === 'unlimited' || config.budget.maxUsd === 0 ? .25 : Math.min(.25, config.budget.maxUsd / Math.max(1, attempts));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Snapshot exact bytes before executing; edits during a run belong to the next revision.
|
|
63
|
+
export async function filesAt(root, paths) {
|
|
64
|
+
const files = Object.create(null); let bytes = 0; const canonicalRoot = await realpath(root);
|
|
65
|
+
async function visit(path) {
|
|
66
|
+
safePath(path);
|
|
67
|
+
const full = resolve(root, path), info = await lstat(full);
|
|
68
|
+
if (info.isSymbolicLink() || relative(canonicalRoot, await realpath(full)).startsWith('..')) throw new Error(`Eval refuses symlink/outside path: ${path}`);
|
|
69
|
+
if (info.isDirectory()) {
|
|
70
|
+
for (const name of (await readdir(full)).sort()) await visit(join(path, name));
|
|
71
|
+
} else if (info.isFile()) {
|
|
72
|
+
bytes += info.size;
|
|
73
|
+
if (bytes > 25_000_000) throw new Error('Eval fixture/source snapshot exceeds 25 MB. Select smaller paths.');
|
|
74
|
+
files[path] = { data: (await readFile(full)).toString('base64'), executable: !!(info.mode & 0o111) };
|
|
75
|
+
} else throw new Error(`Eval requires regular files: ${path}`);
|
|
76
|
+
}
|
|
77
|
+
for (const path of paths) await visit(path);
|
|
78
|
+
return files;
|
|
79
|
+
}
|
|
80
|
+
export async function snapshot(root, config) {
|
|
81
|
+
const tasks = [];
|
|
82
|
+
for (const task of config.tasks) {
|
|
83
|
+
if (!(await lstat(join(root, task.fixture))).isDirectory() || !(await lstat(join(root, task.grader))).isFile()) throw new Error(`${task.id}: fixture must be a directory and grader a standalone file.`);
|
|
84
|
+
tasks.push({ ...task, fixtureFiles: await filesAt(root, [task.fixture]), graderFiles: await filesAt(root, [task.grader]) });
|
|
85
|
+
}
|
|
86
|
+
const variants = [];
|
|
87
|
+
for (const variant of config.variants) variants.push({ ...variant, sourceFiles: await filesAt(root, variant.files) });
|
|
88
|
+
for (const task of tasks) for (const variant of variants) {
|
|
89
|
+
const fixtureNames = new Set(Object.keys(task.fixtureFiles).map(path => relative(task.fixture, path)));
|
|
90
|
+
if (Object.keys(variant.sourceFiles).some(path => fixtureNames.has(path))) throw new Error(`${variant.id} overwrites a fixture file for ${task.id}. Keep CLI files and task inputs separate.`);
|
|
91
|
+
}
|
|
92
|
+
const compatibility = digest({ tasks, connections: config.connections, repeats: config.repeats, variantIds: variants.map(v => v.id), timeoutSeconds: config.timeoutSeconds });
|
|
93
|
+
return { tasks, variants, compatibility, revision: digest({ tasks, variants, config }) };
|
|
94
|
+
}
|
|
95
|
+
export async function materialize(files, dest, strip = '') {
|
|
96
|
+
for (const [path, file] of Object.entries(files)) {
|
|
97
|
+
const target = join(dest, strip ? relative(strip, path) : path);
|
|
98
|
+
await mkdir(dirname(target), { recursive: true });
|
|
99
|
+
await writeFile(target, Buffer.from(file.data, 'base64'), { mode: file.executable ? 0o700 : 0o600 });
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export const starter = {
|
|
104
|
+
version: 1, scope: null, connections: [],
|
|
105
|
+
tasks: [{ id: 'json', description: 'Extract a customer name and item count from text into a strict JSON object.', prompt: 'Read request.txt. Return only JSON with keys name (string) and count (number).', fixture: 'eval/fixtures/json', grader: 'eval/grade.mjs' }],
|
|
106
|
+
variants: [{ id: 'bare', files: [], instructions: '' }, { id: 'cli', files: ['eval/tool.mjs'], instructions: 'You can use node eval/tool.mjs request.txt to extract the fields.' }],
|
|
107
|
+
repeats: { min: 3, max: 10 }, budget: { maxUsd: 0, reservationUsd: 'auto' }, timeoutSeconds: 180,
|
|
108
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
|
|
3
|
+
// No shell interpolation. Bound both time and output, and stop descendants too.
|
|
4
|
+
export function execute(command, args, { cwd, env = process.env, input = '', timeoutMs = 180_000, signal } = {}) {
|
|
5
|
+
return new Promise(resolve => {
|
|
6
|
+
const start = performance.now();
|
|
7
|
+
let stdout = '', stderr = '', bytes = 0, reason = null, escalation;
|
|
8
|
+
const child = spawn(command, args, { cwd, env, detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'] });
|
|
9
|
+
const kill = sig => {
|
|
10
|
+
try {
|
|
11
|
+
if (process.platform === 'win32') { const killer = spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' }); killer.on('error', () => child.kill(sig)); }
|
|
12
|
+
else process.kill(-child.pid, sig);
|
|
13
|
+
} catch {}
|
|
14
|
+
};
|
|
15
|
+
const stop = why => { if (reason) return; reason = why; kill('SIGTERM'); escalation = setTimeout(() => kill('SIGKILL'), 500); };
|
|
16
|
+
const abort = () => stop('cancelled');
|
|
17
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
18
|
+
if (signal?.aborted) abort();
|
|
19
|
+
const timer = setTimeout(() => stop('timeout'), timeoutMs);
|
|
20
|
+
const collect = (chunk, which) => {
|
|
21
|
+
bytes += chunk.length;
|
|
22
|
+
if (bytes > 4_000_000) return stop('output_limit');
|
|
23
|
+
if (which === 'out') stdout += chunk; else stderr += chunk;
|
|
24
|
+
};
|
|
25
|
+
child.stdout.on('data', chunk => collect(chunk, 'out'));
|
|
26
|
+
child.stderr.on('data', chunk => collect(chunk, 'err'));
|
|
27
|
+
child.on('error', () => { reason = 'spawn_failed'; });
|
|
28
|
+
child.stdin.on('error', () => {});
|
|
29
|
+
child.stdin.end(input);
|
|
30
|
+
child.on('close', code => {
|
|
31
|
+
clearTimeout(timer); clearTimeout(escalation); signal?.removeEventListener('abort', abort);
|
|
32
|
+
resolve({ code, reason, stdout, stderr, seconds: (performance.now() - start) / 1000 });
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function agentEnvironment(names = []) {
|
|
38
|
+
const result = {};
|
|
39
|
+
for (const key of ['PATH', 'HOME', 'USERPROFILE', 'SystemRoot', 'TMPDIR', 'TMP', 'TEMP', 'LANG', 'TERM', ...names]) {
|
|
40
|
+
if (process.env[key] !== undefined) result[key] = process.env[key];
|
|
41
|
+
}
|
|
42
|
+
result.OPENMERIT_EVAL = '1';
|
|
43
|
+
return result;
|
|
44
|
+
}
|