dsh-eval 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/metrics.js ADDED
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Pure metric folding for dsh-eval: one pass over a session trace produces
3
+ * the automatic metric set, and pricing converts provider token buckets into
4
+ * USD. The fold mirrors session-stats wall-time semantics and adds the
5
+ * eval-owned failure and retry counters.
6
+ *
7
+ * @module dsh-eval/metrics
8
+ */
9
+ import { isTokenDelta } from '@deepseek-ai/dsh-llm/message';
10
+ function initialState() {
11
+ return {
12
+ turns: 0,
13
+ lastTurn: null,
14
+ steps: 0,
15
+ toolCalls: 0,
16
+ toolResults: 0,
17
+ toolSuccess: 0,
18
+ invalidToolCalls: 0,
19
+ retries: 0,
20
+ tokens: { inputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, outputTokens: 0 },
21
+ llmMs: 0,
22
+ toolMs: 0,
23
+ ttftMs: 0,
24
+ openStep: null,
25
+ pendingCalls: new Map(),
26
+ firstTime: null,
27
+ lastTime: null,
28
+ };
29
+ }
30
+ /** Add one message's provider usage to the totals, defaulting absent cache buckets. */
31
+ function addUsage(totals, usage) {
32
+ totals.inputTokens += usage.inputTokens;
33
+ totals.outputTokens += usage.outputTokens;
34
+ totals.cacheReadTokens += usage.cacheReadTokens ?? 0;
35
+ totals.cacheWriteTokens += usage.cacheWriteTokens ?? 0;
36
+ }
37
+ /**
38
+ * Fold a session trace into automatic metrics without pricing.
39
+ * @param events - the trace's durable events in log order.
40
+ * @returns the folded metrics with `costUsd: null`.
41
+ */
42
+ export function foldMetrics(events) {
43
+ const state = initialState();
44
+ for (const event of events) {
45
+ switch (event.type) {
46
+ case 'step/start':
47
+ state.openStep = {
48
+ turn: event.data.turn,
49
+ step: event.data.step,
50
+ start: event.time,
51
+ firstToken: null,
52
+ };
53
+ break;
54
+ case 'assistant/chunk': {
55
+ const open = state.openStep;
56
+ if (open === null || open.turn !== event.data.turn || open.step !== event.data.step
57
+ || open.firstToken !== null || !isTokenDelta(event.data.chunk))
58
+ break;
59
+ state.openStep = { ...open, firstToken: event.time };
60
+ break;
61
+ }
62
+ case 'assistant/message': {
63
+ const open = state.openStep;
64
+ if (open === null || open.turn !== event.data.turn || open.step !== event.data.step)
65
+ break;
66
+ state.llmMs += Math.max(0, event.time - open.start);
67
+ if (open.firstToken !== null)
68
+ state.ttftMs += Math.max(0, open.firstToken - open.start);
69
+ if (event.data.usage !== undefined)
70
+ addUsage(state.tokens, event.data.usage);
71
+ state.openStep = null;
72
+ break;
73
+ }
74
+ case 'tool/call':
75
+ state.toolCalls += 1;
76
+ state.pendingCalls.set(String(event.data.callId), event.time);
77
+ break;
78
+ case 'tool/result': {
79
+ state.toolResults += 1;
80
+ if (event.data.message.content.at(0)?.isError !== true)
81
+ state.toolSuccess += 1;
82
+ if (event.data.error !== undefined)
83
+ state.invalidToolCalls += 1;
84
+ const dispatched = state.pendingCalls.get(String(event.data.message.source.callId));
85
+ if (dispatched !== undefined) {
86
+ state.toolMs += Math.max(0, event.time - dispatched);
87
+ state.pendingCalls.delete(String(event.data.message.source.callId));
88
+ }
89
+ break;
90
+ }
91
+ case 'step/end':
92
+ state.steps += 1;
93
+ if (state.lastTurn !== event.data.turn) {
94
+ state.turns += 1;
95
+ state.lastTurn = event.data.turn;
96
+ }
97
+ state.openStep = null;
98
+ break;
99
+ case 'turn/end':
100
+ state.pendingCalls.clear();
101
+ break;
102
+ case 'llm/retry':
103
+ state.retries += 1;
104
+ break;
105
+ default:
106
+ break;
107
+ }
108
+ state.firstTime = state.firstTime === null ? event.time : Math.min(state.firstTime, event.time);
109
+ state.lastTime = state.lastTime === null ? event.time : Math.max(state.lastTime, event.time);
110
+ }
111
+ const tokens = { ...state.tokens };
112
+ return {
113
+ turns: state.turns,
114
+ steps: state.steps,
115
+ toolCalls: state.toolCalls,
116
+ toolResults: state.toolResults,
117
+ toolSuccess: state.toolSuccess,
118
+ toolSuccessRate: state.toolResults > 0 ? state.toolSuccess / state.toolResults : null,
119
+ invalidToolCalls: state.invalidToolCalls,
120
+ retries: state.retries,
121
+ tokens,
122
+ totalTokens: tokens.inputTokens + tokens.cacheReadTokens + tokens.cacheWriteTokens + tokens.outputTokens,
123
+ contextTokens: tokens.inputTokens + tokens.cacheReadTokens + tokens.cacheWriteTokens,
124
+ llmMs: state.llmMs,
125
+ toolMs: state.toolMs,
126
+ ttftMs: state.ttftMs,
127
+ latencyMs: state.firstTime !== null && state.lastTime !== null
128
+ ? Math.max(0, state.lastTime - state.firstTime)
129
+ : 0,
130
+ costUsd: null,
131
+ };
132
+ }
133
+ /**
134
+ * Convert token buckets into USD using per-million-token prices.
135
+ * @param tokens - summed token buckets.
136
+ * @param pricing - per-million-token USD prices.
137
+ * @returns the estimated cost in USD.
138
+ */
139
+ export function computeCost(tokens, pricing) {
140
+ return (tokens.inputTokens * pricing.inputUsdPerMTokens
141
+ + tokens.cacheReadTokens * pricing.cacheReadUsdPerMTokens
142
+ + tokens.cacheWriteTokens * pricing.cacheWriteUsdPerMTokens
143
+ + tokens.outputTokens * pricing.outputUsdPerMTokens) / 1_000_000;
144
+ }
145
+ /**
146
+ * Fold metrics and attach cost when a pricing table entry exists.
147
+ * @param events - the trace's durable events in log order.
148
+ * @param pricing - the benchmark model's pricing, or undefined for no cost.
149
+ * @returns the folded metrics.
150
+ */
151
+ export function computeMetrics(events, pricing) {
152
+ const metrics = foldMetrics(events);
153
+ return pricing === undefined ? metrics : { ...metrics, costUsd: computeCost(metrics.tokens, pricing) };
154
+ }
155
+ /**
156
+ * Aggregate per-trial metrics: arithmetic means for counts and wall times,
157
+ * pooled success rate, and the mean cost when every trial priced it.
158
+ * @param items - completed trials' metrics.
159
+ * @returns the aggregate, or null when no trial is included.
160
+ */
161
+ export function aggregateMetrics(items) {
162
+ if (items.length === 0)
163
+ return null;
164
+ const mean = (select) => items.reduce((total, metrics) => total + select(metrics), 0) / items.length;
165
+ const toolResults = items.reduce((total, metrics) => total + metrics.toolResults, 0);
166
+ const toolSuccess = items.reduce((total, metrics) => total + metrics.toolSuccess, 0);
167
+ const costValues = items
168
+ .map(metrics => metrics.costUsd)
169
+ .filter((value) => value !== null);
170
+ const tokens = {
171
+ inputTokens: mean(metrics => metrics.tokens.inputTokens),
172
+ cacheReadTokens: mean(metrics => metrics.tokens.cacheReadTokens),
173
+ cacheWriteTokens: mean(metrics => metrics.tokens.cacheWriteTokens),
174
+ outputTokens: mean(metrics => metrics.tokens.outputTokens),
175
+ };
176
+ return {
177
+ turns: mean(metrics => metrics.turns),
178
+ steps: mean(metrics => metrics.steps),
179
+ toolCalls: mean(metrics => metrics.toolCalls),
180
+ toolResults,
181
+ toolSuccess,
182
+ toolSuccessRate: toolResults > 0 ? toolSuccess / toolResults : null,
183
+ invalidToolCalls: mean(metrics => metrics.invalidToolCalls),
184
+ retries: mean(metrics => metrics.retries),
185
+ tokens,
186
+ totalTokens: mean(metrics => metrics.totalTokens),
187
+ contextTokens: mean(metrics => metrics.contextTokens),
188
+ llmMs: mean(metrics => metrics.llmMs),
189
+ toolMs: mean(metrics => metrics.toolMs),
190
+ ttftMs: mean(metrics => metrics.ttftMs),
191
+ latencyMs: mean(metrics => metrics.latencyMs),
192
+ costUsd: costValues.length === items.length
193
+ ? costValues.reduce((total, value) => total + value, 0) / items.length
194
+ : null,
195
+ };
196
+ }
package/lib/report.js ADDED
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Run-report persistence and markdown rendering for dsh-eval.
3
+ *
4
+ * @module dsh-eval/report
5
+ */
6
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
7
+ import { dirname, resolve } from 'node:path';
8
+ /**
9
+ * Write a run report as indented JSON with a trailing newline.
10
+ * @param run - the run record to persist.
11
+ * @param path - output path; parent directories are created.
12
+ */
13
+ export async function writeRunReport(run, path) {
14
+ const absolute = resolve(path);
15
+ await mkdir(dirname(absolute), { recursive: true });
16
+ await writeFile(absolute, `${JSON.stringify(run, null, 2)}\n`, 'utf8');
17
+ }
18
+ /**
19
+ * Load a persisted run report, rejecting anything without the required surface.
20
+ * @param path - path to the run JSON.
21
+ * @returns the loaded run record.
22
+ */
23
+ export async function loadRunReport(path) {
24
+ const value = JSON.parse(await readFile(resolve(path), 'utf8'));
25
+ if (typeof value !== 'object' || value === null
26
+ || !Array.isArray(value.cases)) {
27
+ throw new Error(`${path} is not a dsh-eval run report`);
28
+ }
29
+ return value;
30
+ }
31
+ /** Render a nullable percentage with a dash placeholder. */
32
+ function formatRate(value) {
33
+ return value === null ? '–' : `${(value * 100).toFixed(1)}%`;
34
+ }
35
+ /** Render a nullable USD cost with a dash placeholder. */
36
+ function formatUsd(value) {
37
+ return value === null ? '–' : `$${value.toFixed(6)}`;
38
+ }
39
+ /** Render a nullable grading boolean with a dash placeholder. */
40
+ function formatGrade(value) {
41
+ return value === null ? '–' : value ? 'yes' : 'no';
42
+ }
43
+ /** Render a nullable score as `value/max` with a dash placeholder. */
44
+ function formatScore(value, maxScore) {
45
+ return value === null ? '–' : `${value.toFixed(1)}/${maxScore}`;
46
+ }
47
+ /**
48
+ * Render a run report as a markdown table: one row per trial plus the
49
+ * aggregate row.
50
+ * @param run - the run record to render.
51
+ * @returns the markdown text.
52
+ */
53
+ export function renderMarkdownReport(run) {
54
+ const judge = run.judge;
55
+ const judged = judge !== undefined;
56
+ const header = judged
57
+ ? [
58
+ '| case | trial | status | steps | tools | success | invalid | retries | tokens | cost | latency ms | task | tool-acc | score | halluc |',
59
+ '|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|',
60
+ ]
61
+ : [
62
+ '| case | trial | status | steps | tools | success | invalid | retries | tokens | cost | latency ms | task | tool-acc |',
63
+ '|---|---|---|---|---|---|---|---|---|---|---|---|---|',
64
+ ];
65
+ const rows = run.cases.map((result) => {
66
+ const metrics = result.metrics;
67
+ const base = metrics === undefined
68
+ ? ['–', '–', '–', '–', '–', '–', '–', '–', '–', '–']
69
+ : [
70
+ String(metrics.steps),
71
+ String(metrics.toolCalls),
72
+ formatRate(metrics.toolSuccessRate),
73
+ String(metrics.invalidToolCalls),
74
+ String(metrics.retries),
75
+ String(metrics.totalTokens),
76
+ formatUsd(metrics.costUsd),
77
+ String(metrics.latencyMs),
78
+ formatGrade(result.grade?.taskSuccess ?? null),
79
+ formatGrade(result.grade?.toolSelectionAccuracy ?? null),
80
+ ];
81
+ const judgeCells = judged
82
+ ? [
83
+ formatScore(result.judge?.finalAnswerScore ?? null, judge.maxScore),
84
+ formatGrade(result.judge?.hallucination ?? null),
85
+ ]
86
+ : [];
87
+ return `| ${result.caseId} | ${result.trial} | ${result.status} | ${[...base, ...judgeCells].join(' | ')} |`;
88
+ });
89
+ const aggregate = run.aggregate;
90
+ const aggregateJudgeCells = judged
91
+ ? [
92
+ formatScore(run.grading?.finalAnswerScore ?? null, judge.maxScore),
93
+ formatRate(run.grading?.hallucinationRate ?? null),
94
+ ]
95
+ : [];
96
+ const aggregateCells = aggregate === null
97
+ ? ['no completed trials', '–', '–', '–', '–', '–', '–', '–', '–', '–', '–']
98
+ : [
99
+ 'completed',
100
+ aggregate.steps.toFixed(1),
101
+ aggregate.toolCalls.toFixed(1),
102
+ formatRate(aggregate.toolSuccessRate),
103
+ aggregate.invalidToolCalls.toFixed(1),
104
+ aggregate.retries.toFixed(1),
105
+ aggregate.totalTokens.toFixed(1),
106
+ formatUsd(aggregate.costUsd),
107
+ aggregate.latencyMs.toFixed(1),
108
+ formatRate(run.grading?.taskSuccessRate ?? null),
109
+ formatRate(run.grading?.toolSelectionAccuracyRate ?? null),
110
+ ];
111
+ const aggregateRow = `| aggregate | – | ${[...aggregateCells, ...aggregateJudgeCells].join(' | ')} |`;
112
+ return [
113
+ `# Eval: ${run.benchmark}`,
114
+ '',
115
+ `- model: ${run.model}`,
116
+ ...(judged ? [`- judge: ${judge.model}`] : []),
117
+ `- trials per case: ${run.trials}`,
118
+ `- created: ${new Date(run.createdAt).toISOString()}`,
119
+ `- traces: ${run.tempRoot}`,
120
+ '',
121
+ ...header,
122
+ ...rows,
123
+ aggregateRow,
124
+ '',
125
+ ].join('\n');
126
+ }
package/lib/runner.js ADDED
@@ -0,0 +1,326 @@
1
+ /**
2
+ * Benchmark runner for dsh-eval: one fresh subprocess per case x trial.
3
+ *
4
+ * Each trial owns a private temp directory with a copied workspace, an
5
+ * isolated DSH_HOME, and a patch overlay that forces plain-JSONL persistence
6
+ * and non-interactive workspace-scoped permissions. The spawned command is
7
+ * the same trusted dsh harness (credentials flow through deliberately: the
8
+ * child must reach the real model API, and the session log never stores
9
+ * them), so the defensive scrubbed-env rule's leak concern does not apply to
10
+ * this child. Timeout kills the direct child and reports timed-out orthogonally
11
+ * from its exit code; Windows descendants of a killed process may survive.
12
+ *
13
+ * @module dsh-eval/runner
14
+ */
15
+ import { spawn } from 'node:child_process';
16
+ import { cp, mkdir, mkdtemp, writeFile } from 'node:fs/promises';
17
+ import { tmpdir } from 'node:os';
18
+ import { join } from 'node:path';
19
+ import { tryJudgeTrial } from "./judge.js";
20
+ import { aggregateMetrics, computeMetrics } from "./metrics.js";
21
+ import { findSessionLogs, loadTrace, mergeTraces } from "./trace.js";
22
+ /** Cap per-stream child output so a runaway trial cannot exhaust memory. */
23
+ const MAX_OUTPUT_BYTES = 512 * 1024;
24
+ /** The child's trailing diagnostic for failed harvests. */
25
+ function diagnostic(outcome) {
26
+ const tail = outcome.stderr.slice(-2000);
27
+ const status = outcome.timedOut ? 'timed out' : `exited with code ${String(outcome.exitCode)}`;
28
+ return tail === '' ? `no session log found; dsh ${status}` : `no session log found; dsh ${status}: ${tail}`;
29
+ }
30
+ /** Human-readable error text. */
31
+ function message(error) {
32
+ /* v8 ignore next 3 -- every call site passes a node:fs or spawn Error; a non-Error rejection is impossible through the public API. */
33
+ return error instanceof Error ? error.message : String(error);
34
+ }
35
+ /** Reduce a case id to one safe temp-directory segment. */
36
+ function sanitizeSegment(value) {
37
+ const safe = value.replace(/[^A-Za-z0-9._-]/gu, '-').replace(/^-+|-+$/gu, '');
38
+ return safe === '' ? 'case' : safe;
39
+ }
40
+ /**
41
+ * Build the per-trial overlay: plain-JSONL persistence, non-interactive
42
+ * permissions, and the keyless replay plugin when recorded logs exist.
43
+ * @param replay - the replay primary log and child logs, or undefined.
44
+ * @returns the overlay YAML text.
45
+ */
46
+ function evalOverlay(replay) {
47
+ const lines = [
48
+ '- id: session-persistence-jsonl',
49
+ ' config:',
50
+ " root: !!js dshHomePath('sessions')",
51
+ ' packChunks: false',
52
+ ' compression: none',
53
+ '- id: sandbox-policy',
54
+ ' config:',
55
+ ' mode: workspace-write',
56
+ ' workspaceRoot: !!js process.cwd()',
57
+ '- id: approval',
58
+ ' config:',
59
+ ' policy: never',
60
+ ];
61
+ if (replay !== undefined) {
62
+ lines.push('- id: llm-replay', " name: '@deepseek-ai/dsh-llm-replay'", ' config:', ` file: ${JSON.stringify(replay.file)}`, ...(replay.childFiles.length === 0 ? [] : [` childFiles: ${JSON.stringify(replay.childFiles)}`]));
63
+ }
64
+ return `${lines.join('\n')}\n`;
65
+ }
66
+ /** Split a single command string into argv on whitespace. */
67
+ function splitWords(value) {
68
+ return value.trim().split(/\s+/u).filter(part => part !== '');
69
+ }
70
+ /**
71
+ * Grade one trial against its expectations: the expected tool is matched
72
+ * against recorded tool-call names, and the check command runs in the trial
73
+ * workspace with the same timeout as the agent. A spawn failure or timeout
74
+ * reads as task failure, never as an aborted run.
75
+ * @param caseValue - the case being graded.
76
+ * @param trace - the harvested trace.
77
+ * @param workspace - the trial's workspace, where the check runs.
78
+ * @param timeoutMs - check timeout, matching the trial timeout.
79
+ * @returns the grading outcome; unconfigured fields stay null.
80
+ */
81
+ async function gradeTrial(caseValue, trace, workspace, timeoutMs) {
82
+ const expected = caseValue.expected;
83
+ if (expected === undefined)
84
+ return { taskSuccess: null, toolSelectionAccuracy: null };
85
+ const expectedTool = expected.tool;
86
+ const toolSelectionAccuracy = expectedTool === undefined
87
+ ? null
88
+ : trace.events.some(event => event.type === 'tool/call' && event.data.name.includes(expectedTool));
89
+ let taskSuccess = null;
90
+ if (expected.check !== undefined) {
91
+ try {
92
+ const outcome = await runCommand(splitWords(expected.check), [], workspace, { ...process.env }, timeoutMs);
93
+ taskSuccess = !outcome.timedOut && outcome.exitCode === 0;
94
+ }
95
+ catch {
96
+ taskSuccess = false;
97
+ }
98
+ }
99
+ return { taskSuccess, toolSelectionAccuracy };
100
+ }
101
+ /** Pool one nullable boolean across graded trials into a rate, or null. */
102
+ function pooledRate(items, select) {
103
+ const values = items
104
+ .map(result => select(result.grade))
105
+ .filter((value) => value !== null);
106
+ return values.length === 0 ? null : values.filter(value => value).length / values.length;
107
+ }
108
+ /** Reduce completed trials' grades into pooled run-level rates. */
109
+ function gradingOf(results) {
110
+ const taskSuccessRate = pooledRate(results, grade => grade?.taskSuccess ?? null);
111
+ const toolSelectionAccuracyRate = pooledRate(results, grade => grade?.toolSelectionAccuracy ?? null);
112
+ const finalScores = results
113
+ .map(result => result.judge?.finalAnswerScore ?? null)
114
+ .filter((value) => value !== null);
115
+ const finalAnswerScore = finalScores.length === 0
116
+ ? null
117
+ : finalScores.reduce((total, value) => total + value, 0) / finalScores.length;
118
+ const hallucinated = results
119
+ .map(result => result.judge?.hallucination ?? null)
120
+ .filter((value) => value !== null);
121
+ const hallucinationRate = hallucinated.length === 0
122
+ ? null
123
+ : hallucinated.filter(value => value).length / hallucinated.length;
124
+ return taskSuccessRate === null && toolSelectionAccuracyRate === null
125
+ && finalAnswerScore === null && hallucinationRate === null
126
+ ? null
127
+ : { taskSuccessRate, toolSelectionAccuracyRate, finalAnswerScore, hallucinationRate };
128
+ }
129
+ /**
130
+ * Spawn one command and collect its output, enforcing the timeout with a
131
+ * direct kill. The four outcome facts (exit code, timeout, stdout, stderr)
132
+ * are reported independently so a trapped or killed child cannot read as a
133
+ * clean success.
134
+ * @param command - the executable and its fixed argv.
135
+ * @param args - invocation args appended after `command`.
136
+ * @param cwd - the child's working directory.
137
+ * @param env - the child's environment.
138
+ * @param timeoutMs - kill the child after this many milliseconds.
139
+ * @returns the orthogonal outcome facts.
140
+ */
141
+ function runCommand(command, args, cwd, env, timeoutMs) {
142
+ const executable = command[0];
143
+ if (executable === undefined) {
144
+ return Promise.reject(new Error('eval: dsh command must not be empty'));
145
+ }
146
+ return new Promise((resolveOutcome, reject) => {
147
+ const child = spawn(executable, [...command.slice(1), ...args], {
148
+ cwd,
149
+ env,
150
+ stdio: ['ignore', 'pipe', 'pipe'],
151
+ windowsHide: true,
152
+ });
153
+ let stdout = '';
154
+ let stderr = '';
155
+ let timedOut = false;
156
+ let settled = false;
157
+ const cap = (current, chunk) => (current.length >= MAX_OUTPUT_BYTES
158
+ ? current
159
+ : current + chunk.toString('utf8').slice(0, MAX_OUTPUT_BYTES - current.length));
160
+ child.stdout.on('data', (chunk) => { stdout = cap(stdout, chunk); });
161
+ child.stderr.on('data', (chunk) => { stderr = cap(stderr, chunk); });
162
+ const timer = setTimeout(() => {
163
+ /* v8 ignore next 3 -- close clears the timer; only a same-tick close/kill race reaches here. */
164
+ if (settled)
165
+ return;
166
+ timedOut = true;
167
+ child.kill();
168
+ }, timeoutMs);
169
+ child.on('error', (error) => {
170
+ clearTimeout(timer);
171
+ /* v8 ignore next 3 -- spawn emits one error before close; the guard covers only an impossible duplicate error event. */
172
+ if (settled)
173
+ return;
174
+ settled = true;
175
+ reject(error);
176
+ });
177
+ child.on('close', (code) => {
178
+ clearTimeout(timer);
179
+ if (settled)
180
+ return;
181
+ settled = true;
182
+ resolveOutcome({ exitCode: code, timedOut, stdout, stderr });
183
+ });
184
+ });
185
+ }
186
+ /**
187
+ * Run one case x trial in its private temp directory and harvest its trace.
188
+ * @param benchmark - the loaded benchmark.
189
+ * @param caseValue - the case to run.
190
+ * @param trial - 1-based trial index.
191
+ * @param root - this run's temp root.
192
+ * @returns the trial result; a failed subprocess with no log is an `error` trial.
193
+ */
194
+ async function runCaseTrial(benchmark, caseValue, trial, root, judgeChat) {
195
+ const trialDir = join(root, `${sanitizeSegment(caseValue.id)}-${trial}`);
196
+ const workspace = join(trialDir, 'workspace');
197
+ const dshHome = join(trialDir, 'dsh-home');
198
+ await mkdir(workspace, { recursive: true });
199
+ await mkdir(dshHome, { recursive: true, mode: 0o700 });
200
+ if (caseValue.workspace !== undefined)
201
+ await cp(caseValue.workspace, workspace, { recursive: true });
202
+ const replayFixture = benchmark.replay === undefined
203
+ ? undefined
204
+ : join(benchmark.replay.dir, `${sanitizeSegment(caseValue.id)}-${trial}`);
205
+ let replay;
206
+ if (replayFixture !== undefined) {
207
+ const logs = await findSessionLogs(replayFixture);
208
+ if (logs.length === 0) {
209
+ return {
210
+ caseId: caseValue.id,
211
+ trial,
212
+ status: 'error',
213
+ error: `no replay fixture found at ${replayFixture}`,
214
+ exitCode: null,
215
+ timedOut: false,
216
+ };
217
+ }
218
+ const primary = logs[0];
219
+ replay = { file: primary, childFiles: logs.slice(1) };
220
+ }
221
+ const overlayPath = join(trialDir, 'eval.cordis.yml');
222
+ await writeFile(overlayPath, evalOverlay(replay), 'utf8');
223
+ let outcome;
224
+ try {
225
+ outcome = await runCommand(benchmark.command, ['--profile', benchmark.profile, '--patch', overlayPath, caseValue.prompt], workspace, { ...process.env, DSH_HOME: dshHome }, benchmark.timeoutMs);
226
+ }
227
+ catch (error) {
228
+ return {
229
+ caseId: caseValue.id,
230
+ trial,
231
+ status: 'error',
232
+ error: `failed to spawn dsh: ${message(error)}`,
233
+ exitCode: null,
234
+ timedOut: false,
235
+ };
236
+ }
237
+ const tracePaths = await findSessionLogs(dshHome);
238
+ if (tracePaths.length === 0) {
239
+ return {
240
+ caseId: caseValue.id,
241
+ trial,
242
+ status: 'error',
243
+ error: diagnostic(outcome),
244
+ exitCode: outcome.exitCode,
245
+ timedOut: outcome.timedOut,
246
+ };
247
+ }
248
+ try {
249
+ const loaded = [];
250
+ for (const path of tracePaths)
251
+ loaded.push({ path, trace: await loadTrace(path) });
252
+ loaded.sort((a, b) => a.trace.createdAt - b.trace.createdAt);
253
+ // tracePaths.length > 0 above guarantees a non-empty loaded list.
254
+ const primaryPath = loaded[0].path;
255
+ const trace = mergeTraces(loaded.map(entry => entry.trace));
256
+ const pricing = benchmark.pricing?.[benchmark.model];
257
+ const metrics = computeMetrics(trace.events, pricing);
258
+ const grade = await gradeTrial(caseValue, trace, workspace, benchmark.timeoutMs);
259
+ const judge = benchmark.judge === undefined || judgeChat === undefined
260
+ ? undefined
261
+ : await tryJudgeTrial(caseValue, trace, benchmark.judge, judgeChat);
262
+ return {
263
+ caseId: caseValue.id,
264
+ trial,
265
+ status: 'completed',
266
+ tracePath: primaryPath,
267
+ tracePaths: loaded.map(entry => entry.path),
268
+ exitCode: outcome.exitCode,
269
+ timedOut: outcome.timedOut,
270
+ metrics,
271
+ ...(grade.taskSuccess !== null || grade.toolSelectionAccuracy !== null ? { grade } : {}),
272
+ ...(judge !== undefined ? { judge } : {}),
273
+ };
274
+ }
275
+ catch (error) {
276
+ return {
277
+ caseId: caseValue.id,
278
+ trial,
279
+ status: 'error',
280
+ error: `failed to read trace: ${message(error)}`,
281
+ exitCode: outcome.exitCode,
282
+ timedOut: outcome.timedOut,
283
+ };
284
+ }
285
+ }
286
+ /**
287
+ * Run every case x trial sequentially and aggregate the completed trials.
288
+ * @param benchmark - the loaded benchmark.
289
+ * @param options - runtime overrides and test seams.
290
+ * @returns the completed run record, written by the caller.
291
+ */
292
+ export async function runBenchmark(benchmark, options = {}) {
293
+ if (benchmark.judge !== undefined && options.judgeChat === undefined) {
294
+ throw new Error('eval: benchmark configures a judge but no LLM chat seam is available');
295
+ }
296
+ if (benchmark.judge !== undefined && benchmark.replay !== undefined) {
297
+ throw new Error('eval: judge and replay cannot be combined in one run');
298
+ }
299
+ const root = await mkdtemp(join(options.tempRoot ?? tmpdir(), 'dsh-eval-'));
300
+ const trials = options.trials ?? benchmark.trials;
301
+ const effective = {
302
+ ...benchmark,
303
+ ...(options.profile !== undefined ? { profile: options.profile } : {}),
304
+ ...(options.command !== undefined ? { command: options.command } : {}),
305
+ };
306
+ const results = [];
307
+ for (const caseValue of effective.cases) {
308
+ for (let trial = 1; trial <= trials; trial++) {
309
+ results.push(await runCaseTrial(effective, caseValue, trial, root, options.judgeChat));
310
+ }
311
+ }
312
+ const completed = results.filter((result) => result.status === 'completed' && result.metrics !== undefined);
313
+ return {
314
+ benchmark: benchmark.name,
315
+ model: benchmark.model,
316
+ createdAt: Date.now(),
317
+ trials,
318
+ seed: benchmark.seed,
319
+ pricing: benchmark.pricing?.[benchmark.model] ?? null,
320
+ ...(benchmark.judge !== undefined ? { judge: benchmark.judge } : {}),
321
+ tempRoot: root,
322
+ cases: results,
323
+ aggregate: aggregateMetrics(completed.map(result => result.metrics)),
324
+ grading: gradingOf(completed),
325
+ };
326
+ }