@linxin666/dsh-liangshen 0.3.21 → 0.3.22

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,771 @@
1
+ /**
2
+ * One bounded live benchmark run: a real DeepSeek session driven through the
3
+ * profile's own composition, with the evaluated preset supplied from an
4
+ * ISOLATED preset root.
5
+ *
6
+ * Isolation rules this script follows:
7
+ * - The harness home stays the real one, so credentials, settings, and the model
8
+ * route resolve exactly as they do for a user session. Nothing is copied or read
9
+ * by this script.
10
+ * - The evaluated preset is written to a temporary root and selected through the
11
+ * roster's own `roots` config, so the shipped/user roots cannot shadow it and no
12
+ * installed preset is edited.
13
+ * - Session persistence is redirected into the run directory, so real session
14
+ * history is never appended to.
15
+ *
16
+ * The candidate matrix follows the LiangShen V4.1 Flash improvement plan:
17
+ * B (current persona), P (candidate persona), T (candidate persona + PTC from the
18
+ * first turn), N (candidate persona + native tools throughout), and M (the
19
+ * official bundle's Minimal preset as an external reference). Persona wording and
20
+ * tool strategy vary independently, and a run records the baseline it ran against
21
+ * so an aggregated report can attribute a difference to one factor.
22
+ *
23
+ * Usage:
24
+ * node tools/benchmark-live-run.mjs --variant B [--timeout 300000] [--keep]
25
+ * node tools/benchmark-live-run.mjs --tasks tools/tasks/liangshen-v41-flash.json --groups B,P,T,N,M --repeat 3 --max-sessions 60 --budget-usd 5 --out .benchmark-results
26
+ */
27
+
28
+ import { execFileSync, spawn } from 'node:child_process'
29
+ import { createHash } from 'node:crypto'
30
+ import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
31
+ import { createRequire } from 'node:module'
32
+ import { tmpdir } from 'node:os'
33
+ import { dirname, join, relative, resolve, sep } from 'node:path'
34
+ import { fileURLToPath } from 'node:url'
35
+
36
+ const HERE = dirname(fileURLToPath(import.meta.url))
37
+ const PACKAGE_ROOT = resolve(HERE, '..')
38
+ const PRESET_SOURCE = join(PACKAGE_ROOT, 'presets', 'liangshen')
39
+ const DRIVER = join(HERE, 'benchmark-driver.mjs').replace(/\\/g, '/')
40
+ const require = createRequire(import.meta.url)
41
+
42
+ /** Fixed route every variant runs on, so the comparison isolates the preset. */
43
+ export const FIXED_ROUTE = { provider: 'deepseek-official', model: 'deepseek-flash', reasoningEffort: 'max' }
44
+
45
+ /** The two turns the protocol smoke check uses: an anchored exploration, then a promoted mutation. */
46
+ export const DEFAULT_TURNS = [
47
+ 'List the files in the current directory with the shell, then reply DONE and stop.',
48
+ 'Create a file named hello.txt whose only content is OK, then reply DONE and stop.',
49
+ ]
50
+
51
+ /**
52
+ * The candidate persona for groups P/T/N. It keeps the identity line and replaces
53
+ * the shipped discipline: no ban on reasoning through concrete implementation, a
54
+ * loop exits by changing method or using a tool instead of stopping, and PDCA is
55
+ * expressed as inspect, smallest sufficient change, verify.
56
+ */
57
+ export const CANDIDATE_PERSONA = [
58
+ 'You are a helpful software engineer assistant.',
59
+ '',
60
+ 'Understand the task and inspect relevant files before making changes.',
61
+ 'Make the smallest change that satisfies the requirements and workspace instructions.',
62
+ 'Reason as deeply as needed, avoiding repetition without new evidence.',
63
+ 'Use tools to test uncertain assumptions and verify the result.',
64
+ 'Preserve existing comments and explain non-obvious behavior where necessary.',
65
+ 'Finish when the requested outcome is verified; report remaining limitations.',
66
+ ].join('\n')
67
+
68
+ /**
69
+ * Variant definitions: what changes in the evaluated preset copy. `persona` picks
70
+ * the prompt wording, `anchors` the staged tool surface (`null` keeps the shipped
71
+ * default, an empty list disables staging), `ptc` the presentation after the
72
+ * boundary, and `official` selects the bundle's Minimal preset untouched.
73
+ */
74
+ export const LIVE_VARIANTS = {
75
+ B: {
76
+ persona: 'current',
77
+ anchors: null,
78
+ ptc: true,
79
+ note: 'baseline: shipped persona, four-tool anchor, PTC after the boundary',
80
+ },
81
+ P: {
82
+ persona: 'candidate',
83
+ anchors: null,
84
+ ptc: true,
85
+ note: 'candidate persona, four-tool anchor, PTC after the boundary',
86
+ },
87
+ T: {
88
+ persona: 'candidate',
89
+ anchors: [],
90
+ ptc: true,
91
+ note: 'candidate persona, PTC from the first turn',
92
+ },
93
+ N: {
94
+ persona: 'candidate',
95
+ anchors: [],
96
+ ptc: false,
97
+ note: 'candidate persona, full native roster throughout',
98
+ },
99
+ M: {
100
+ persona: 'minimal',
101
+ anchors: null,
102
+ ptc: null,
103
+ official: true,
104
+ note: 'external reference: the official Minimal preset, official configuration',
105
+ },
106
+ }
107
+
108
+ /** Build the exact cmd.exe argument vector for a trusted .cmd shim. */
109
+ function windowsCmdShimArgs(binary, args) {
110
+ const unsafe = /[&|<>"'`%!\n\r\0]/
111
+ if (/["%\n\r\0]/.test(binary) || args.some((arg) => unsafe.test(arg))) {
112
+ throw new Error('benchmark: unsafe Windows command argument')
113
+ }
114
+ const commandLine = '""' + binary + '" ' + args.map((arg) => '"' + arg + '"').join(' ') + '"'
115
+ return ['/d', '/s', '/c', commandLine]
116
+ }
117
+
118
+ /** Spawn one process, capturing output, with a hard timeout. */
119
+ function spawnCaptured(command, args, options, timeoutMs) {
120
+ return new Promise((resolveResult) => {
121
+ const child = spawn(command, args, { ...options, stdio: ['ignore', 'pipe', 'pipe'] })
122
+ let stdout = ''
123
+ let stderr = ''
124
+ let timedOut = false
125
+ const timer = setTimeout(() => {
126
+ timedOut = true
127
+ child.kill('SIGKILL')
128
+ }, timeoutMs)
129
+ child.stdout.on('data', (chunk) => { stdout += chunk.toString() })
130
+ child.stderr.on('data', (chunk) => { stderr += chunk.toString() })
131
+ child.on('error', (error) => {
132
+ clearTimeout(timer)
133
+ resolveResult({ code: null, stdout, stderr: stderr + String(error), timedOut })
134
+ })
135
+ child.on('close', (code) => {
136
+ clearTimeout(timer)
137
+ resolveResult({ code, stdout, stderr, timedOut })
138
+ })
139
+ })
140
+ }
141
+
142
+ /** The directory the installed bundle publishes the official Minimal preset in. */
143
+ export function officialMinimalPresetDir() {
144
+ try {
145
+ const pkg = require.resolve('@deepseek-ai/dsh-agent-presets/package.json')
146
+ return join(dirname(pkg), 'presets', 'minimal')
147
+ } catch (error) {
148
+ throw new Error(`benchmark: the official Minimal preset is unavailable: ${error instanceof Error ? error.message : String(error)}`)
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Content hash of every file under one preset directory, so a run records the
154
+ * exact evaluated source instead of a path that a later edit could change.
155
+ */
156
+ export function hashTree(dir) {
157
+ const files = []
158
+ const walk = (current) => {
159
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
160
+ const full = join(current, entry.name)
161
+ if (entry.isDirectory()) walk(full)
162
+ else if (entry.isFile()) files.push(full)
163
+ }
164
+ }
165
+ walk(dir)
166
+ files.sort()
167
+ const hash = createHash('sha256')
168
+ for (const file of files) {
169
+ hash.update(relative(dir, file).split(sep).join('/'))
170
+ hash.update('\0')
171
+ hash.update(readFileSync(file))
172
+ hash.update('\0')
173
+ }
174
+ return hash.digest('hex')
175
+ }
176
+
177
+ /**
178
+ * Replace the persona block scalar with candidate wording, matching only the
179
+ * `prefix: |-` scalar and leaving every other composition row untouched.
180
+ */
181
+ export function replacePersonaPrefix(text, persona) {
182
+ const lines = text.split('\n')
183
+ const start = lines.findIndex((line) => /^\s*prefix: \|-\s*$/.test(line))
184
+ if (start < 0) throw new Error('benchmark: the preset composition carries no persona prefix scalar to vary')
185
+ const bodyIndent = lines[start].match(/^(\s*)/)[1] + ' '
186
+ let end = start + 1
187
+ while (end < lines.length) {
188
+ const line = lines[end]
189
+ if (line.trim() === '' || line.startsWith(bodyIndent)) { end += 1; continue }
190
+ break
191
+ }
192
+ let blockEnd = end
193
+ while (blockEnd > start + 1 && lines[blockEnd - 1].trim() === '') blockEnd -= 1
194
+ const replacement = persona.split('\n').map((line) => bodyIndent + line)
195
+ return [...lines.slice(0, start + 1), ...replacement, ...lines.slice(blockEnd)].join('\n')
196
+ }
197
+
198
+ /** Copy the preset and apply the variant's configuration change. */
199
+ export function materializePreset(root, variantId, variant) {
200
+ const target = join(root, variantId)
201
+ cpSync(variant.official === true ? officialMinimalPresetDir() : PRESET_SOURCE, target, { recursive: true })
202
+ if (variant.official === true) return target
203
+ const composition = join(target, 'agent.cordis.yml')
204
+ if (variant.anchors !== null && variant.anchors !== undefined) {
205
+ const text = readFileSync(composition, 'utf8')
206
+ // Anchor on the config line: the composition also NAMES `anchorTools: [bash]`
207
+ // inside its prose, and rewriting a comment would leave the real surface alone.
208
+ const replaced = text.replace(/^(\s*)anchorTools: \[[^\]]*\]/m, `$1anchorTools: [${variant.anchors.join(', ')}]`)
209
+ if (replaced === text) throw new Error('benchmark: the preset composition carries no anchorTools line to vary')
210
+ writeFileSync(composition, replaced)
211
+ }
212
+ if (variant.ptc === false) {
213
+ const text = readFileSync(composition, 'utf8')
214
+ const replaced = text.replace(/ptcPresentation: true/, 'ptcPresentation: false')
215
+ if (replaced === text) throw new Error('benchmark: the preset composition carries no ptcPresentation line to vary')
216
+ writeFileSync(composition, replaced)
217
+ }
218
+ if (variant.persona === 'candidate') {
219
+ const text = readFileSync(composition, 'utf8')
220
+ writeFileSync(composition, replacePersonaPrefix(text, CANDIDATE_PERSONA))
221
+ }
222
+ return target
223
+ }
224
+
225
+ /** Every session log under one root, newest last. */
226
+ function sessionLogs(root) {
227
+ const found = []
228
+ const walk = (dir) => {
229
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
230
+ const full = join(dir, entry.name)
231
+ if (entry.isDirectory()) walk(full)
232
+ else if (entry.name.endsWith('.jsonl')) found.push(full)
233
+ }
234
+ }
235
+ if (existsSync(root)) walk(root)
236
+ return found.sort((a, b) => statSync(a).mtimeMs - statSync(b).mtimeMs)
237
+ }
238
+
239
+ /** A non-negative safe integer token count, or undefined for anything else. */
240
+ function countOf(value) {
241
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined
242
+ }
243
+
244
+ /**
245
+ * Provider-reported token totals across one session's attempts, reading the usage
246
+ * chunks the harness records on assistant messages. One event contributes its
247
+ * stream usage or its message usage, never both, so an attempt is not double-counted.
248
+ */
249
+ export function summarizeUsage(events) {
250
+ const totals = {
251
+ attempts: 0,
252
+ inputTokens: 0,
253
+ outputTokens: 0,
254
+ cacheReadTokens: 0,
255
+ cacheWriteTokens: 0,
256
+ reasoningTokens: 0,
257
+ totalTokens: 0,
258
+ }
259
+ const add = (usage) => {
260
+ if (usage === null || typeof usage !== 'object') return false
261
+ const input = countOf(usage.inputTokens)
262
+ const output = countOf(usage.outputTokens)
263
+ if (input === undefined && output === undefined) return false
264
+ totals.attempts += 1
265
+ totals.inputTokens += input ?? 0
266
+ totals.outputTokens += output ?? 0
267
+ totals.cacheReadTokens += countOf(usage.cacheReadTokens) ?? 0
268
+ totals.cacheWriteTokens += countOf(usage.cacheWriteTokens) ?? 0
269
+ totals.reasoningTokens += countOf(usage.reasoningTokens) ?? 0
270
+ totals.totalTokens += countOf(usage.totalTokens) ?? ((input ?? 0) + (output ?? 0))
271
+ return true
272
+ }
273
+ for (const event of events) {
274
+ if (event?.type !== 'assistant/message' && event?.type !== 'assistant/attempt') continue
275
+ let seen = false
276
+ if (Array.isArray(event.data?.stream)) {
277
+ for (const chunk of event.data.stream) {
278
+ if (chunk?.type === 'usage' && add(chunk.usage)) seen = true
279
+ }
280
+ }
281
+ if (!seen && !add(event.data?.message?.usage)) add(event.data?.usage)
282
+ }
283
+ return { ...totals, uncachedInputTokens: totals.inputTokens }
284
+ }
285
+
286
+ /**
287
+ * Read one session log into the evidence the comparison actually needs.
288
+ *
289
+ * The durable shapes this reads are the ones the harness writes:
290
+ * `request/header` carries `data.header.{config,tools}` (the real route and the
291
+ * exact wire surface of that request), `system/message` carries
292
+ * `data.message.content[].text` (the assembled system prompt of that turn), and
293
+ * `assistant/message` carries the provider usage chunks.
294
+ */
295
+ export function summarizeSession(logPath) {
296
+ const lines = readFileSync(logPath, 'utf8').split('\n').filter((line) => line.trim() !== '')
297
+ const events = lines.map((line) => { try { return JSON.parse(line) } catch { return null } }).filter(Boolean)
298
+
299
+ const requests = events.filter((event) => event.type === 'request/header').map((event) => {
300
+ const header = event.data?.header ?? {}
301
+ const config = header.config ?? {}
302
+ return {
303
+ seq: event.seq,
304
+ provider: config.provider,
305
+ model: config.model,
306
+ reasoningEffort: config.reasoningEffort,
307
+ tools: Array.isArray(header.tools) ? header.tools.map((tool) => tool?.name).filter(Boolean) : [],
308
+ }
309
+ })
310
+
311
+ const prompts = events.filter((event) => event.type === 'system/message').map((event) => {
312
+ const blocks = Array.isArray(event.data?.message?.content) ? event.data.message.content : []
313
+ const text = blocks.filter((block) => block?.type === 'text').map((block) => block.text).join('\n')
314
+ return {
315
+ turn: event.data?.turn,
316
+ step: event.data?.step,
317
+ chars: text.length,
318
+ carriesPersona: text.includes('You are a helpful software engineer assistant.'),
319
+ carriesWorkspaceLine: text.includes('Your working directory is '),
320
+ carriesWorkspaceInstructions: text.includes('Instructions from:'),
321
+ carriesSdkSection: text.includes('declare const tools') || text.includes('ToolArgsMap'),
322
+ carriesPtcRule: text.includes('run_code'),
323
+ }
324
+ })
325
+
326
+ const toolCallsByName = {}
327
+ for (const event of events) {
328
+ if (event.type !== 'tool/call') continue
329
+ const toolName = event.data?.name
330
+ if (typeof toolName === 'string' && toolName !== '') {
331
+ toolCallsByName[toolName] = (toolCallsByName[toolName] ?? 0) + 1
332
+ }
333
+ }
334
+
335
+ return {
336
+ requests,
337
+ prompts,
338
+ usage: summarizeUsage(events),
339
+ ptcDispatches: events.filter((event) => event.type === 'tool/ptc-dispatch').length,
340
+ toolCalls: events.filter((event) => event.type === 'tool/call').length,
341
+ toolCallsByName,
342
+ toolErrors: events.filter((event) => event.type === 'tool/result' && event.data?.error !== undefined).length,
343
+ approvalsAsked: events.filter((event) => event.type === 'approval/asked').length,
344
+ humanInterventions: toolCallsByName.ask_user_question ?? 0,
345
+ }
346
+ }
347
+
348
+ const EMPTY_EVIDENCE = {
349
+ requests: [],
350
+ prompts: [],
351
+ usage: {
352
+ attempts: 0,
353
+ inputTokens: 0,
354
+ outputTokens: 0,
355
+ cacheReadTokens: 0,
356
+ cacheWriteTokens: 0,
357
+ reasoningTokens: 0,
358
+ totalTokens: 0,
359
+ uncachedInputTokens: 0,
360
+ },
361
+ ptcDispatches: 0,
362
+ toolCalls: 0,
363
+ toolCallsByName: {},
364
+ toolErrors: 0,
365
+ approvalsAsked: 0,
366
+ humanInterventions: 0,
367
+ }
368
+
369
+ /** One git fact for the baseline record, or null when git is unavailable. */
370
+ function gitValue(args) {
371
+ try {
372
+ return execFileSync('git', args, { cwd: PACKAGE_ROOT, encoding: 'utf8' }).trim()
373
+ } catch {
374
+ return null
375
+ }
376
+ }
377
+
378
+ /** The installed CLI version, read without touching the running DSH service. */
379
+ async function dshVersion() {
380
+ const spec = process.platform === 'win32'
381
+ ? { command: 'cmd.exe', args: windowsCmdShimArgs('dsh', ['--version']), windowsVerbatimArguments: true }
382
+ : { command: 'dsh', args: ['--version'] }
383
+ try {
384
+ const result = await spawnCaptured(spec.command, spec.args, {}, 15000)
385
+ const line = `${result.stdout}\n${result.stderr}`.split(/\r?\n/).map((entry) => entry.trim()).find((entry) => entry !== '')
386
+ return line ?? null
387
+ } catch {
388
+ return null
389
+ }
390
+ }
391
+
392
+ /**
393
+ * The reproducible environment a comparison is only valid within: repository
394
+ * commit, shipped preset source, DSH version, route, platform, and the limits the
395
+ * suite was allowed to spend.
396
+ */
397
+ export async function collectBaseline() {
398
+ return {
399
+ recordedAt: new Date().toISOString(),
400
+ repository: { commit: gitValue(['rev-parse', 'HEAD']), dirty: gitValue(['status', '--porcelain']) },
401
+ presetSource: PRESET_SOURCE,
402
+ presetSourceHash: hashTree(PRESET_SOURCE),
403
+ dshVersion: await dshVersion(),
404
+ route: { ...FIXED_ROUTE },
405
+ platform: process.platform,
406
+ node: process.version,
407
+ }
408
+ }
409
+
410
+ /** Load a task corpus file (`{ version, tasks: [...] }`). */
411
+ export function loadTaskFile(path) {
412
+ const parsed = JSON.parse(readFileSync(path, 'utf8'))
413
+ if (!Array.isArray(parsed?.tasks) || parsed.tasks.length === 0) {
414
+ throw new Error(`benchmark: ${path} carries no tasks array`)
415
+ }
416
+ for (const task of parsed.tasks) {
417
+ if (typeof task?.id !== 'string' || !Array.isArray(task?.turns) || typeof task?.check !== 'string') {
418
+ throw new Error(`benchmark: task ${JSON.stringify(task?.id)} needs an id, turns, and a check`)
419
+ }
420
+ }
421
+ return parsed
422
+ }
423
+
424
+ /** The task corpus revision a report is only valid within. */
425
+ export function taskRevision(corpus) {
426
+ if (corpus === undefined) return null
427
+ return {
428
+ id: corpus.id ?? null,
429
+ version: corpus.version ?? null,
430
+ tasks: corpus.tasks.length,
431
+ hash: createHash('sha256').update(JSON.stringify(corpus.tasks)).digest('hex'),
432
+ }
433
+ }
434
+
435
+ /** Write a task's seed files into a fresh workspace. */
436
+ function writeTaskFiles(workspace, files) {
437
+ for (const [name, content] of Object.entries(files ?? {})) {
438
+ const target = join(workspace, name)
439
+ mkdirSync(dirname(target), { recursive: true })
440
+ writeFileSync(target, String(content), 'utf8')
441
+ }
442
+ }
443
+
444
+ /**
445
+ * Run one task's acceptance check in the workspace. The check is a Node module
446
+ * body, so a task never depends on a platform shell's quoting rules.
447
+ */
448
+ export async function evaluateCheck(workspace, check, timeoutMs = 120000) {
449
+ const result = await spawnCaptured(
450
+ process.execPath,
451
+ ['--input-type=module', '-e', check],
452
+ { cwd: workspace },
453
+ timeoutMs,
454
+ )
455
+ return {
456
+ passed: result.code === 0 && !result.timedOut,
457
+ exitCode: result.code,
458
+ timedOut: result.timedOut,
459
+ stderrTail: result.stderr.split('\n').filter((line) => line.trim() !== '').slice(-6).join('\n'),
460
+ }
461
+ }
462
+
463
+ /** Whether a value is a usable per-million price rate. */
464
+ function isRate(value) {
465
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0
466
+ }
467
+
468
+ /** The price entry a route resolves to, keyed "provider/model" or by bare model. */
469
+ export function routePrices(prices, route) {
470
+ if (prices === null || prices === undefined) return undefined
471
+ return prices[route.provider + '/' + route.model] ?? prices[route.model]
472
+ }
473
+
474
+ /**
475
+ * Validate a price entry before a run spends anything. A missing or non-numeric
476
+ * rate would otherwise silently price every run at zero and disable a budget stop.
477
+ */
478
+ export function assertPriceEntry(entry, routeKey) {
479
+ for (const key of ['input', 'output']) {
480
+ if (!isRate(entry?.[key])) {
481
+ throw new Error('benchmark: the price entry for ' + routeKey + ' needs a finite non-negative ' + key + ' rate per million tokens')
482
+ }
483
+ }
484
+ for (const key of ['cacheRead', 'cacheWrite']) {
485
+ if (entry[key] !== undefined && !isRate(entry[key])) {
486
+ throw new Error('benchmark: the price entry for ' + routeKey + ' has a non-finite ' + key + ' rate')
487
+ }
488
+ }
489
+ }
490
+
491
+ /** Estimated USD for one run's usage under an optional per-million price table. */
492
+ export function priceRun(usage, prices, route) {
493
+ const entry = routePrices(prices, route)
494
+ if (entry === undefined) return null
495
+ assertPriceEntry(entry, route.provider + '/' + route.model)
496
+ const cost = (tokens, perMillion) => ((countOf(tokens) ?? 0) / 1_000_000) * perMillion
497
+ return cost(usage.uncachedInputTokens, entry.input)
498
+ + cost(usage.outputTokens, entry.output)
499
+ + cost(usage.cacheReadTokens, entry.cacheRead ?? entry.input)
500
+ + cost(usage.cacheWriteTokens, entry.cacheWrite ?? entry.input)
501
+ }
502
+
503
+ /** Build the variant patch that redirects persistence and selects the isolated preset. */
504
+ function buildPatch({ variantId, presetRoot, runDir, turns }) {
505
+ return [
506
+ '- id: headless-startup',
507
+ ' disabled: true',
508
+ '',
509
+ '- id: headless-runner',
510
+ ' disabled: true',
511
+ '',
512
+ '- id: session-persistence-jsonl',
513
+ ' config:',
514
+ ` root: ${JSON.stringify(join(runDir, 'sessions').replace(/\\/g, '/'))}`,
515
+ ' compression: none',
516
+ '',
517
+ '- id: agent-default-model',
518
+ ' config:',
519
+ ` provider: ${FIXED_ROUTE.provider}`,
520
+ ` model: ${FIXED_ROUTE.model}`,
521
+ ` reasoningEffort: ${FIXED_ROUTE.reasoningEffort}`,
522
+ '',
523
+ '- insert:',
524
+ ' - id: agent-presets',
525
+ " name: '@deepseek-ai/dsh-agent-presets'",
526
+ ' config:',
527
+ ` default: ${variantId}`,
528
+ ' includeShippedRoot: false',
529
+ ' includeUserRoot: false',
530
+ ' roots:',
531
+ ` - path: ${JSON.stringify(presetRoot.replace(/\\/g, '/'))}`,
532
+ " trust: 'user'",
533
+ '',
534
+ '- insert:',
535
+ ' - id: benchmark-driver',
536
+ ` name: ${JSON.stringify(DRIVER)}`,
537
+ ' config:',
538
+ ` preset: ${JSON.stringify(variantId)}`,
539
+ ' turns:',
540
+ ...(turns ?? DEFAULT_TURNS).map((turn) => ` - ${JSON.stringify(turn)}`),
541
+ '',
542
+ ].join('\n')
543
+ }
544
+
545
+ /**
546
+ * Run one variant through one turn list in an isolated preset root, optionally
547
+ * seeded with a task corpus entry and graded by its acceptance check.
548
+ */
549
+ export async function runLiveCase(options) {
550
+ const variantId = options.variant
551
+ const variant = LIVE_VARIANTS[variantId]
552
+ if (variant === undefined) throw new Error(`benchmark: unknown variant "${variantId}"`)
553
+
554
+ const runDir = mkdtempSync(join(tmpdir(), `dsh-bench-${variantId}-`))
555
+ try {
556
+ const presetRoot = join(runDir, 'presets')
557
+ mkdirSync(presetRoot, { recursive: true })
558
+ const presetDir = materializePreset(presetRoot, variantId, variant)
559
+
560
+ const workspace = join(runDir, 'workspace')
561
+ mkdirSync(workspace, { recursive: true })
562
+ if (options.task !== undefined) writeTaskFiles(workspace, options.task.files)
563
+
564
+ const turns = options.turns ?? options.task?.turns ?? DEFAULT_TURNS
565
+ const patch = buildPatch({ variantId, presetRoot, runDir, turns })
566
+
567
+ const patchPath = join(runDir, 'variant.patch.yml')
568
+ writeFileSync(patchPath, patch, 'utf8')
569
+
570
+ const args = ['--profile', 'headless', '--patch', patchPath, 'run the configured turns']
571
+ const spec = process.platform === 'win32'
572
+ ? { command: 'cmd.exe', args: windowsCmdShimArgs('dsh', args), windowsVerbatimArguments: true }
573
+ : { command: 'dsh', args }
574
+ const started = Date.now()
575
+ const child = await spawnCaptured(
576
+ spec.command,
577
+ spec.args,
578
+ {
579
+ cwd: workspace,
580
+ env: { ...process.env },
581
+ ...(spec.windowsVerbatimArguments === true ? { windowsVerbatimArguments: true } : {}),
582
+ },
583
+ options.timeoutMs ?? 300000,
584
+ )
585
+
586
+ const outcomePath = join(workspace, 'benchmark-driver-outcome.json')
587
+ const outcome = existsSync(outcomePath) ? JSON.parse(readFileSync(outcomePath, 'utf8')) : undefined
588
+ const logs = sessionLogs(join(runDir, 'sessions'))
589
+ const evidence = logs.length > 0 ? summarizeSession(logs.at(-1)) : EMPTY_EVIDENCE
590
+ const check = options.task === undefined
591
+ ? undefined
592
+ : await evaluateCheck(workspace, options.task.check, options.timeoutMs ?? 120000)
593
+
594
+ return {
595
+ variant: variantId,
596
+ note: variant.note,
597
+ taskId: options.task?.id ?? null,
598
+ category: options.task?.category ?? null,
599
+ repetition: options.repetition ?? 1,
600
+ runDir: options.keep === true ? runDir : undefined,
601
+ presetDir: options.keep === true ? presetDir : undefined,
602
+ variantPresetHash: hashTree(presetDir),
603
+ turns,
604
+ patch,
605
+ exitCode: child.code,
606
+ timedOut: child.timedOut,
607
+ passed: check === undefined ? null : check.passed === true && child.code === 0 && !child.timedOut,
608
+ check,
609
+ durationMs: Date.now() - started,
610
+ outcome,
611
+ stderrTail: child.stderr.split('\n').filter((line) => line.trim() !== '').slice(-12).join('\n'),
612
+ ...evidence,
613
+ workspaceFiles: existsSync(workspace) ? readdirSync(workspace) : [],
614
+ }
615
+ } finally {
616
+ if (options.keep !== true) rmSync(runDir, { recursive: true, force: true })
617
+ }
618
+ }
619
+
620
+ /** Backward-compatible single-run entry point used by the smoke invocation. */
621
+ export async function runLiveVariant(options) {
622
+ return runLiveCase(options)
623
+ }
624
+
625
+ /**
626
+ /**
627
+ * The ordered run plan: every group inside each task and repetition. A group-major
628
+ * walk would let a session or cost limit exhaust the first groups and leave the
629
+ * rest with zero sessions, so the plan keeps each task's arms together and lets a
630
+ * truncated run still support a paired comparison.
631
+ */
632
+ export function suitePlan(groups, tasks, repeat) {
633
+ const plan = []
634
+ for (const task of tasks) {
635
+ for (let repetition = 1; repetition <= repeat; repetition += 1) {
636
+ for (const group of groups) plan.push({ group, task, repetition })
637
+ }
638
+ }
639
+ return plan
640
+ }
641
+
642
+ /**
643
+ * Run the staged matrix over a task corpus: every group, task, and repetition in
644
+ * order, stopping at the session or cost limit instead of expanding on its own.
645
+ */
646
+ export async function runLiveSuite(options) {
647
+ const outDir = options.outDir ?? '.benchmark-results'
648
+ mkdirSync(outDir, { recursive: true })
649
+ const groups = options.groups ?? Object.keys(LIVE_VARIANTS)
650
+ const corpus = options.tasks
651
+ const repeat = options.repeat ?? 3
652
+ const maxSessions = options.maxSessions ?? Number.POSITIVE_INFINITY
653
+ const budgetUsd = options.budgetUsd ?? Number.POSITIVE_INFINITY
654
+ const timeoutMs = options.timeoutMs ?? 300000
655
+ const prices = options.prices ?? null
656
+
657
+ const routeKey = FIXED_ROUTE.provider + '/' + FIXED_ROUTE.model
658
+ const routePrice = routePrices(prices, FIXED_ROUTE)
659
+ // A budget gate that cannot price a run would silently never trigger, which is
660
+ // exactly the unbounded spend the plan forbids; validate instead of pretending.
661
+ if (routePrice !== undefined) assertPriceEntry(routePrice, routeKey)
662
+ if (Number.isFinite(budgetUsd) && routePrice === undefined) {
663
+ throw new Error('benchmark: --budget-usd needs a price entry for ' + routeKey + '; pass --prices <file>')
664
+ }
665
+ if (!Number.isFinite(maxSessions) && !Number.isFinite(budgetUsd)) {
666
+ process.stderr.write('benchmark: no --max-sessions or --budget-usd bound was given; the matrix will run to the end of the corpus\n')
667
+ }
668
+
669
+ const baseline = await collectBaseline()
670
+ baseline.taskRevision = taskRevision(corpus)
671
+ baseline.suite = {
672
+ groups,
673
+ repeat,
674
+ maxSessions: Number.isFinite(maxSessions) ? maxSessions : null,
675
+ budgetUsd: Number.isFinite(budgetUsd) ? budgetUsd : null,
676
+ priced: routePrice !== undefined,
677
+ }
678
+
679
+ const runs = []
680
+ let sessions = 0
681
+ let estimatedCostUsd = 0
682
+ let stopReason = 'completed'
683
+
684
+ for (const group of groups) {
685
+ if (LIVE_VARIANTS[group] === undefined) throw new Error('benchmark: unknown variant "' + group + '"')
686
+ }
687
+
688
+ outer: for (const step of suitePlan(groups, corpus.tasks, repeat)) {
689
+ const group = step.group
690
+ const task = step.task
691
+ const repetition = step.repetition
692
+ if (sessions >= maxSessions) { stopReason = 'session-limit'; break outer }
693
+ if (estimatedCostUsd >= budgetUsd) { stopReason = 'budget-limit'; break outer }
694
+ const run = await runLiveCase({
695
+ variant: group,
696
+ task,
697
+ turns: task.turns,
698
+ repetition,
699
+ timeoutMs,
700
+ keep: options.keep === true,
701
+ })
702
+ sessions += 1
703
+ const costUsd = priceRun(run.usage, prices, FIXED_ROUTE)
704
+ if (costUsd !== null) estimatedCostUsd += costUsd
705
+ const record = { baseline, costUsd, ...run }
706
+ const file = join(outDir, 'live-' + group + '-' + task.id + '-r' + repetition + '.json')
707
+ writeFileSync(file, JSON.stringify(record, null, 2))
708
+ runs.push({ file, group, taskId: task.id, repetition, passed: run.passed, costUsd })
709
+ process.stdout.write(group + ' ' + task.id + ' r' + repetition + ': ' + (run.passed === true ? 'pass' : run.passed === false ? 'fail' : 'n/a') + ' in ' + run.durationMs + 'ms' + (costUsd === null ? '' : ' $' + costUsd.toFixed(4)) + '\n')
710
+ }
711
+
712
+ const suite = {
713
+ baseline,
714
+ stopReason,
715
+ sessions,
716
+ estimatedCostUsd: prices === null ? null : estimatedCostUsd,
717
+ runs,
718
+ }
719
+ writeFileSync(join(outDir, 'suite.json'), JSON.stringify(suite, null, 2))
720
+ return suite
721
+ }
722
+
723
+ const isMain = process.argv[1] !== undefined
724
+ && (await import('node:url')).pathToFileURL(process.argv[1]).href === import.meta.url
725
+
726
+ if (isMain) {
727
+ const args = process.argv.slice(2)
728
+ const read = (flag, fallback) => {
729
+ const index = args.indexOf(flag)
730
+ return index === -1 ? fallback : args[index + 1]
731
+ }
732
+ const outDir = read('--out', '.benchmark-results')
733
+ const timeoutMs = Number(read('--timeout', '300000'))
734
+
735
+ if (args.includes('--tasks')) {
736
+ const corpus = loadTaskFile(read('--tasks'))
737
+ const pricesPath = read('--prices', undefined)
738
+ const suite = await runLiveSuite({
739
+ tasks: corpus,
740
+ groups: read('--groups', undefined)?.split(',').map((entry) => entry.trim()).filter(Boolean),
741
+ repeat: Number(read('--repeat', '3')),
742
+ maxSessions: Number(read('--max-sessions', '0')) > 0 ? Number(read('--max-sessions', '0')) : Number.POSITIVE_INFINITY,
743
+ budgetUsd: Number(read('--budget-usd', '0')) > 0 ? Number(read('--budget-usd', '0')) : Number.POSITIVE_INFINITY,
744
+ timeoutMs,
745
+ prices: pricesPath === undefined ? null : JSON.parse(readFileSync(pricesPath, 'utf8')),
746
+ keep: args.includes('--keep'),
747
+ outDir,
748
+ })
749
+ console.log(`suite: ${suite.sessions} session(s), stop ${suite.stopReason}`)
750
+ console.log(`aggregate with: node tools/benchmark-report.mjs ${outDir}`)
751
+ } else {
752
+ const variant = read('--variant', 'B')
753
+ const report = await runLiveCase({ variant, timeoutMs, keep: args.includes('--keep') })
754
+ mkdirSync(outDir, { recursive: true })
755
+ const outFile = join(outDir, `live-${variant}.json`)
756
+ writeFileSync(outFile, JSON.stringify({ baseline: await collectBaseline(), ...report }, null, 2))
757
+
758
+ const route = report.requests[0]
759
+ console.log(`variant ${report.variant}: ${report.note}`)
760
+ console.log(` exit ${report.exitCode} in ${report.durationMs}ms route ${route?.provider ?? '?'}/${route?.model ?? '?'}/${route?.reasoningEffort ?? '?'}`)
761
+ for (const request of report.requests) {
762
+ console.log(` request seq ${request.seq}: ${request.tools.length} tool(s) [${request.tools.join(', ')}]`)
763
+ }
764
+ for (const prompt of report.prompts) {
765
+ console.log(` prompt turn ${prompt.turn}.${prompt.step}: ${prompt.chars} chars persona=${prompt.carriesPersona} cwdLine=${prompt.carriesWorkspaceLine} instructions=${prompt.carriesWorkspaceInstructions} sdk=${prompt.carriesSdkSection} ptcRule=${prompt.carriesPtcRule}`)
766
+ }
767
+ console.log(` tool calls ${report.toolCalls}, ptc dispatches ${report.ptcDispatches}, workspace ${JSON.stringify(report.workspaceFiles)}`)
768
+ console.log(` tokens ${report.usage.totalTokens} (input ${report.usage.uncachedInputTokens}, output ${report.usage.outputTokens}, cacheRead ${report.usage.cacheReadTokens})`)
769
+ console.log(` report ${outFile}`)
770
+ }
771
+ }