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/import.js ADDED
@@ -0,0 +1,318 @@
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
+ import { readFile } from 'node:fs/promises';
12
+ import { basename, dirname, resolve } from 'node:path';
13
+ import { computeMetrics } from "./metrics.js";
14
+ import { parseSessionLog } from "./trace.js";
15
+ /** Synthetic event-time spacing keeps imported metrics deterministic. */
16
+ const STEP_MS = 1000;
17
+ /** Epoch base for imported traces without a real timestamp. */
18
+ const BASE_MS = 1_700_000_000_000;
19
+ /** Join an external-log line's timestamp (ISO or epoch) with a synthetic offset. */
20
+ function eventTime(lineIndex) {
21
+ return BASE_MS + lineIndex * STEP_MS;
22
+ }
23
+ /** Extract display text from a string, a text block, or a block array. */
24
+ function textOf(value) {
25
+ if (typeof value === 'string')
26
+ return value;
27
+ if (Array.isArray(value)) {
28
+ return value.flatMap((block) => {
29
+ if (typeof block !== 'object' || block === null)
30
+ return [];
31
+ const text = block.text;
32
+ return typeof text === 'string' ? [text] : [];
33
+ }).join('');
34
+ }
35
+ return '';
36
+ }
37
+ /** Stable synthetic session id from the source filename. */
38
+ function sessionIdFrom(source) {
39
+ const safe = basename(source).replace(/[^A-Za-z0-9._-]/gu, '-').replace(/^-+|-+$/gu, '');
40
+ return safe === '' ? 'imported' : safe;
41
+ }
42
+ /** Assemble parsed events into a validated trace with contiguous seqs. */
43
+ function assembleTrace(events, id) {
44
+ const lines = [
45
+ JSON.stringify({ type: 'session', version: 0, id, createdAt: eventTime(0), delegationDepth: 0 }),
46
+ ...events.map((event, index) => JSON.stringify({ seq: index, time: eventTime(index + 1), type: event.type, data: event.data })),
47
+ '',
48
+ ];
49
+ return parseSessionLog(lines.join('\n'));
50
+ }
51
+ /** Close the current synthesized turn with step/end and turn/end. */
52
+ function closeTurn(events, turn, step, open) {
53
+ if (!open)
54
+ return false;
55
+ events.push({ type: 'step/end', data: { turn, step } });
56
+ events.push({ type: 'turn/end', data: { turn, reason: { kind: 'completed' } } });
57
+ return true;
58
+ }
59
+ /**
60
+ * Import a Codex session JSONL (lines of `response_item` records) as a trace.
61
+ * @param text - the Codex log's UTF-8 text.
62
+ * @param source - the source file path, used for the synthetic session id.
63
+ * @returns the imported trace; non-`response_item` lines are skipped.
64
+ */
65
+ export function importCodexLog(text, source) {
66
+ const events = [];
67
+ let turn = 0;
68
+ let step = 0;
69
+ let open = false;
70
+ let callCounter = 0;
71
+ let messageCounter = 0;
72
+ const close = () => {
73
+ open = closeTurn(events, turn, step, open);
74
+ };
75
+ for (const line of text.split(/\r?\n/u)) {
76
+ if (line.trim() === '')
77
+ continue;
78
+ let record;
79
+ try {
80
+ record = JSON.parse(line);
81
+ }
82
+ catch {
83
+ continue;
84
+ }
85
+ if (typeof record !== 'object' || record === null)
86
+ continue;
87
+ const row = record;
88
+ if (row.type !== 'response_item' || typeof row.payload !== 'object' || row.payload === null)
89
+ continue;
90
+ const payload = row.payload;
91
+ if (payload.type === 'message' && payload.role === 'user') {
92
+ close();
93
+ turn += 1;
94
+ step = 0;
95
+ open = true;
96
+ messageCounter += 1;
97
+ events.push({ type: 'turn/start', data: { turn } });
98
+ events.push({
99
+ type: 'user/message',
100
+ data: {
101
+ id: `user-${messageCounter}`,
102
+ role: 'user',
103
+ content: [{ type: 'text', text: textOf(payload.content) }],
104
+ source: { kind: 'user' },
105
+ },
106
+ });
107
+ events.push({ type: 'step/start', data: { turn, step } });
108
+ }
109
+ else if (payload.type === 'message' && payload.role === 'assistant') {
110
+ messageCounter += 1;
111
+ events.push({
112
+ type: 'assistant/message',
113
+ data: {
114
+ turn,
115
+ step,
116
+ message: {
117
+ id: `assistant-${messageCounter}`,
118
+ role: 'assistant',
119
+ content: [{ type: 'text', text: textOf(payload.content) }],
120
+ source: { kind: 'model' },
121
+ },
122
+ },
123
+ });
124
+ }
125
+ else if (payload.type === 'function_call') {
126
+ callCounter += 1;
127
+ const callId = typeof payload.call_id === 'string' ? payload.call_id : `codex-call-${callCounter}`;
128
+ const name = typeof payload.name === 'string' ? payload.name : 'tool';
129
+ const argumentsText = typeof payload.arguments === 'string' ? payload.arguments : '{}';
130
+ events.push({ type: 'tool/call', data: { turn, step, callId, name, arguments: argumentsText } });
131
+ }
132
+ else if (payload.type === 'function_call_output') {
133
+ callCounter += 1;
134
+ const callId = typeof payload.call_id === 'string' ? payload.call_id : `codex-call-${callCounter}`;
135
+ const output = textOf(payload.output ?? payload.content);
136
+ events.push({
137
+ type: 'tool/result',
138
+ data: {
139
+ turn,
140
+ step,
141
+ message: {
142
+ id: `tool-result-${callCounter}`,
143
+ role: 'user',
144
+ content: [{ type: 'tool-result', text: output, isError: payload.is_error === true }],
145
+ source: { kind: 'tool', callId },
146
+ },
147
+ },
148
+ });
149
+ }
150
+ }
151
+ close();
152
+ return assembleTrace(events, sessionIdFrom(source));
153
+ }
154
+ /** Whether a Claude Code user message carries only tool results (not a new turn). */
155
+ function isToolResultUser(content) {
156
+ if (!Array.isArray(content))
157
+ return false;
158
+ return content.every(block => typeof block === 'object' && block !== null && block.type === 'tool_result');
159
+ }
160
+ /**
161
+ * Import a Claude Code session JSONL (lines of `user`/`assistant` records) as
162
+ * a trace.
163
+ * @param text - the Claude Code log's UTF-8 text.
164
+ * @param source - the source file path, used for the synthetic session id.
165
+ * @returns the imported trace; non-user/assistant lines are skipped.
166
+ */
167
+ export function importClaudeLog(text, source) {
168
+ const events = [];
169
+ let turn = 0;
170
+ let step = 0;
171
+ let open = false;
172
+ let messageCounter = 0;
173
+ const close = () => {
174
+ open = closeTurn(events, turn, step, open);
175
+ };
176
+ for (const line of text.split(/\r?\n/u)) {
177
+ if (line.trim() === '')
178
+ continue;
179
+ let record;
180
+ try {
181
+ record = JSON.parse(line);
182
+ }
183
+ catch {
184
+ continue;
185
+ }
186
+ if (typeof record !== 'object' || record === null)
187
+ continue;
188
+ const row = record;
189
+ if ((row.type !== 'user' && row.type !== 'assistant')
190
+ || typeof row.message !== 'object' || row.message === null)
191
+ continue;
192
+ const message = row.message;
193
+ const content = message.content;
194
+ if (row.type === 'user' && !isToolResultUser(content)) {
195
+ close();
196
+ turn += 1;
197
+ step = 0;
198
+ open = true;
199
+ messageCounter += 1;
200
+ events.push({ type: 'turn/start', data: { turn } });
201
+ events.push({
202
+ type: 'user/message',
203
+ data: {
204
+ id: `user-${messageCounter}`,
205
+ role: 'user',
206
+ content: [{ type: 'text', text: textOf(content) }],
207
+ source: { kind: 'user' },
208
+ },
209
+ });
210
+ events.push({ type: 'step/start', data: { turn, step } });
211
+ continue;
212
+ }
213
+ if (row.type === 'assistant') {
214
+ if (typeof content === 'string') {
215
+ messageCounter += 1;
216
+ events.push({
217
+ type: 'assistant/message',
218
+ data: {
219
+ turn,
220
+ step,
221
+ message: {
222
+ id: `assistant-${messageCounter}`,
223
+ role: 'assistant',
224
+ content: [{ type: 'text', text: content }],
225
+ source: { kind: 'model' },
226
+ },
227
+ },
228
+ });
229
+ }
230
+ else {
231
+ for (const block of Array.isArray(content) ? content : []) {
232
+ if (typeof block !== 'object' || block === null)
233
+ continue;
234
+ const item = block;
235
+ if (item.type === 'text') {
236
+ messageCounter += 1;
237
+ events.push({
238
+ type: 'assistant/message',
239
+ data: {
240
+ turn,
241
+ step,
242
+ message: {
243
+ id: `assistant-${messageCounter}`,
244
+ role: 'assistant',
245
+ content: [{ type: 'text', text: typeof item.text === 'string' ? item.text : '' }],
246
+ source: { kind: 'model' },
247
+ },
248
+ },
249
+ });
250
+ }
251
+ else if (item.type === 'tool_use') {
252
+ const callId = typeof item.id === 'string' ? item.id : `claude-call-${messageCounter}`;
253
+ const name = typeof item.name === 'string' ? item.name : 'tool';
254
+ const argumentsText = JSON.stringify(item.input ?? {});
255
+ events.push({ type: 'tool/call', data: { turn, step, callId, name, arguments: argumentsText } });
256
+ }
257
+ }
258
+ }
259
+ continue;
260
+ }
261
+ // Reaching here means a tool-result user message: the plain-user branch
262
+ // above already excluded non-tool-result content.
263
+ const blocks = content;
264
+ for (const item of blocks) {
265
+ const callId = typeof item.tool_use_id === 'string' ? item.tool_use_id : `claude-call-${messageCounter}`;
266
+ events.push({
267
+ type: 'tool/result',
268
+ data: {
269
+ turn,
270
+ step,
271
+ message: {
272
+ id: `tool-result-${messageCounter}`,
273
+ role: 'user',
274
+ content: [{ type: 'tool-result', text: textOf(item.content), isError: item.is_error === true }],
275
+ source: { kind: 'tool', callId },
276
+ },
277
+ },
278
+ });
279
+ }
280
+ }
281
+ close();
282
+ return assembleTrace(events, sessionIdFrom(source));
283
+ }
284
+ /**
285
+ * Load an external session log and build a one-trial run record from it.
286
+ * @param format - the external harness format.
287
+ * @param path - the session JSONL path.
288
+ * @param caseId - the imported trial's case id.
289
+ * @returns the run record with one completed trial.
290
+ */
291
+ export async function importTraceFile(format, path, caseId) {
292
+ const absolute = resolve(path);
293
+ const text = await readFile(absolute, 'utf8');
294
+ const trace = format === 'codex'
295
+ ? importCodexLog(text, absolute)
296
+ : importClaudeLog(text, absolute);
297
+ const metrics = computeMetrics(trace.events, undefined);
298
+ return {
299
+ benchmark: `import:${format}`,
300
+ model: 'imported',
301
+ createdAt: Date.now(),
302
+ trials: 1,
303
+ seed: 0,
304
+ pricing: null,
305
+ tempRoot: dirname(absolute),
306
+ cases: [{
307
+ caseId,
308
+ trial: 1,
309
+ status: 'completed',
310
+ tracePath: absolute,
311
+ exitCode: null,
312
+ timedOut: false,
313
+ metrics,
314
+ }],
315
+ aggregate: metrics,
316
+ grading: null,
317
+ };
318
+ }
package/lib/index.js 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
@@ -14,6 +14,7 @@
14
14
  import { loadBenchmark } from "./benchmark.js";
15
15
  import { applyEval } from "./command.js";
16
16
  import { compareRuns, renderCompareMarkdown } from "./compare.js";
17
+ import { importTraceFile } from "./import.js";
17
18
  import { llmJudgeChat } from "./judge.js";
18
19
  import { renderMarkdownReport, writeRunReport, loadRunReport } from "./report.js";
19
20
  import { runBenchmark } from "./runner.js";
@@ -62,6 +63,12 @@ function summary(run) {
62
63
  */
63
64
  export async function executeEval(values, io, services = {}) {
64
65
  try {
66
+ if (values.kind === 'import') {
67
+ const run = await importTraceFile(values.format, values.path, values.caseId);
68
+ await writeRunReport(run, values.outPath);
69
+ io.stdout.write(`Wrote ${values.outPath} (1 imported trial, ${summary(run)})\n`);
70
+ return 0;
71
+ }
65
72
  if (values.kind === 'report') {
66
73
  const run = await loadRunReport(values.runPath);
67
74
  io.stdout.write(renderMarkdownReport(run));
package/lib/judge.js ADDED
@@ -0,0 +1,165 @@
1
+ /**
2
+ * LLM-judge scoring for dsh-eval: builds a judging prompt from the case and
3
+ * its trace, calls an injected chat seam, and parses the model's strict-JSON
4
+ * verdict into a final-answer score and hallucination flag. The production
5
+ * seam wraps the dsh-llm stream API; tests inject a fake so the suite stays
6
+ * keyless.
7
+ *
8
+ * @module dsh-eval/judge
9
+ */
10
+ import { BlockAssembler, createMessage } from '@deepseek-ai/dsh-llm';
11
+ /** Concatenate one message's text blocks. */
12
+ function blockText(blocks) {
13
+ return blocks.flatMap(block => block.type === 'text' ? [block.text] : []).join('');
14
+ }
15
+ /**
16
+ * Summarize a trace for the judge: final assistant answer, the distinct tool
17
+ * names called, and the failure counters a hallucination call needs.
18
+ * @param trace - the merged trial trace.
19
+ * @returns a compact human-readable summary.
20
+ */
21
+ export function summarizeTrace(trace) {
22
+ let finalAnswer = '';
23
+ const toolNames = [];
24
+ let invalidToolCalls = 0;
25
+ let retries = 0;
26
+ for (const event of trace.events) {
27
+ if (event.type === 'assistant/message')
28
+ finalAnswer = blockText(event.data.message.content);
29
+ if (event.type === 'tool/call') {
30
+ if (!toolNames.includes(event.data.name))
31
+ toolNames.push(event.data.name);
32
+ }
33
+ if (event.type === 'tool/result' && event.data.error !== undefined)
34
+ invalidToolCalls += 1;
35
+ if (event.type === 'llm/retry')
36
+ retries += 1;
37
+ }
38
+ return [
39
+ `final answer: ${finalAnswer === '' ? '(none)' : finalAnswer}`,
40
+ `tools called: ${toolNames.length === 0 ? '(none)' : toolNames.join(', ')}`,
41
+ `invalid tool calls: ${invalidToolCalls}`,
42
+ `llm retries: ${retries}`,
43
+ ].join('\n');
44
+ }
45
+ /**
46
+ * Build the judge's system instructions and task prompt.
47
+ * @param caseValue - the benchmark case being judged.
48
+ * @param trace - the merged trial trace.
49
+ * @param judge - the judge configuration.
50
+ * @returns the system and prompt texts.
51
+ */
52
+ export function buildJudgePrompt(caseValue, trace, judge) {
53
+ const system = [
54
+ 'You are an impartial evaluation judge for agent task completion.',
55
+ `Score the agent's final answer from 0 to ${judge.maxScore} against the task,`,
56
+ 'and set "hallucination" to true only when the final answer asserts facts',
57
+ 'not supported by the task or the trace.',
58
+ 'Return STRICT JSON with exactly these fields:',
59
+ `{"finalAnswerScore": <integer 0..${judge.maxScore}>, "hallucination": <true|false>, "rationale": "<one short sentence>"}`,
60
+ ...(judge.rubric !== undefined ? ['Rubric:', judge.rubric] : []),
61
+ ].join('\n');
62
+ const prompt = [
63
+ `Task id: ${caseValue.id}`,
64
+ `Task: ${caseValue.prompt}`,
65
+ 'Trace summary:',
66
+ summarizeTrace(trace),
67
+ ].join('\n');
68
+ return { system, prompt };
69
+ }
70
+ /** Extract the JSON object from a model reply, accepting fenced output. */
71
+ function parseJsonObject(text) {
72
+ const cleaned = text.trim();
73
+ const fenced = cleaned.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/u);
74
+ const candidate = fenced?.[1] ?? cleaned;
75
+ try {
76
+ const value = JSON.parse(candidate);
77
+ return typeof value === 'object' && value !== null
78
+ ? value
79
+ : null;
80
+ }
81
+ catch {
82
+ return null;
83
+ }
84
+ }
85
+ /**
86
+ * Parse the judge model's strict-JSON reply into a verdict. Unusable output
87
+ * yields null fields, never a fabricated verdict.
88
+ * @param text - the raw model reply.
89
+ * @param maxScore - the configured maximum score.
90
+ * @returns the parsed verdict.
91
+ */
92
+ export function parseJudgeVerdict(text, maxScore) {
93
+ const value = parseJsonObject(text);
94
+ if (value === null)
95
+ return { finalAnswerScore: null, hallucination: null };
96
+ const score = value.finalAnswerScore;
97
+ const hallucination = value.hallucination;
98
+ const rationale = value.rationale;
99
+ const finalAnswerScore = typeof score === 'number' && Number.isFinite(score) && score >= 0 && score <= maxScore
100
+ ? score
101
+ : null;
102
+ const parsedHallucination = typeof hallucination === 'boolean' ? hallucination : null;
103
+ const parsedRationale = typeof rationale === 'string' && rationale.trim() !== '' ? rationale : undefined;
104
+ return {
105
+ finalAnswerScore,
106
+ hallucination: parsedHallucination,
107
+ ...(parsedRationale !== undefined ? { rationale: parsedRationale } : {}),
108
+ };
109
+ }
110
+ /**
111
+ * Judge one trial through the chat seam.
112
+ * @param caseValue - the benchmark case being judged.
113
+ * @param trace - the merged trial trace.
114
+ * @param judge - the judge configuration.
115
+ * @param chat - the injected chat seam.
116
+ * @returns the parsed verdict; a chat failure rejects.
117
+ */
118
+ export async function judgeTrial(caseValue, trace, judge, chat) {
119
+ const { system, prompt } = buildJudgePrompt(caseValue, trace, judge);
120
+ return parseJudgeVerdict(await chat({ provider: judge.provider, model: judge.model, system, prompt }), judge.maxScore);
121
+ }
122
+ /**
123
+ * Judge one trial, converting a chat failure into an all-null verdict so a
124
+ * judge outage reads as unjudged rather than a failed trial.
125
+ * @param caseValue - the benchmark case being judged.
126
+ * @param trace - the merged trial trace.
127
+ * @param judge - the judge configuration.
128
+ * @param chat - the injected chat seam.
129
+ * @returns the parsed verdict, or all-null when the chat call threw.
130
+ */
131
+ export async function tryJudgeTrial(caseValue, trace, judge, chat) {
132
+ try {
133
+ return await judgeTrial(caseValue, trace, judge, chat);
134
+ }
135
+ catch {
136
+ return { finalAnswerScore: null, hallucination: null };
137
+ }
138
+ }
139
+ /**
140
+ * Build the production chat seam over a dsh-llm stream: one user turn, zero
141
+ * temperature, and text-block assembly of the reply.
142
+ * @param stream - the llm service's stream method.
143
+ * @returns a chat seam reading only text blocks from the stream.
144
+ */
145
+ export function llmJudgeChat(stream) {
146
+ return async (request) => {
147
+ const assembler = new BlockAssembler();
148
+ for await (const chunk of stream({
149
+ provider: request.provider,
150
+ model: request.model,
151
+ system: request.system,
152
+ messages: [createMessage({
153
+ role: 'user',
154
+ content: [{ type: 'text', text: request.prompt }],
155
+ source: { kind: 'user' },
156
+ })],
157
+ temperature: 0,
158
+ })) {
159
+ assembler.push(chunk);
160
+ }
161
+ return assembler.message().content
162
+ .flatMap(block => block.type === 'text' ? [block.text] : [])
163
+ .join('');
164
+ };
165
+ }