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.
package/src/trace.ts ADDED
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Session-log harvesting and parsing for dsh-eval. A trial's headless dsh
3
+ * writes a plain-JSONL session log under its DSH_HOME; the importer reads the
4
+ * header line, decodes every event row (packed chunk rows included) through
5
+ * the session package's storage decoder, and enforces seq continuity.
6
+ *
7
+ * @module dsh-eval/trace
8
+ */
9
+
10
+ import { readFile, readdir, stat } from 'node:fs/promises'
11
+ import { join } from 'node:path'
12
+ import { decodeStorageRecord, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
13
+ import { z } from 'zod'
14
+ import type { EvalTrace } from './types.ts'
15
+
16
+ const headerSchema = z.object({
17
+ type: z.literal('session'),
18
+ id: z.string().min(1),
19
+ createdAt: z.number().nonnegative(),
20
+ }).loose()
21
+
22
+ /**
23
+ * Parse a plain-JSONL session log into a trace.
24
+ * @param text - the log file's UTF-8 text, header line first.
25
+ * @returns the parsed trace.
26
+ * @throws when the header is missing or malformed, a row is not valid JSON,
27
+ * or event seqs are not contiguous.
28
+ */
29
+ export function parseSessionLog(text: string): EvalTrace {
30
+ const lines = text.split(/\r?\n/u).filter(line => line.trim() !== '')
31
+ if (lines.length === 0) throw new Error('empty session log')
32
+ const header = headerSchema.parse(JSON.parse(lines[0] as string))
33
+ const events: SessionEvent[] = []
34
+ for (let index = 1; index < lines.length; index++) {
35
+ const line = lines[index] as string
36
+ let record: unknown
37
+ try {
38
+ record = JSON.parse(line)
39
+ } catch {
40
+ throw new Error(`corrupt session log: invalid JSON at line ${index + 1}`)
41
+ }
42
+ for (const event of decodeStorageRecord(record)) {
43
+ if (event.seq !== events.length) {
44
+ throw new Error(
45
+ `corrupt session log: seq gap at line ${index + 1} (expected ${events.length}, got ${event.seq})`,
46
+ )
47
+ }
48
+ events.push(event)
49
+ }
50
+ }
51
+ return {
52
+ sessionId: SessionId(header.id),
53
+ createdAt: header.createdAt,
54
+ events,
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Load and parse the primary session log at a path.
60
+ * @param path - absolute path to a `session.jsonl` file.
61
+ * @returns the parsed trace.
62
+ */
63
+ export async function loadTrace(path: string): Promise<EvalTrace> {
64
+ return parseSessionLog(await readFile(path, 'utf8'))
65
+ }
66
+
67
+ /**
68
+ * Find the newest primary `session.jsonl` under a DSH_HOME tree, descending
69
+ * into directories without following symlinks.
70
+ * @param root - the DSH_HOME directory to scan.
71
+ * @returns the newest primary log's absolute path, or null when none exists.
72
+ */
73
+ export async function findPrimarySessionLog(root: string): Promise<string | null> {
74
+ let entries
75
+ try {
76
+ entries = await readdir(root, { withFileTypes: true })
77
+ } catch {
78
+ return null
79
+ }
80
+ let best: { path: string; mtime: number } | null = null
81
+ for (const entry of entries) {
82
+ if (entry.isDirectory()) {
83
+ const found = await findPrimarySessionLog(join(root, entry.name))
84
+ if (found !== null) {
85
+ const mtime = (await stat(found)).mtimeMs
86
+ if (best === null || mtime > best.mtime) best = { path: found, mtime }
87
+ }
88
+ } else if (entry.isFile() && entry.name === 'session.jsonl') {
89
+ const mtime = (await stat(join(root, entry.name))).mtimeMs
90
+ if (best === null || mtime > best.mtime) best = { path: join(root, entry.name), mtime }
91
+ }
92
+ }
93
+ return best?.path ?? null
94
+ }
package/src/types.ts ADDED
@@ -0,0 +1,189 @@
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
+
9
+ import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session'
10
+
11
+ /** One model arm's per-million-token pricing, in USD. */
12
+ export interface BenchmarkPricing {
13
+ /** Billed uncached input tokens. */
14
+ inputUsdPerMTokens: number
15
+ /** Billed cache-read input tokens. */
16
+ cacheReadUsdPerMTokens: number
17
+ /** Billed cache-write input tokens. */
18
+ cacheWriteUsdPerMTokens: number
19
+ /** Billed output tokens. */
20
+ outputUsdPerMTokens: number
21
+ }
22
+
23
+ /** One benchmark task: a prompt and an optional workspace copied per trial. */
24
+ export interface BenchmarkCase {
25
+ /** Stable case id, used in run output and trial directory names. */
26
+ id: string
27
+ /** The task text handed to the headless agent. */
28
+ prompt: string
29
+ /** Absolute path to a workspace tree copied into each trial, when provided. */
30
+ workspace?: string
31
+ /** Scripted grading annotations, when the case is graded. */
32
+ expected?: BenchmarkExpectation
33
+ }
34
+
35
+ /** Expected-tool and check-command annotations for scripted grading. */
36
+ export interface BenchmarkExpectation {
37
+ /** Substring matched against every recorded tool call name. */
38
+ tool?: string
39
+ /** Command run in the trial workspace after the agent exits; exit 0 means task success. */
40
+ check?: string
41
+ }
42
+
43
+ /** A validated benchmark document. */
44
+ export interface Benchmark {
45
+ /** Benchmark name; also the run record's `benchmark` field. */
46
+ name: string
47
+ /** Model id used for pricing lookup and reported per run. */
48
+ model: string
49
+ /** dsh profile spawned per trial; defaults to `headless`. */
50
+ profile: string
51
+ /** Command that launches dsh, as argv. */
52
+ command: readonly string[]
53
+ /** Trials per case. */
54
+ trials: number
55
+ /** Per-trial timeout in milliseconds. */
56
+ timeoutMs: number
57
+ /** Reserved deterministic seed for future paired comparisons. */
58
+ seed: number
59
+ /** The benchmark's cases, in order. */
60
+ cases: readonly BenchmarkCase[]
61
+ /** Pricing keyed by model id; an absent model reports `costUsd: null`. */
62
+ pricing?: Readonly<Record<string, BenchmarkPricing>>
63
+ /** Directory the benchmark document was loaded from; relative paths resolve against it. */
64
+ baseDir: string
65
+ }
66
+
67
+ /**
68
+ * One harvested session log. v0.1 carries the durable dsh session event
69
+ * vocabulary directly; neutral importers for other harness formats are
70
+ * deferred to the comparison milestone.
71
+ */
72
+ export interface EvalTrace {
73
+ /** Session id from the persisted log header. */
74
+ sessionId: SessionId
75
+ /** Session creation time from the persisted log header, epoch milliseconds. */
76
+ createdAt: number
77
+ /** Durable events in log order. */
78
+ events: readonly SessionEvent[]
79
+ }
80
+
81
+ /** Disjoint provider-reported token buckets over one run. */
82
+ export interface EvalTokenUsage {
83
+ /** Uncached input tokens. */
84
+ inputTokens: number
85
+ /** Cache-read input tokens. */
86
+ cacheReadTokens: number
87
+ /** Cache-write input tokens. */
88
+ cacheWriteTokens: number
89
+ /** Output tokens. */
90
+ outputTokens: number
91
+ }
92
+
93
+ /** Automatic metrics folded from one session trace. */
94
+ export interface EvalCaseMetrics {
95
+ /** Distinct turns carrying at least one closed step. */
96
+ turns: number
97
+ /** Closed `step/end` events, completed and failed alike. */
98
+ steps: number
99
+ /** Recorded `tool/call` events. */
100
+ toolCalls: number
101
+ /** Recorded `tool/result` events. */
102
+ toolResults: number
103
+ /** Results whose model-facing `isError` flag is false. */
104
+ toolSuccess: number
105
+ /** `toolSuccess / toolResults`, or null when no result landed. */
106
+ toolSuccessRate: number | null
107
+ /** Results carrying an internal failure identity (`tool/result.error`). */
108
+ invalidToolCalls: number
109
+ /** Durable `llm/retry` decisions. */
110
+ retries: number
111
+ /** Summed provider usage buckets. */
112
+ tokens: EvalTokenUsage
113
+ /** Sum of all four token buckets. */
114
+ totalTokens: number
115
+ /** Billed input (`input + cacheRead + cacheWrite`). */
116
+ contextTokens: number
117
+ /** Summed model wall time, `step/start` to `assistant/message`, milliseconds. */
118
+ llmMs: number
119
+ /** Summed tool wall time over matched `tool/call` to `tool/result`, milliseconds. */
120
+ toolMs: number
121
+ /** Summed first-token latency, `step/start` to the first token delta, milliseconds. */
122
+ ttftMs: number
123
+ /** Wall time from the first to the last recorded event, milliseconds. */
124
+ latencyMs: number
125
+ /** Estimated USD cost from the benchmark pricing table, or null without one. */
126
+ costUsd: number | null
127
+ }
128
+
129
+ /** Outcome of one case x trial. */
130
+ export interface EvalTrialResult {
131
+ /** Benchmark case id. */
132
+ caseId: string
133
+ /** 1-based trial index. */
134
+ trial: number
135
+ /** `completed` when a persisted trace was harvested; `error` otherwise. */
136
+ status: 'completed' | 'error'
137
+ /** Human-readable failure detail for `error` trials. */
138
+ error?: string
139
+ /** Absolute path of the harvested primary session log. */
140
+ tracePath?: string
141
+ /** The child process's exit code, or null when it was killed. */
142
+ exitCode: number | null
143
+ /** Whether the trial hit its timeout and killed the child. */
144
+ timedOut: boolean
145
+ /** Folded metrics for `completed` trials. */
146
+ metrics?: EvalCaseMetrics
147
+ /** Scripted grading outcome for `completed` trials with expectations. */
148
+ grade?: EvalGrade
149
+ }
150
+
151
+ /** Scripted grading outcome for one trial. */
152
+ export interface EvalGrade {
153
+ /** Whether the check command exited 0, or null when no check is configured. */
154
+ taskSuccess: boolean | null
155
+ /** Whether an expected tool was called, or null when no tool is configured. */
156
+ toolSelectionAccuracy: boolean | null
157
+ }
158
+
159
+ /** Pooled grading rates over completed trials. */
160
+ export interface EvalRunGrading {
161
+ /** Pooled task-success rate, or null when no trial carried a check. */
162
+ taskSuccessRate: number | null
163
+ /** Pooled tool-selection-accuracy rate, or null when no trial carried an expected tool. */
164
+ toolSelectionAccuracyRate: number | null
165
+ }
166
+
167
+ /** A persisted eval run. */
168
+ export interface EvalRun {
169
+ /** Benchmark name. */
170
+ benchmark: string
171
+ /** Model id the benchmark targeted. */
172
+ model: string
173
+ /** Run creation time, epoch milliseconds. */
174
+ createdAt: number
175
+ /** Trials per case actually executed. */
176
+ trials: number
177
+ /** Benchmark seed. */
178
+ seed: number
179
+ /** Resolved pricing for the benchmark model, or null without one. */
180
+ pricing: BenchmarkPricing | null
181
+ /** Root holding every trial's workspace, overlay, and harvested trace. */
182
+ tempRoot: string
183
+ /** Per-trial outcomes in execution order. */
184
+ cases: readonly EvalTrialResult[]
185
+ /** Mean/pooled metrics over completed trials, or null when none completed. */
186
+ aggregate: EvalCaseMetrics | null
187
+ /** Pooled scripted-grading rates over completed trials, or null when ungraded. */
188
+ grading: EvalRunGrading | null
189
+ }