dsh-eval 0.1.0-rc.6

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