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/src/import.ts ADDED
@@ -0,0 +1,327 @@
1
+ /**
2
+ * Cross-harness trace import: Codex and Claude Code session JSONL become the
3
+ * eval trace vocabulary so report and compare can fold metrics over runs
4
+ * recorded by other agents. Each importer synthesizes one turn (and one step)
5
+ * per user message, preserving assistant text and tool calls/results; model
6
+ * token usage is not part of either external format, so token metrics stay
7
+ * zero.
8
+ *
9
+ * @module dsh-eval/import
10
+ */
11
+
12
+ import { readFile } from 'node:fs/promises'
13
+ import { basename, dirname, resolve } from 'node:path'
14
+ import { computeMetrics } from './metrics.ts'
15
+ import { parseSessionLog } from './trace.ts'
16
+ import type { EvalRun, EvalTrace } from './types.ts'
17
+
18
+ /** Synthetic event-time spacing keeps imported metrics deterministic. */
19
+ const STEP_MS = 1000
20
+ /** Epoch base for imported traces without a real timestamp. */
21
+ const BASE_MS = 1_700_000_000_000
22
+
23
+ /** A pending event row before seq/time assignment. */
24
+ interface ParsedEvent {
25
+ type: string
26
+ data: unknown
27
+ }
28
+
29
+ /** Join an external-log line's timestamp (ISO or epoch) with a synthetic offset. */
30
+ function eventTime(lineIndex: number): number {
31
+ return BASE_MS + lineIndex * STEP_MS
32
+ }
33
+
34
+ /** Extract display text from a string, a text block, or a block array. */
35
+ function textOf(value: unknown): string {
36
+ if (typeof value === 'string') return value
37
+ if (Array.isArray(value)) {
38
+ return value.flatMap((block) => {
39
+ if (typeof block !== 'object' || block === null) return []
40
+ const text = (block as Record<string, unknown>).text
41
+ return typeof text === 'string' ? [text] : []
42
+ }).join('')
43
+ }
44
+ return ''
45
+ }
46
+
47
+ /** Stable synthetic session id from the source filename. */
48
+ function sessionIdFrom(source: string): string {
49
+ const safe = basename(source).replace(/[^A-Za-z0-9._-]/gu, '-').replace(/^-+|-+$/gu, '')
50
+ return safe === '' ? 'imported' : safe
51
+ }
52
+
53
+ /** Assemble parsed events into a validated trace with contiguous seqs. */
54
+ function assembleTrace(events: readonly ParsedEvent[], id: string): EvalTrace {
55
+ const lines = [
56
+ JSON.stringify({ type: 'session', version: 0, id, createdAt: eventTime(0), delegationDepth: 0 }),
57
+ ...events.map((event, index) => JSON.stringify({ seq: index, time: eventTime(index + 1), type: event.type, data: event.data })),
58
+ '',
59
+ ]
60
+ return parseSessionLog(lines.join('\n'))
61
+ }
62
+
63
+ /** Close the current synthesized turn with step/end and turn/end. */
64
+ function closeTurn(
65
+ events: ParsedEvent[],
66
+ turn: number,
67
+ step: number,
68
+ open: boolean,
69
+ ): boolean {
70
+ if (!open) return false
71
+ events.push({ type: 'step/end', data: { turn, step } })
72
+ events.push({ type: 'turn/end', data: { turn, reason: { kind: 'completed' } } })
73
+ return true
74
+ }
75
+
76
+ /**
77
+ * Import a Codex session JSONL (lines of `response_item` records) as a trace.
78
+ * @param text - the Codex log's UTF-8 text.
79
+ * @param source - the source file path, used for the synthetic session id.
80
+ * @returns the imported trace; non-`response_item` lines are skipped.
81
+ */
82
+ export function importCodexLog(text: string, source: string): EvalTrace {
83
+ const events: ParsedEvent[] = []
84
+ let turn = 0
85
+ let step = 0
86
+ let open = false
87
+ let callCounter = 0
88
+ let messageCounter = 0
89
+ const close = (): void => {
90
+ open = closeTurn(events, turn, step, open)
91
+ }
92
+ for (const line of text.split(/\r?\n/u)) {
93
+ if (line.trim() === '') continue
94
+ let record: unknown
95
+ try {
96
+ record = JSON.parse(line)
97
+ } catch {
98
+ continue
99
+ }
100
+ if (typeof record !== 'object' || record === null) continue
101
+ const row = record as Record<string, unknown>
102
+ if (row.type !== 'response_item' || typeof row.payload !== 'object' || row.payload === null) continue
103
+ const payload = row.payload as Record<string, unknown>
104
+ if (payload.type === 'message' && payload.role === 'user') {
105
+ close()
106
+ turn += 1
107
+ step = 0
108
+ open = true
109
+ messageCounter += 1
110
+ events.push({ type: 'turn/start', data: { turn } })
111
+ events.push({
112
+ type: 'user/message',
113
+ data: {
114
+ id: `user-${messageCounter}`,
115
+ role: 'user',
116
+ content: [{ type: 'text', text: textOf(payload.content) }],
117
+ source: { kind: 'user' },
118
+ },
119
+ })
120
+ events.push({ type: 'step/start', data: { turn, step } })
121
+ } else if (payload.type === 'message' && payload.role === 'assistant') {
122
+ messageCounter += 1
123
+ events.push({
124
+ type: 'assistant/message',
125
+ data: {
126
+ turn,
127
+ step,
128
+ message: {
129
+ id: `assistant-${messageCounter}`,
130
+ role: 'assistant',
131
+ content: [{ type: 'text', text: textOf(payload.content) }],
132
+ source: { kind: 'model' },
133
+ },
134
+ },
135
+ })
136
+ } else if (payload.type === 'function_call') {
137
+ callCounter += 1
138
+ const callId = typeof payload.call_id === 'string' ? payload.call_id : `codex-call-${callCounter}`
139
+ const name = typeof payload.name === 'string' ? payload.name : 'tool'
140
+ const argumentsText = typeof payload.arguments === 'string' ? payload.arguments : '{}'
141
+ events.push({ type: 'tool/call', data: { turn, step, callId, name, arguments: argumentsText } })
142
+ } else if (payload.type === 'function_call_output') {
143
+ callCounter += 1
144
+ const callId = typeof payload.call_id === 'string' ? payload.call_id : `codex-call-${callCounter}`
145
+ const output = textOf(payload.output ?? payload.content)
146
+ events.push({
147
+ type: 'tool/result',
148
+ data: {
149
+ turn,
150
+ step,
151
+ message: {
152
+ id: `tool-result-${callCounter}`,
153
+ role: 'user',
154
+ content: [{ type: 'tool-result', text: output, isError: payload.is_error === true }],
155
+ source: { kind: 'tool', callId },
156
+ },
157
+ },
158
+ })
159
+ }
160
+ }
161
+ close()
162
+ return assembleTrace(events, sessionIdFrom(source))
163
+ }
164
+
165
+ /** Whether a Claude Code user message carries only tool results (not a new turn). */
166
+ function isToolResultUser(content: unknown): boolean {
167
+ if (!Array.isArray(content)) return false
168
+ return content.every(block =>
169
+ typeof block === 'object' && block !== null && (block as Record<string, unknown>).type === 'tool_result')
170
+ }
171
+
172
+ /**
173
+ * Import a Claude Code session JSONL (lines of `user`/`assistant` records) as
174
+ * a trace.
175
+ * @param text - the Claude Code log's UTF-8 text.
176
+ * @param source - the source file path, used for the synthetic session id.
177
+ * @returns the imported trace; non-user/assistant lines are skipped.
178
+ */
179
+ export function importClaudeLog(text: string, source: string): EvalTrace {
180
+ const events: ParsedEvent[] = []
181
+ let turn = 0
182
+ let step = 0
183
+ let open = false
184
+ let messageCounter = 0
185
+ const close = (): void => {
186
+ open = closeTurn(events, turn, step, open)
187
+ }
188
+ for (const line of text.split(/\r?\n/u)) {
189
+ if (line.trim() === '') continue
190
+ let record: unknown
191
+ try {
192
+ record = JSON.parse(line)
193
+ } catch {
194
+ continue
195
+ }
196
+ if (typeof record !== 'object' || record === null) continue
197
+ const row = record as Record<string, unknown>
198
+ if ((row.type !== 'user' && row.type !== 'assistant')
199
+ || typeof row.message !== 'object' || row.message === null) continue
200
+ const message = row.message as Record<string, unknown>
201
+ const content = message.content
202
+ if (row.type === 'user' && !isToolResultUser(content)) {
203
+ close()
204
+ turn += 1
205
+ step = 0
206
+ open = true
207
+ messageCounter += 1
208
+ events.push({ type: 'turn/start', data: { turn } })
209
+ events.push({
210
+ type: 'user/message',
211
+ data: {
212
+ id: `user-${messageCounter}`,
213
+ role: 'user',
214
+ content: [{ type: 'text', text: textOf(content) }],
215
+ source: { kind: 'user' },
216
+ },
217
+ })
218
+ events.push({ type: 'step/start', data: { turn, step } })
219
+ continue
220
+ }
221
+ if (row.type === 'assistant') {
222
+ if (typeof content === 'string') {
223
+ messageCounter += 1
224
+ events.push({
225
+ type: 'assistant/message',
226
+ data: {
227
+ turn,
228
+ step,
229
+ message: {
230
+ id: `assistant-${messageCounter}`,
231
+ role: 'assistant',
232
+ content: [{ type: 'text', text: content }],
233
+ source: { kind: 'model' },
234
+ },
235
+ },
236
+ })
237
+ } else {
238
+ for (const block of Array.isArray(content) ? content : []) {
239
+ if (typeof block !== 'object' || block === null) continue
240
+ const item = block as Record<string, unknown>
241
+ if (item.type === 'text') {
242
+ messageCounter += 1
243
+ events.push({
244
+ type: 'assistant/message',
245
+ data: {
246
+ turn,
247
+ step,
248
+ message: {
249
+ id: `assistant-${messageCounter}`,
250
+ role: 'assistant',
251
+ content: [{ type: 'text', text: typeof item.text === 'string' ? item.text : '' }],
252
+ source: { kind: 'model' },
253
+ },
254
+ },
255
+ })
256
+ } else if (item.type === 'tool_use') {
257
+ const callId = typeof item.id === 'string' ? item.id : `claude-call-${messageCounter}`
258
+ const name = typeof item.name === 'string' ? item.name : 'tool'
259
+ const argumentsText = JSON.stringify(item.input ?? {})
260
+ events.push({ type: 'tool/call', data: { turn, step, callId, name, arguments: argumentsText } })
261
+ }
262
+ }
263
+ }
264
+ continue
265
+ }
266
+ // Reaching here means a tool-result user message: the plain-user branch
267
+ // above already excluded non-tool-result content.
268
+ const blocks = content as readonly Record<string, unknown>[]
269
+ for (const item of blocks) {
270
+ const callId = typeof item.tool_use_id === 'string' ? item.tool_use_id : `claude-call-${messageCounter}`
271
+ events.push({
272
+ type: 'tool/result',
273
+ data: {
274
+ turn,
275
+ step,
276
+ message: {
277
+ id: `tool-result-${messageCounter}`,
278
+ role: 'user',
279
+ content: [{ type: 'tool-result', text: textOf(item.content), isError: item.is_error === true }],
280
+ source: { kind: 'tool', callId },
281
+ },
282
+ },
283
+ })
284
+ }
285
+ }
286
+ close()
287
+ return assembleTrace(events, sessionIdFrom(source))
288
+ }
289
+
290
+ /** Import formats the CLI accepts. */
291
+ export type ImportFormat = 'codex' | 'claude-code'
292
+
293
+ /**
294
+ * Load an external session log and build a one-trial run record from it.
295
+ * @param format - the external harness format.
296
+ * @param path - the session JSONL path.
297
+ * @param caseId - the imported trial's case id.
298
+ * @returns the run record with one completed trial.
299
+ */
300
+ export async function importTraceFile(format: ImportFormat, path: string, caseId: string): Promise<EvalRun> {
301
+ const absolute = resolve(path)
302
+ const text = await readFile(absolute, 'utf8')
303
+ const trace = format === 'codex'
304
+ ? importCodexLog(text, absolute)
305
+ : importClaudeLog(text, absolute)
306
+ const metrics = computeMetrics(trace.events, undefined)
307
+ return {
308
+ benchmark: `import:${format}`,
309
+ model: 'imported',
310
+ createdAt: Date.now(),
311
+ trials: 1,
312
+ seed: 0,
313
+ pricing: null,
314
+ tempRoot: dirname(absolute),
315
+ cases: [{
316
+ caseId,
317
+ trial: 1,
318
+ status: 'completed',
319
+ tracePath: absolute,
320
+ exitCode: null,
321
+ timedOut: false,
322
+ metrics,
323
+ }],
324
+ aggregate: metrics,
325
+ grading: null,
326
+ }
327
+ }
package/src/index.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * dsh-eval 鈥?agent evaluation over headless dsh profiles.
2
+ * dsh-eval — agent evaluation over headless dsh profiles.
3
3
  *
4
4
  * The eval bundle mounts this command-line plugin over dsh-base. It parses
5
5
  * `dsh --profile eval run <benchmark.yaml>` / `report <run.json>`, spawns one
@@ -16,6 +16,7 @@ import type { Context } from '@deepseek-ai/cordis'
16
16
  import { loadBenchmark } from './benchmark.ts'
17
17
  import { applyEval, type EvalStartupValues } from './command.ts'
18
18
  import { compareRuns, renderCompareMarkdown } from './compare.ts'
19
+ import { importTraceFile } from './import.ts'
19
20
  import { llmJudgeChat, type JudgeChat } from './judge.ts'
20
21
  import { renderMarkdownReport, writeRunReport, loadRunReport } from './report.ts'
21
22
  import { runBenchmark } from './runner.ts'
@@ -78,6 +79,12 @@ export async function executeEval(
78
79
  services: { judgeChat?: JudgeChat | undefined } = {},
79
80
  ): Promise<number> {
80
81
  try {
82
+ if (values.kind === 'import') {
83
+ const run = await importTraceFile(values.format, values.path, values.caseId)
84
+ await writeRunReport(run, values.outPath)
85
+ io.stdout.write(`Wrote ${values.outPath} (1 imported trial, ${summary(run)})\n`)
86
+ return 0
87
+ }
81
88
  if (values.kind === 'report') {
82
89
  const run = await loadRunReport(values.runPath)
83
90
  io.stdout.write(renderMarkdownReport(run))
package/src/runner.ts CHANGED
@@ -23,21 +23,6 @@ import { tryJudgeTrial, type JudgeChat } from './judge.ts'
23
23
  import { aggregateMetrics, computeMetrics } from './metrics.ts'
24
24
  import { findSessionLogs, loadTrace, mergeTraces } from './trace.ts'
25
25
 
26
- /** Overlay forcing the harvested log to plain JSONL and the run to be non-interactive. */
27
- const EVAL_OVERLAY = `- id: session-persistence-jsonl
28
- config:
29
- root: !!js dshHomePath('sessions')
30
- packChunks: false
31
- compression: none
32
- - id: sandbox-policy
33
- config:
34
- mode: workspace-write
35
- workspaceRoot: !!js process.cwd()
36
- - id: approval
37
- config:
38
- policy: never
39
- `
40
-
41
26
  /** Cap per-stream child output so a runaway trial cannot exhaust memory. */
42
27
  const MAX_OUTPUT_BYTES = 512 * 1024
43
28
 
@@ -82,6 +67,39 @@ function sanitizeSegment(value: string): string {
82
67
  return safe === '' ? 'case' : safe
83
68
  }
84
69
 
70
+ /**
71
+ * Build the per-trial overlay: plain-JSONL persistence, non-interactive
72
+ * permissions, and the keyless replay plugin when recorded logs exist.
73
+ * @param replay - the replay primary log and child logs, or undefined.
74
+ * @returns the overlay YAML text.
75
+ */
76
+ function evalOverlay(replay: { file: string; childFiles: readonly string[] } | undefined): string {
77
+ const lines = [
78
+ '- id: session-persistence-jsonl',
79
+ ' config:',
80
+ " root: !!js dshHomePath('sessions')",
81
+ ' packChunks: false',
82
+ ' compression: none',
83
+ '- id: sandbox-policy',
84
+ ' config:',
85
+ ' mode: workspace-write',
86
+ ' workspaceRoot: !!js process.cwd()',
87
+ '- id: approval',
88
+ ' config:',
89
+ ' policy: never',
90
+ ]
91
+ if (replay !== undefined) {
92
+ lines.push(
93
+ '- id: llm-replay',
94
+ " name: '@deepseek-ai/dsh-llm-replay'",
95
+ ' config:',
96
+ ` file: ${JSON.stringify(replay.file)}`,
97
+ ...(replay.childFiles.length === 0 ? [] : [` childFiles: ${JSON.stringify(replay.childFiles)}`]),
98
+ )
99
+ }
100
+ return `${lines.join('\n')}\n`
101
+ }
102
+
85
103
  /** Split a single command string into argv on whitespace. */
86
104
  function splitWords(value: string): string[] {
87
105
  return value.trim().split(/\s+/u).filter(part => part !== '')
@@ -236,8 +254,27 @@ async function runCaseTrial(
236
254
  await mkdir(workspace, { recursive: true })
237
255
  await mkdir(dshHome, { recursive: true, mode: 0o700 })
238
256
  if (caseValue.workspace !== undefined) await cp(caseValue.workspace, workspace, { recursive: true })
257
+ const replayFixture = benchmark.replay === undefined
258
+ ? undefined
259
+ : join(benchmark.replay.dir, `${sanitizeSegment(caseValue.id)}-${trial}`)
260
+ let replay: { file: string; childFiles: string[] } | undefined
261
+ if (replayFixture !== undefined) {
262
+ const logs = await findSessionLogs(replayFixture)
263
+ if (logs.length === 0) {
264
+ return {
265
+ caseId: caseValue.id,
266
+ trial,
267
+ status: 'error',
268
+ error: `no replay fixture found at ${replayFixture}`,
269
+ exitCode: null,
270
+ timedOut: false,
271
+ }
272
+ }
273
+ const primary = logs[0]!
274
+ replay = { file: primary, childFiles: logs.slice(1) }
275
+ }
239
276
  const overlayPath = join(trialDir, 'eval.cordis.yml')
240
- await writeFile(overlayPath, EVAL_OVERLAY, 'utf8')
277
+ await writeFile(overlayPath, evalOverlay(replay), 'utf8')
241
278
  let outcome: SpawnOutcome
242
279
  try {
243
280
  outcome = await runCommand(
@@ -315,6 +352,9 @@ export async function runBenchmark(benchmark: Benchmark, options: RunOptions = {
315
352
  if (benchmark.judge !== undefined && options.judgeChat === undefined) {
316
353
  throw new Error('eval: benchmark configures a judge but no LLM chat seam is available')
317
354
  }
355
+ if (benchmark.judge !== undefined && benchmark.replay !== undefined) {
356
+ throw new Error('eval: judge and replay cannot be combined in one run')
357
+ }
318
358
  const root = await mkdtemp(join(options.tempRoot ?? tmpdir(), 'dsh-eval-'))
319
359
  const trials = options.trials ?? benchmark.trials
320
360
  const effective: Benchmark = {
package/src/types.ts CHANGED
@@ -52,6 +52,16 @@ export interface BenchmarkJudge {
52
52
  maxScore: number
53
53
  }
54
54
 
55
+ /** Keyless replay configuration: recorded session logs replayed instead of live model calls. */
56
+ export interface BenchmarkReplay {
57
+ /**
58
+ * Directory holding one recorded-log tree per trial, named
59
+ * `<caseId>-<trial>/session.jsonl` (child logs ride alongside). A run with
60
+ * a key records these under its `tempRoot`.
61
+ */
62
+ dir: string
63
+ }
64
+
55
65
  /** A validated benchmark document. */
56
66
  export interface Benchmark {
57
67
  /** Benchmark name; also the run record's `benchmark` field. */
@@ -74,6 +84,8 @@ export interface Benchmark {
74
84
  pricing?: Readonly<Record<string, BenchmarkPricing>>
75
85
  /** LLM-judge configuration, when final-answer scoring is enabled. */
76
86
  judge?: BenchmarkJudge
87
+ /** Keyless replay configuration, when model calls replay from recorded logs. */
88
+ replay?: BenchmarkReplay
77
89
  /** Directory the benchmark document was loaded from; relative paths resolve against it. */
78
90
  baseDir: string
79
91
  }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 hccccc01333
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.