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,177 @@
1
+ /**
2
+ * Pure types of the dsh-eval domain: benchmark configuration, harvested
3
+ * traces, per-trial metrics, and the persisted run record. This file contains
4
+ * no runtime code.
5
+ *
6
+ * @module dsh-eval/types
7
+ */
8
+ import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session';
9
+ /** One model arm's per-million-token pricing, in USD. */
10
+ export interface BenchmarkPricing {
11
+ /** Billed uncached input tokens. */
12
+ inputUsdPerMTokens: number;
13
+ /** Billed cache-read input tokens. */
14
+ cacheReadUsdPerMTokens: number;
15
+ /** Billed cache-write input tokens. */
16
+ cacheWriteUsdPerMTokens: number;
17
+ /** Billed output tokens. */
18
+ outputUsdPerMTokens: number;
19
+ }
20
+ /** One benchmark task: a prompt and an optional workspace copied per trial. */
21
+ export interface BenchmarkCase {
22
+ /** Stable case id, used in run output and trial directory names. */
23
+ id: string;
24
+ /** The task text handed to the headless agent. */
25
+ prompt: string;
26
+ /** Absolute path to a workspace tree copied into each trial, when provided. */
27
+ workspace?: string;
28
+ /** Scripted grading annotations, when the case is graded. */
29
+ expected?: BenchmarkExpectation;
30
+ }
31
+ /** Expected-tool and check-command annotations for scripted grading. */
32
+ export interface BenchmarkExpectation {
33
+ /** Substring matched against every recorded tool call name. */
34
+ tool?: string;
35
+ /** Command run in the trial workspace after the agent exits; exit 0 means task success. */
36
+ check?: string;
37
+ }
38
+ /** A validated benchmark document. */
39
+ export interface Benchmark {
40
+ /** Benchmark name; also the run record's `benchmark` field. */
41
+ name: string;
42
+ /** Model id used for pricing lookup and reported per run. */
43
+ model: string;
44
+ /** dsh profile spawned per trial; defaults to `headless`. */
45
+ profile: string;
46
+ /** Command that launches dsh, as argv. */
47
+ command: readonly string[];
48
+ /** Trials per case. */
49
+ trials: number;
50
+ /** Per-trial timeout in milliseconds. */
51
+ timeoutMs: number;
52
+ /** Reserved deterministic seed for future paired comparisons. */
53
+ seed: number;
54
+ /** The benchmark's cases, in order. */
55
+ cases: readonly BenchmarkCase[];
56
+ /** Pricing keyed by model id; an absent model reports `costUsd: null`. */
57
+ pricing?: Readonly<Record<string, BenchmarkPricing>>;
58
+ /** Directory the benchmark document was loaded from; relative paths resolve against it. */
59
+ baseDir: string;
60
+ }
61
+ /**
62
+ * One harvested session log. v0.1 carries the durable dsh session event
63
+ * vocabulary directly; neutral importers for other harness formats are
64
+ * deferred to the comparison milestone.
65
+ */
66
+ export interface EvalTrace {
67
+ /** Session id from the persisted log header. */
68
+ sessionId: SessionId;
69
+ /** Session creation time from the persisted log header, epoch milliseconds. */
70
+ createdAt: number;
71
+ /** Durable events in log order. */
72
+ events: readonly SessionEvent[];
73
+ }
74
+ /** Disjoint provider-reported token buckets over one run. */
75
+ export interface EvalTokenUsage {
76
+ /** Uncached input tokens. */
77
+ inputTokens: number;
78
+ /** Cache-read input tokens. */
79
+ cacheReadTokens: number;
80
+ /** Cache-write input tokens. */
81
+ cacheWriteTokens: number;
82
+ /** Output tokens. */
83
+ outputTokens: number;
84
+ }
85
+ /** Automatic metrics folded from one session trace. */
86
+ export interface EvalCaseMetrics {
87
+ /** Distinct turns carrying at least one closed step. */
88
+ turns: number;
89
+ /** Closed `step/end` events, completed and failed alike. */
90
+ steps: number;
91
+ /** Recorded `tool/call` events. */
92
+ toolCalls: number;
93
+ /** Recorded `tool/result` events. */
94
+ toolResults: number;
95
+ /** Results whose model-facing `isError` flag is false. */
96
+ toolSuccess: number;
97
+ /** `toolSuccess / toolResults`, or null when no result landed. */
98
+ toolSuccessRate: number | null;
99
+ /** Results carrying an internal failure identity (`tool/result.error`). */
100
+ invalidToolCalls: number;
101
+ /** Durable `llm/retry` decisions. */
102
+ retries: number;
103
+ /** Summed provider usage buckets. */
104
+ tokens: EvalTokenUsage;
105
+ /** Sum of all four token buckets. */
106
+ totalTokens: number;
107
+ /** Billed input (`input + cacheRead + cacheWrite`). */
108
+ contextTokens: number;
109
+ /** Summed model wall time, `step/start` to `assistant/message`, milliseconds. */
110
+ llmMs: number;
111
+ /** Summed tool wall time over matched `tool/call` to `tool/result`, milliseconds. */
112
+ toolMs: number;
113
+ /** Summed first-token latency, `step/start` to the first token delta, milliseconds. */
114
+ ttftMs: number;
115
+ /** Wall time from the first to the last recorded event, milliseconds. */
116
+ latencyMs: number;
117
+ /** Estimated USD cost from the benchmark pricing table, or null without one. */
118
+ costUsd: number | null;
119
+ }
120
+ /** Outcome of one case x trial. */
121
+ export interface EvalTrialResult {
122
+ /** Benchmark case id. */
123
+ caseId: string;
124
+ /** 1-based trial index. */
125
+ trial: number;
126
+ /** `completed` when a persisted trace was harvested; `error` otherwise. */
127
+ status: 'completed' | 'error';
128
+ /** Human-readable failure detail for `error` trials. */
129
+ error?: string;
130
+ /** Absolute path of the harvested primary session log. */
131
+ tracePath?: string;
132
+ /** The child process's exit code, or null when it was killed. */
133
+ exitCode: number | null;
134
+ /** Whether the trial hit its timeout and killed the child. */
135
+ timedOut: boolean;
136
+ /** Folded metrics for `completed` trials. */
137
+ metrics?: EvalCaseMetrics;
138
+ /** Scripted grading outcome for `completed` trials with expectations. */
139
+ grade?: EvalGrade;
140
+ }
141
+ /** Scripted grading outcome for one trial. */
142
+ export interface EvalGrade {
143
+ /** Whether the check command exited 0, or null when no check is configured. */
144
+ taskSuccess: boolean | null;
145
+ /** Whether an expected tool was called, or null when no tool is configured. */
146
+ toolSelectionAccuracy: boolean | null;
147
+ }
148
+ /** Pooled grading rates over completed trials. */
149
+ export interface EvalRunGrading {
150
+ /** Pooled task-success rate, or null when no trial carried a check. */
151
+ taskSuccessRate: number | null;
152
+ /** Pooled tool-selection-accuracy rate, or null when no trial carried an expected tool. */
153
+ toolSelectionAccuracyRate: number | null;
154
+ }
155
+ /** A persisted eval run. */
156
+ export interface EvalRun {
157
+ /** Benchmark name. */
158
+ benchmark: string;
159
+ /** Model id the benchmark targeted. */
160
+ model: string;
161
+ /** Run creation time, epoch milliseconds. */
162
+ createdAt: number;
163
+ /** Trials per case actually executed. */
164
+ trials: number;
165
+ /** Benchmark seed. */
166
+ seed: number;
167
+ /** Resolved pricing for the benchmark model, or null without one. */
168
+ pricing: BenchmarkPricing | null;
169
+ /** Root holding every trial's workspace, overlay, and harvested trace. */
170
+ tempRoot: string;
171
+ /** Per-trial outcomes in execution order. */
172
+ cases: readonly EvalTrialResult[];
173
+ /** Mean/pooled metrics over completed trials, or null when none completed. */
174
+ aggregate: EvalCaseMetrics | null;
175
+ /** Pooled scripted-grading rates over completed trials, or null when ungraded. */
176
+ grading: EvalRunGrading | null;
177
+ }
package/package.json ADDED
@@ -0,0 +1,88 @@
1
+ {
2
+ "name": "dsh-eval",
3
+ "description": "Agent evaluation platform: benchmark YAML, headless run orchestration, trace-based metrics, and run reports",
4
+ "version": "0.1.0-rc.6",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/hccccc01333/dsh-eval.git"
11
+ },
12
+ "type": "module",
13
+ "main": "lib/index.js",
14
+ "types": "lib/types/index.d.ts",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./lib/types/index.d.ts",
18
+ "default": "./lib/index.js"
19
+ },
20
+ "./invariant": {
21
+ "types": "./lib/types/invariant.d.ts",
22
+ "default": "./lib/invariant.js"
23
+ },
24
+ "./types": {
25
+ "types": "./lib/types/types.d.ts",
26
+ "default": "./lib/types/types.js"
27
+ },
28
+ "./cordis.patch.yml": "./cordis.patch.yml",
29
+ "./src/*": "./src/*",
30
+ "./package.json": "./package.json"
31
+ },
32
+ "files": [
33
+ "lib/index.js",
34
+ "lib/invariant.js",
35
+ "cordis.patch.yml",
36
+ "lib/types/**/*.js",
37
+ "lib/types/**/*.d.ts",
38
+ "src/**/*.ts"
39
+ ],
40
+ "license": "MIT",
41
+ "keywords": [
42
+ "deepseek-harness",
43
+ "dsh",
44
+ "dsh-plugin",
45
+ "agent-evaluation",
46
+ "benchmark",
47
+ "eval"
48
+ ],
49
+ "dsh": {
50
+ "bundle": {
51
+ "patch": "./cordis.patch.yml"
52
+ }
53
+ },
54
+ "dependencies": {
55
+ "commander": "^15.0.0",
56
+ "js-yaml": "^4.2.0",
57
+ "zod": "^4.4.3"
58
+ },
59
+ "peerDependencies": {
60
+ "@deepseek-ai/cordis": "^4.0.1",
61
+ "@deepseek-ai/dsh-cmdline": "^0.1.0-rc.6",
62
+ "@deepseek-ai/dsh-invariants": "^0.1.0-rc.6",
63
+ "@deepseek-ai/dsh-llm": "^0.1.0-rc.6",
64
+ "@deepseek-ai/dsh-llm-retry": "^0.1.0-rc.6",
65
+ "@deepseek-ai/dsh-session": "^0.1.0-rc.6"
66
+ },
67
+ "devDependencies": {
68
+ "@types/js-yaml": "^4.0.9",
69
+ "@types/node": "^22.20.0",
70
+ "@vitest/coverage-v8": "4.1.10",
71
+ "typescript": "^6.0.3",
72
+ "vitest": "^4.1.8",
73
+ "@deepseek-ai/cordis": "^4.0.1",
74
+ "@deepseek-ai/cordis-plugin-include": "^1.0.6",
75
+ "@deepseek-ai/cordis-plugin-loader": "^1.0.2",
76
+ "@deepseek-ai/dsh-cmdline": "^0.1.0-rc.5",
77
+ "@deepseek-ai/dsh-invariants": "^0.1.0-rc.5",
78
+ "@deepseek-ai/dsh-llm": "^0.1.0-rc.5",
79
+ "@deepseek-ai/dsh-llm-retry": "^0.1.0-rc.5",
80
+ "@deepseek-ai/dsh-session": "^0.1.0-rc.5"
81
+ },
82
+ "scripts": {
83
+ "build": "tsc -p tsconfig.build.json",
84
+ "test": "vitest run",
85
+ "test:coverage": "vitest run --coverage",
86
+ "typecheck": "tsc --noEmit"
87
+ }
88
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Benchmark document loading and validation for dsh-eval. YAML parses with
3
+ * js-yaml's safe loader; zod validates the parsed shape; prompt files and
4
+ * workspaces resolve against the benchmark file's directory.
5
+ *
6
+ * @module dsh-eval/benchmark
7
+ */
8
+
9
+ import { readFile } from 'node:fs/promises'
10
+ import { dirname, isAbsolute, resolve } from 'node:path'
11
+ import { load } from 'js-yaml'
12
+ import { z } from 'zod'
13
+ import type { Benchmark, BenchmarkCase } from './types.ts'
14
+
15
+ const pricingSchema = z.object({
16
+ inputUsdPerMTokens: z.number().nonnegative(),
17
+ cacheReadUsdPerMTokens: z.number().nonnegative(),
18
+ cacheWriteUsdPerMTokens: z.number().nonnegative(),
19
+ outputUsdPerMTokens: z.number().nonnegative(),
20
+ }).strict()
21
+
22
+ const benchmarkCaseSchema = z.object({
23
+ id: z.string().min(1),
24
+ prompt: z.string().min(1).optional(),
25
+ promptFile: z.string().min(1).optional(),
26
+ workspace: z.string().min(1).optional(),
27
+ expected: z.object({
28
+ tool: z.string().min(1).optional(),
29
+ check: z.string().min(1).optional(),
30
+ }).strict().refine(
31
+ expectation => expectation.tool !== undefined || expectation.check !== undefined,
32
+ { message: 'expected needs at least one of tool or check' },
33
+ ).optional(),
34
+ }).strict().refine(
35
+ caseValue => (caseValue.prompt === undefined) !== (caseValue.promptFile === undefined),
36
+ { message: 'each case needs exactly one of prompt or promptFile' },
37
+ )
38
+
39
+ const benchmarkSchema = z.object({
40
+ name: z.string().min(1),
41
+ model: z.string().min(1),
42
+ profile: z.string().min(1).default('headless'),
43
+ command: z.array(z.string().min(1)).default(['dsh']),
44
+ trials: z.number().int().positive().default(1),
45
+ timeoutMs: z.number().int().positive().default(600_000),
46
+ seed: z.number().int().default(0),
47
+ cases: z.array(benchmarkCaseSchema).min(1),
48
+ pricing: z.record(z.string().min(1), pricingSchema).optional(),
49
+ }).strict()
50
+
51
+ /**
52
+ * Resolve one parsed case's prompt and workspace against the benchmark
53
+ * directory. Prompt files are read at load time so a run fails before any
54
+ * trial starts.
55
+ * @param parsed - the zod-validated case document.
56
+ * @param baseDir - absolute directory the benchmark file lives in.
57
+ * @returns the resolved runtime case.
58
+ */
59
+ async function resolveCase(
60
+ parsed: z.infer<typeof benchmarkCaseSchema>,
61
+ baseDir: string,
62
+ ): Promise<BenchmarkCase> {
63
+ const prompt = parsed.prompt
64
+ ?? await readFile(resolve(baseDir, parsed.promptFile as string), 'utf8')
65
+ return {
66
+ id: parsed.id,
67
+ prompt,
68
+ ...(parsed.workspace !== undefined
69
+ ? { workspace: isAbsolute(parsed.workspace) ? parsed.workspace : resolve(baseDir, parsed.workspace) }
70
+ : {}),
71
+ ...(parsed.expected !== undefined
72
+ ? {
73
+ expected: {
74
+ ...(parsed.expected.tool !== undefined ? { tool: parsed.expected.tool } : {}),
75
+ ...(parsed.expected.check !== undefined ? { check: parsed.expected.check } : {}),
76
+ },
77
+ }
78
+ : {}),
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Parse benchmark YAML text into a validated runtime document.
84
+ * @param text - the benchmark document's YAML source.
85
+ * @param baseDir - absolute directory used to resolve prompt and workspace paths.
86
+ * @returns the validated benchmark.
87
+ */
88
+ export async function parseBenchmark(text: string, baseDir: string): Promise<Benchmark> {
89
+ const value = load(text)
90
+ if (typeof value !== 'object' || value === null) {
91
+ throw new Error('benchmark document must be a YAML mapping')
92
+ }
93
+ const parsed = benchmarkSchema.parse(value)
94
+ const cases: BenchmarkCase[] = []
95
+ for (const caseValue of parsed.cases) {
96
+ cases.push(await resolveCase(caseValue, baseDir))
97
+ }
98
+ const pricing = parsed.pricing
99
+ return {
100
+ name: parsed.name,
101
+ model: parsed.model,
102
+ profile: parsed.profile,
103
+ command: parsed.command,
104
+ trials: parsed.trials,
105
+ timeoutMs: parsed.timeoutMs,
106
+ seed: parsed.seed,
107
+ cases,
108
+ ...(pricing !== undefined ? { pricing } : {}),
109
+ baseDir,
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Load and validate a benchmark document from disk.
115
+ * @param path - path to the benchmark YAML file.
116
+ * @returns the validated benchmark.
117
+ */
118
+ export async function loadBenchmark(path: string): Promise<Benchmark> {
119
+ const absolute = resolve(path)
120
+ return parseBenchmark(await readFile(absolute, 'utf8'), dirname(absolute))
121
+ }
package/src/command.ts ADDED
@@ -0,0 +1,115 @@
1
+ /**
2
+ * The eval app's commander program: `run <benchmark.yaml>` executes a
3
+ * benchmark and writes its JSON report; `report <run.json>` renders one as
4
+ * markdown. Parsing follows the cmdline contract: the action publishes an
5
+ * ordinary service, and help or a rejection publishes nothing.
6
+ *
7
+ * @module dsh-eval/command
8
+ */
9
+
10
+ import { Command } from 'commander'
11
+ import type { Context } from '@deepseek-ai/cordis'
12
+ import { parseCmdline } from '@deepseek-ai/dsh-cmdline'
13
+
14
+ /** What the eval app resolved from its command line. */
15
+ export type EvalStartupValues =
16
+ | {
17
+ kind: 'run'
18
+ benchmarkPath: string
19
+ outPath: string
20
+ trials?: number
21
+ dshCommand?: readonly string[]
22
+ profile?: string
23
+ }
24
+ | {
25
+ kind: 'report'
26
+ runPath: string
27
+ }
28
+ | {
29
+ kind: 'compare'
30
+ runPathA: string
31
+ runPathB: string
32
+ }
33
+
34
+ /** Options accepted by `eval run`. */
35
+ interface RunCommandOptions {
36
+ out: string
37
+ trials?: number
38
+ dsh?: string
39
+ profile?: string
40
+ }
41
+
42
+ /** Split a single `--dsh` value into argv on whitespace. */
43
+ function splitCommand(value: string | undefined): readonly string[] | undefined {
44
+ if (value === undefined) return undefined
45
+ const command = value.trim().split(/\s+/u).filter(part => part !== '')
46
+ return command.length === 0 ? undefined : command
47
+ }
48
+
49
+ /**
50
+ * Build a fresh eval commander program. The root action rejects a bare
51
+ * invocation; the `run` and `report` actions hand the resolved values to the
52
+ * publish callback. The callback, not a Cordis service, carries the values
53
+ * because the plugin's own fiber is not yet active when the parse action runs
54
+ * and a strict `ctx.get` would miss a just-provided service.
55
+ * @param publish - receives the resolved invocation once a subcommand runs.
56
+ * @returns the configured program.
57
+ */
58
+ export function evalCommand(publish: (values: EvalStartupValues) => void): Command {
59
+ const program = new Command()
60
+ .name('dsh --profile eval')
61
+ .description('Run agent evaluations over headless dsh profiles and report trace-based metrics.')
62
+ .helpOption('-h, --help', 'show this help')
63
+ .action(() => {
64
+ program.error('error: eval needs a subcommand: run <benchmark.yaml> or report <run.json>')
65
+ })
66
+ const run = program.command('run').description('run a benchmark and write its JSON report')
67
+ run
68
+ .argument('<benchmark.yaml>', 'path to the benchmark document')
69
+ .option('--out <path>', 'output run JSON path', 'eval-run.json')
70
+ .option('--trials <n>', 'override the benchmark trials count', (value) => {
71
+ const parsed = Number(value)
72
+ if (!Number.isInteger(parsed) || parsed <= 0) program.error('error: --trials must be a positive integer')
73
+ return parsed
74
+ })
75
+ .option('--dsh <cmd>', 'override the dsh launcher command, space-separated')
76
+ .option('--profile <name>', 'override the spawned dsh profile')
77
+ .action((benchmarkPath: string, options: RunCommandOptions) => {
78
+ const dshCommand = splitCommand(options.dsh)
79
+ publish({
80
+ kind: 'run',
81
+ benchmarkPath,
82
+ outPath: options.out,
83
+ ...(options.trials !== undefined ? { trials: options.trials } : {}),
84
+ ...(dshCommand !== undefined ? { dshCommand } : {}),
85
+ ...(options.profile !== undefined ? { profile: options.profile } : {}),
86
+ })
87
+ })
88
+ const report = program.command('report').description('render a persisted run JSON as markdown')
89
+ report
90
+ .argument('<run.json>', 'path to a run report')
91
+ .action((runPath: string) => {
92
+ publish({ kind: 'report', runPath })
93
+ })
94
+ const compare = program.command('compare').description('compare two persisted run reports as a markdown table')
95
+ compare
96
+ .argument('<run-a.json>', 'baseline run report')
97
+ .argument('<run-b.json>', 'candidate run report')
98
+ .action((runPathA: string, runPathB: string) => {
99
+ publish({ kind: 'compare', runPathA, runPathB })
100
+ })
101
+ return program
102
+ }
103
+
104
+ /**
105
+ * Parse the launcher's inner arguments with the eval program and return what
106
+ * the invoked command published.
107
+ * @param ctx - plugin context carrying `cmdlineArgs` and `appExit`.
108
+ * @returns the resolved invocation, or undefined when help or an error exited.
109
+ */
110
+ export function applyEval(ctx: Context): EvalStartupValues | undefined {
111
+ let resolved: EvalStartupValues | undefined
112
+ const program = evalCommand((values) => { resolved = values })
113
+ parseCmdline(ctx, program)
114
+ return resolved
115
+ }
package/src/compare.ts ADDED
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Cross-run comparison for dsh-eval: two persisted run reports become a row
3
+ * list of metric values and deltas, rendered as a markdown table.
4
+ *
5
+ * @module dsh-eval/compare
6
+ */
7
+
8
+ import type { EvalRun } from './types.ts'
9
+
10
+ /** One compared metric row. */
11
+ export interface CompareRow {
12
+ /** Metric label. */
13
+ metric: string
14
+ /** Run A's rendered value. */
15
+ a: string
16
+ /** Run B's rendered value. */
17
+ b: string
18
+ /** Signed delta (`b - a`) for numeric rows, or a dash for text rows. */
19
+ delta: string
20
+ }
21
+
22
+ /** Render a nullable number with a dash placeholder. */
23
+ function formatNumber(value: number | null, digits = 1): string {
24
+ return value === null ? '–' : value.toFixed(digits)
25
+ }
26
+
27
+ /** Render a nullable rate as percent with a dash placeholder. */
28
+ function formatRate(value: number | null): string {
29
+ return value === null ? '–' : `${(value * 100).toFixed(1)}%`
30
+ }
31
+
32
+ /** Render a signed delta between two nullable numbers. */
33
+ function formatDelta(a: number | null, b: number | null, unit: 'pp' | '' = ''): string {
34
+ if (a === null || b === null) return '–'
35
+ const delta = unit === 'pp' ? (b - a) * 100 : b - a
36
+ return `${delta >= 0 ? '+' : ''}${delta.toFixed(1)}${unit}`
37
+ }
38
+
39
+ /** Pull one nullable numeric value from a run for comparison. */
40
+ type RunSelector = (run: EvalRun) => number | null
41
+
42
+ /**
43
+ * Build the comparison rows between two runs.
44
+ * @param a - the baseline run.
45
+ * @param b - the candidate run.
46
+ * @returns the row list in display order.
47
+ */
48
+ export function compareRuns(a: EvalRun, b: EvalRun): CompareRow[] {
49
+ const completed = (run: EvalRun): number => run.cases.filter(result => result.status === 'completed').length
50
+ const rates = (selector: RunSelector, label: string, unit: 'pp' | ''): CompareRow => {
51
+ const aValue = selector(a)
52
+ const bValue = selector(b)
53
+ return {
54
+ metric: label,
55
+ a: unit === 'pp' ? formatRate(aValue) : formatNumber(aValue),
56
+ b: unit === 'pp' ? formatRate(bValue) : formatNumber(bValue),
57
+ delta: unit === 'pp' ? formatDelta(aValue, bValue, 'pp') : formatDelta(aValue, bValue),
58
+ }
59
+ }
60
+ const numeric = (selector: RunSelector, label: string): CompareRow => rates(selector, label, '')
61
+ return [
62
+ { metric: 'benchmark', a: a.benchmark, b: b.benchmark, delta: '–' },
63
+ { metric: 'model', a: a.model, b: b.model, delta: '–' },
64
+ numeric(run => completed(run), 'completed trials'),
65
+ numeric(run => run.aggregate?.steps ?? null, 'steps/trial'),
66
+ rates(run => run.aggregate?.toolSuccessRate ?? null, 'tool success', 'pp'),
67
+ rates(run => run.grading?.taskSuccessRate ?? null, 'task success', 'pp'),
68
+ rates(run => run.grading?.toolSelectionAccuracyRate ?? null, 'tool selection accuracy', 'pp'),
69
+ numeric(run => run.aggregate?.invalidToolCalls ?? null, 'invalid tool calls/trial'),
70
+ numeric(run => run.aggregate?.retries ?? null, 'retries/trial'),
71
+ numeric(run => run.aggregate?.totalTokens ?? null, 'tokens/trial'),
72
+ numeric(run => run.aggregate?.costUsd ?? null, 'cost/trial (USD)'),
73
+ numeric(run => run.aggregate?.latencyMs ?? null, 'latency/trial (ms)'),
74
+ ]
75
+ }
76
+
77
+ /**
78
+ * Render comparison rows as a markdown table.
79
+ * @param rows - the rows from {@link compareRuns}.
80
+ * @returns the markdown text.
81
+ */
82
+ export function renderCompareMarkdown(rows: readonly CompareRow[]): string {
83
+ return [
84
+ '# Compare',
85
+ '',
86
+ '| metric | run A | run B | delta (B - A) |',
87
+ '|---|---|---|---|',
88
+ ...rows.map(row => `| ${row.metric} | ${row.a} | ${row.b} | ${row.delta} |`),
89
+ '',
90
+ ].join('\n')
91
+ }
package/src/index.ts ADDED
@@ -0,0 +1,97 @@
1
+ /**
2
+ * dsh-eval 鈥?agent evaluation over headless dsh profiles.
3
+ *
4
+ * The eval bundle mounts this command-line plugin over dsh-base. It parses
5
+ * `dsh --profile eval run <benchmark.yaml>` / `report <run.json>`, spawns one
6
+ * headless dsh subprocess per case x trial, harvests each persisted session
7
+ * log as a trace, folds automatic metrics, scripted grading (task success,
8
+ * tool-selection accuracy), and cross-run comparison, and writes a JSON run
9
+ * report. LLM-judge metrics (final-answer score, hallucination) and paired
10
+ * same-seed trials are deferred to later milestones.
11
+ *
12
+ * @module dsh-eval
13
+ */
14
+
15
+ import type { Context } from '@deepseek-ai/cordis'
16
+ import { loadBenchmark } from './benchmark.ts'
17
+ import { applyEval, type EvalStartupValues } from './command.ts'
18
+ import { compareRuns, renderCompareMarkdown } from './compare.ts'
19
+ import { renderMarkdownReport, writeRunReport, loadRunReport } from './report.ts'
20
+ import { runBenchmark } from './runner.ts'
21
+
22
+ /** Stable Cordis plugin name. */
23
+ export const name = 'eval'
24
+ /** The launcher-provided command line is the only required service. */
25
+ export const inject = ['cmdlineArgs']
26
+
27
+ /** Process-facing output streams; tests substitute captures. */
28
+ export interface EvalIo {
29
+ stdout: { write(chunk: string): unknown }
30
+ stderr: { write(chunk: string): unknown }
31
+ }
32
+
33
+ /** The process streams the eval app writes to; tests substitute captures. */
34
+ export const internals: EvalIo = {
35
+ stdout: process.stdout,
36
+ stderr: process.stderr,
37
+ }
38
+
39
+ /** Aggregate-success sentence for the run summary line. */
40
+ function summary(run: Awaited<ReturnType<typeof runBenchmark>>): string {
41
+ const aggregate = run.aggregate
42
+ if (aggregate === null) return 'no completed trials'
43
+ const rate = aggregate.toolSuccessRate === null ? 'n/a' : `${(aggregate.toolSuccessRate * 100).toFixed(1)}%`
44
+ const taskRate = run.grading?.taskSuccessRate
45
+ const task = taskRate === null || taskRate === undefined
46
+ ? ''
47
+ : `, task success ${(taskRate * 100).toFixed(1)}%`
48
+ return `tool success ${rate}${task}, ${aggregate.steps.toFixed(1)} steps/trial`
49
+ }
50
+
51
+ /**
52
+ * Execute one eval invocation to completion.
53
+ * @param values - the resolved command-line invocation.
54
+ * @param io - output streams for the report and diagnostics.
55
+ * @returns the process exit code; nonzero for any failure or a run with no
56
+ * completed trials.
57
+ */
58
+ export async function executeEval(values: EvalStartupValues, io: EvalIo): Promise<number> {
59
+ try {
60
+ if (values.kind === 'report') {
61
+ const run = await loadRunReport(values.runPath)
62
+ io.stdout.write(renderMarkdownReport(run))
63
+ return 0
64
+ }
65
+ if (values.kind === 'compare') {
66
+ const a = await loadRunReport(values.runPathA)
67
+ const b = await loadRunReport(values.runPathB)
68
+ io.stdout.write(renderCompareMarkdown(compareRuns(a, b)))
69
+ return 0
70
+ }
71
+ const benchmark = await loadBenchmark(values.benchmarkPath)
72
+ const run = await runBenchmark(benchmark, {
73
+ ...(values.trials !== undefined ? { trials: values.trials } : {}),
74
+ ...(values.dshCommand !== undefined ? { command: values.dshCommand } : {}),
75
+ ...(values.profile !== undefined ? { profile: values.profile } : {}),
76
+ })
77
+ await writeRunReport(run, values.outPath)
78
+ io.stdout.write(`Wrote ${values.outPath} (${run.cases.length} trials, ${summary(run)})\n`)
79
+ return run.aggregate === null ? 1 : 0
80
+ } catch (error) {
81
+ io.stderr.write(`dsh eval: ${error instanceof Error ? error.message : String(error)}\n`)
82
+ return 1
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Mount the eval command-line app: parse the invocation, run it asynchronously,
88
+ * and request launcher exit with the result code.
89
+ * @param ctx - plugin context carrying the command line and launcher exit.
90
+ */
91
+ export function apply(ctx: Context): void {
92
+ const exit = ctx.get('appExit')
93
+ if (exit === undefined) throw new Error('eval: the launcher must provide ctx.appExit before the tree mounts')
94
+ const values = applyEval(ctx)
95
+ if (values === undefined) return
96
+ void executeEval(values, internals).then((code) => { exit(code) })
97
+ }