-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrun-eval.ts
More file actions
2798 lines (2598 loc) · 101 KB
/
Copy pathrun-eval.ts
File metadata and controls
2798 lines (2598 loc) · 101 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 { createRequire as createNodeRequire } from 'node:module';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import pLimit from 'p-limit';
import {
DEFAULT_THRESHOLD,
type EvalRunOverride,
type EvalTargetRef,
type EvalTest,
type EvaluationCache,
type EvaluationResult,
type ExecutionDefaults,
type ExperimentArtifactMetadata,
type ExperimentConfig,
type FailOnError,
type ResolvedTarget,
ResponseCache,
RunBudgetTracker,
type RunRuntimeSourceMetadata,
type TrialsConfig,
buildExperimentArtifactMetadata,
buildTraceFromMessages,
runEvaluation as defaultRunEvaluation,
deriveCategory,
ensureVSCodeSubagents,
loadConfig,
loadTestSuite,
loadTestSuiteFromYamlObject,
loadTsConfig,
resolveTargetDefinition,
shouldEnableCache,
shouldSkipCacheForTemperature,
subscribeToCodexLogEntries,
subscribeToCopilotCliLogEntries,
subscribeToCopilotSdkLogEntries,
subscribeToPiLogEntries,
} from '@agentv/core';
import {
type VersionCheckResult,
enforceRequiredVersion,
formatRequiredVersionFailureNote,
} from '../../version-check.js';
import {
agentSkillsToAgentVYamlObject,
readAgentSkillsEvalsFile,
} from '../read-adapters/agent-skills-evals.js';
import {
type RemoteExportStatus,
type ResultsPublishOverrides,
getRelativeRunPath,
loadNormalizedResultsConfig,
maybeAutoExportRunArtifacts,
} from '../results/remote.js';
import {
aggregateRunDir,
buildEvalTestTargetKey,
buildEvaluationResultTargetKey,
buildTestTargetKey,
deduplicateByTestIdTarget,
parseJsonlResults,
writeArtifactsFromResults,
writeInitialRunSummaryArtifact,
} from './artifact-writer.js';
import { loadEnvFromHierarchy } from './env.js';
import { type OutputWriter, createOutputWriter } from './output-writer.js';
import { ProgressDisplay, type Verdict, type WorkerProgress } from './progress-display.js';
import {
RESULT_INDEX_FILENAME,
buildDefaultRunDirFromName,
createRunDirName,
discoverRunManifestPaths,
normalizeExperimentName,
resolveRunIndexPath,
} from './result-layout.js';
import {
buildExclusionFilter,
loadErrorTestIds,
loadFullyCompletedTestIds,
loadNonErrorResults,
} from './retry-errors.js';
import { resolveCachedRunDir, saveRunCache } from './run-cache.js';
import { findRepoRoot, resolveEvalPaths } from './shared.js';
import {
calculateEvaluationSummary,
formatEvaluationSummary,
formatMatrixSummary,
} from './statistics.js';
import { type TargetSelection, selectMultipleTargets, selectTarget } from './targets.js';
import type { TaskBundleTargetSelection } from './task-bundle.js';
import { WipCheckpointLoop } from './wip-checkpoint.js';
const DEFAULT_WORKERS = 3;
const loadCjsModule = createNodeRequire(import.meta.url);
const micromatch = loadCjsModule('micromatch') as {
isMatch(id: string, pattern: string): boolean;
};
type LoadTestSuiteOptions = Parameters<typeof loadTestSuite>[2];
async function loadCliEvalSuite(
testFilePath: string,
repoRoot: string,
options?: LoadTestSuiteOptions,
): ReturnType<typeof loadTestSuite> {
if (path.extname(testFilePath).toLowerCase() === '.json') {
const adapterSuite = readAgentSkillsEvalsFile(testFilePath);
return loadTestSuiteFromYamlObject(
testFilePath,
agentSkillsToAgentVYamlObject(adapterSuite),
repoRoot,
options,
);
}
return loadTestSuite(testFilePath, repoRoot, options);
}
function shouldSkipExistingResultForResume(
result: Pick<EvaluationResult, 'executionStatus'>,
rerunFailed: boolean,
): boolean {
if (rerunFailed) {
return result.executionStatus === 'ok';
}
return result.executionStatus !== 'execution_error';
}
interface ResumeIdentityEntry {
readonly kind: 'precise' | 'legacy';
readonly key: string;
readonly result: EvaluationResult;
}
interface ResumeIdentityMatcher {
readonly preciseKeys: Set<string>;
readonly legacyKeys: Set<string>;
}
function hasNonEmptyString(value: unknown): value is string {
return typeof value === 'string' && value.trim().length > 0;
}
function objectRecord(value: unknown): Record<string, unknown> | undefined {
return typeof value === 'object' && value !== null && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
}
function resultProjectionDimensions(result: EvaluationResult): Record<string, unknown> | undefined {
const projectionIdentity = objectRecord(
(result as unknown as Record<string, unknown>).projectionIdentity,
);
return objectRecord(projectionIdentity?.dimensions);
}
function hasCanonicalResultIdentity(result: EvaluationResult): boolean {
const source = result.source;
const dimensions = resultProjectionDimensions(result);
const resultRecord = result as unknown as Record<string, unknown>;
return (
hasNonEmptyString(dimensions?.evalPath) ||
hasNonEmptyString(dimensions?.suite) ||
hasNonEmptyString(dimensions?.promptId) ||
hasNonEmptyString(resultRecord.evalPath) ||
hasNonEmptyString(source?.evalFileRepoPath) ||
hasNonEmptyString(source?.evalFilePath) ||
hasNonEmptyString(source?.evalFileAbsolutePath) ||
hasNonEmptyString(result.suite) ||
hasNonEmptyString(result.prompt?.id)
);
}
function resultResumeIdentityEntry(result: EvaluationResult): ResumeIdentityEntry {
if (hasCanonicalResultIdentity(result)) {
return {
kind: 'precise',
key: buildEvaluationResultTargetKey(result),
result,
};
}
return {
kind: 'legacy',
key: buildTestTargetKey(result.testId, result.target, result.variant),
result,
};
}
function latestResumeIdentityEntries(
results: readonly EvaluationResult[],
): readonly ResumeIdentityEntry[] {
const latestByIdentity = new Map<string, ResumeIdentityEntry>();
for (const result of results) {
const entry = resultResumeIdentityEntry(result);
latestByIdentity.set(`${entry.kind}:${entry.key}`, entry);
}
return Array.from(latestByIdentity.values());
}
function createResumeIdentityMatcher(): ResumeIdentityMatcher {
return { preciseKeys: new Set<string>(), legacyKeys: new Set<string>() };
}
function addResumeIdentityEntry(matcher: ResumeIdentityMatcher, entry: ResumeIdentityEntry): void {
if (entry.kind === 'legacy') {
matcher.legacyKeys.add(entry.key);
return;
}
matcher.preciseKeys.add(entry.key);
}
function uniqueStrings(values: readonly (string | undefined)[]): string[] {
return Array.from(new Set(values.filter(hasNonEmptyString)));
}
function buildPlannedResumeIdentityKeys(
test: EvalTest,
target: string,
variant: string | undefined,
): readonly string[] {
const keys = new Set<string>([buildEvalTestTargetKey(test, target, variant)]);
const evalPaths = uniqueStrings([
test.source?.evalFileRepoPath,
test.source?.evalFilePath,
test.source?.evalFileAbsolutePath,
]);
const suites = Array.from(new Set<string | null>([test.suite ?? null, null]));
const promptIds = Array.from(new Set<string | null>([test.prompt?.id ?? null, null]));
for (const evalPath of evalPaths) {
for (const suite of suites) {
for (const promptId of promptIds) {
keys.add(
JSON.stringify({
eval_path: evalPath,
suite,
test_id: test.id ?? 'unknown',
prompt_id: promptId,
target: target ?? 'unknown',
variant: variant ?? null,
}),
);
}
}
}
return Array.from(keys);
}
function resumeIdentityMatches(
matcher: ResumeIdentityMatcher,
test: EvalTest,
target: string,
variant: string | undefined,
): boolean {
return (
buildPlannedResumeIdentityKeys(test, target, variant).some((key) =>
matcher.preciseKeys.has(key),
) || matcher.legacyKeys.has(buildTestTargetKey(test.id, target, variant))
);
}
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>: canonical artifact directory */
readonly outputDir?: string;
/** Removed: use --output for run directories */
readonly removedOut?: string;
readonly agentTimeoutSeconds?: number;
readonly cliAgentTimeoutSeconds?: number;
readonly maxRetries: number;
readonly cache: boolean;
readonly cachePath?: string;
readonly noCache: boolean;
readonly tsConfigCache?: boolean;
readonly tsConfigCachePath?: string;
readonly verbose: boolean;
readonly retryErrors?: string;
readonly resume: boolean;
readonly rerunFailed: boolean;
readonly rerunFailedSource?: string;
readonly workspacePath?: string;
readonly keepWorkspaces: boolean;
/** Removed: use --output instead */
readonly artifacts?: string;
/** Removed: the run directory always uses index.jsonl */
readonly outputFormat?: string;
readonly graderTarget?: string;
readonly model?: string;
readonly outputMessages: number | 'all';
readonly threshold?: number;
readonly cliThreshold?: number;
readonly tags: readonly string[];
readonly excludeTags: readonly string[];
/** Promptfoo-shaped `--tag key=value` entries (CLI layer of the tags map). */
readonly tagMap: Record<string, string>;
readonly transcript?: string;
readonly recordReplay?: string;
readonly recordReplayVariant?: string;
readonly experiment?: string;
readonly experimentConfig?: ExperimentConfig;
readonly experimentMetadata?: ExperimentArtifactMetadata;
readonly experimentTargets?: readonly string[];
readonly experimentTargetRefs?: readonly EvalTargetRef[];
readonly targetModelOverride?: string;
readonly experimentTrialsConfig?: TrialsConfig;
readonly budgetUsd?: number;
readonly cliBudgetUsd?: number;
readonly sourceMetadataByEvalFile?: ReadonlyMap<string, Record<string, unknown>>;
readonly resultsOverrides?: ResultsPublishOverrides;
}
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;
}
function resultsRepoOverride(
value: string | undefined,
): Pick<ResultsPublishOverrides, 'repo' | 'repo_path'> {
if (!value) {
return {};
}
if (
value === 'current' ||
value === '.' ||
value.startsWith('./') ||
value.startsWith('../') ||
value.startsWith('/') ||
value.startsWith('~/') ||
value.startsWith('~\\') ||
/^[A-Za-z]:[/\\]/.test(value)
) {
return { repo_path: value === 'current' ? '.' : value };
}
return { repo: value };
}
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 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);
}
function normalizeSourceMetadataByEvalFile(
value: unknown,
): ReadonlyMap<string, Record<string, unknown>> | undefined {
if (value instanceof Map) {
const entries = [...value.entries()].filter(
(entry): entry is [string, Record<string, unknown>] =>
typeof entry[0] === 'string' &&
typeof entry[1] === 'object' &&
entry[1] !== null &&
!Array.isArray(entry[1]),
);
return entries.length > 0
? new Map(entries.map(([key, metadata]) => [path.resolve(key), metadata]))
: undefined;
}
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
const entries = Object.entries(value).filter(
(entry): entry is [string, Record<string, unknown>] =>
typeof entry[1] === 'object' && entry[1] !== null && !Array.isArray(entry[1]),
);
return entries.length > 0
? new Map(entries.map(([key, metadata]) => [path.resolve(key), metadata]))
: undefined;
}
return undefined;
}
const LEGACY_OUTPUT_FILE_EXTENSIONS = new Set([
'.jsonl',
'.json',
'.xml',
'.yaml',
'.yml',
'.html',
'.htm',
]);
function looksLikeLegacyOutputFilePath(value: string): boolean {
return LEGACY_OUTPUT_FILE_EXTENSIONS.has(path.extname(value).toLowerCase());
}
function outputFileMigrationMessage(value: string): string {
const ext = path.extname(value).toLowerCase();
const removalHint =
ext === '.xml'
? 'JUnit XML export from agentv eval has been removed.'
: 'Flat result file export from agentv eval has been removed.';
return `--output expects a run directory, not a file path: ${value}\n${removalHint} Set --output <dir> for the canonical run artifacts; AgentV always writes <dir>/${RESULT_INDEX_FILENAME}.`;
}
function artifactsMigrationMessage(artifactsDir: string, outputDir?: string): string {
const lines = [`--artifacts was removed from agentv eval. Use --output ${artifactsDir} instead.`];
if (outputDir && looksLikeLegacyOutputFilePath(outputDir)) {
const ext = path.extname(outputDir).toLowerCase();
lines.push(
ext === '.xml'
? 'JUnit XML export from agentv eval has been removed.'
: 'Flat result file export from agentv eval has been removed.',
);
lines.push(`Migration example: --output ${artifactsDir}`);
}
return lines.join('\n');
}
/**
* 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;
}
/**
* Split repeatable `--tag` values into two shapes, mirroring the suite-level
* `tags` union (selection list vs promptfoo map):
*
* - `--tag key=value` (contains `=`) -> a `Record<string,string>` tag-map entry
* (promptfoo-shaped run metadata; the reserved `experiment` key feeds the
* experiment namespace).
* - `--tag name` (no `=`) -> a bare selection tag, preserving the existing
* file-level `--tag`/`--exclude-tag` AND-filter behavior.
*
* On repeated `key=value` for the same key, the last value wins. An empty value
* (`--tag experiment=`) is kept as an explicit empty string so callers can
* detect an intentional clear.
*/
export function splitCliTags(value: unknown): {
selectionTags: readonly string[];
tagMap: Record<string, string>;
} {
const selectionTags: string[] = [];
const tagMap: Record<string, string> = {};
for (const entry of normalizeStringArray(value)) {
const eq = entry.indexOf('=');
if (eq === -1) {
selectionTags.push(entry);
continue;
}
const key = entry.slice(0, eq).trim();
if (key.length === 0) {
continue;
}
tagMap[key] = entry.slice(eq + 1).trim();
}
return { selectionTags, tagMap };
}
/**
* Resolve the effective promptfoo-shaped tags map for a run by merging layers
* with precedence CLI `--tag key=value` > project config `tags` > eval `tags`.
* Returns undefined when no layer contributes any entry.
*/
export function resolveEffectiveTags(layers: {
evalTags?: Record<string, string>;
configTags?: Record<string, string>;
cliTags?: Record<string, string>;
}): Record<string, string> | undefined {
const merged: Record<string, string> = {
...(layers.evalTags ?? {}),
...(layers.configTags ?? {}),
...(layers.cliTags ?? {}),
};
return Object.keys(merged).length > 0 ? merged : undefined;
}
/**
* Keep an emitted tags map's `experiment` key in lockstep with the resolved
* experiment namespace so a row's `experiment` field and `tags.experiment` never
* disagree — but only when an experiment was intentionally set (`--experiment`,
* i.e. `experimentIsIntentional`, or an authored `tags.experiment`). A tags map
* that carries no experiment (e.g. only `--tag team=core`) must not gain an
* eval-default experiment key, and no tags map means nothing to emit.
*/
export function syncTagsExperiment(
resolvedTags: Record<string, string> | undefined,
options: { experimentIsIntentional: boolean; normalizedExperiment: string },
): Record<string, string> | undefined {
if (!resolvedTags) {
return undefined;
}
if (!options.experimentIsIntentional && resolvedTags.experiment === undefined) {
return resolvedTags;
}
return { ...resolvedTags, experiment: options.normalizedExperiment };
}
/**
* Resolve the experiment namespace and its provenance for a run.
*
* Precedence: `--experiment` (CLI) > `tags.experiment` (resolved tags map) >
* the eval-derived default (multi-eval label, suite `metadata.name`, or eval
* filename). This keeps `--experiment` authoritative while letting a
* promptfoo-shaped `tags.experiment` label a run, and preserves the existing
* default fallback when neither is set.
*/
export function resolveExperimentNamespace(params: {
cliExperiment?: string;
tagsExperiment?: string;
isMultiEval: boolean;
suiteName?: string;
resultGroupName: string;
}): {
experiment: string;
source: RunRuntimeSourceMetadata['experiment_namespace_source'];
} {
if (params.cliExperiment) {
return { experiment: params.cliExperiment, source: 'cli' };
}
if (params.tagsExperiment) {
return { experiment: params.tagsExperiment, source: 'tags' };
}
const source: RunRuntimeSourceMetadata['experiment_namespace_source'] = params.isMultiEval
? 'multi_eval'
: params.suiteName
? 'eval_metadata'
: 'eval_filename';
return { experiment: params.resultGroupName, source };
}
/**
* 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;
}
/**
* Deprecated compatibility hook for the old output-as-messages JSONL surface.
* Result `output` is now the final answer string; full transcript data stays
* under `trace.messages` and is intentionally not trimmed here.
*/
export function trimOutputMessages(
output: EvaluationResult['output'],
_outputMessages: number | 'all',
): EvaluationResult['output'] {
return output;
}
export function prepareResultForJsonl(
result: EvaluationResult,
options: { readonly outputMessages: number | 'all' },
): EvaluationResult {
return {
...result,
output: trimOutputMessages(result.output, options.outputMessages),
};
}
function normalizeOptions(
rawOptions: Record<string, unknown>,
config?: Awaited<ReturnType<typeof loadTsConfig>>,
yamlExecution?: ExecutionDefaults,
): NormalizedOptions {
const cliWorkers = normalizeOptionalNumber(rawOptions.workers);
const configWorkers = config?.execution?.maxConcurrency ?? yamlExecution?.max_concurrency;
const workers = cliWorkers ?? configWorkers ?? 0;
const cliOutputDir = normalizeString(rawOptions.output);
// 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 cliThreshold = normalizeOptionalNumber(rawOptions.threshold);
const cliBudgetUsd = normalizeOptionalNumber(rawOptions.budgetUsd);
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 --output > config output.dir > auto-generated
const cliOut = normalizeString(rawOptions.out);
const configOutputDir = normalizeString(config?.output?.dir);
const cliWorkspacePath = normalizeString(rawOptions.workspacePath);
const configWorkspacePath = normalizeString(yamlExecution?.workspace_path);
const workspacePath = cliWorkspacePath ?? configWorkspacePath;
const resultsRepo = normalizeString(rawOptions.resultsRepo);
const resultsPush = normalizeBoolean(rawOptions.resultsPush);
const resultsNoPush = normalizeBoolean(rawOptions.noResultsPush);
const resultsRequirePush = normalizeBoolean(rawOptions.resultsRequirePush);
const resultsOverrides: ResultsPublishOverrides = {
...resultsRepoOverride(resultsRepo),
...(normalizeString(rawOptions.resultsBranch) !== undefined && {
branch: normalizeString(rawOptions.resultsBranch),
}),
...(normalizeString(rawOptions.resultsRemote) !== undefined && {
remote: normalizeString(rawOptions.resultsRemote),
}),
...(resultsPush || resultsNoPush ? { auto_push: resultsPush && !resultsNoPush } : {}),
...(resultsRequirePush ? { require_push: true } : {}),
};
const cliTags = splitCliTags(rawOptions.tag);
return {
target: singleTarget,
cliTargets,
targetsPath: normalizeString(rawOptions.targets),
filter: normalizeFilter(rawOptions.filter),
workers: workers > 0 ? workers : undefined,
outputDir: cliOutputDir ?? configOutputDir,
removedOut: cliOut,
agentTimeoutSeconds: cliAgentTimeout ?? configAgentTimeoutSeconds,
cliAgentTimeoutSeconds: cliAgentTimeout,
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,
retryErrors: normalizeString(rawOptions.retryErrors),
resume:
normalizeBoolean(rawOptions.resume) || normalizeString(rawOptions.rerunFailed) !== undefined,
rerunFailed: normalizeString(rawOptions.rerunFailed) !== undefined,
rerunFailedSource: normalizeString(rawOptions.rerunFailed),
workspacePath,
// Precedence: CLI > YAML config > TS config
keepWorkspaces:
normalizeBoolean(rawOptions.keepWorkspaces) ||
yamlExecution?.keep_workspaces === true ||
config?.execution?.keepWorkspaces === true,
artifacts: normalizeString(rawOptions.artifacts),
outputFormat: normalizeString(rawOptions.outputFormat),
graderTarget: normalizeString(rawOptions.graderTarget),
model: normalizeString(rawOptions.model),
outputMessages: normalizeOutputMessages(normalizeString(rawOptions.outputMessages)),
threshold: cliThreshold,
cliThreshold,
tags: cliTags.selectionTags,
excludeTags: normalizeStringArray(rawOptions.excludeTag),
tagMap: cliTags.tagMap,
transcript: normalizeString(rawOptions.transcript),
recordReplay: normalizeString(rawOptions.recordReplay),
recordReplayVariant: normalizeString(rawOptions.recordReplayVariant),
experiment: normalizeString(rawOptions.experiment),
budgetUsd: cliBudgetUsd,
cliBudgetUsd,
sourceMetadataByEvalFile: normalizeSourceMetadataByEvalFile(
rawOptions.sourceMetadataByEvalFile,
),
resultsOverrides: Object.keys(resultsOverrides).length > 0 ? resultsOverrides : undefined,
} satisfies NormalizedOptions;
}
function withSourceMetadata(
result: EvaluationResult,
testFilePath: string,
options: NormalizedOptions,
): EvaluationResult {
const sourceMetadata = options.sourceMetadataByEvalFile?.get(path.resolve(testFilePath));
if (!sourceMetadata) {
return result;
}
return {
...result,
metadata: {
...result.metadata,
...sourceMetadata,
},
};
}
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 deriveEvalResultGroupName(evalFilePath: string | undefined): string {
if (!evalFilePath) {
return 'eval';
}
return (
path
.basename(evalFilePath)
.replace(/\.eval\.ya?ml$/i, '')
.replace(/\.ya?ml$/i, '')
.replace(/[^A-Za-z0-9._-]/g, '-') || 'eval'
);
}
const CLI_RUNTIME_SOURCE_OPTION_KEYS = [
'target',
'targets',
'filter',
'tag',
'excludeTag',
'workers',
'dryRun',
'dryRunDelay',
'dryRunDelayMin',
'dryRunDelayMax',
'agentTimeout',
'maxRetries',
'cache',
'cachePath',
'noCache',
'graderTarget',
'model',
'threshold',
'budgetUsd',
'transcript',
'recordReplay',
'recordReplayVariant',
'workspacePath',
] as const;
function hasCliRuntimeSource(rawOptions: Record<string, unknown>): boolean {
return CLI_RUNTIME_SOURCE_OPTION_KEYS.some((key) => {
const value = rawOptions[key];
if (Array.isArray(value)) {
return value.some((entry) => typeof entry === 'string' && entry.trim().length > 0);
}
if (typeof value === 'string') {
return value.trim().length > 0 && value.trim() !== 'default';
}
if (typeof value === 'number') {
return Number.isFinite(value) && value !== 0;
}
return value === true;
});
}
function toRuntimeSourcePath(cwd: string, filePath: string | undefined): string | undefined {
const trimmed = filePath?.trim();
if (!trimmed) {
return undefined;
}
const resolved = path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
const relative = path.relative(cwd, resolved);
const displayPath =
relative && !relative.startsWith('..') && !path.isAbsolute(relative) ? relative : trimmed;
return displayPath.split(path.sep).join('/');
}
function uniqueRuntimeSourcePaths(values: Iterable<string | undefined>): readonly string[] {
return [...new Set([...values].filter((value): value is string => Boolean(value)))].sort();
}
function testSourceEvalPath(cwd: string, test: EvalTest): string | undefined {
return (
toRuntimeSourcePath(cwd, test.source?.evalFileRepoPath) ??
toRuntimeSourcePath(cwd, test.source?.evalFileAbsolutePath) ??
toRuntimeSourcePath(cwd, test.source?.evalFilePath)
);
}
function testSourceEvalPathForComparison(test: EvalTest): string | undefined {
const sourcePath = test.source?.evalFileAbsolutePath ?? test.source?.evalFilePath;
return sourcePath ? path.resolve(sourcePath) : undefined;
}
function buildRuntimeConfigSource(params: {
readonly activeTestFiles: readonly string[];
readonly fileMetadata: ReadonlyMap<string, { readonly options: NormalizedOptions }>;
readonly hasCliRuntimeConfig: boolean;
}): RunRuntimeSourceMetadata['config_source'] {
const inlineFingerprints = new Set<string>();
let hasInlineExperiment = false;
let hasDefaultRuntime = false;
for (const activeTestFile of params.activeTestFiles) {
const experimentMetadata = params.fileMetadata.get(activeTestFile)?.options.experimentMetadata;
if (experimentMetadata) {
hasInlineExperiment = true;
inlineFingerprints.add(experimentMetadata.fingerprint ?? activeTestFile);
} else {
hasDefaultRuntime = true;
}
}
if (
(hasInlineExperiment && params.hasCliRuntimeConfig) ||
(hasInlineExperiment && hasDefaultRuntime) ||
inlineFingerprints.size > 1
) {
return 'mixed';
}
if (params.hasCliRuntimeConfig) {
return 'cli_flags';
}
if (hasInlineExperiment) {
return 'inline_experiment';
}
return 'defaults';
}
function buildRuntimeSourceMetadata(params: {
readonly cwd: string;
readonly activeTestFiles: readonly string[];
readonly sourceTests: readonly EvalTest[];
readonly fileMetadata: ReadonlyMap<string, { readonly options: NormalizedOptions }>;
readonly experimentNamespace: string;
readonly experimentNamespaceSource: RunRuntimeSourceMetadata['experiment_namespace_source'];
readonly hasCliRuntimeConfig: boolean;
}): RunRuntimeSourceMetadata {
const evalFiles = uniqueRuntimeSourcePaths(
params.activeTestFiles.map((filePath) => toRuntimeSourcePath(params.cwd, filePath)),
);
const activeResolvedFiles = new Set(
params.activeTestFiles.map((filePath) => path.resolve(filePath)),
);
const sourceEvalFiles = uniqueRuntimeSourcePaths(
params.sourceTests.map((test) => testSourceEvalPath(params.cwd, test)),
);
const hasImportedSuite = params.sourceTests.some((test) => test.source?.importedSuiteName);
const hasNonActiveSourceFile = params.sourceTests.some((test) => {
const sourceFile = testSourceEvalPathForComparison(test);
return sourceFile ? !activeResolvedFiles.has(sourceFile) : false;
});
const kind =
params.activeTestFiles.length > 1
? 'multi_eval'
: hasImportedSuite || hasNonActiveSourceFile
? 'wrapper_eval'
: 'direct_suite';
const wrapperEvalFile =
kind === 'wrapper_eval'
? toRuntimeSourcePath(params.cwd, params.activeTestFiles[0])
: undefined;
return {
schema_version: 'agentv.runtime_source.v1',
kind,
config_source: buildRuntimeConfigSource({
activeTestFiles: params.activeTestFiles,
fileMetadata: params.fileMetadata,
hasCliRuntimeConfig: params.hasCliRuntimeConfig,
}),
experiment_namespace: params.experimentNamespace,
experiment_namespace_source: params.experimentNamespaceSource,
eval_files: evalFiles,
...(wrapperEvalFile && { wrapper_eval_file: wrapperEvalFile }),
...(sourceEvalFiles.length > 0 && { source_eval_files: sourceEvalFiles }),
};
}
type ResolvedExperimentForRun = {
readonly name?: string;
};
function resolveExperimentForRun(explicitExperiment?: string): ResolvedExperimentForRun {
return explicitExperiment ? { name: explicitExperiment } : {};
}
function applyExperimentOptions(
options: NormalizedOptions,
experiment: ExperimentConfig | undefined,
): NormalizedOptions {
if (!experiment) {
return options;
}
const experimentTargetRefs = buildExperimentTargetRefs(experiment);
const experimentTargetNames = experimentTargetRefs?.map((target) => target.name) ?? [];
const experimentTarget =
experiment.target && experiment.target.trim().length > 0 ? experiment.target : undefined;
const experimentTargets =
options.cliTargets.length === 0
? experimentTargetNames.length > 0
? experimentTargetNames
: experimentTarget
? [experimentTarget]
: undefined
: undefined;
return {
...options,
target: options.target,
agentTimeoutSeconds: options.agentTimeoutSeconds ?? experiment.timeoutSeconds,
workspacePath: options.workspacePath,
budgetUsd: options.budgetUsd ?? experiment.budgetUsd,
threshold: options.threshold ?? experiment.threshold,
experimentConfig: experiment,
experimentMetadata: buildExperimentArtifactMetadata(experiment),
experimentTargets,
experimentTargetRefs: options.cliTargets.length === 0 ? experimentTargetRefs : undefined,
targetModelOverride: options.targetModelOverride ?? experiment.model,
experimentTrialsConfig: buildExperimentTrialsConfig(experiment),
};
}
function buildExperimentTargetRefs(
experiment: ExperimentConfig,
): readonly EvalTargetRef[] | undefined {