-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrun-eval.ts
More file actions
1840 lines (1690 loc) · 67.8 KB
/
Copy pathrun-eval.ts
File metadata and controls
1840 lines (1690 loc) · 67.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { constants, existsSync, mkdirSync } from 'node:fs';
import { access, readFile } from 'node:fs/promises';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import {
DEFAULT_THRESHOLD,
type EvalTest,
type EvaluationCache,
type EvaluationResult,
type ExecutionDefaults,
type FailOnError,
type OtelTraceExporter as OtelTraceExporterType,
type ResolvedTarget,
ResponseCache,
RunBudgetTracker,
type TrialsConfig,
runEvaluation as defaultRunEvaluation,
deriveCategory,
ensureVSCodeSubagents,
loadConfig,
loadTestSuite,
loadTsConfig,
resolveTargetDefinition,
shouldEnableCache,
shouldSkipCacheForTemperature,
subscribeToCodexLogEntries,
subscribeToCopilotCliLogEntries,
subscribeToCopilotSdkLogEntries,
subscribeToPiLogEntries,
} from '@agentv/core';
import { enforceRequiredVersion } from '../../version-check.js';
import { maybeAutoExportRunArtifacts } from '../results/remote.js';
import {
aggregateRunDir,
buildTestTargetKey,
deduplicateByTestIdTarget,
parseJsonlResults,
writeArtifactsFromResults,
writeInitialBenchmarkArtifact,
} from './artifact-writer.js';
import { writeBenchmarkJson } from './benchmark-writer.js';
import { loadEnvFromHierarchy } from './env.js';
import { type OutputWriter, createOutputWriter, createWriterFromPath } from './output-writer.js';
import { ProgressDisplay, type Verdict, type WorkerProgress } from './progress-display.js';
import { buildDefaultRunDir, normalizeExperimentName } from './result-layout.js';
import {
buildExclusionFilter,
loadErrorTestIds,
loadFullyCompletedTestIds,
loadNonErrorResults,
} from './retry-errors.js';
import { resolveCachedRunDir, saveRunCache } from './run-cache.js';
import { findRepoRoot } from './shared.js';
import {
calculateEvaluationSummary,
formatEvaluationSummary,
formatMatrixSummary,
} from './statistics.js';
import { type TargetSelection, selectMultipleTargets, selectTarget } from './targets.js';
const DEFAULT_WORKERS = 3;
function shouldSkipExistingResultForResume(
result: Pick<EvaluationResult, 'executionStatus'>,
rerunFailed: boolean,
): boolean {
if (rerunFailed) {
return result.executionStatus === 'ok';
}
return result.executionStatus !== 'execution_error';
}
interface RunEvalCommandInput {
readonly testFiles: readonly string[];
readonly rawOptions: Record<string, unknown>;
}
interface NormalizedOptions {
readonly target?: string;
readonly cliTargets: readonly string[];
readonly targetsPath?: string;
readonly filter?: string | readonly string[];
readonly workers?: number;
/** --output <dir>: artifact directory (new canonical meaning) */
readonly outputDir?: string;
/** Legacy --out <path>: deprecated, treated as artifact dir */
readonly outPath?: string;
/** --export <paths...>: additional output files */
readonly exportPaths: readonly string[];
readonly dryRun: boolean;
readonly dryRunDelay: number;
readonly dryRunDelayMin: number;
readonly dryRunDelayMax: number;
readonly agentTimeoutSeconds?: number;
readonly maxRetries: number;
readonly cache: boolean;
readonly cachePath?: string;
readonly noCache: boolean;
readonly tsConfigCache?: boolean;
readonly tsConfigCachePath?: string;
readonly verbose: boolean;
readonly otelFile?: string;
readonly exportOtel: boolean;
readonly otelBackend?: string;
readonly otelCaptureContent: boolean;
readonly otelGroupTurns: boolean;
readonly retryErrors?: string;
readonly resume: boolean;
readonly rerunFailed: boolean;
readonly workspaceMode?: 'pooled' | 'temp' | 'static';
readonly workspacePath?: string;
readonly keepWorkspaces: boolean;
/** Deprecated: benchmark.json is always written to artifact dir */
readonly benchmarkJson?: string;
/** Deprecated: use --output instead */
readonly artifacts?: string;
readonly graderTarget?: string;
readonly model?: string;
readonly outputMessages: number | 'all';
readonly threshold?: number;
readonly tags: readonly string[];
readonly excludeTags: readonly string[];
readonly transcript?: string;
readonly experiment?: string;
readonly budgetUsd?: number;
}
function normalizeBoolean(value: unknown): boolean {
return value === true;
}
function normalizeString(value: unknown): string | undefined {
if (typeof value !== 'string') {
return undefined;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
export function resolveTimestampPlaceholder(value: string): string {
if (!value.includes('{timestamp}')) {
return value;
}
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
return value.replaceAll('{timestamp}', timestamp);
}
function normalizeNumber(value: unknown, fallback: number): number {
if (typeof value === 'number' && Number.isFinite(value)) {
return value;
}
if (typeof value === 'string') {
const parsed = Number.parseInt(value, 10);
if (!Number.isNaN(parsed)) {
return parsed;
}
}
return fallback;
}
function normalizeOptionalNumber(value: unknown): number | undefined {
if (typeof value === 'number' && Number.isFinite(value)) {
return value;
}
if (typeof value === 'string') {
const parsed = Number.parseInt(value, 10);
if (!Number.isNaN(parsed)) {
return parsed;
}
}
return undefined;
}
function normalizeWorkspaceMode(value: unknown): 'pooled' | 'temp' | 'static' | undefined {
return value === 'pooled' || value === 'temp' || value === 'static' ? value : undefined;
}
function normalizeStringArray(value: unknown): readonly string[] {
if (Array.isArray(value)) {
return value.filter((v): v is string => typeof v === 'string' && v.trim().length > 0);
}
return [];
}
function normalizeFilter(value: unknown): string | readonly string[] | undefined {
if (Array.isArray(value)) {
const filters = normalizeStringArray(value);
if (filters.length === 0) {
return undefined;
}
return filters.length === 1 ? filters[0] : filters;
}
return normalizeString(value);
}
/**
* Check whether an eval file's tags satisfy --tag / --exclude-tag filters.
*
* - `--tag X` means the file must have tag X (AND logic: all specified tags must be present)
* - `--exclude-tag X` means the file must NOT have tag X (AND logic: none of the specified tags may be present)
* - When both are used, both conditions must hold.
* - Files without tags are excluded when --tag is specified, but included when only --exclude-tag is specified.
*/
export function matchesTagFilters(
fileTags: readonly string[] | undefined,
includeTags: readonly string[],
excludeTags: readonly string[],
): boolean {
const tags = new Set(fileTags ?? []);
// --tag: every specified tag must be present
if (includeTags.length > 0) {
for (const required of includeTags) {
if (!tags.has(required)) return false;
}
}
// --exclude-tag: none of the specified tags may be present
for (const excluded of excludeTags) {
if (tags.has(excluded)) return false;
}
return true;
}
/**
* Normalize --output-messages value. Accepts a number (>= 1) or "all".
* Defaults to 1 (last assistant message only).
*/
function normalizeOutputMessages(cliValue: string | undefined): number | 'all' {
if (cliValue === undefined) {
return 1;
}
if (cliValue === 'all') {
return 'all';
}
const parsed = Number.parseInt(cliValue, 10);
if (Number.isNaN(parsed) || !Number.isInteger(parsed) || parsed < 1) {
console.warn(
`Warning: Invalid --output-messages value '${cliValue}'. Must be a positive integer or 'all'. Defaulting to 1.`,
);
return 1;
}
return parsed;
}
/**
* Trim output messages for results JSONL.
* Each message is stripped to { role, content } only.
*
* - `1` (default): last assistant message only (legacy behavior)
* - `N`: last N messages (any role)
* - `'all'`: all messages
*/
export function trimOutputMessages(
output: EvaluationResult['output'],
outputMessages: number | 'all',
): EvaluationResult['output'] {
const messages = output ?? [];
if (outputMessages === 'all') {
return messages.map((m) => ({ role: m.role, content: m.content }));
}
if (outputMessages === 1) {
// Legacy behavior: last assistant message only
const lastAssistant = messages.filter((m) => m.role === 'assistant').at(-1);
return lastAssistant ? [{ role: lastAssistant.role, content: lastAssistant.content }] : [];
}
// Last N messages (any role), trimmed to { role, content }
const sliced = messages.slice(-outputMessages);
return sliced.map((m) => ({ role: m.role, content: m.content }));
}
function normalizeOptions(
rawOptions: Record<string, unknown>,
config?: Awaited<ReturnType<typeof loadTsConfig>>,
yamlExecution?: ExecutionDefaults,
): NormalizedOptions {
const cliWorkers = normalizeOptionalNumber(rawOptions.workers);
const configWorkers = config?.execution?.workers;
const workers = cliWorkers ?? configWorkers ?? 0;
// --output is now a single optional string (artifact directory)
const cliOutputDir = normalizeString(rawOptions.output);
// --export is the new repeatable flag for additional output files
const rawExportPaths = rawOptions.export;
const exportPaths: string[] = Array.isArray(rawExportPaths)
? rawExportPaths.filter((v): v is string => typeof v === 'string' && v.trim().length > 0)
: [];
// Normalize --target: can be a string (legacy) or string[] (multioption)
const rawTarget = rawOptions.target;
let cliTargets: string[] = [];
let singleTarget: string | undefined;
if (Array.isArray(rawTarget)) {
cliTargets = rawTarget.filter((v): v is string => typeof v === 'string' && v.trim().length > 0);
singleTarget = cliTargets.length === 1 ? cliTargets[0] : undefined;
} else if (typeof rawTarget === 'string') {
const trimmed = rawTarget.trim();
if (trimmed.length > 0 && trimmed !== 'default') {
cliTargets = [trimmed];
singleTarget = trimmed;
}
}
const cliAgentTimeout = normalizeOptionalNumber(rawOptions.agentTimeout);
const configAgentTimeoutSeconds =
config?.execution?.agentTimeoutMs != null ? config.execution.agentTimeoutMs / 1000 : undefined;
const cliMaxRetries = normalizeOptionalNumber(rawOptions.maxRetries);
const configMaxRetries = config?.execution?.maxRetries;
// Response cache: CLI request/path, then eval YAML, then TypeScript config, then default off.
const cliCachePath = normalizeString(rawOptions.cachePath);
const cliCache = normalizeBoolean(rawOptions.cache) || cliCachePath !== undefined;
const cliNoCache = normalizeBoolean(rawOptions.noCache);
const configCacheEnabled = config?.cache?.enabled;
const configCachePath = normalizeString(config?.cache?.path);
// Output dir: CLI --out > config output.dir > auto-generated
const cliOut = normalizeString(rawOptions.out);
const configOut = config?.output?.dir;
const cliWorkspacePath = normalizeString(rawOptions.workspacePath);
const cliWorkspaceModeRaw = normalizeString(rawOptions.workspaceMode);
const cliWorkspaceMode = normalizeWorkspaceMode(rawOptions.workspaceMode);
if (cliWorkspacePath && cliWorkspaceModeRaw && cliWorkspaceMode !== 'static') {
throw new Error('--workspace-path requires --workspace-mode=static (or omit --workspace-mode)');
}
const yamlExecutionRecord = yamlExecution as Record<string, unknown> | undefined;
const yamlWorkspaceMode = normalizeWorkspaceMode(yamlExecutionRecord?.workspace_mode);
const yamlWorkspacePath = normalizeString(yamlExecutionRecord?.workspace_path);
const workspacePath = cliWorkspacePath ?? yamlWorkspacePath;
const workspaceMode = cliWorkspacePath ? 'static' : (cliWorkspaceMode ?? yamlWorkspaceMode);
return {
target: singleTarget,
cliTargets,
targetsPath: normalizeString(rawOptions.targets),
filter: normalizeFilter(rawOptions.filter),
workers: workers > 0 ? workers : undefined,
outputDir: cliOutputDir,
outPath: cliOut ?? configOut,
exportPaths,
dryRun: normalizeBoolean(rawOptions.dryRun),
dryRunDelay: normalizeNumber(rawOptions.dryRunDelay, 0),
dryRunDelayMin: normalizeNumber(rawOptions.dryRunDelayMin, 0),
dryRunDelayMax: normalizeNumber(rawOptions.dryRunDelayMax, 0),
agentTimeoutSeconds: cliAgentTimeout ?? configAgentTimeoutSeconds,
maxRetries: cliMaxRetries ?? configMaxRetries ?? 2,
cache: cliCache,
cachePath: cliCachePath,
noCache: cliNoCache,
tsConfigCache: configCacheEnabled,
tsConfigCachePath: configCachePath,
// Boolean OR: config `true` cannot be overridden to `false` from CLI.
// Intentional — there are no --no-verbose / --no-keep-workspaces flags.
// Precedence: CLI > YAML config > TS config
verbose:
normalizeBoolean(rawOptions.verbose) ||
yamlExecution?.verbose === true ||
config?.execution?.verbose === true,
// Precedence: CLI > YAML config > TS config
otelFile:
normalizeString(rawOptions.otelFile) ??
(yamlExecution?.otel_file
? resolveTimestampPlaceholder(yamlExecution.otel_file)
: undefined) ??
(config?.execution?.otelFile
? resolveTimestampPlaceholder(config.execution.otelFile)
: undefined),
exportOtel: normalizeBoolean(rawOptions.exportOtel) || yamlExecution?.export_otel === true,
otelBackend: normalizeString(rawOptions.otelBackend) ?? yamlExecution?.otel_backend,
otelCaptureContent:
normalizeBoolean(rawOptions.otelCaptureContent) ||
yamlExecution?.otel_capture_content === true,
otelGroupTurns:
normalizeBoolean(rawOptions.otelGroupTurns) || yamlExecution?.otel_group_turns === true,
retryErrors: normalizeString(rawOptions.retryErrors),
resume: normalizeBoolean(rawOptions.resume) || normalizeBoolean(rawOptions.rerunFailed),
rerunFailed: normalizeBoolean(rawOptions.rerunFailed),
workspaceMode,
workspacePath,
// Precedence: CLI > YAML config > TS config
keepWorkspaces:
normalizeBoolean(rawOptions.keepWorkspaces) ||
yamlExecution?.keep_workspaces === true ||
config?.execution?.keepWorkspaces === true,
benchmarkJson: normalizeString(rawOptions.benchmarkJson),
artifacts: normalizeString(rawOptions.artifacts),
graderTarget: normalizeString(rawOptions.graderTarget),
model: normalizeString(rawOptions.model),
outputMessages: normalizeOutputMessages(normalizeString(rawOptions.outputMessages)),
threshold: normalizeOptionalNumber(rawOptions.threshold),
tags: normalizeStringArray(rawOptions.tag),
excludeTags: normalizeStringArray(rawOptions.excludeTag),
transcript: normalizeString(rawOptions.transcript),
experiment: normalizeString(rawOptions.experiment),
budgetUsd: normalizeOptionalNumber(rawOptions.budgetUsd),
} satisfies NormalizedOptions;
}
async function ensureFileExists(filePath: string, description: string): Promise<void> {
try {
await access(filePath, constants.F_OK);
} catch {
throw new Error(`${description} not found: ${filePath}`);
}
}
function buildDefaultOutputPathForExperiment(cwd: string, experiment?: string): string {
const runDir = buildDefaultRunDir(cwd, experiment);
mkdirSync(runDir, { recursive: true });
return path.join(runDir, 'index.jsonl');
}
type ProgressReporter = {
readonly isInteractive: boolean;
start(): void;
setTotal(total: number): void;
update(workerId: number, progress: WorkerProgress): void;
finish(): void;
addLogPaths(paths: readonly string[]): void;
};
function createProgressReporter(
maxWorkers: number,
options?: { verbose?: boolean },
): ProgressReporter {
const display = new ProgressDisplay(maxWorkers, options);
return {
isInteractive: display.isInteractiveMode(),
start: () => display.start(),
setTotal: (total: number) => display.setTotalTests(total),
update: (workerId: number, progress: WorkerProgress) =>
display.updateWorker({ ...progress, workerId }),
finish: () => display.finish(),
addLogPaths: (paths: readonly string[]) => display.addLogPaths(paths),
};
}
function makeTestCaseKey(testFilePath: string, testId: string): string {
return `${path.resolve(testFilePath)}::${testId}`;
}
/** Show the resolved target name when `default` is a `use_target` redirect. */
function resolveTargetLabel(requestedName: string, resolvedName: string): string {
if (resolvedName !== requestedName) {
return `${requestedName} → ${resolvedName}`;
}
return requestedName;
}
function createDisplayIdTracker(): { getOrAssign(testCaseKey: string): number } {
const map = new Map<string, number>();
let nextId = 1;
return {
getOrAssign(testCaseKey: string): number {
const existing = map.get(testCaseKey);
if (existing !== undefined) {
return existing;
}
const assigned = nextId++;
map.set(testCaseKey, assigned);
return assigned;
},
};
}
/**
* Extract the model name from a resolved target, if available.
* Azure uses `deploymentName`; most other providers use `model`.
* CLI and mock providers have no model field.
*/
function extractModelName(target: ResolvedTarget): string | undefined {
if (target.kind === 'azure') {
return target.config.deploymentName;
}
if ('model' in target.config && typeof target.config.model === 'string') {
return target.config.model;
}
return undefined;
}
/**
* Build the inline label suffix (e.g. `[provider=azure, model=gpt-4]`).
*/
function buildTargetLabelSuffix(providerLabel: string, target: ResolvedTarget): string {
const parts = [`provider=${providerLabel}`];
const model = extractModelName(target);
if (model) parts.push(`model=${model}`);
return `[${parts.join(', ')}]`;
}
/**
* Override CLI provider verbose setting based on CLI --verbose flag.
* CLI provider logs should only appear when --verbose is passed.
*/
function applyVerboseOverride(selection: TargetSelection, cliVerbose: boolean): TargetSelection {
const { resolvedTarget } = selection;
// Only CLI providers have a verbose setting in their config
if (resolvedTarget.kind !== 'cli') {
return selection;
}
// Set verbose to match CLI --verbose flag
return {
...selection,
resolvedTarget: {
...resolvedTarget,
config: {
...resolvedTarget.config,
verbose: cliVerbose,
},
},
};
}
async function prepareFileMetadata(params: {
readonly testFilePath: string;
readonly repoRoot: string;
readonly cwd: string;
readonly options: NormalizedOptions;
}): Promise<{
readonly testIds: readonly string[];
readonly testCases: readonly EvalTest[];
readonly selections: readonly { selection: TargetSelection; inlineTargetLabel: string }[];
readonly trialsConfig?: TrialsConfig;
readonly suiteTargets?: readonly string[];
readonly yamlWorkers?: number;
readonly yamlCache?: boolean;
readonly yamlCachePath?: string;
readonly budgetUsd?: number;
readonly failOnError?: FailOnError;
readonly threshold?: number;
readonly tags?: readonly string[];
readonly providerFactory?: (
target: import('@agentv/core').ResolvedTarget,
) => import('@agentv/core').Provider;
}> {
const { testFilePath, repoRoot, cwd, options } = params;
await ensureFileExists(testFilePath, 'Test file');
await loadEnvFromHierarchy({
testFilePath,
repoRoot,
verbose: options.verbose,
});
const relativePath = path.relative(cwd, testFilePath);
const category = deriveCategory(relativePath);
const suite = await loadTestSuite(testFilePath, repoRoot, {
verbose: options.verbose,
filter: options.filter,
category,
});
const testIds = suite.tests.map((value) => value.id);
const suiteTargets = suite.targets;
let selections: { selection: TargetSelection; inlineTargetLabel: string }[];
if (options.transcript) {
// --transcript mode: bypass target resolution entirely.
// Create a synthetic TargetSelection for the transcript provider.
const transcriptSelection: TargetSelection = {
definitions: [],
resolvedTarget: {
kind: 'transcript',
name: 'transcript',
config: {} as Record<string, never>,
},
targetName: 'transcript',
targetSource: 'cli',
targetsFilePath: options.transcript,
};
selections = [
{
selection: transcriptSelection,
inlineTargetLabel: `transcript (${path.basename(options.transcript)})`,
},
];
} else if (suite.inlineTarget && options.cliTargets.length === 0) {
const targetDefinition = suite.inlineTarget;
const resolvedTarget = options.dryRun
? ({
kind: 'mock',
name: `${targetDefinition.name}-dry-run`,
graderTarget: undefined,
config: {
// Schema-valid grader response so --dry-run works end-to-end with LLM graders.
// Satisfies freeform (score), rubric (checks, overall_reasoning), and score-range (checks) without real LLM calls.
response: '{"score":1,"assertions":[],"checks":[],"overall_reasoning":"dry-run mock"}',
delayMs: options.dryRunDelay,
delayMinMs: options.dryRunDelayMin,
delayMaxMs: options.dryRunDelayMax,
},
} satisfies ResolvedTarget)
: resolveTargetDefinition(targetDefinition, process.env, testFilePath, {
emitDeprecationWarnings: false,
});
selections = [
{
selection: {
definitions: [targetDefinition],
resolvedTarget,
targetName: targetDefinition.name,
targetSource: 'test-file',
targetsFilePath: testFilePath,
},
inlineTargetLabel: resolveTargetLabel(targetDefinition.name, resolvedTarget.name),
},
];
} else if (suite.providerFactory && options.cliTargets.length === 0) {
const taskTarget: ResolvedTarget = {
kind: 'mock',
name: 'custom-task',
graderTarget: undefined,
config: {},
};
selections = [
{
selection: {
definitions: [],
resolvedTarget: taskTarget,
targetName: 'custom-task',
targetSource: 'test-file',
targetsFilePath: testFilePath,
},
inlineTargetLabel: 'custom-task',
},
];
} else {
// Determine target names: CLI --target flags override YAML
const cliTargets = options.cliTargets;
const suiteTargets = suite.targets;
const suiteTargetRefs = suite.targetRefs;
// Resolve which target names to use (precedence: CLI > suite YAML targets > default)
let targetNames: readonly string[];
if (cliTargets.length > 0) {
targetNames = cliTargets;
} else if (suiteTargets && suiteTargets.length > 0) {
targetNames = suiteTargets;
} else {
targetNames = [];
}
if (targetNames.length > 1) {
// Matrix mode: multiple targets
const multiSelections = await selectMultipleTargets({
testFilePath,
repoRoot,
cwd,
explicitTargetsPath: options.targetsPath,
dryRun: options.dryRun,
dryRunDelay: options.dryRunDelay,
dryRunDelayMin: options.dryRunDelayMin,
dryRunDelayMax: options.dryRunDelayMax,
env: process.env,
targetNames,
targetRefs: suiteTargetRefs,
});
selections = multiSelections.map((sel) => ({
selection: sel,
inlineTargetLabel: resolveTargetLabel(sel.targetName, sel.resolvedTarget.name),
}));
} else {
// Single target mode (legacy path)
const selection = await selectTarget({
testFilePath,
repoRoot,
cwd,
explicitTargetsPath: options.targetsPath,
cliTargetName: targetNames.length === 1 ? targetNames[0] : options.target,
dryRun: options.dryRun,
dryRunDelay: options.dryRunDelay,
dryRunDelayMin: options.dryRunDelayMin,
dryRunDelayMax: options.dryRunDelayMax,
env: process.env,
});
// Attach target hooks from eval file if available
const singleTargetHooks = suiteTargetRefs?.find(
(ref) => ref.name === selection.targetName,
)?.hooks;
const augmentedSelection: TargetSelection = singleTargetHooks
? { ...selection, targetHooks: singleTargetHooks }
: selection;
selections = [
{
selection: augmentedSelection,
inlineTargetLabel: resolveTargetLabel(
augmentedSelection.targetName,
augmentedSelection.resolvedTarget.name,
),
},
];
}
}
return {
testIds,
testCases: suite.tests,
selections,
trialsConfig: suite.trials,
suiteTargets,
yamlWorkers: suite.workers,
yamlCache: suite.cacheConfig?.enabled,
yamlCachePath: suite.cacheConfig?.cachePath,
budgetUsd: suite.budgetUsd,
failOnError: suite.failOnError,
threshold: suite.threshold,
tags: suite.metadata?.tags,
providerFactory: suite.providerFactory,
};
}
async function runSingleEvalFile(params: {
readonly testFilePath: string;
readonly cwd: string;
readonly repoRoot: string;
readonly options: NormalizedOptions;
readonly outputWriter: OutputWriter;
readonly otelExporter?: OtelTraceExporterType | null;
readonly cache?: EvaluationCache;
readonly evaluationRunner: typeof defaultRunEvaluation;
readonly workersOverride?: number;
readonly yamlWorkers?: number;
readonly progressReporter: ProgressReporter;
readonly seenTestCases: Set<string>;
readonly displayIdTracker: { getOrAssign(testCaseKey: string): number };
readonly selection: TargetSelection;
readonly inlineTargetLabel: string;
readonly testCases: readonly EvalTest[];
readonly trialsConfig?: TrialsConfig;
readonly matrixMode?: boolean;
readonly budgetUsd?: number;
readonly runBudgetTracker?: RunBudgetTracker;
readonly failOnError?: FailOnError;
readonly threshold?: number;
readonly providerFactory?: (
target: import('@agentv/core').ResolvedTarget,
) => import('@agentv/core').Provider;
}): Promise<{ results: EvaluationResult[] }> {
const {
testFilePath,
cwd,
repoRoot,
options,
outputWriter,
otelExporter,
cache,
evaluationRunner,
workersOverride,
yamlWorkers,
progressReporter,
seenTestCases,
displayIdTracker,
selection,
inlineTargetLabel,
testCases,
trialsConfig,
matrixMode,
budgetUsd,
runBudgetTracker,
failOnError,
providerFactory,
} = params;
const targetName = selection.targetName;
await ensureFileExists(testFilePath, 'Test file');
// CLI provider verbose logging should only be enabled when --verbose flag is passed
const resolvedTargetSelection = applyVerboseOverride(selection, options.verbose);
const providerLabel = options.dryRun
? `${resolvedTargetSelection.resolvedTarget.kind} (dry-run)`
: resolvedTargetSelection.resolvedTarget.kind;
const targetMessage = options.verbose
? `Using target (${resolvedTargetSelection.targetSource}): ${resolvedTargetSelection.targetName} ${buildTargetLabelSuffix(providerLabel, resolvedTargetSelection.resolvedTarget)} via ${resolvedTargetSelection.targetsFilePath}`
: `Using target: ${inlineTargetLabel}`;
if (!progressReporter.isInteractive || options.verbose) {
console.log(`${targetMessage}`);
}
// Hint about pipeline for CLI agent targets
const targetKind = resolvedTargetSelection.resolvedTarget.kind;
if ((targetKind === 'claude-cli' || targetKind === 'copilot-cli') && !options.dryRun) {
console.log('');
console.log(' TIP: For subagent-mode evals, use `agentv pipeline` instead of `eval run`.');
console.log(' The agent orchestrates executor + grader subagents directly.');
console.log(' Run: agentv pipeline --help');
console.log('');
}
const agentTimeoutMs =
options.agentTimeoutSeconds != null
? Math.max(0, options.agentTimeoutSeconds) * 1000
: undefined;
// Resolve workers: CLI flag > eval YAML execution.workers > target setting > default
const workerPreference = workersOverride ?? options.workers;
let resolvedWorkers =
workerPreference ??
yamlWorkers ??
resolvedTargetSelection.resolvedTarget.workers ??
DEFAULT_WORKERS;
if (resolvedWorkers < 1 || resolvedWorkers > 50) {
throw new Error(`Workers must be between 1 and 50, got: ${resolvedWorkers}`);
}
// VSCode providers require window focus, so only 1 worker is allowed
const isVSCodeProvider = ['vscode', 'vscode-insiders'].includes(
resolvedTargetSelection.resolvedTarget.kind,
);
if (isVSCodeProvider && resolvedWorkers > 1) {
console.warn(
`Warning: VSCode providers require window focus. Limiting workers from ${resolvedWorkers} to 1 to prevent race conditions.`,
);
resolvedWorkers = 1;
}
// Auto-provision subagents for VSCode targets
if (isVSCodeProvider && !options.dryRun) {
const vsConfig = resolvedTargetSelection.resolvedTarget.config as { executable?: string };
await ensureVSCodeSubagents({
kind: resolvedTargetSelection.resolvedTarget.kind as 'vscode' | 'vscode-insiders',
count: resolvedWorkers,
verbose: options.verbose,
vscodeCmd: vsConfig.executable,
});
}
// Use streaming spans only for live remote export. File exports should use
// post-hoc exportResult(result), which has the complete EvaluationResult and
// avoids cross-test interleaving issues under parallel execution.
const useStreamingObserver = !!(otelExporter && options.exportOtel);
const streamingObserver = useStreamingObserver
? (otelExporter?.createStreamingObserver() ?? null)
: null;
const results = await evaluationRunner({
testFilePath,
repoRoot,
target: resolvedTargetSelection.resolvedTarget,
targets: resolvedTargetSelection.definitions,
env: process.env,
maxRetries: Math.max(0, options.maxRetries),
agentTimeoutMs,
cache,
useCache: (() => {
// Skip cache if not enabled
if (!cache) return false;
// Skip cache when target has temperature > 0 (non-deterministic)
const targetConfig = resolvedTargetSelection.resolvedTarget.config as Record<string, unknown>;
if (shouldSkipCacheForTemperature(targetConfig)) {
if (options.verbose) {
console.log('Cache skipped: target temperature > 0');
}
return false;
}
return true;
})(),
filter: options.filter,
evalCases: testCases,
verbose: options.verbose,
maxConcurrency: resolvedWorkers,
workspaceMode: options.workspaceMode,
workspacePath: options.workspacePath,
keepWorkspaces: options.keepWorkspaces,
trials: trialsConfig,
budgetUsd,
runBudgetTracker,
failOnError,
graderTarget: options.graderTarget,
model: options.model,
threshold: options.threshold,
targetHooks: resolvedTargetSelection.targetHooks,
providerFactory,
streamCallbacks: streamingObserver?.getStreamCallbacks(),
onResult: async (result: EvaluationResult) => {
(
streamingObserver as { completeFromResult?: (result: EvaluationResult) => void } | null
)?.completeFromResult?.(result);
// Finalize the streaming observer span with score.
streamingObserver?.finalizeEvalCase(result.score, result.error);
// Trim output messages for results JSONL based on --output-messages.
// Each message is trimmed to { role, content } only (no toolCalls, startTime, etc.).
// Full output with tool calls goes to OTel.
const trimmedOutput = trimOutputMessages(result.output, options.outputMessages);
const trimmedResult: EvaluationResult = {
...result,
output: trimmedOutput,
};
await outputWriter.append(trimmedResult);
// Export to OTel if exporter is configured (skip batch export when streaming is active)
if (otelExporter && !streamingObserver) {
try {
await otelExporter.exportResult(result);
} catch (err) {
// Export failures don't fail the evaluation
if (options.verbose) {
console.warn(
`OTel export warning: ${err instanceof Error ? err.message : String(err)}`,
);
}
}
}
},
onProgress: async (event) => {
const testCaseKeyId = matrixMode ? `${event.testId}@${targetName}` : event.testId;
const testCaseKey = makeTestCaseKey(testFilePath, testCaseKeyId);
if (event.status === 'pending' && !seenTestCases.has(testCaseKey)) {
seenTestCases.add(testCaseKey);
progressReporter.setTotal(seenTestCases.size);
}
const displayId = displayIdTracker.getOrAssign(testCaseKey);
// Start streaming observer when eval case begins execution
if (event.status === 'running' && streamingObserver) {
streamingObserver.startEvalCase(event.testId, targetName, testFilePath);
}
// Map executionStatus to verdict for display
let verdict: Verdict | undefined;
if (event.executionStatus === 'ok') verdict = 'PASS';
else if (event.executionStatus === 'quality_failure') verdict = 'FAIL';
else if (event.executionStatus === 'execution_error') verdict = 'ERROR';
progressReporter.update(displayId, {
workerId: displayId,
testId: matrixMode ? `${event.testId}@${targetName}` : event.testId,
status: event.status,
startedAt: event.startedAt,
completedAt: event.completedAt,
error: event.error,
targetLabel: inlineTargetLabel,
score: event.score,
verdict,
durationMs: event.durationMs,
totalDurationMs: event.evalRunDurationMs,
});
},
});
return { results: [...results] };
}
export interface RunEvalResult {
readonly executionErrorCount: number;
readonly outputPath: string;
readonly testFiles: readonly string[];
readonly target?: string;
/** True when --threshold is set and mean score is below the threshold */
readonly thresholdFailed?: boolean;
/** True when all tests had execution errors and no evaluation was performed */
readonly allExecutionErrors?: boolean;
/** True when --budget-usd was set and the run-level budget was exceeded */
readonly budgetExceeded?: boolean;
}
interface RemoteEvalSummaryInput {
readonly evalFile: string;
readonly results: EvaluationResult[];
}
export async function runEvalCommand(
input: RunEvalCommandInput,
): Promise<RunEvalResult | undefined> {
const cwd = process.cwd();
// Set AGENTV_RUN_TIMESTAMP so CLI targets can group artifacts under the same run folder.
if (!process.env.AGENTV_RUN_TIMESTAMP) {
process.env.AGENTV_RUN_TIMESTAMP = new Date()
.toISOString()
.replace(/:/g, '-')
.replace(/\./g, '-');
}
// Load agentv.config.ts (if present) for default values
let config: Awaited<ReturnType<typeof loadTsConfig>> = null;
try {
config = await loadTsConfig(cwd);
} catch (err) {
console.warn(
`Warning: Failed to load agentv config: ${err instanceof Error ? err.message : String(err)}`,
);
}