Skip to content

Python API

Reference for the agent_eval package, generated from the source docstrings and type hints. Most users drive the harness through the slash commands and eval.yaml — this page is for extending it (for example, writing a custom runner) or embedding it in your own tooling.

Autodoc

These entries are rendered by mkdocstrings. The documentation build runs pip install -e . so the package is importable; add more ::: directives to this page to surface additional modules.

Configuration

The entire eval.yaml surface is parsed into EvalConfig. See the eval.yaml reference for the YAML-level documentation of every field.

agent_eval.config.EvalConfig dataclass

EvalConfig(name='', description='', skill=None, permissions=dict(), hooks=HooksConfig(), execution=ExecutionConfig(), runner=RunnerConfig(), models=ModelsConfig(), mlflow=MlflowConfig(), dataset=DatasetConfig(), generation=GenerationConfig(), outputs=list(), inputs=InputsConfig(), traces=TracesConfig(), judges=list(), reward=None, thresholds=dict(), config_dir=None, config_path=None, config_chain=list(), model='', subagent_model='', run_id='', baseline='')

Complete evaluation suite configuration.

Structure is schema-driven: dataset and output structures are described in natural language. The harness interprets these descriptions via LLM (once, cached) to drive prepare, collect, and score steps.

project_root property

project_root

Project root directory (always CWD, not the eval.yaml location).

eval_name

eval_name()

Derive eval identifier with backward-compatible fallback chain.

Priority order (backward-compatible with existing skill evals): 1. skill field - preserves existing skill-based eval runs 2. name field - allows explicit naming for prompt-mode evals 3. directory/filename - pure path-based derivation 4. "eval" - final fallback

This ensures existing skill evals continue to work while enabling prompt mode to use either explicit names or path-based identifiers.

Source code in agent_eval/config.py
def eval_name(self) -> str:
    """Derive eval identifier with backward-compatible fallback chain.

    Priority order (backward-compatible with existing skill evals):
    1. skill field - preserves existing skill-based eval runs
    2. name field - allows explicit naming for prompt-mode evals
    3. directory/filename - pure path-based derivation
    4. "eval" - final fallback

    This ensures existing skill evals continue to work while enabling
    prompt mode to use either explicit names or path-based identifiers.
    """
    # Priority 1: skill field (backward compat with existing evals).
    # Resolve through resolve_skill() so execution.skill-only configs
    # still name the run after the skill under test.
    skill = self.resolve_skill()
    if skill:
        return skill

    # Priority 2: name field (explicit identifier, sanitized)
    # Skip if name == path.stem (auto-set default from from_yaml)
    if self.name and not (self.config_path and self.name == self.config_path.stem):
        # Sanitize: convert spaces to hyphens, keep only safe chars
        sanitized = self.name.lower().replace(" ", "-")
        sanitized = "".join(c for c in sanitized if c.isalnum() or c in "._-")
        if sanitized and _is_valid_eval_name(sanitized):
            return sanitized

    # Priority 3: derive from path (new behavior for prompt mode)
    if self.config_path:
        if self.config_path.name == "eval.yaml":
            # Nested: eval/user-guides/eval.yaml → "user-guides"
            # Check if grandparent directory is named "eval"
            if self.config_path.parent.parent.name == "eval":
                return self.config_path.parent.name
            # Root: eval.yaml at project root → "eval"
            else:
                return "eval"
        # Flat: eval/user-guides.yaml → "user-guides"
        else:
            return self.config_path.stem

    # Final fallback
    return "eval"

from_yaml classmethod

from_yaml(path)

Load config from a YAML file.

Source code in agent_eval/config.py
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
@classmethod
def from_yaml(cls, path: str | Path) -> "EvalConfig":
    """Load config from a YAML file."""
    path = Path(path)
    if not path.exists():
        raise FileNotFoundError(f"Config not found: {path}")

    # The single raw loader resolves `extends:`; paths below (dataset,
    # eval_name) are taken from the ROOT of the chain, the base config.
    raw, chain = load_raw(path)
    root_path = Path(chain[0])

    # Deprecation: top-level `skill:` is auto-normalized into
    # execution.skill (below) but the canonical home is the execution
    # block, symmetric with execution.prompt. Warn once per load; only
    # for a non-empty value that isn't already mirrored in execution.
    exec_raw = raw.get("execution", {})
    if raw.get("skill") and not (exec_raw.get("skill") or "").strip():
        import warnings
        warnings.warn(
            f"Top-level 'skill:' in {path} is deprecated; move it under "
            "execution.skill (it is auto-normalized for now and will be "
            "removed in a future release).",
            DeprecationWarning,
            stacklevel=2,
        )

    # Dataset
    dataset = raw.get("dataset", {})

    # Execution config — including an optional multi-step pipeline.
    steps = []
    for i, s in enumerate(exec_raw.get("steps") or []):
        if not isinstance(s, dict):
            raise ValueError(f"execution.steps[{i}] must be a mapping")
        step_runner = None
        if s.get("runner"):
            step_runner = _parse_runner_config(
                s.get("runner"), context=f"execution.steps[{i}].runner")
        step_env = s.get("env") or {}
        if not isinstance(step_env, dict):
            raise ValueError(
                f"execution.steps[{i}].env must be a mapping")
        step_timeout = s.get("timeout")
        if step_timeout is not None and (
                not isinstance(step_timeout, int)
                or isinstance(step_timeout, bool)
                or step_timeout <= 0):
            raise ValueError(
                f"execution.steps[{i}].timeout must be a positive integer")
        step_budget = s.get("max_budget_usd")
        if step_budget is not None and (
                not isinstance(step_budget, (int, float))
                or isinstance(step_budget, bool)
                or step_budget < 0):
            raise ValueError(
                f"execution.steps[{i}].max_budget_usd must be a "
                "non-negative number")
        step = StepConfig(
            id=s.get("id", "") or "",
            name=s.get("name", "") or "",
            skill=s.get("skill", "") or "",
            prompt=s.get("prompt", "") or "",
            arguments=s.get("arguments", "") or "",
            env=step_env,
            timeout=step_timeout,
            max_budget_usd=step_budget,
            runner=step_runner,
            on_failure=s.get("on_failure", "fail"),
        )
        if not ((step.skill and step.skill.strip())
                or (step.prompt and step.prompt.strip())):
            raise ValueError(
                f"execution.steps[{i}] ('{step.id}') must set either "
                "skill or prompt")
        steps.append(step)

    execution = ExecutionConfig(
        mode=exec_raw.get("mode", "case"),
        skill=exec_raw.get("skill", "") or raw.get("skill", ""),
        prompt=exec_raw.get("prompt", ""),
        arguments=exec_raw.get("arguments", ""),
        timeout=exec_raw.get("timeout"),
        max_budget_usd=exec_raw.get("max_budget_usd"),
        parallelism=_optional_int(
            exec_raw.get("parallelism"), "execution.parallelism"),
        judge_parallelism=_optional_int(
            exec_raw.get("judge_parallelism"), "execution.judge_parallelism"),
        env=exec_raw.get("env") or {},
        project_hooks=exec_raw.get("project_hooks", True),
        # Default to [] only when absent/null; any other value goes through
        # unchanged so ExecutionConfig rejects a non-list (`false`, "types").
        symlinks=(
            [] if exec_raw.get("symlinks") is None else exec_raw["symlinks"]
        ),
        steps=steps,
    )

    # Runner config (block form)
    runner = _parse_runner_config(raw.get("runner"), context="runner")
    if runner.type == "fullsend" and execution.prompt and execution.prompt.strip():
        raise ValueError(
            "runner.type: the 'fullsend' runner cannot be used with "
            "execution.prompt: it runs a skill as FULLSEND_TASK and does not "
            "support prompt mode — set execution.skill")
    for i, step in enumerate(steps):
        eff = step.runner or runner
        if eff.type == "fullsend" and step.prompt and step.prompt.strip():
            raise ValueError(
                f"execution.steps[{i}]: the 'fullsend' runner cannot run a "
                "prompt step (prompt mode is unsupported) — set skill")

    # Models block (+ the provider registry, spec 014 Decision 17)
    if "providers" in raw:
        raise ValueError(
            "'providers' moved: declare providers under `models.providers` "
            "(spec 014 Decision 17)")
    models_raw = raw.get("models", {}) or {}
    models = ModelsConfig(
        skill=models_raw.get("skill"),
        subagent=models_raw.get("subagent"),
        judge=models_raw.get("judge"),
        hook=models_raw.get("hook"),
        judge_verdict=_check_verdict_policy(models_raw.get("judge_verdict"),
                                            "models.judge_verdict"),
        providers=_parse_providers(models_raw.get("providers")),
    )

    # MLflow block. Experiment defaults to the eval's top-level
    # `name` only when an `mlflow:` block is present — so omitting
    # the block entirely leaves MLflow off (no accidental experiment
    # creation on shared tracking servers).
    has_mlflow_block = "mlflow" in raw and raw["mlflow"] is not None
    mlflow_raw = raw.get("mlflow") or {}
    if has_mlflow_block:
        experiment = mlflow_raw.get("experiment") or raw.get("name", "")
    else:
        experiment = ""
    mlflow = MlflowConfig(
        experiment=experiment,
        tracking_uri=mlflow_raw.get("tracking_uri"),
        tags=mlflow_raw.get("tags", {}) or {},
    )

    # Dataset — path, schema, and workspace file provisioning
    ws_raw = dataset.get("workspace", {}) or {}
    ws_files_raw = ws_raw.get("files", []) or []
    ws_files = []
    for i, f in enumerate(ws_files_raw):
        if isinstance(f, str):
            ws_files.append(
                _validate_relative_path(f.rstrip("/"), "dataset.workspace.files")
            )
        elif isinstance(f, dict):
            field_ctx = f"dataset.workspace.files[{i}]"
            missing = {"dest", "source"} - set(f)
            if missing:
                raise ValueError(
                    f"{field_ctx} is missing required key(s): "
                    f"{', '.join(sorted(missing))}"
                )
            extra = set(f) - {"dest", "source"}
            if extra:
                raise ValueError(
                    f"{field_ctx} has unknown key(s): {', '.join(sorted(extra))} "
                    f"(only 'dest' and 'source' are allowed)"
                )
            dest, source = f["dest"], f["source"]
            if not isinstance(dest, str) or not dest:
                raise ValueError(f"{field_ctx}.dest must be a non-empty string")
            if not isinstance(source, str) or not source:
                raise ValueError(f"{field_ctx}.source must be a non-empty string")
            # dest becomes a filesystem path inside the workspace, so reject
            # traversal/absolute. source is resolved (and containment-checked)
            # at materialization time, so it may be relative or absolute here.
            ws_files.append(
                WorkspaceFile(
                    # "/" strips to "" (which _validate_relative_path would
                    # wave through); normalize to "." so reject_root catches it.
                    dest=_validate_relative_path(
                        dest.rstrip("/") or ".", f"{field_ctx}.dest",
                        reject_root=True,
                    ),
                    source=source,
                )
            )
        else:
            raise ValueError(
                f"dataset.workspace.files[{i}] must be a string or a "
                f"{{dest, source}} mapping, got {type(f).__name__}"
            )
    dataset_config = DatasetConfig(
        path=_validate_relative_path(
            dataset.get("path", ""), "dataset.path", allow_absolute=True
        ),
        schema=dataset.get("schema", ""),
        workspace=WorkspaceConfig(files=ws_files),
    )
    # Generation — synthetic test-case generation (optional) with validation
    gen_raw = raw.get("generation") or {}
    seeds = []
    for i, s in enumerate(gen_raw.get("seeds") or []):
        category = s.get("category", "")
        count = s.get("count")
        if not category or not isinstance(category, str):
            raise ValueError(
                f"generation.seeds[{i}].category must be a non-empty string, got: {category!r}")
        # count is required — a silent default would swallow a mistyped field name
        if not isinstance(count, int) or count < 1:
            raise ValueError(
                f"generation.seeds[{i}].count must be an integer >= 1, got: {count!r}")

        # Exactly one prompt discriminator (mirrors judges: builtin/prompt_file/prompt)
        discriminators = [
            k for k in ("builtin", "prompt_file", "prompt") if s.get(k)
        ]
        if len(discriminators) != 1:
            raise ValueError(
                f"generation.seeds[{i}] ('{category}') must set exactly one of "
                f"builtin / prompt_file / prompt, got: {discriminators or 'none'}")

        seeds.append(GenerationSeed(
            category=category,
            count=count,
            builtin=s.get("builtin", ""),
            prompt_file=s.get("prompt_file", ""),
            prompt=s.get("prompt", ""),
            description=s.get("description", ""),
        ))

    # Provenance: absent normalizes to 'skill' (the default source).
    strategy = gen_raw.get("strategy") or "skill"
    if strategy not in GENERATION_STRATEGIES:
        raise ValueError(
            f"generation.strategy must be one of "
            f"{', '.join(GENERATION_STRATEGIES)}, got: {strategy!r}")
    if strategy == "synthetic" and not seeds:
        raise ValueError(
            "generation.strategy is 'synthetic' but generation.seeds is empty.")
    if seeds and strategy != "synthetic":
        raise ValueError(
            f"generation.seeds are only valid with strategy: synthetic "
            f"(got strategy: {strategy}).")

    generation_config = GenerationConfig(
        strategy=strategy,
        context=gen_raw.get("context", {}),
        seeds=seeds,
    )

    config = cls(
        name=raw.get("name", root_path.stem),
        description=raw.get("description", ""),
        skill=raw.get("skill") or None,  # Convert empty string to None
        permissions=raw.get("permissions", {}),
        execution=execution,
        runner=runner,
        models=models,
        mlflow=mlflow,
        config_dir=root_path.parent,
        config_path=root_path,
        config_chain=config_chain_display(chain),
        dataset=dataset_config,
        generation=generation_config,
    )

    # Outputs (path or tool)
    for i, o in enumerate(raw.get("outputs", [])):
        out_path = _validate_relative_path(
            o.get("path", ""), f"outputs[{i}].path", reject_root=True
        )
        # Normalise once, here, to the spelling `collect.py` keys its
        # manifest by (`_safe_path_component`: `str(Path(...))`). `./out`
        # and `out/` are the same directory, so every reader of
        # `outputs[].path` — including the reserved-name check below —
        # must see one spelling, and that check cannot drift from the
        # consumer. An empty path (a tool output) stays empty.
        if out_path:
            out_path = str(Path(out_path))
        # `collection.json` records a case's per-output counts and its
        # unlistable paths in one mapping, so an output by this name would
        # put an int where the loss list goes and fail validation for a
        # case that lost nothing. Rejected here rather than reshaped: the
        # manifest is internal, and a reserved output name is the idiom
        # this file already uses (`RESERVED_WORKSPACE_NAMES`).
        if out_path == COLLECTION_LOSS_KEY:
            raise ValueError(
                f"outputs[{i}].path: {COLLECTION_LOSS_KEY!r} is reserved — "
                "collection records lost paths under that name")
        config.outputs.append(
            OutputConfig(
                path=out_path,
                tool=o.get("tool", ""),
                schema=o.get("schema", ""),
                batch_pattern=o.get("batch_pattern", ""),
                types=o.get("types") or None,
            )
        )

    _reject_reserved_symlinks(config)

    # Inputs (tool interception)
    inputs_raw = raw.get("inputs", {})
    for t in inputs_raw.get("tools") or []:
        config.inputs.tools.append(
            ToolInputConfig(
                match=t.get("match", ""),
                prompt=t.get("prompt", ""),
                prompt_file=t.get("prompt_file", ""),
            )
        )

    # Traces
    traces = raw.get("traces", {})
    if traces:
        config.traces = TracesConfig(
            stdout=traces.get("stdout", True),
            stderr=traces.get("stderr", True),
            events=traces.get("events", True),
            metrics=traces.get("metrics", True),
        )

    # Judges
    for j in raw.get("judges", []):
        builtin_val = j.get("builtin", "")
        if builtin_val is None:
            builtin_val = ""
        if not isinstance(builtin_val, str):
            raise ValueError(
                f"Judge '{j.get('name', '')}': 'builtin' must be a string"
            )
        args_val = j.get("arguments")
        if args_val is None:
            args_val = {}
        elif not isinstance(args_val, dict):
            raise ValueError(
                f"Judge '{j.get('name', '')}': 'arguments' must be a mapping"
            )
        agent_val = j.get("agent")
        if agent_val is None:
            agent_val = {}
        elif not isinstance(agent_val, dict):
            raise ValueError(
                f"Judge '{j.get('name', '')}': 'agent' must be a mapping"
            )
        elif agent_val.get("runner") is not None:
            # Parse the nested runner: sub-block with the SAME block-parsing
            # logic as the top-level runner, so a judge's runner is fully
            # validated. Shallow-copy so the raw YAML isn't mutated.
            if not isinstance(agent_val["runner"], dict):
                raise ValueError(
                    f"Judge '{j.get('name', '')}': 'agent.runner' must be a mapping"
                )
            agent_val = dict(agent_val)
            agent_val["runner"] = _parse_runner_config(
                agent_val["runner"],
                context=f"Judge '{j.get('name', '')}': agent.runner",
                reject_fullsend="an agent judge's runner",
            )
        # A bare string would be iterated per character downstream
        # (`denied_tools: Bash` -> deny B,a,s,h), silently denying nothing.
        for tools_key in ("allowed_tools", "denied_tools"):
            tools_val = agent_val.get(tools_key)
            if tools_val is None:
                continue
            if (not isinstance(tools_val, list)
                    or any(not isinstance(t, str) for t in tools_val)):
                raise ValueError(
                    f"Judge '{j.get('name', '')}': 'agent.{tools_key}' "
                    f"must be a list of tool names"
                )
            _warn_unknown_tool_names(
                tools_val, f"Judge '{j.get('name', '')}': "
                           f"'agent.{tools_key}'",
                is_allow=(tools_key == "allowed_tools"))
            # The forced deny-by-default mode is claude-code-only; a judge
            # on another runner never hits it.
            judge_runner = agent_val.get("runner")
            if (tools_key == "allowed_tools" and tools_val
                    and (judge_runner is None
                         or judge_runner.type == "claude-code")):
                _warn_allow_without_write_rule(
                    tools_val, f"Judge '{j.get('name', '')}': "
                               f"'agent.{tools_key}'")
        score_range_val = j.get("score_range")
        if score_range_val is not None:
            jname = j.get("name", "")
            if (not isinstance(score_range_val, list)
                    or len(score_range_val) != 2):
                raise ValueError(
                    f"Judge '{jname}': 'score_range' must be a [min, max] list")
            try:
                lo, hi = float(score_range_val[0]), float(score_range_val[1])
            except (TypeError, ValueError) as exc:
                raise ValueError(
                    f"Judge '{jname}': 'score_range' values must be numeric") from exc
            if not (math.isfinite(lo) and math.isfinite(hi)) or lo >= hi:
                raise ValueError(
                    f"Judge '{jname}': 'score_range' must be finite and "
                    "increasing [min, max]")
            score_range_val = [lo, hi]
        examples_val = j.get("examples")
        if examples_val is not None:
            jname = j.get("name", "")
            if not isinstance(examples_val, dict):
                raise ValueError(
                    f"Judge '{jname}': 'examples' must be a mapping")
            unknown = set(examples_val) - {"source", "count", "mix"}
            if unknown:
                raise ValueError(
                    f"Judge '{jname}': 'examples' has unknown key(s): "
                    f"{', '.join(sorted(unknown))} (only 'source', "
                    "'count' and 'mix' are allowed)")
            ex_source = examples_val.get("source", "reviews")
            if ex_source not in JUDGE_EXAMPLE_SOURCES:
                raise ValueError(
                    f"Judge '{jname}': examples.source must be one of "
                    f"{', '.join(JUDGE_EXAMPLE_SOURCES)}, got: {ex_source!r}")
            ex_count = examples_val.get("count", 3)
            if (not isinstance(ex_count, int) or isinstance(ex_count, bool)
                    or ex_count < 1):
                raise ValueError(
                    f"Judge '{jname}': examples.count must be an integer "
                    f">= 1, got: {ex_count!r}")
            ex_mix = examples_val.get("mix", ["pass", "fail"])
            if (not isinstance(ex_mix, list) or not ex_mix
                    or any(m not in ("pass", "fail") for m in ex_mix)
                    or len(set(ex_mix)) != len(ex_mix)):
                raise ValueError(
                    f"Judge '{jname}': examples.mix must be a non-empty "
                    "list of unique values from 'pass'/'fail', got: "
                    f"{ex_mix!r}")
            examples_val = JudgeExamplesConfig(
                source=ex_source, count=ex_count, mix=list(ex_mix))
        config.judges.append(
            JudgeConfig(
                name=j.get("name", ""),
                description=j.get("description", ""),
                condition=j.get("if", ""),
                check=j.get("check", ""),
                prompt=j.get("prompt", ""),
                prompt_file=j.get("prompt_file", ""),
                llm_rubric=j.get("llm_rubric", ""),
                context=j.get("context", []),
                feedback_type=j.get("feedback_type", ""),
                score_range=score_range_val,
                model=j.get("model", ""),
                module=j.get("module", ""),
                function=j.get("function", ""),
                builtin=builtin_val,
                arguments=args_val,
                step=j.get("step", "") or "",
                samples=int(j.get("samples", 1)),
                examples=examples_val,
                agent=agent_val,
                provider_options=j.get("provider_options") or {},
                verdict=_check_verdict_policy(
                    j.get("verdict"), f"Judge '{j.get('name', '')}': 'verdict'",
                    default=""),
                feedback_rationale=bool(j.get("feedback_rationale", False)),
            )
        )

    # Per-step judge scoping: a judge's `step:` must name a defined
    # execution step (fail loud on typos, like reward.judge validation).
    step_ids = {s.id for s in execution.steps}
    for jc in config.judges:
        if not jc.step:
            continue
        if not execution.steps:
            raise ValueError(
                f"Judge '{jc.name}': 'step: {jc.step}' requires an "
                "execution.steps pipeline")
        if jc.step not in step_ids:
            raise ValueError(
                f"Judge '{jc.name}': 'step: {jc.step}' does not match any "
                f"execution step id ({sorted(step_ids)})")

    # Scale coherence: a judge's declared scale has to agree with its
    # feedback_type and with the scorer that will actually run it. Each of
    # these used to be accepted and then quietly ignored at scoring time,
    # which is how a judge shipped scoring on a scale nobody declared.
    from agent_eval.judges import builtin_judge_kind, builtin_judge_names

    for jc in config.judges:
        builtin_kind = builtin_judge_kind(jc.builtin) if jc.builtin else None
        if jc.builtin and builtin_kind is None:
            raise ValueError(
                f"Judge '{jc.name}': unknown builtin judge '{jc.builtin}' "
                f"(available: {', '.join(builtin_judge_names())})")
        if jc.feedback_type not in ("", "bool", "int", "float"):
            raise ValueError(
                f"Judge '{jc.name}': unsupported feedback_type "
                f"'{jc.feedback_type}' — use 'bool', 'int', or 'float'. "
                "Categorical ('str'/'Literal[...]') verdicts are not "
                "supported by the LLM/agent judge paths.")
        if jc.feedback_type == "bool" and jc.score_range:
            raise ValueError(
                f"Judge '{jc.name}': 'score_range' has no meaning with "
                "'feedback_type: bool' (the verdict is pass/fail) — "
                "drop one of the two")
        if (jc.feedback_type == "int" and jc.score_range
                and any(float(b) != int(b) for b in jc.score_range)):
            raise ValueError(
                f"Judge '{jc.name}': 'feedback_type: int' cannot express "
                f"the fractional 'score_range' {jc.score_range} — use "
                "'feedback_type: float'")
        if (builtin_kind == "llm"
                and (jc.feedback_type not in ("", "bool") or jc.score_range)):
            raise ValueError(
                f"Judge '{jc.name}': builtin LLM judge '{jc.builtin}' is "
                "always scored as pass/fail, so 'feedback_type'/"
                "'score_range' would be silently ignored")
        # `examples` only exists where the harness renders the judge's
        # own prompt — LLM and agent judges. On any other type the block
        # would be silently ignored, so reject it at load like the
        # score_range declarations above.
        if jc.examples and (jc.builtin or jc.check
                            or jc.module or jc.function):
            kind = ("builtin" if jc.builtin
                    else "check" if jc.check else "code")
            raise ValueError(
                f"Judge '{jc.name}': 'examples' only applies to LLM and "
                "agent judges (prompt/prompt_file/llm_rubric/agent) — on "
                f"a {kind} judge it would be silently ignored")
        # The reserved pairwise judge never goes through the per-judge
        # prompt renderer (score.py routes it into the A/B comparison
        # flow), so an `examples` block there would be silently ignored
        # too.
        if jc.examples and jc.name == "pairwise":
            raise ValueError(
                "Judge 'pairwise': 'examples' does not apply to the "
                "pairwise comparison judge — its prompt is rendered by "
                "the comparison flow, which never injects exemplars")
        # `feedback_type` is optional, and score.py's `_numeric_bounds`
        # treats anything that is not "bool" as numeric — so the judge that
        # most needs this warning is the one that declares neither field,
        # and gating on ("int", "float") alone never reached it.
        # The judge named "pairwise" is exempt: score.py routes it past
        # the numeric path by that name into the A/B/tie verdict flow, so
        # no scale — declared or defaulted — is ever applied to it.
        if (jc.feedback_type in ("int", "float", "") and not jc.score_range
                and not jc.builtin and jc.name != "pairwise"
                and (jc.prompt or jc.prompt_file or jc.llm_rubric)):
            import warnings
            warnings.warn(
                f"Judge '{jc.name}': numeric judge has no 'score_range', "
                "so it is scored on the unenforced [1, 5] default — "
                "declare one to have the returned value checked",
                stacklevel=2)

    # Reward composition
    if "reward" in raw:
        reward_raw = raw.get("reward")
        if not isinstance(reward_raw, dict):
            raise ValueError("reward must be a mapping when provided")
        sr = reward_raw.get("score_range")
        reward_score_range = None
        if sr is not None:
            if not isinstance(sr, list) or len(sr) != 2:
                raise ValueError(
                    "reward.score_range must be a [min, max] list")
            try:
                score_min = float(sr[0])
                score_max = float(sr[1])
            except (TypeError, ValueError) as exc:
                raise ValueError(
                    "reward.score_range values must be numeric") from exc
            if (not (math.isfinite(score_min) and math.isfinite(score_max))
                    or score_min >= score_max):
                raise ValueError(
                    "reward.score_range must be finite and increasing "
                    "[min, max]")
            reward_score_range = [score_min, score_max]
        weights = reward_raw.get("weights", {}) or {}
        if not isinstance(weights, dict):
            raise ValueError("reward.weights must be a mapping")
        try:
            weights = {str(k): float(v) for k, v in weights.items()}
        except (TypeError, ValueError) as exc:
            raise ValueError(
                "reward.weights values must be numeric") from exc
        if any(v < 0 for v in weights.values()):
            raise ValueError("reward.weights values must be non-negative")
        raw_list = reward_raw.get("raw", []) or []
        if not isinstance(raw_list, list):
            raw_list = [raw_list]
        # Single-judge mode: one judge's value is the reward. Mutually
        # exclusive with the composition inputs.
        judge = reward_raw.get("judge")
        if judge is not None:
            if not isinstance(judge, str) or not judge.strip():
                raise ValueError(
                    "reward.judge must be a non-empty judge name")
            conflicting = [k for k in ("formula", "weights", "raw")
                           if k in reward_raw]
            if conflicting:
                raise ValueError(
                    "reward.judge cannot be combined with "
                    f"{'/'.join(conflicting)}")
            judge_names = {j.name for j in config.judges if j.name}
            if judge not in judge_names:
                raise ValueError(
                    f"reward.judge '{judge}' does not match any defined "
                    "judge")
        normalize = reward_raw.get("normalize", False)
        if not isinstance(normalize, bool):
            raise ValueError("reward.normalize must be a boolean")
        # gate defaults to False in judge mode, True for composition.
        gate = reward_raw.get("gate", judge is None)
        if not isinstance(gate, bool):
            raise ValueError("reward.gate must be a boolean")
        formula = str(reward_raw.get("formula", "weighted"))
        # Validate expression formulas now so a typo or unsafe construct
        # fails loudly here, not silently as reward 0.0 on every case at
        # run time. Bare references ("weighted") are resolved at compute
        # time, so skip the expression check for them. Skipped in judge
        # mode, where formula is unused.
        if judge is None and not re.fullmatch(
                r"[A-Za-z_][\w.\-]*", formula.strip()):
            from agent_eval.harbor.reward import validate_formula
            try:
                validate_formula(formula)
            except ValueError as exc:
                raise ValueError(
                    f"reward.formula is invalid: {exc}") from exc
        config.reward = RewardConfig(
            formula=formula,
            weights=weights,
            gate=gate,
            score_range=reward_score_range,
            raw=[str(r) for r in raw_list],
            judge=judge,
            normalize=normalize,
        )
        if sr is not None:
            _warn_reward_range_precedence(config)
        _warn_reward_judge_clamp(config)

    # Thresholds
    config.thresholds = raw.get("thresholds", {})

    # Hooks
    hooks_raw = raw.get("hooks", {}) or {}
    phases = ["before_all", "before_each", "after_each", "before_step",
              "after_step", "before_scoring", "after_all", "before_report"]
    for phase in phases:
        entries = []

        for h in (hooks_raw.get(phase) or []):
            # Left as None when unset: the phase default is applied at
            # run time by `hooks.effective_on_failure`, in one place.
            on_failure_val = h.get("on_failure")
            if on_failure_val is not None and on_failure_val not in (
                    "fail", "continue"):
                raise ValueError(
                    f"hooks.{phase}: on_failure must be 'fail' or "
                    f"'continue', got '{on_failure_val}'")
            timeout_val = h.get("timeout", 120)
            if not isinstance(timeout_val, int) or timeout_val <= 0:
                raise ValueError(
                    f"hooks.{phase}: timeout must be a positive "
                    f"integer, got {timeout_val}")
            entries.append(HookEntry(
                command=h.get("command", ""),
                timeout=timeout_val,
                description=h.get("description", ""),
                on_failure=on_failure_val,
                condition=h.get("condition", ""),
            ))
        setattr(config.hooks, phase, entries)

    if config.execution.mode == "batch":
        per_case = []
        if config.hooks.before_each:
            per_case.append("before_each")
        if config.hooks.after_each:
            per_case.append("after_each")
        if config.hooks.before_step:
            per_case.append("before_step")
        if config.hooks.after_step:
            per_case.append("after_step")
        if per_case:
            import warnings
            warnings.warn(
                f"hooks.{', '.join(per_case)} ignored in batch mode "
                f"(per-case hooks only run in case/prompt mode)",
                stacklevel=2,
            )

    resolved_skill = config.resolve_skill()
    if resolved_skill:
        try:
            _validate_path_segment(resolved_skill, f"skill name in {path}")
        except ValueError as e:
            raise ValueError(str(e)) from e

    runners = [config.runner]
    runners.extend(
        step.runner for step in config.execution.steps if step.runner)
    for runner in runners:
        # codex, cursor and fullsend do not support tool interception
        # (fullsend strips the harness's interception hooks from the
        # uploaded workspace settings, keeping only the project's own);
        # reject at load (same altitude as codex) rather than only at
        # runner construction.
        if (runner.type in ("codex", "cursor", "fullsend")
                and config.inputs.tools):
            raise ValueError(
                f"runner.type '{runner.type}' does not support "
                "inputs.tools interception; use claude-code or remove "
                "the tool interceptors")
        # codex and fullsend cannot enforce repository answer-key
        # protections in workspace_mode: repo (cursor can).
        if (runner.type in ("codex", "fullsend")
                and runner.workspace_mode == "repo"):
            raise ValueError(
                f"runner.type '{runner.type}' does not support "
                "workspace_mode: repo because repository answer-key "
                "protections cannot be enforced")

    # Fail fast on a judge model that cannot be routed to a provider backend.
    # Only statically-known models are checked (`models.judge` and per-judge
    # `model:`); a model supplied solely via EVAL_JUDGE_MODEL is validated
    # when the judge is built. Local import avoids an import cycle
    # (prompt_backends -> agent_eval.agent -> config).
    from agent_eval.prompt_backends import (
        require_sdk_judge_for_runner, resolve_judge_backend,
        split_model_uri)
    # Agent judges route their model through the runner (any provider prefix
    # is stripped to the bare id), not an SDK, so an explicit non-SDK provider
    # is valid for them — validate only judges that resolve to an SDK backend.
    # Only a non-agent judge that calls a model is checked: a check/code
    # judge never does, so neither models.judge (checked only when such a
    # judge inherits it) nor its own `model:` can fail to route.
    def _calls_llm(jc):
        return bool(jc.prompt or jc.prompt_file or jc.llm_rubric
                    or (jc.builtin and builtin_judge_kind(jc.builtin) == "llm"))

    llm_judges = [jc for jc in config.judges if not jc.agent and _calls_llm(jc)]
    inherits_default = [jc for jc in llm_judges if not jc.model]
    judge_models = []
    if config.models.judge and inherits_default:
        judge_models.append(("models.judge", config.models.judge))
    for jc in llm_judges:
        if jc.model:
            judge_models.append((f"judge '{jc.name}' model", jc.model))
    for label, model in judge_models:
        try:
            backend, _ = resolve_judge_backend(model)
        except ValueError as e:
            raise ValueError(f"{label}: {e}") from e
        require_sdk_judge_for_runner(config.runner.type, backend, label)

    # OpenRouter judges (spec 014): `provider_options` is validated by the
    # provider kind of the judge's statically-known model, and an `agent:`
    # judge cannot use an `openrouter:/` model — it runs through the
    # runner, which has no OpenRouter transport yet.
    for jc in config.judges:
        static_model = jc.model or config.models.judge or ""
        provider, _bare = split_model_uri(static_model)
        if jc.agent and provider == "openrouter":
            raise ValueError(
                f"Judge '{jc.name}': agent judges run through the runner, "
                f"which cannot serve '{static_model}' yet (spec 014 "
                "rollout); use a Claude model or 'runner:/<model>'")
        jc.provider_options = validate_judge_provider_options(
            jc.provider_options, static_model, jc.name)

    # Agent roles under an OpenRouter plan (spec 014 Config validation).
    validate_openrouter_roles(config)

    return config

is_prompt_mode

is_prompt_mode()

True when the eval runs a direct prompt (no skill wrapper).

Source code in agent_eval/config.py
def is_prompt_mode(self) -> bool:
    """True when the eval runs a direct prompt (no skill wrapper)."""
    return bool(self.execution.prompt and self.execution.prompt.strip())

resolve_path

resolve_path(relative)

Resolve a path relative to the config file's directory.

Absolute paths are returned as-is. Relative paths resolve against config_dir (falling back to cwd when config_dir is None).

Source code in agent_eval/config.py
def resolve_path(self, relative: Path | str) -> Path:
    """Resolve a path relative to the config file's directory.

    Absolute paths are returned as-is. Relative paths resolve against
    config_dir (falling back to cwd when config_dir is None).
    """
    p = Path(relative)
    if p.is_absolute():
        return p
    base = self.config_dir if self.config_dir is not None else Path.cwd()
    return base / p

resolve_skill

resolve_skill()

Canonical skill name for skill mode, or None for prompt mode.

Prefers execution.skill (the current location) and falls back to the deprecated top-level skill field. Returns None when neither is set — i.e. prompt mode or an unconfigured target. All execution substrates (local, Harbor, EvalHub) MUST resolve the target through this method so a config authored with only execution.skill runs the skill instead of silently degrading to prompt mode.

Source code in agent_eval/config.py
def resolve_skill(self) -> Optional[str]:
    """Canonical skill name for skill mode, or None for prompt mode.

    Prefers ``execution.skill`` (the current location) and falls back to
    the deprecated top-level ``skill`` field.  Returns None when neither
    is set — i.e. prompt mode or an unconfigured target.  All execution
    substrates (local, Harbor, EvalHub) MUST resolve the target through
    this method so a config authored with only ``execution.skill`` runs
    the skill instead of silently degrading to prompt mode.
    """
    return self.execution.skill or self.skill or None

Runners

A runner adapts a generic evaluation call to a specific agent runtime and returns a normalized RunResult. To support a new agent, subclass EvalRunner, implement the three abstract members below, and register it in the RUNNERS registry — see Runners.

agent_eval/agent/base.py
class EvalRunner(ABC):
    """Abstract runner -- one implementation per agent platform."""

    @classmethod
    @abstractmethod
    def from_config(cls, config, *, log_prefix=None, **overrides):
        """Construct a runner from an EvalConfig."""

    @property
    @abstractmethod
    def name(self) -> str:
        """Short identifier for this runner (e.g. 'claude-code')."""

    @abstractmethod
    def execute(self, target, args, workspace, model, ...) -> RunResult:
        """Run one invocation and return a normalized RunResult."""

Every runner returns the same normalized result, so scoring and reporting are runner-agnostic:

agent_eval.agent.base.RunResult dataclass

RunResult(exit_code, stdout, stderr, duration_s, token_usage=None, cost_usd=None, num_turns=None, resolved_model=None, models_used=None, per_model_usage=None, per_model_turns=None, permission_denials=None, raw_output=None, message_ids=None, generation_ids=None, cost_source=None, cost_usd_estimate=None, providers=None, error_class=None, budget=None)

Result of a single skill invocation.

to_case_result

to_case_result()

The per-case run_result.json payload, serialized identically by every caller: duration rounded to 0.1s and the list fields defaulted to [] — a denial that lived only in raw stdout was invisible to every downstream reader, so the empty list is written explicitly. Hook results and cost reconciliation are applied by the callers that know them, on the returned dict.

Source code in agent_eval/agent/base.py
def to_case_result(self) -> dict:
    """The per-case ``run_result.json`` payload, serialized identically
    by every caller: duration rounded to 0.1s and the list fields
    defaulted to ``[]`` — a denial that lived only in raw stdout was
    invisible to every downstream reader, so the empty list is written
    explicitly. Hook results and cost reconciliation are applied by the
    callers that know them, on the returned dict."""
    return {
        "exit_code": self.exit_code,
        "duration_s": round(self.duration_s, 1),
        "token_usage": self.token_usage,
        "cost_usd": self.cost_usd,
        "num_turns": self.num_turns,
        "per_model_usage": self.per_model_usage,
        "per_model_turns": self.per_model_turns,
        "permission_denials": self.permission_denials or [],
        "message_ids": self.message_ids or [],
        "generation_ids": self.generation_ids or [],
        "cost_source": self.cost_source,
        "error_class": self.error_class,
        "budget": self.budget,
    }