@agentv/core 4.10.0 → 4.11.2-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/evaluation/content.ts","../src/evaluation/types.ts","../src/evaluation/file-utils.ts","../src/evaluation/providers/targets.ts","../src/evaluation/providers/types.ts","../src/evaluation/interpolation.ts","../src/evaluation/loaders/case-file-loader.ts"],"sourcesContent":["/**\n * Multimodal content types for the AgentV pipeline.\n *\n * Models structured content blocks (text, images, files) that flow end-to-end\n * without lossy flattening. Modeled after Inspect AI's discriminated union approach.\n *\n * ## Content model\n *\n * `Message.content` accepts `string | Content[]`:\n * - `string` — backward-compatible plain text (most common case)\n * - `Content[]` — array of typed content blocks for multimodal messages\n *\n * Binary data (images, files) is referenced by URL/base64 string or filesystem\n * path — never raw bytes. This keeps payloads serializable and lets code graders\n * access files via path without decoding.\n *\n * ## How to extend\n *\n * To add a new content variant (e.g., `ContentAudio`):\n * 1. Define the interface with a unique `type` discriminant\n * 2. Add it to the `Content` union\n * 3. Update `getTextContent()` if the new type has extractable text\n * 4. Update `isContent()` type guard with the new type string\n */\n\n// ---------------------------------------------------------------------------\n// Content block types\n// ---------------------------------------------------------------------------\n\n/** A text content block. */\nexport interface ContentText {\n readonly type: 'text';\n readonly text: string;\n}\n\n/**\n * An image content block.\n * `source` is a URL, data URI (base64), or filesystem path.\n */\nexport interface ContentImage {\n readonly type: 'image';\n readonly media_type: string;\n readonly source: string;\n}\n\n/**\n * A file content block.\n * `path` is a filesystem path or URL referencing the file.\n */\nexport interface ContentFile {\n readonly type: 'file';\n readonly media_type: string;\n readonly path: string;\n}\n\n/** Discriminated union of all content block types. */\nexport type Content = ContentText | ContentImage | ContentFile;\n\n// ---------------------------------------------------------------------------\n// Type guards\n// ---------------------------------------------------------------------------\n\nconst CONTENT_TYPES = new Set<string>(['text', 'image', 'file']);\n\n/** Check whether a value is a valid `Content` block. */\nexport function isContent(value: unknown): value is Content {\n if (!value || typeof value !== 'object') return false;\n const v = value as Record<string, unknown>;\n return typeof v.type === 'string' && CONTENT_TYPES.has(v.type);\n}\n\n/** Check whether a value is a `Content[]` array (at least one valid block). */\nexport function isContentArray(value: unknown): value is Content[] {\n return Array.isArray(value) && value.length > 0 && value.every(isContent);\n}\n\n// ---------------------------------------------------------------------------\n// Accessors\n// ---------------------------------------------------------------------------\n\n/**\n * Extract plain text from `string | Content[]`.\n *\n * - If `content` is a string, returns it directly.\n * - If `content` is a `Content[]`, concatenates all `ContentText.text` values\n * (separated by newlines) and returns the result.\n * - Returns `''` for `undefined`/`null`/unrecognized shapes.\n *\n * This is a **non-destructive** accessor — the original `Content[]` is preserved.\n */\nexport function getTextContent(content: string | Content[] | undefined | null): string {\n if (content == null) return '';\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return '';\n\n const parts: string[] = [];\n for (const block of content) {\n if (block.type === 'text') {\n parts.push(block.text);\n }\n }\n return parts.join('\\n');\n}\n","import type { TokenUsage, ToolTrajectoryEvaluatorConfig, TraceSummary } from './trace.js';\n\n/** A single assertion verdict with optional evidence. */\nexport interface AssertionEntry {\n readonly text: string;\n readonly passed: boolean;\n readonly evidence?: string;\n}\n\n/**\n * JSON primitive values appearing in AgentV payloads.\n */\nexport type JsonPrimitive = string | number | boolean | null;\n\n/**\n * Immutable JSON object representation for test fixtures.\n */\nexport interface JsonObject {\n readonly [key: string]: JsonValue;\n}\n\n/**\n * Recursive JSON value supporting nested structures.\n */\nexport type JsonValue = JsonPrimitive | JsonObject | readonly JsonValue[];\n\nconst TEST_MESSAGE_ROLE_VALUES = ['system', 'user', 'assistant', 'tool'] as const;\n\n/**\n * Immutable list of supported message roles.\n */\nexport const TEST_MESSAGE_ROLES = TEST_MESSAGE_ROLE_VALUES;\n\n/**\n * Role literals used by test messages.\n */\nexport type TestMessageRole = (typeof TEST_MESSAGE_ROLE_VALUES)[number];\n\nconst TEST_MESSAGE_ROLE_SET: ReadonlySet<string> = new Set(TEST_MESSAGE_ROLE_VALUES);\n\n/**\n * Text or structured payload attached to a message.\n */\nexport type TestMessageContent = string | JsonObject | readonly JsonObject[];\n\n/**\n * System-authored instruction message.\n */\nexport type SystemTestMessage = {\n readonly role: 'system';\n readonly content: TestMessageContent;\n};\n\n/**\n * User-authored prompt message.\n */\nexport type UserTestMessage = {\n readonly role: 'user';\n readonly content: TestMessageContent;\n};\n\n/**\n * Assistant response message.\n */\nexport type AssistantTestMessage = {\n readonly role: 'assistant';\n readonly content: TestMessageContent;\n};\n\n/**\n * Tool invocation message.\n */\nexport type ToolTestMessage = {\n readonly role: 'tool';\n readonly content: TestMessageContent;\n};\n\n/**\n * Conversation message union with role discrimination.\n */\nexport type TestMessage =\n | SystemTestMessage\n | UserTestMessage\n | AssistantTestMessage\n | ToolTestMessage;\n\n/**\n * Guard validating supported message roles.\n */\nexport function isTestMessageRole(value: unknown): value is TestMessageRole {\n return typeof value === 'string' && TEST_MESSAGE_ROLE_SET.has(value);\n}\n\n/**\n * Guard matching AgentV JSON objects.\n */\nexport function isJsonObject(value: unknown): value is JsonObject {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n return Object.values(value as Record<string, unknown>).every(isJsonValue);\n}\n\n/**\n * Guard matching AgentV JSON values.\n */\nexport function isJsonValue(value: unknown): value is JsonValue {\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n return true;\n }\n if (Array.isArray(value)) {\n return value.every(isJsonValue);\n }\n if (typeof value === 'object') {\n return isJsonObject(value);\n }\n return false;\n}\n\n/**\n * Guard validating raw test messages.\n * A valid test message has:\n * - A valid role (system, user, assistant, tool)\n * - Either content (string or array of objects) OR tool_calls (for assistant messages)\n */\nexport function isTestMessage(value: unknown): value is TestMessage {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const candidate = value as { role?: unknown; content?: unknown; tool_calls?: unknown };\n if (!isTestMessageRole(candidate.role)) {\n return false;\n }\n // Check for valid content\n if (typeof candidate.content === 'string') {\n return true;\n }\n if (Array.isArray(candidate.content) && candidate.content.every(isJsonObject)) {\n return true;\n }\n // Allow messages with tool_calls but no content (for expected_output format)\n if (Array.isArray(candidate.tool_calls) && candidate.tool_calls.length > 0) {\n return true;\n }\n // Allow messages with structured content object (e.g., { recommendation: ..., summary: ... })\n if (isJsonObject(candidate.content)) {\n return true;\n }\n return false;\n}\n\nconst EVALUATOR_KIND_VALUES = [\n 'code-grader',\n 'llm-grader',\n 'rubric',\n 'composite',\n 'tool-trajectory',\n 'field-accuracy',\n 'latency',\n 'cost',\n 'token-usage',\n 'execution-metrics',\n 'skill-trigger',\n 'contains',\n 'contains-any',\n 'contains-all',\n 'icontains',\n 'icontains-any',\n 'icontains-all',\n 'starts-with',\n 'ends-with',\n 'regex',\n 'is-json',\n 'equals',\n 'rubrics',\n 'inline-assert',\n] as const;\n\nexport type EvaluatorKind = (typeof EVALUATOR_KIND_VALUES)[number];\n\nconst EVALUATOR_KIND_SET: ReadonlySet<string> = new Set(EVALUATOR_KIND_VALUES);\n\nexport function isEvaluatorKind(value: unknown): value is EvaluatorKind {\n return typeof value === 'string' && EVALUATOR_KIND_SET.has(value);\n}\n\n/**\n * Configuration for enabling target access in code-grader evaluators.\n * When present, the runtime will start a local proxy server that allows\n * the script to invoke configured targets without direct credential access.\n */\nexport type TargetAccessConfig = {\n /** Maximum number of target invocations allowed per execution (default: 50) */\n readonly max_calls?: number;\n};\n\n/**\n * Configuration for workspace lifecycle commands (before_all, after_all, before_each, after_each).\n * Commands are executed with workspace context passed via stdin.\n */\nexport type WorkspaceScriptConfig = {\n /** Command array to execute (e.g., [\"bun\", \"run\", \"setup.ts\"]) */\n readonly command: readonly string[];\n /** @deprecated Use `command` instead */\n readonly script?: readonly string[];\n /** Optional timeout in milliseconds (default: 60000 for setup, 30000 for teardown) */\n readonly timeout_ms?: number;\n readonly timeoutMs?: number;\n /** Optional working directory for command execution */\n readonly cwd?: string;\n};\n\n/**\n * Workspace configuration for eval tests.\n * Can be specified at suite level and overridden per-case.\n * Merge strategy: template/scripts replaced, env deep-merged.\n *\n * Lifecycle hooks follow bun:test/Vitest naming:\n * - before_all: runs ONCE before first test, creates shared workspace\n * - after_all: runs ONCE after last test, final cleanup\n * - before_each: runs before each test (optional)\n * - after_each: runs after each test (e.g., reset git state)\n */\nexport type RepoSource =\n | { readonly type: 'git'; readonly url: string }\n | { readonly type: 'local'; readonly path: string };\n\nexport type RepoCheckout = {\n readonly ref?: string;\n /** SWE-bench-friendly alias for ref when pinning a dataset snapshot commit */\n readonly base_commit?: string;\n readonly resolve?: 'remote' | 'local';\n readonly ancestor?: number;\n};\n\nexport type RepoClone = {\n readonly depth?: number;\n readonly filter?: string;\n readonly sparse?: readonly string[];\n};\n\nexport type RepoConfig = {\n /** Target path inside the workspace. Optional for Docker repos targeting the container's working directory. */\n readonly path?: string;\n /** Clone source. Optional for Docker prebuilt images where repos exist inside the container. */\n readonly source?: RepoSource;\n readonly checkout?: RepoCheckout;\n readonly clone?: RepoClone;\n};\n\nexport type WorkspaceHookConfig = {\n /** Optional command array to execute (e.g., [\"bun\", \"run\", \"setup.ts\"]) */\n readonly command?: readonly string[];\n /** @deprecated Use `command` instead */\n readonly script?: readonly string[];\n /** Optional timeout in milliseconds */\n readonly timeout_ms?: number;\n readonly timeoutMs?: number;\n /** Optional working directory for command execution */\n readonly cwd?: string;\n /** Optional reset policy for this hook */\n readonly reset?: 'none' | 'fast' | 'strict';\n};\n\nexport type WorkspaceHooksConfig = {\n /** Whether hooks are enabled (default: true). When false, all hooks are skipped. */\n readonly enabled?: boolean;\n /** Runs once before first test in the workspace lifecycle */\n readonly before_all?: WorkspaceHookConfig;\n /** Runs before each test case */\n readonly before_each?: WorkspaceHookConfig;\n /** Runs after each test case */\n readonly after_each?: WorkspaceHookConfig;\n /** Runs once after final test in the workspace lifecycle */\n readonly after_all?: WorkspaceHookConfig;\n};\n\n/**\n * Docker-based workspace configuration.\n * When present, code-grader commands run inside a Docker container\n * instead of on the host.\n */\nexport type DockerWorkspaceConfig = {\n /** Docker image to use (e.g. 'swebench/sweb.eval.x86_64.django__django-15180') */\n readonly image: string;\n /** Container execution timeout in seconds (default: 1800) */\n readonly timeout?: number;\n /** Memory limit (e.g. '4g', '512m') */\n readonly memory?: string;\n /** CPU limit (e.g. 2, 0.5) */\n readonly cpus?: number;\n};\n\nexport type WorkspaceConfig = {\n /** Template directory or .code-workspace file. Directories are copied to temp workspace.\n * .code-workspace files are used by VS Code providers; CLI providers use the parent directory. */\n readonly template?: string;\n /** Isolation strategy for workspace: shared (default) or per_test */\n readonly isolation?: 'shared' | 'per_test';\n /** Repository definitions to clone/checkout into workspace */\n readonly repos?: readonly RepoConfig[];\n /** Workspace lifecycle hooks */\n readonly hooks?: WorkspaceHooksConfig;\n /** Workspace materialization mode */\n readonly mode?: 'pooled' | 'temp' | 'static';\n /** Required when mode=static: use this existing directory directly */\n readonly path?: string;\n /** Docker-based workspace: run grader commands inside a container */\n readonly docker?: DockerWorkspaceConfig;\n};\n\nexport type CodeEvaluatorConfig = {\n readonly name: string;\n readonly type: 'code-grader';\n readonly command: readonly string[];\n /** @deprecated Use `command` instead */\n readonly script?: readonly string[];\n readonly resolvedScriptPath?: string;\n readonly cwd?: string;\n readonly resolvedCwd?: string;\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n /** When true, inverts the evaluator score (1 - score) and swaps pass/fail verdict */\n readonly negate?: boolean;\n /** Pass-through configuration for the code-grader (any unrecognized YAML properties) */\n readonly config?: JsonObject;\n /** When present, enables target access via local proxy */\n readonly target?: TargetAccessConfig;\n /** Optional content preprocessors inherited from suite/evaluator config */\n readonly preprocessors?: readonly ContentPreprocessorConfig[];\n};\n\n/**\n * Executable prompt template configuration.\n * Matches code-grader pattern for consistency.\n */\nexport type PromptScriptConfig = {\n /** Command array to execute (e.g., [\"bun\", \"run\", \"template.ts\"]) */\n readonly command: readonly string[];\n /** @deprecated Use `command` instead */\n readonly script?: readonly string[];\n /** Pass-through configuration for the prompt template */\n readonly config?: Record<string, unknown>;\n};\n\nexport type ContentPreprocessorConfig = {\n /** MIME type or short alias such as \"xlsx\" or \"html\" */\n readonly type: string;\n /** Command array to execute (stdin JSON payload -> stdout text) */\n readonly command: readonly string[];\n /** Resolved absolute path for the command script (last argv element) */\n readonly resolvedCommand?: readonly string[];\n};\n\nexport type LlmGraderEvaluatorConfig = {\n readonly name: string;\n readonly type: 'llm-grader';\n /** Text prompt (inline or file path) or executable script config */\n readonly prompt?: string | PromptScriptConfig;\n readonly promptPath?: string;\n /** Resolved absolute path for prompt file (used for text template prompts) */\n readonly resolvedPromptPath?: string;\n /** Resolved script array for executable prompts (matches code-grader pattern) */\n readonly resolvedPromptScript?: readonly string[];\n readonly rubrics?: readonly RubricItem[];\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n /** When true, inverts the evaluator score (1 - score) and swaps pass/fail verdict */\n readonly negate?: boolean;\n /** Optional target override for this grader (uses a named LLM target from targets.yaml). */\n readonly target?: string;\n /** Pass-through configuration for custom evaluator prompts (legacy, prefer prompt.config) */\n readonly config?: Record<string, unknown>;\n /** Maximum agent steps for agentv built-in mode (default 10, max 50). Ignored in LLM mode. */\n readonly max_steps?: number;\n /** Temperature override for grader calls */\n readonly temperature?: number;\n /** Optional content preprocessors for ContentFile blocks in assistant output */\n readonly preprocessors?: readonly ContentPreprocessorConfig[];\n};\n\n/** @deprecated Use `LlmGraderEvaluatorConfig` instead */\nexport type LlmJudgeEvaluatorConfig = LlmGraderEvaluatorConfig;\n\n/**\n * Score range definition for analytic rubric scoring.\n * Each range maps an integer score band (0-10) to an outcome description.\n */\nexport type ScoreRange = {\n /** Inclusive integer range [min, max] within 0-10 */\n readonly score_range: readonly [number, number];\n /** Description of what this score range represents */\n readonly outcome: string;\n};\n\n/**\n * Rubric item for LLM grader evaluation.\n * Supports two modes:\n * - Checklist mode: boolean satisfied/not-satisfied with `outcome`\n * - Score-range mode: 0-10 integer scoring with `score_ranges`\n */\nexport type RubricItem = {\n readonly id: string;\n /**\n * For checklist rubrics: the outcome text (required).\n * For score-range rubrics: optional overall criterion description.\n */\n readonly outcome?: string;\n readonly weight: number;\n /**\n * Legacy boolean gating (treated as min_score: 1.0 for score-range rubrics).\n */\n readonly required?: boolean;\n /**\n * Minimum score (0-1 scale) required to pass this criterion.\n * Internally compared against normalized score (rawScore / 10).\n */\n readonly min_score?: number;\n /**\n * @deprecated Use min_score (0-1 scale) instead.\n * Legacy: minimum score on 0-10 integer scale.\n */\n readonly required_min_score?: number;\n /**\n * Score range definitions for analytic rubric scoring.\n * When present, the grader outputs an integer 0-10 score per criterion.\n * Ranges must be non-overlapping and cover 0-10 inclusive.\n */\n readonly score_ranges?: readonly ScoreRange[];\n};\n\nexport type CompositeAggregatorConfig =\n | { readonly type: 'weighted_average'; readonly weights?: Record<string, number> }\n | { readonly type: 'code-grader'; readonly path: string; readonly cwd?: string }\n | {\n readonly type: 'llm-grader';\n readonly prompt?: string;\n readonly promptPath?: string;\n readonly model?: string;\n }\n | { readonly type: 'threshold'; readonly threshold: number };\n\nexport type CompositeEvaluatorConfig = {\n readonly name: string;\n readonly type: 'composite';\n readonly assertions: readonly EvaluatorConfig[];\n readonly aggregator: CompositeAggregatorConfig;\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n /** When true, inverts the evaluator score (1 - score) and swaps pass/fail verdict */\n readonly negate?: boolean;\n};\n\n/**\n * Match type for field accuracy evaluation.\n * Note: For fuzzy string matching (Levenshtein, Jaro-Winkler, etc.), use a code-grader evaluator.\n * See examples/features/document-extraction/fuzzy_match.ts for an example.\n */\nexport type FieldMatchType = 'exact' | 'numeric_tolerance' | 'date';\n\n/**\n * Aggregation strategy for combining field scores.\n */\nexport type FieldAggregationType = 'weighted_average' | 'all_or_nothing';\n\n/**\n * Configuration for a single field to evaluate.\n */\nexport type FieldConfig = {\n /** Dot-notation path to the field (e.g., \"invoice.vendor.name\" or \"items[0].amount\") */\n readonly path: string;\n /** Match strategy for this field */\n readonly match: FieldMatchType;\n /** Whether this field is required (missing required fields count as failures) */\n readonly required?: boolean;\n /** Weight for aggregation (default: 1.0) */\n readonly weight?: number;\n /** Tolerance for numeric matching (absolute value unless relative is true) */\n readonly tolerance?: number;\n /** Whether tolerance is relative (percentage) vs absolute */\n readonly relative?: boolean;\n /** Date formats to try when parsing (default: common formats) */\n readonly formats?: readonly string[];\n};\n\n/**\n * Configuration for the field-accuracy evaluator.\n */\nexport type FieldAccuracyEvaluatorConfig = {\n readonly name: string;\n readonly type: 'field-accuracy';\n /** Fields to compare between candidate and expected */\n readonly fields: readonly FieldConfig[];\n /** Strategy for combining field scores (default: weighted_average) */\n readonly aggregation?: FieldAggregationType;\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n /** When true, inverts the evaluator score (1 - score) and swaps pass/fail verdict */\n readonly negate?: boolean;\n};\n\n/**\n * Configuration for the latency evaluator.\n * Checks execution duration against a threshold.\n */\nexport type LatencyEvaluatorConfig = {\n readonly name: string;\n readonly type: 'latency';\n /** Maximum allowed duration in milliseconds */\n readonly threshold: number;\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n /** When true, inverts the evaluator score (1 - score) and swaps pass/fail verdict */\n readonly negate?: boolean;\n};\n\n/**\n * Configuration for the cost evaluator.\n * Checks execution cost against a budget.\n */\nexport type CostEvaluatorConfig = {\n readonly name: string;\n readonly type: 'cost';\n /** Maximum allowed cost in USD */\n readonly budget: number;\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n /** When true, inverts the evaluator score (1 - score) and swaps pass/fail verdict */\n readonly negate?: boolean;\n};\n\n/**\n * Configuration for the token-usage evaluator.\n * Checks provider-reported token usage against configured limits.\n */\nexport type TokenUsageEvaluatorConfig = {\n readonly name: string;\n readonly type: 'token-usage';\n /** Maximum allowed total tokens (input + output + cached, when present) */\n readonly max_total?: number;\n /** Maximum allowed input tokens (prompt) */\n readonly max_input?: number;\n /** Maximum allowed output tokens (completion) */\n readonly max_output?: number;\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n /** When true, inverts the evaluator score (1 - score) and swaps pass/fail verdict */\n readonly negate?: boolean;\n};\n\n/**\n * Configuration for the execution-metrics evaluator.\n * Provides declarative threshold-based checks on execution metrics.\n * Only specified thresholds are checked; omitted ones are ignored.\n */\nexport type ExecutionMetricsEvaluatorConfig = {\n readonly name: string;\n readonly type: 'execution-metrics';\n /** Maximum allowed number of tool calls */\n readonly max_tool_calls?: number;\n /** Maximum allowed number of LLM calls (assistant messages) */\n readonly max_llm_calls?: number;\n /** Maximum allowed total tokens (input + output) */\n readonly max_tokens?: number;\n /** Maximum allowed cost in USD */\n readonly max_cost_usd?: number;\n /** Maximum allowed duration in milliseconds */\n readonly max_duration_ms?: number;\n /** Target exploration ratio (0-1, proportion of read-only tool calls) */\n readonly target_exploration_ratio?: number;\n /** Tolerance for exploration ratio check (default: 0.2) */\n readonly exploration_tolerance?: number;\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n /** When true, inverts the evaluator score (1 - score) and swaps pass/fail verdict */\n readonly negate?: boolean;\n};\n\n/**\n * Configuration for the contains assertion evaluator.\n * Checks whether the candidate output contains a specified substring.\n */\nexport type ContainsEvaluatorConfig = {\n readonly name: string;\n readonly type: 'contains';\n readonly value: string;\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n /** When true, inverts the evaluator score (1 - score) and swaps pass/fail verdict */\n readonly negate?: boolean;\n};\n\n/**\n * Configuration for the contains_any assertion evaluator.\n * Checks whether the candidate output contains ANY of the specified substrings.\n */\nexport type ContainsAnyEvaluatorConfig = {\n readonly name: string;\n readonly type: 'contains-any';\n readonly value: readonly string[];\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n /** When true, inverts the evaluator score (1 - score) and swaps pass/fail verdict */\n readonly negate?: boolean;\n};\n\n/**\n * Configuration for the contains_all assertion evaluator.\n * Checks whether the candidate output contains ALL of the specified substrings.\n */\nexport type ContainsAllEvaluatorConfig = {\n readonly name: string;\n readonly type: 'contains-all';\n readonly value: readonly string[];\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n /** When true, inverts the evaluator score (1 - score) and swaps pass/fail verdict */\n readonly negate?: boolean;\n};\n\n/**\n * Configuration for the icontains assertion evaluator.\n * Case-insensitive check whether the candidate output contains a specified substring.\n */\nexport type IcontainsEvaluatorConfig = {\n readonly name: string;\n readonly type: 'icontains';\n readonly value: string;\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n /** When true, inverts the evaluator score (1 - score) and swaps pass/fail verdict */\n readonly negate?: boolean;\n};\n\n/**\n * Configuration for the icontains_any assertion evaluator.\n * Case-insensitive check whether the candidate output contains ANY of the specified substrings.\n */\nexport type IcontainsAnyEvaluatorConfig = {\n readonly name: string;\n readonly type: 'icontains-any';\n readonly value: readonly string[];\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n /** When true, inverts the evaluator score (1 - score) and swaps pass/fail verdict */\n readonly negate?: boolean;\n};\n\n/**\n * Configuration for the icontains_all assertion evaluator.\n * Case-insensitive check whether the candidate output contains ALL of the specified substrings.\n */\nexport type IcontainsAllEvaluatorConfig = {\n readonly name: string;\n readonly type: 'icontains-all';\n readonly value: readonly string[];\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n /** When true, inverts the evaluator score (1 - score) and swaps pass/fail verdict */\n readonly negate?: boolean;\n};\n\n/**\n * Configuration for the starts_with assertion evaluator.\n * Checks whether the candidate output starts with a specified string (both trimmed).\n */\nexport type StartsWithEvaluatorConfig = {\n readonly name: string;\n readonly type: 'starts-with';\n readonly value: string;\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n /** When true, inverts the evaluator score (1 - score) and swaps pass/fail verdict */\n readonly negate?: boolean;\n};\n\n/**\n * Configuration for the ends_with assertion evaluator.\n * Checks whether the candidate output ends with a specified string (both trimmed).\n */\nexport type EndsWithEvaluatorConfig = {\n readonly name: string;\n readonly type: 'ends-with';\n readonly value: string;\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n /** When true, inverts the evaluator score (1 - score) and swaps pass/fail verdict */\n readonly negate?: boolean;\n};\n\n/**\n * Configuration for the regex assertion evaluator.\n * Checks whether the candidate output matches a regular expression pattern.\n */\nexport type RegexEvaluatorConfig = {\n readonly name: string;\n readonly type: 'regex';\n readonly value: string;\n /** Optional regex flags (e.g., \"i\" for case-insensitive, \"m\" for multiline) */\n readonly flags?: string;\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n /** When true, inverts the evaluator score (1 - score) and swaps pass/fail verdict */\n readonly negate?: boolean;\n};\n\n/**\n * Configuration for the is_json assertion evaluator.\n * Checks whether the candidate output is valid JSON.\n */\nexport type IsJsonEvaluatorConfig = {\n readonly name: string;\n readonly type: 'is-json';\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n /** When true, inverts the evaluator score (1 - score) and swaps pass/fail verdict */\n readonly negate?: boolean;\n};\n\n/**\n * Configuration for the equals assertion evaluator.\n * Checks whether the candidate output exactly equals a specified string.\n */\nexport type EqualsEvaluatorConfig = {\n readonly name: string;\n readonly type: 'equals';\n readonly value: string;\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n /** When true, inverts the evaluator score (1 - score) and swaps pass/fail verdict */\n readonly negate?: boolean;\n};\n\n/**\n * Configuration for the rubrics evaluator.\n * Evaluates candidate output against a list of rubric criteria.\n */\nexport type RubricsEvaluatorConfig = {\n readonly name: string;\n readonly type: 'rubrics';\n readonly criteria: readonly RubricItem[];\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n /** When true, inverts the evaluator score (1 - score) and swaps pass/fail verdict */\n readonly negate?: boolean;\n};\n\n/**\n * Configuration for the skill-trigger evaluator.\n * Detects whether the agent invoked a named skill as its first tool call.\n * Tool-name resolution is automatic based on the provider kind.\n * For providers not covered by the built-in mapping, use a code-grader.\n */\nexport type SkillTriggerEvaluatorConfig = {\n readonly name: string;\n readonly type: 'skill-trigger';\n /** The skill name to check for (case-sensitive substring match) */\n readonly skill: string;\n /** Whether the skill is expected to trigger (default: true) */\n readonly should_trigger?: boolean;\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n readonly negate?: boolean;\n};\n\n/**\n * Configuration for the inline-assert evaluator.\n * Wraps an AssertFn for in-process evaluation via the evaluate() API.\n */\nexport type InlineAssertEvaluatorConfig = {\n readonly name: string;\n readonly type: 'inline-assert';\n readonly weight?: number;\n readonly required?: boolean | number;\n /** Minimum score (0-1) for this evaluator to pass. Independent of `required` gate. */\n readonly min_score?: number;\n readonly negate?: boolean;\n};\n\nexport type EvaluatorConfig =\n | CodeEvaluatorConfig\n | LlmGraderEvaluatorConfig\n | CompositeEvaluatorConfig\n | ToolTrajectoryEvaluatorConfig\n | FieldAccuracyEvaluatorConfig\n | LatencyEvaluatorConfig\n | CostEvaluatorConfig\n | TokenUsageEvaluatorConfig\n | ExecutionMetricsEvaluatorConfig\n | SkillTriggerEvaluatorConfig\n | ContainsEvaluatorConfig\n | ContainsAnyEvaluatorConfig\n | ContainsAllEvaluatorConfig\n | IcontainsEvaluatorConfig\n | IcontainsAnyEvaluatorConfig\n | IcontainsAllEvaluatorConfig\n | StartsWithEvaluatorConfig\n | EndsWithEvaluatorConfig\n | RegexEvaluatorConfig\n | IsJsonEvaluatorConfig\n | EqualsEvaluatorConfig\n | RubricsEvaluatorConfig\n | InlineAssertEvaluatorConfig;\n\n/**\n * Eval test definition sourced from AgentV specs.\n */\nexport interface EvalTest {\n readonly id: string;\n readonly suite?: string;\n readonly category?: string;\n readonly conversation_id?: string;\n readonly question: string;\n readonly input: readonly TestMessage[];\n readonly expected_output: readonly JsonObject[];\n readonly reference_answer?: string;\n readonly file_paths: readonly string[];\n readonly criteria: string;\n readonly evaluator?: EvaluatorKind;\n readonly assertions?: readonly EvaluatorConfig[];\n /** Suite-level preprocessors used by the implicit default llm-grader. */\n readonly preprocessors?: readonly ContentPreprocessorConfig[];\n /** Workspace configuration (merged from suite-level and case-level) */\n readonly workspace?: WorkspaceConfig;\n /** Arbitrary metadata passed to workspace scripts via stdin */\n readonly metadata?: Record<string, unknown>;\n /** Per-test target override (matrix evaluation) */\n readonly targets?: readonly string[];\n /** Per-test score threshold override (0-1). Resolution: CLI > test > suite > DEFAULT_THRESHOLD. */\n readonly threshold?: number;\n}\n\n/** @deprecated Use `EvalTest` instead */\nexport type EvalCase = EvalTest;\n\n/**\n * Supported trial aggregation strategies.\n */\nexport type TrialStrategy = 'pass_at_k' | 'mean' | 'confidence_interval';\n\n/**\n * Configuration for running multiple trials per eval case.\n */\nexport interface TrialsConfig {\n readonly count: number;\n readonly strategy: TrialStrategy;\n readonly costLimitUsd?: number;\n}\n\n/**\n * Result of a single trial attempt.\n */\nexport interface TrialResult {\n readonly attempt: number;\n readonly score: number;\n readonly verdict: EvaluationVerdict;\n readonly scores?: readonly EvaluatorResult[];\n readonly error?: string;\n readonly costUsd?: number;\n /** Primary classification for this trial attempt */\n readonly executionStatus?: ExecutionStatus;\n /** Pipeline stage where failure occurred */\n readonly failureStage?: FailureStage;\n /** Machine-readable failure reason code */\n readonly failureReasonCode?: string;\n}\n\n/**\n * Aggregation metadata for pass_at_k strategy.\n */\nexport interface PassAtKAggregation {\n readonly strategy: 'pass_at_k';\n readonly passedAttempts: number;\n readonly totalAttempts: number;\n}\n\n/**\n * Aggregation metadata for mean strategy.\n */\nexport interface MeanAggregation {\n readonly strategy: 'mean';\n readonly mean: number;\n readonly min: number;\n readonly max: number;\n}\n\n/**\n * Aggregation metadata for confidence_interval strategy.\n */\nexport interface ConfidenceIntervalAggregation {\n readonly strategy: 'confidence_interval';\n readonly mean: number;\n readonly ci95Lower: number;\n readonly ci95Upper: number;\n readonly stddev: number;\n}\n\n/**\n * Discriminated union of trial aggregation results.\n */\nexport type TrialAggregation = PassAtKAggregation | MeanAggregation | ConfidenceIntervalAggregation;\n\n/**\n * Primary classification of evaluation outcome.\n * - 'ok': evaluation completed, score reflects model quality (score >= 0.8)\n * - 'quality_failure': evaluation completed but model scored below threshold\n * - 'execution_error': evaluation could not complete due to infrastructure/tooling error\n */\nexport type ExecutionStatus = 'ok' | 'quality_failure' | 'execution_error';\n\n/**\n * Pipeline stage where the failure occurred.\n */\nexport type FailureStage = 'setup' | 'repo_setup' | 'agent' | 'evaluator' | 'teardown';\n\n/**\n * Structured error detail for execution failures.\n */\nexport interface ExecutionError {\n readonly message: string;\n readonly stage: FailureStage;\n}\n\n/**\n * Tolerance for execution errors in an eval run.\n * - `true`: halt on first execution error\n * - `false`: never halt on errors (default)\n */\nexport type FailOnError = boolean;\n\n/**\n * Evaluator scorecard for a single eval case run.\n */\nexport interface EvaluationResult {\n readonly timestamp: string;\n readonly testId: string;\n readonly suite?: string;\n readonly category?: string;\n readonly conversationId?: string;\n readonly score: number;\n readonly assertions: readonly AssertionEntry[];\n readonly target: string;\n /**\n * The target that actually served the response, when different from the\n * primary target. Present only when a fallback target was used.\n */\n readonly targetUsed?: string;\n /** Token usage metrics from provider (optional) */\n readonly tokenUsage?: TokenUsage;\n /** Total cost in USD (optional, from provider) */\n readonly costUsd?: number;\n /** Candidate/agent execution duration in milliseconds (excludes grading time) */\n readonly durationMs?: number;\n /** ISO 8601 timestamp when execution started */\n readonly startTime?: string;\n /** ISO 8601 timestamp when execution ended */\n readonly endTime?: string;\n readonly requests?: {\n readonly agent?: JsonObject;\n readonly lm?: JsonObject;\n readonly evaluator?: JsonObject;\n };\n readonly scores?: readonly EvaluatorResult[];\n readonly error?: string;\n /** Lightweight summary of the execution trace (always included when available) */\n readonly trace?: TraceSummary;\n /** Path to the temporary workspace directory (included on failure for debugging) */\n readonly workspacePath?: string;\n /** Input messages sent to the agent. Always Message[] for consistent shape with output. */\n readonly input?: readonly import('./providers/types.js').Message[];\n /** Output messages from agent execution. Always present — at minimum contains the final assistant message. */\n readonly output: readonly import('./providers/types.js').Message[];\n /** Captured output from workspace before_all script */\n readonly beforeAllOutput?: string;\n /** Captured output from workspace before_each script */\n readonly beforeEachOutput?: string;\n /** Captured output from workspace after_all script */\n readonly afterAllOutput?: string;\n /** Captured output from workspace after_each script */\n readonly afterEachOutput?: string;\n /** Unified diff of workspace file changes (when workspace_template is configured) */\n readonly fileChanges?: string;\n /** Individual trial results (only present when trials.count > 1) */\n readonly trials?: readonly TrialResult[];\n /** Aggregation metadata describing how the final score was computed from trials */\n readonly aggregation?: TrialAggregation;\n /** Whether the trial loop was terminated early due to cost limit */\n readonly costLimited?: boolean;\n /** Whether the evaluation was skipped due to suite-level budget exhaustion */\n readonly budgetExceeded?: boolean;\n /** Aggregate metrics for the full eval run (candidate + grading) */\n readonly evalRun?: {\n readonly durationMs?: number;\n readonly tokenUsage?: TokenUsage;\n };\n /** Primary classification: ok, quality_failure, or execution_error */\n readonly executionStatus: ExecutionStatus;\n /** Pipeline stage where failure occurred (only when executionStatus !== 'ok') */\n readonly failureStage?: FailureStage;\n /** Machine-readable failure reason code (only when executionStatus !== 'ok') */\n readonly failureReasonCode?: string;\n /** Structured error detail (only when executionStatus === 'execution_error') */\n readonly executionError?: ExecutionError;\n}\n\nexport type EvaluationVerdict = 'pass' | 'fail' | 'skip';\n\nexport interface EvaluatorResult {\n readonly name: string;\n readonly type: EvaluatorKind;\n readonly score: number;\n readonly weight?: number;\n readonly verdict?: EvaluationVerdict;\n readonly assertions: readonly AssertionEntry[];\n readonly rawRequest?: JsonObject;\n readonly input?: JsonObject;\n /** Target name used for grading (e.g., the LLM provider name). */\n readonly target?: string;\n readonly scores?: readonly EvaluatorResult[];\n /** Optional structured details from code graders (e.g., TP/TN/FP/FN counts). */\n readonly details?: JsonObject;\n /** Token usage from LLM calls made by this evaluator (optional). */\n readonly tokenUsage?: TokenUsage;\n /** Wall-clock duration of this grader execution in milliseconds. */\n readonly durationMs?: number;\n /** ISO 8601 UTC timestamp when this grader started executing. */\n readonly startedAt?: string;\n /** ISO 8601 UTC timestamp when this grader finished executing. */\n readonly endedAt?: string;\n}\n","import { constants } from 'node:fs';\nimport { access, readFile } from 'node:fs/promises';\nimport path from 'node:path';\n\nexport async function fileExists(filePath: string): Promise<boolean> {\n try {\n await access(filePath, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Normalize line endings to LF (\\n).\n * This ensures consistent behavior across Windows (CRLF) and Unix (LF) systems.\n */\nexport function normalizeLineEndings(content: string): string {\n return content.replace(/\\r\\n/g, '\\n');\n}\n\n/**\n * Read a text file and normalize line endings to LF (\\n).\n * This ensures consistent behavior across Windows (CRLF) and Unix (LF) systems.\n */\nexport async function readTextFile(filePath: string): Promise<string> {\n const content = await readFile(filePath, 'utf8');\n return normalizeLineEndings(content);\n}\n\n/**\n * Read a JSON file and parse it.\n */\nexport async function readJsonFile<T = unknown>(filePath: string): Promise<T> {\n const content = await readFile(filePath, 'utf8');\n return JSON.parse(content) as T;\n}\n\n/**\n * Find git repository root by walking up the directory tree.\n */\nexport async function findGitRoot(startPath: string): Promise<string | null> {\n let currentDir = path.dirname(path.resolve(startPath));\n const root = path.parse(currentDir).root;\n\n while (currentDir !== root) {\n const gitPath = path.join(currentDir, '.git');\n if (await fileExists(gitPath)) {\n return currentDir;\n }\n\n const parentDir = path.dirname(currentDir);\n if (parentDir === currentDir) {\n break;\n }\n currentDir = parentDir;\n }\n\n return null;\n}\n\n/**\n * Build a chain of directories walking from a file's location up to repo root.\n * Used for discovering configuration files like targets.yaml or config.yaml.\n */\nexport function buildDirectoryChain(filePath: string, repoRoot: string): readonly string[] {\n const directories: string[] = [];\n const seen = new Set<string>();\n const boundary = path.resolve(repoRoot);\n let current: string | undefined = path.resolve(path.dirname(filePath));\n\n while (current !== undefined) {\n if (!seen.has(current)) {\n directories.push(current);\n seen.add(current);\n }\n if (current === boundary) {\n break;\n }\n const parent = path.dirname(current);\n if (parent === current) {\n break;\n }\n current = parent;\n }\n\n if (!seen.has(boundary)) {\n directories.push(boundary);\n }\n\n return directories;\n}\n\n/**\n * Build search roots for file resolution, matching yaml-parser behavior.\n * Searches from eval file directory up to repo root.\n */\nexport function buildSearchRoots(evalPath: string, repoRoot: string): readonly string[] {\n const uniqueRoots: string[] = [];\n const addRoot = (root: string): void => {\n const normalized = path.resolve(root);\n if (!uniqueRoots.includes(normalized)) {\n uniqueRoots.push(normalized);\n }\n };\n\n let currentDir = path.dirname(evalPath);\n let reachedBoundary = false;\n while (!reachedBoundary) {\n addRoot(currentDir);\n const parentDir = path.dirname(currentDir);\n if (currentDir === repoRoot || parentDir === currentDir) {\n reachedBoundary = true;\n } else {\n currentDir = parentDir;\n }\n }\n\n addRoot(repoRoot);\n addRoot(process.cwd());\n return uniqueRoots;\n}\n\n/**\n * Trim leading path separators for display.\n */\nfunction trimLeadingSeparators(value: string): string {\n const trimmed = value.replace(/^[/\\\\]+/, '');\n return trimmed.length > 0 ? trimmed : value;\n}\n\n/**\n * Resolve a file reference using search roots, matching yaml-parser behavior.\n */\nexport async function resolveFileReference(\n rawValue: string,\n searchRoots: readonly string[],\n): Promise<{\n readonly displayPath: string;\n readonly resolvedPath?: string;\n readonly attempted: readonly string[];\n}> {\n const displayPath = trimLeadingSeparators(rawValue);\n const potentialPaths: string[] = [];\n\n if (path.isAbsolute(rawValue)) {\n potentialPaths.push(path.normalize(rawValue));\n }\n\n for (const base of searchRoots) {\n potentialPaths.push(path.resolve(base, displayPath));\n }\n\n const attempted: string[] = [];\n const seen = new Set<string>();\n for (const candidate of potentialPaths) {\n const absoluteCandidate = path.resolve(candidate);\n if (seen.has(absoluteCandidate)) {\n continue;\n }\n seen.add(absoluteCandidate);\n attempted.push(absoluteCandidate);\n if (await fileExists(absoluteCandidate)) {\n return { displayPath, resolvedPath: absoluteCandidate, attempted };\n }\n }\n\n return { displayPath, attempted };\n}\n","import path from 'node:path';\nimport { z } from 'zod';\n\nimport type { EnvLookup, TargetDefinition } from './types.js';\n\n// ---------------------------------------------------------------------------\n// Zod Schemas for CLI Provider Configuration\n// ---------------------------------------------------------------------------\n\n/**\n * Loose input schema for HTTP healthcheck configuration.\n * Accepts raw YAML input before normalization and validation.\n *\n * @example\n * ```yaml\n * healthcheck:\n * url: http://localhost:8080/health\n * timeout_seconds: 30\n * ```\n */\nexport const CliHealthcheckHttpInputSchema = z\n .object({\n url: z.string().min(1, 'healthcheck URL is required'),\n timeout_seconds: z.number().positive().optional(),\n })\n .passthrough();\n\n/**\n * Loose input schema for command healthcheck configuration.\n * Accepts raw YAML input before normalization and validation.\n *\n * @example\n * ```yaml\n * healthcheck:\n * command: curl http://localhost:8080/health\n * cwd: /app\n * timeout_seconds: 10\n * ```\n */\nexport const CliHealthcheckCommandInputSchema = z\n .object({\n command: z.string().min(1, 'healthcheck command is required'),\n cwd: z.string().optional(),\n timeout_seconds: z.number().positive().optional(),\n })\n .passthrough();\n\n/**\n * Union for healthcheck input configuration.\n * The healthcheck type is self-describing: presence of `url` indicates HTTP,\n * presence of `command` indicates a command healthcheck.\n *\n * @see CliHealthcheckHttpInputSchema for HTTP healthcheck configuration\n * @see CliHealthcheckCommandInputSchema for command healthcheck configuration\n */\nexport const CliHealthcheckInputSchema = z.union([\n CliHealthcheckHttpInputSchema,\n CliHealthcheckCommandInputSchema,\n]);\n\n/**\n * Loose input schema for CLI target configuration.\n * Accepts raw YAML input before normalization and validation.\n *\n * This schema validates the raw YAML input structure before normalization\n * and environment variable resolution. Unknown properties are allowed\n * (passthrough mode) to support future extensions.\n *\n * @example\n * ```yaml\n * targets:\n * - name: my-agent\n * provider: cli\n * command: agent run {PROMPT}\n * timeout_seconds: 120\n * healthcheck:\n * url: http://localhost:8080/health\n * ```\n */\nexport const CliTargetInputSchema = z\n .object({\n name: z.string().min(1, 'target name is required'),\n provider: z\n .string()\n .refine((p) => p.toLowerCase() === 'cli', { message: \"provider must be 'cli'\" }),\n\n // Command - required\n command: z.string(),\n\n // Files format - optional\n files_format: z.string().optional(),\n attachments_format: z.string().optional(),\n\n // Working directory - optional\n cwd: z.string().optional(),\n\n // Workspace template directory - optional (mutually exclusive with cwd)\n workspace_template: z.string().optional(),\n\n // Timeout in seconds - optional\n timeout_seconds: z.number().positive().optional(),\n\n // Healthcheck configuration - optional\n healthcheck: CliHealthcheckInputSchema.optional(),\n\n // Verbose mode - optional\n verbose: z.boolean().optional(),\n cli_verbose: z.boolean().optional(),\n\n // Keep temp files - optional\n keep_temp_files: z.boolean().optional(),\n keep_output_files: z.boolean().optional(),\n\n // Common target fields\n grader_target: z.string().optional(),\n judge_target: z.string().optional(), // backward compat\n workers: z.number().int().min(1).optional(),\n provider_batching: z.boolean().optional(),\n })\n .passthrough();\n\n/**\n * Strict normalized schema for HTTP healthcheck configuration.\n * Rejects unknown properties.\n * This is an internal schema used as part of CliHealthcheckSchema.\n */\nconst CliHealthcheckHttpSchema = z\n .object({\n url: z.string().min(1),\n timeoutMs: z.number().positive().optional(),\n })\n .strict();\n\n/**\n * Strict normalized schema for command healthcheck configuration.\n * Rejects unknown properties.\n * This is an internal schema used as part of CliHealthcheckSchema.\n */\nconst CliHealthcheckCommandSchema = z\n .object({\n command: z.string().min(1),\n cwd: z.string().optional(),\n timeoutMs: z.number().positive().optional(),\n })\n .strict();\n\n/**\n * Strict normalized schema for healthcheck configuration.\n * Union supporting HTTP and command healthchecks, distinguished by the\n * presence of `url` (HTTP) or `command` (command).\n * Rejects unknown properties to catch typos and misconfigurations.\n *\n * @see CliHealthcheckHttpSchema for HTTP healthcheck fields\n * @see CliHealthcheckCommandSchema for command healthcheck fields\n */\nexport const CliHealthcheckSchema = z.union([\n CliHealthcheckHttpSchema,\n CliHealthcheckCommandSchema,\n]);\n\n/**\n * Strict normalized schema for CLI target configuration.\n * This is the final validated shape after environment variable resolution\n * and internal field normalization.\n *\n * Uses .strict() to reject unknown properties, ensuring configuration\n * errors are caught early rather than silently ignored.\n *\n * @example\n * ```typescript\n * const config: CliNormalizedConfig = {\n * command: 'agent run {PROMPT}',\n * timeoutMs: 120000,\n * verbose: true,\n * };\n * CliTargetConfigSchema.parse(config); // Validates the normalized config\n * ```\n */\nexport const CliTargetConfigSchema = z\n .object({\n command: z.string().min(1),\n filesFormat: z.string().optional(),\n cwd: z.string().optional(),\n workspaceTemplate: z.string().optional(),\n timeoutMs: z.number().positive().optional(),\n healthcheck: CliHealthcheckSchema.optional(),\n verbose: z.boolean().optional(),\n keepTempFiles: z.boolean().optional(),\n })\n .strict();\n\n// Type inference from schemas\nexport type CliHealthcheckInput = z.infer<typeof CliHealthcheckInputSchema>;\nexport type CliTargetInput = z.infer<typeof CliTargetInputSchema>;\nexport type CliNormalizedHealthcheck = z.infer<typeof CliHealthcheckSchema>;\nexport type CliNormalizedConfig = z.infer<typeof CliTargetConfigSchema>;\n\n/**\n * Resolved CLI configuration type derived from CliTargetConfigSchema.\n * This is the final validated shape used by the CLI provider at runtime.\n * Using Readonly to ensure immutability for runtime safety.\n */\nexport type CliResolvedConfig = Readonly<CliNormalizedConfig>;\n\n/**\n * Normalizes a healthcheck input from raw YAML input to the strict internal\n * form used by the CLI provider. Resolves environment variables.\n *\n * @param input - The loose healthcheck input from YAML\n * @param env - Environment variable lookup\n * @param targetName - Name of the target (for error messages)\n * @param evalFilePath - Optional path to eval file for relative path resolution\n * @returns Normalized healthcheck configuration\n */\nexport function normalizeCliHealthcheck(\n input: CliHealthcheckInput,\n env: EnvLookup,\n targetName: string,\n evalFilePath?: string,\n): CliNormalizedHealthcheck {\n const timeoutSeconds = input.timeout_seconds;\n const timeoutMs = timeoutSeconds !== undefined ? Math.floor(timeoutSeconds * 1000) : undefined;\n\n if ('url' in input && input.url) {\n const url = resolveString(input.url, env, `${targetName} healthcheck URL`);\n return {\n url,\n timeoutMs,\n };\n }\n\n // command healthcheck\n if (!('command' in input) || !input.command) {\n throw new Error(\n `${targetName} healthcheck: Either 'command' or 'url' is required for healthcheck`,\n );\n }\n const command = resolveString(input.command, env, `${targetName} healthcheck command`, true);\n\n let cwd = resolveOptionalString(input.cwd, env, `${targetName} healthcheck cwd`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n // Resolve relative cwd paths against eval file directory\n if (cwd && evalFilePath && !path.isAbsolute(cwd)) {\n cwd = path.resolve(path.dirname(path.resolve(evalFilePath)), cwd);\n }\n // Fallback: if cwd is not set and we have an eval file path, use the eval directory\n if (!cwd && evalFilePath) {\n cwd = path.dirname(path.resolve(evalFilePath));\n }\n\n return {\n command,\n cwd,\n timeoutMs,\n };\n}\n\n/**\n * Normalizes a CLI target input from raw YAML input to the strict internal\n * form used by the CLI provider. Resolves environment variables.\n *\n * This function resolves environment variable references using\n * ${{ VAR_NAME }} syntax and converts external YAML field names to the\n * internal runtime shape.\n *\n * @param input - The loose CLI target input from YAML\n * @param env - Environment variable lookup\n * @param evalFilePath - Optional path to eval file for relative path resolution\n * @returns Normalized CLI configuration matching CliResolvedConfig\n */\nexport function normalizeCliTargetInput(\n input: CliTargetInput,\n env: EnvLookup,\n evalFilePath?: string,\n): CliNormalizedConfig {\n const targetName = input.name;\n\n const command = resolveString(input.command, env, `${targetName} CLI command`, true);\n\n // Coalesce files format variants\n const filesFormatSource = input.files_format ?? input.attachments_format;\n const filesFormat = resolveOptionalLiteralString(filesFormatSource);\n\n // Resolve workspace template (mutually exclusive with cwd)\n const workspaceTemplateSource = input.workspace_template;\n let workspaceTemplate = resolveOptionalString(\n workspaceTemplateSource,\n env,\n `${targetName} workspace template`,\n {\n allowLiteral: true,\n optionalEnv: true,\n },\n );\n\n // Resolve relative workspace template paths against eval file directory\n if (workspaceTemplate && evalFilePath && !path.isAbsolute(workspaceTemplate)) {\n workspaceTemplate = path.resolve(path.dirname(path.resolve(evalFilePath)), workspaceTemplate);\n }\n\n // Resolve working directory\n let cwd = resolveOptionalString(input.cwd, env, `${targetName} working directory`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n // Resolve relative cwd paths against eval file directory\n if (cwd && evalFilePath && !path.isAbsolute(cwd)) {\n cwd = path.resolve(path.dirname(path.resolve(evalFilePath)), cwd);\n }\n\n // Validate mutual exclusivity of cwd and workspace_template\n if (cwd && workspaceTemplate) {\n throw new Error(\n `${targetName}: 'cwd' and 'workspace_template' are mutually exclusive. Use 'cwd' to run in an existing directory, or 'workspace_template' to copy a template to a temp location.`,\n );\n }\n\n // Fallback: if cwd is not set, workspace_template is not set, and we have an eval file path, use the eval directory\n if (!cwd && !workspaceTemplate && evalFilePath) {\n cwd = path.dirname(path.resolve(evalFilePath));\n }\n\n // Coalesce timeout variants (seconds -> ms)\n const timeoutSeconds = input.timeout_seconds;\n const timeoutMs = timeoutSeconds !== undefined ? Math.floor(timeoutSeconds * 1000) : undefined;\n\n // Coalesce verbose variants\n const verbose = resolveOptionalBoolean(input.verbose ?? input.cli_verbose);\n\n // Coalesce keepTempFiles variants\n const keepTempFiles = resolveOptionalBoolean(input.keep_temp_files ?? input.keep_output_files);\n\n // Normalize healthcheck if present\n const healthcheck = input.healthcheck\n ? normalizeCliHealthcheck(input.healthcheck, env, targetName, evalFilePath)\n : undefined;\n\n return {\n command,\n filesFormat,\n cwd,\n workspaceTemplate,\n timeoutMs,\n healthcheck,\n verbose,\n keepTempFiles,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Other Provider Configurations and Utilities\n// ---------------------------------------------------------------------------\n\n/**\n * Supported CLI placeholder tokens that can be used in command templates.\n * These are replaced with actual values during command execution.\n */\nexport const CLI_PLACEHOLDERS = new Set([\n 'PROMPT',\n 'PROMPT_FILE',\n 'EVAL_ID',\n 'ATTEMPT',\n 'FILES',\n 'OUTPUT_FILE',\n]);\n\nexport interface RetryConfig {\n readonly maxRetries?: number;\n readonly initialDelayMs?: number;\n readonly maxDelayMs?: number;\n readonly backoffFactor?: number;\n readonly retryableStatusCodes?: readonly number[];\n}\n\n/**\n * Selects which OpenAI-compatible API endpoint to use.\n * - \"chat\" (default): POST /chat/completions — universally supported by all OpenAI-compatible providers.\n * - \"responses\": POST /responses — only supported by api.openai.com.\n *\n * Maps to Vercel AI SDK methods: \"chat\" → provider.chat(model), \"responses\" → provider(model).\n */\nexport type ApiFormat = 'chat' | 'responses';\n\n/**\n * Azure OpenAI settings used by the Vercel AI SDK.\n */\nexport interface AzureResolvedConfig {\n readonly resourceName: string;\n readonly deploymentName: string;\n readonly apiKey: string;\n readonly version?: string;\n readonly apiFormat?: ApiFormat;\n readonly temperature?: number;\n readonly maxOutputTokens?: number;\n readonly retry?: RetryConfig;\n}\n\n/**\n * OpenAI-compatible settings used by the Vercel AI SDK.\n */\nexport interface OpenAIResolvedConfig {\n readonly baseURL: string;\n readonly apiKey: string;\n readonly model: string;\n readonly apiFormat?: ApiFormat;\n readonly temperature?: number;\n readonly maxOutputTokens?: number;\n readonly retry?: RetryConfig;\n}\n\n/**\n * OpenRouter settings used by the Vercel AI SDK provider.\n */\nexport interface OpenRouterResolvedConfig {\n readonly apiKey: string;\n readonly model: string;\n readonly temperature?: number;\n readonly maxOutputTokens?: number;\n readonly retry?: RetryConfig;\n}\n\n/**\n * Anthropic Claude settings used by the Vercel AI SDK.\n */\nexport interface AnthropicResolvedConfig {\n readonly apiKey: string;\n readonly model: string;\n readonly temperature?: number;\n readonly maxOutputTokens?: number;\n readonly thinkingBudget?: number;\n readonly retry?: RetryConfig;\n}\n\n/**\n * Google Gemini settings used by the Vercel AI SDK.\n */\nexport interface GeminiResolvedConfig {\n readonly apiKey: string;\n readonly model: string;\n readonly temperature?: number;\n readonly maxOutputTokens?: number;\n readonly retry?: RetryConfig;\n}\n\nexport interface CodexResolvedConfig {\n readonly model?: string;\n readonly executable: string;\n readonly args?: readonly string[];\n readonly cwd?: string;\n readonly workspaceTemplate?: string;\n readonly timeoutMs?: number;\n readonly logDir?: string;\n readonly logFormat?: 'summary' | 'json';\n readonly systemPrompt?: string;\n}\n\nexport interface CopilotCliResolvedConfig {\n readonly executable: string;\n readonly model?: string;\n readonly args?: readonly string[];\n readonly cwd?: string;\n readonly workspaceTemplate?: string;\n readonly timeoutMs?: number;\n readonly logDir?: string;\n readonly logFormat?: 'summary' | 'json';\n readonly systemPrompt?: string;\n}\n\nexport interface CopilotSdkResolvedConfig {\n readonly cliUrl?: string;\n readonly cliPath?: string;\n readonly githubToken?: string;\n readonly model?: string;\n readonly cwd?: string;\n readonly workspaceTemplate?: string;\n readonly timeoutMs?: number;\n readonly logDir?: string;\n readonly logFormat?: 'summary' | 'json';\n readonly systemPrompt?: string;\n /** BYOK provider type: \"azure\", \"openai\", or \"anthropic\". */\n readonly byokType?: string;\n /** BYOK base URL for the provider endpoint. */\n readonly byokBaseUrl?: string;\n /** BYOK API key for authenticating with the provider. */\n readonly byokApiKey?: string;\n /** BYOK bearer token (takes precedence over apiKey when set). */\n readonly byokBearerToken?: string;\n /** BYOK Azure API version (e.g. \"2024-10-21\"). Only used when byokType is \"azure\". */\n readonly byokApiVersion?: string;\n /** BYOK wire API format: \"completions\" or \"responses\". */\n readonly byokWireApi?: string;\n}\n\nexport interface CopilotLogResolvedConfig {\n /** Explicit path to a session directory containing events.jsonl. */\n readonly sessionDir?: string;\n /** Session UUID — combined with sessionStateDir to build the path. */\n readonly sessionId?: string;\n /** Auto-discovery mode. 'latest' picks the most recent session. */\n readonly discover?: 'latest';\n /** Override the default ~/.copilot/session-state directory. */\n readonly sessionStateDir?: string;\n /** Filter discovery by working directory. */\n readonly cwd?: string;\n}\n\nexport interface PiCodingAgentResolvedConfig {\n readonly subprovider?: string;\n readonly model?: string;\n readonly apiKey?: string;\n readonly baseUrl?: string;\n readonly tools?: string;\n readonly thinking?: string;\n readonly cwd?: string;\n readonly workspaceTemplate?: string;\n readonly timeoutMs?: number;\n readonly logDir?: string;\n readonly logFormat?: 'summary' | 'json';\n readonly systemPrompt?: string;\n}\n\nexport interface PiCliResolvedConfig {\n readonly executable: string;\n readonly subprovider?: string;\n readonly model?: string;\n readonly apiKey?: string;\n readonly baseUrl?: string;\n readonly tools?: string;\n readonly thinking?: string;\n readonly args?: readonly string[];\n readonly cwd?: string;\n readonly workspaceTemplate?: string;\n readonly timeoutMs?: number;\n readonly logDir?: string;\n readonly logFormat?: 'summary' | 'json';\n readonly systemPrompt?: string;\n}\n\nexport interface ClaudeResolvedConfig {\n readonly model?: string;\n readonly systemPrompt?: string;\n readonly cwd?: string;\n readonly workspaceTemplate?: string;\n readonly timeoutMs?: number;\n readonly maxTurns?: number;\n readonly maxBudgetUsd?: number;\n readonly logDir?: string;\n readonly logFormat?: 'summary' | 'json';\n}\n\nexport interface MockResolvedConfig {\n readonly response?: string;\n readonly delayMs?: number;\n readonly delayMinMs?: number;\n readonly delayMaxMs?: number;\n}\n\nexport interface VSCodeResolvedConfig {\n readonly executable: string;\n readonly waitForResponse: boolean;\n readonly dryRun: boolean;\n readonly subagentRoot?: string;\n readonly workspaceTemplate?: string;\n readonly timeoutMs?: number;\n}\n\nexport interface AgentVResolvedConfig {\n readonly model: string;\n readonly temperature: number;\n}\n\nexport interface TargetDeprecationWarning {\n readonly location: string;\n readonly message: string;\n}\n\nconst DEPRECATED_TARGET_CAMEL_CASE_FIELDS = new Map<string, string>([\n ['providerBatching', 'provider_batching'],\n ['subagentModeAllowed', 'subagent_mode_allowed'],\n ['fallbackTargets', 'fallback_targets'],\n ['resourceName', 'endpoint'],\n ['baseUrl', 'base_url'],\n ['apiKey', 'api_key'],\n ['deploymentName', 'model'],\n ['thinkingBudget', 'thinking_budget'],\n ['maxTokens', 'max_output_tokens'],\n ['apiFormat', 'api_format'],\n ['timeoutSeconds', 'timeout_seconds'],\n ['logDir', 'log_dir'],\n ['logDirectory', 'log_directory'],\n ['logFormat', 'log_format'],\n ['logOutputFormat', 'log_output_format'],\n ['systemPrompt', 'system_prompt'],\n ['maxTurns', 'max_turns'],\n ['maxBudgetUsd', 'max_budget_usd'],\n ['dryRun', 'dry_run'],\n ['subagentRoot', 'subagent_root'],\n ['filesFormat', 'files_format'],\n ['attachmentsFormat', 'attachments_format'],\n ['cliUrl', 'cli_url'],\n ['cliPath', 'cli_path'],\n ['githubToken', 'github_token'],\n ['sessionDir', 'session_dir'],\n ['sessionId', 'session_id'],\n ['sessionStateDir', 'session_state_dir'],\n ['maxRetries', 'max_retries'],\n ['retryInitialDelayMs', 'retry_initial_delay_ms'],\n ['retryMaxDelayMs', 'retry_max_delay_ms'],\n ['retryBackoffFactor', 'retry_backoff_factor'],\n ['retryStatusCodes', 'retry_status_codes'],\n]);\n\nconst DEPRECATED_HEALTHCHECK_CAMEL_CASE_FIELDS = new Map<string, string>([\n ['timeoutSeconds', 'timeout_seconds'],\n]);\n\nfunction collectDeprecatedCamelCaseWarnings(\n value: unknown,\n location: string,\n aliases: ReadonlyMap<string, string>,\n): TargetDeprecationWarning[] {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return [];\n }\n\n const warnings: TargetDeprecationWarning[] = [];\n for (const [camelCaseField, snakeCaseField] of aliases) {\n if (Object.prototype.hasOwnProperty.call(value, camelCaseField)) {\n warnings.push({\n location: `${location}.${camelCaseField}`,\n message: `camelCase field '${camelCaseField}' is no longer supported in targets.yaml. Use '${snakeCaseField}' instead.`,\n });\n }\n }\n\n return warnings;\n}\n\nfunction assertNoDeprecatedCamelCaseTargetFields(definition: TargetDefinition): void {\n if (Object.prototype.hasOwnProperty.call(definition, 'workspaceTemplate')) {\n throw new Error(\n `${definition.name}: target-level workspace_template has been removed. Use eval-level workspace.template.`,\n );\n }\n\n const warning = findDeprecatedCamelCaseTargetWarnings(\n definition,\n `target \"${definition.name}\"`,\n )[0];\n if (!warning) {\n return;\n }\n\n const fieldMatch = warning.message.match(/field '([^']+)'/);\n const replacementMatch = warning.message.match(/Use '([^']+)' instead/);\n const field = fieldMatch?.[1] ?? 'unknown';\n const replacement = replacementMatch?.[1] ?? 'snake_case';\n throw new Error(\n `${warning.location}: camelCase field '${field}' is no longer supported in targets.yaml. Use '${replacement}' instead.`,\n );\n}\n\nexport function findDeprecatedCamelCaseTargetWarnings(\n target: unknown,\n location: string,\n): readonly TargetDeprecationWarning[] {\n const warnings = collectDeprecatedCamelCaseWarnings(\n target,\n location,\n DEPRECATED_TARGET_CAMEL_CASE_FIELDS,\n );\n\n if (typeof target !== 'object' || target === null || Array.isArray(target)) {\n return warnings;\n }\n\n const healthcheck = (target as { healthcheck?: unknown }).healthcheck;\n warnings.push(\n ...collectDeprecatedCamelCaseWarnings(\n healthcheck,\n `${location}.healthcheck`,\n DEPRECATED_HEALTHCHECK_CAMEL_CASE_FIELDS,\n ),\n );\n\n return warnings;\n}\n\n/**\n * Healthcheck configuration type derived from CliHealthcheckSchema.\n * Supports both HTTP and command-based healthchecks.\n */\nexport type CliHealthcheck = Readonly<CliNormalizedHealthcheck>;\n\n// Note: CliResolvedConfig is a type alias derived from CliNormalizedConfig (see above),\n// which itself is inferred from CliTargetConfigSchema for type safety and single source of truth.\n\n/** Base fields shared by all resolved targets. */\ninterface ResolvedTargetBase {\n readonly name: string;\n readonly graderTarget?: string;\n readonly workers?: number;\n readonly providerBatching?: boolean;\n /**\n * Whether this target can be executed via executor subagents in subagent mode.\n * Defaults to `true` for all non-CLI providers. Set `false` in targets.yaml\n * to force CLI invocation even in subagent mode.\n */\n readonly subagentModeAllowed?: boolean;\n /**\n * Ordered list of target names to try when the primary target fails after\n * exhausting retries. Each fallback is attempted in order.\n */\n readonly fallbackTargets?: readonly string[];\n}\n\nexport type ResolvedTarget =\n | (ResolvedTargetBase & { readonly kind: 'openai'; readonly config: OpenAIResolvedConfig })\n | (ResolvedTargetBase & {\n readonly kind: 'openrouter';\n readonly config: OpenRouterResolvedConfig;\n })\n | (ResolvedTargetBase & { readonly kind: 'azure'; readonly config: AzureResolvedConfig })\n | (ResolvedTargetBase & { readonly kind: 'anthropic'; readonly config: AnthropicResolvedConfig })\n | (ResolvedTargetBase & { readonly kind: 'gemini'; readonly config: GeminiResolvedConfig })\n | (ResolvedTargetBase & { readonly kind: 'codex'; readonly config: CodexResolvedConfig })\n | (ResolvedTargetBase & {\n readonly kind: 'copilot-sdk';\n readonly config: CopilotSdkResolvedConfig;\n })\n | (ResolvedTargetBase & {\n readonly kind: 'copilot-cli';\n readonly config: CopilotCliResolvedConfig;\n })\n | (ResolvedTargetBase & {\n readonly kind: 'copilot-log';\n readonly config: CopilotLogResolvedConfig;\n })\n | (ResolvedTargetBase & {\n readonly kind: 'pi-coding-agent';\n readonly config: PiCodingAgentResolvedConfig;\n })\n | (ResolvedTargetBase & { readonly kind: 'pi-cli'; readonly config: PiCliResolvedConfig })\n | (ResolvedTargetBase & { readonly kind: 'claude'; readonly config: ClaudeResolvedConfig })\n | (ResolvedTargetBase & { readonly kind: 'claude-cli'; readonly config: ClaudeResolvedConfig })\n | (ResolvedTargetBase & { readonly kind: 'claude-sdk'; readonly config: ClaudeResolvedConfig })\n | (ResolvedTargetBase & { readonly kind: 'mock'; readonly config: MockResolvedConfig })\n | (ResolvedTargetBase & {\n readonly kind: 'vscode' | 'vscode-insiders';\n readonly config: VSCodeResolvedConfig;\n })\n | (ResolvedTargetBase & { readonly kind: 'agentv'; readonly config: AgentVResolvedConfig })\n | (ResolvedTargetBase & { readonly kind: 'cli'; readonly config: CliResolvedConfig })\n | (ResolvedTargetBase & { readonly kind: 'transcript'; readonly config: Record<string, never> });\n\n/**\n * Optional settings accepted on ALL target definitions regardless of provider.\n * Exported so the targets validator can reuse the same list — adding a field\n * here automatically makes it valid in targets.yaml without a separate update.\n */\nexport const COMMON_TARGET_SETTINGS = [\n 'use_target',\n 'provider_batching',\n 'subagent_mode_allowed',\n 'fallback_targets',\n] as const;\n\nconst USE_TARGET_ENV_PATTERN = /^\\$\\{\\{\\s*([A-Z0-9_]+)\\s*\\}\\}$/i;\n\nconst BASE_TARGET_SCHEMA = z\n .object({\n name: z.string().min(1, 'target name is required'),\n provider: z.string().optional(),\n use_target: z.string().optional(),\n grader_target: z.string().optional(),\n judge_target: z.string().optional(), // backward compat\n workers: z.number().int().min(1).optional(),\n workspace_template: z.string().optional(),\n subagent_mode_allowed: z.boolean().optional(),\n fallback_targets: z.array(z.string().min(1)).optional(),\n })\n .passthrough();\n\nconst DEFAULT_AZURE_API_VERSION = '2024-12-01-preview';\nconst DEFAULT_AZURE_RESPONSES_API_VERSION = 'v1';\nconst DEFAULT_OPENAI_BASE_URL = 'https://api.openai.com/v1';\n\nfunction normalizeAzureApiVersion(\n value: string | undefined,\n apiFormat: ApiFormat | undefined,\n): string {\n const defaultVersion =\n apiFormat === 'responses' ? DEFAULT_AZURE_RESPONSES_API_VERSION : DEFAULT_AZURE_API_VERSION;\n\n if (!value) {\n return defaultVersion;\n }\n\n const trimmed = value.trim();\n if (trimmed.length === 0) {\n return defaultVersion;\n }\n\n const withoutPrefix = trimmed.replace(/^api[-_]?version\\s*=\\s*/i, '').trim();\n return withoutPrefix.length > 0 ? withoutPrefix : defaultVersion;\n}\n\nfunction resolveRetryConfig(target: z.infer<typeof BASE_TARGET_SCHEMA>): RetryConfig | undefined {\n const maxRetries = resolveOptionalNumber(target.max_retries, `${target.name} max retries`);\n const initialDelayMs = resolveOptionalNumber(\n target.retry_initial_delay_ms,\n `${target.name} retry initial delay`,\n );\n const maxDelayMs = resolveOptionalNumber(\n target.retry_max_delay_ms,\n `${target.name} retry max delay`,\n );\n const backoffFactor = resolveOptionalNumber(\n target.retry_backoff_factor,\n `${target.name} retry backoff factor`,\n );\n const retryableStatusCodes = resolveOptionalNumberArray(\n target.retry_status_codes,\n `${target.name} retry status codes`,\n );\n\n // Only return retry config if at least one field is set\n if (\n maxRetries === undefined &&\n initialDelayMs === undefined &&\n maxDelayMs === undefined &&\n backoffFactor === undefined &&\n retryableStatusCodes === undefined\n ) {\n return undefined;\n }\n\n return {\n maxRetries,\n initialDelayMs,\n maxDelayMs,\n backoffFactor,\n retryableStatusCodes,\n };\n}\n\nexport function resolveDelegatedTargetDefinition(\n name: string,\n definitions: ReadonlyMap<string, TargetDefinition>,\n env: EnvLookup = process.env,\n): TargetDefinition | undefined {\n let definition = definitions.get(name);\n if (!definition) {\n return undefined;\n }\n\n const visited = [definition.name];\n\n for (let depth = 0; depth < 10; depth++) {\n const rawUseTarget =\n typeof definition.use_target === 'string' ? definition.use_target.trim() : undefined;\n if (!rawUseTarget) {\n return definition;\n }\n\n const envMatch = rawUseTarget.match(USE_TARGET_ENV_PATTERN);\n const envVarName = envMatch?.[1];\n const resolvedName = envVarName ? (env[envVarName]?.trim() ?? '') : rawUseTarget;\n\n if (resolvedName.length === 0) {\n if (envVarName) {\n throw new Error(\n `Target \"${definition.name}\" uses use_target: \\${{ ${envVarName} }}, but ${envVarName} is not set. Set ${envVarName} to the name of a concrete target (for example, \"azure\") before running the eval.`,\n );\n }\n\n throw new Error(\n `Target \"${definition.name}\" has an empty use_target value. Point it at a concrete target name before running the eval.`,\n );\n }\n\n const next = definitions.get(resolvedName);\n if (!next) {\n if (envVarName) {\n throw new Error(\n `Target \"${definition.name}\" uses use_target: \\${{ ${envVarName} }}, which resolved to \"${resolvedName}\", but no target named \"${resolvedName}\" exists.`,\n );\n }\n\n throw new Error(\n `Target \"${definition.name}\" uses use_target: \"${resolvedName}\", but no target named \"${resolvedName}\" exists.`,\n );\n }\n\n if (visited.includes(next.name)) {\n const chain = [...visited, next.name].join(' -> ');\n throw new Error(`Circular use_target reference detected: ${chain}`);\n }\n\n definition = next;\n visited.push(definition.name);\n }\n\n throw new Error(\n `Target \"${name}\" exceeded the maximum use_target resolution depth (10). Check for a delegation loop or overly deep alias chain.`,\n );\n}\n\nexport function resolveTargetDefinition(\n definition: TargetDefinition,\n env: EnvLookup = process.env,\n evalFilePath?: string,\n options?: { readonly emitDeprecationWarnings?: boolean },\n): ResolvedTarget {\n void options;\n assertNoDeprecatedCamelCaseTargetFields(definition);\n\n const parsed = BASE_TARGET_SCHEMA.parse(definition);\n if (parsed.workspace_template !== undefined) {\n throw new Error(\n `${parsed.name}: target-level workspace_template has been removed. Use eval-level workspace.template.`,\n );\n }\n if (!parsed.provider) {\n throw new Error(\n `${parsed.name}: 'provider' is required (targets with use_target must be resolved before calling resolveTargetDefinition)`,\n );\n }\n const provider = resolveString(\n parsed.provider,\n env,\n `${parsed.name} provider`,\n true,\n ).toLowerCase();\n const providerBatching = resolveOptionalBoolean(parsed.provider_batching);\n const subagentModeAllowed = resolveOptionalBoolean(parsed.subagent_mode_allowed);\n\n // Shared base fields for all resolved targets\n const fallbackTargets = parsed.fallback_targets;\n const base = {\n name: parsed.name,\n graderTarget: parsed.grader_target ?? parsed.judge_target,\n workers: parsed.workers,\n providerBatching,\n subagentModeAllowed,\n ...(fallbackTargets ? { fallbackTargets } : {}),\n } as const;\n\n switch (provider) {\n case 'openai':\n return {\n kind: 'openai',\n ...base,\n config: resolveOpenAIConfig(parsed, env),\n };\n case 'openrouter':\n return {\n kind: 'openrouter',\n ...base,\n config: resolveOpenRouterConfig(parsed, env),\n };\n case 'azure':\n case 'azure-openai':\n return {\n kind: 'azure',\n ...base,\n config: resolveAzureConfig(parsed, env),\n };\n case 'anthropic':\n return {\n kind: 'anthropic',\n ...base,\n config: resolveAnthropicConfig(parsed, env),\n };\n case 'gemini':\n case 'google':\n case 'google-gemini':\n return {\n kind: 'gemini',\n ...base,\n config: resolveGeminiConfig(parsed, env),\n };\n case 'codex':\n case 'codex-cli':\n return {\n kind: 'codex',\n ...base,\n config: resolveCodexConfig(parsed, env, evalFilePath),\n };\n case 'copilot-sdk':\n case 'copilot_sdk':\n return {\n kind: 'copilot-sdk',\n ...base,\n config: resolveCopilotSdkConfig(parsed, env, evalFilePath),\n };\n case 'copilot':\n case 'copilot-cli':\n return {\n kind: 'copilot-cli',\n ...base,\n config: resolveCopilotCliConfig(parsed, env, evalFilePath),\n };\n case 'copilot-log':\n return {\n kind: 'copilot-log',\n ...base,\n config: resolveCopilotLogConfig(parsed, env),\n };\n case 'pi':\n case 'pi-coding-agent':\n return {\n kind: 'pi-coding-agent',\n ...base,\n config: resolvePiCodingAgentConfig(parsed, env, evalFilePath),\n };\n case 'pi-cli':\n return {\n kind: 'pi-cli',\n ...base,\n config: resolvePiCliConfig(parsed, env, evalFilePath),\n };\n case 'claude':\n case 'claude-code':\n case 'claude-cli':\n return {\n kind: 'claude-cli',\n ...base,\n config: resolveClaudeConfig(parsed, env, evalFilePath),\n };\n case 'claude-sdk':\n return {\n kind: 'claude-sdk',\n ...base,\n config: resolveClaudeConfig(parsed, env, evalFilePath),\n };\n case 'mock':\n return {\n kind: 'mock',\n ...base,\n config: resolveMockConfig(parsed),\n };\n case 'vscode':\n case 'vscode-insiders':\n return {\n kind: provider as 'vscode' | 'vscode-insiders',\n ...base,\n config: resolveVSCodeConfig(parsed, env, provider === 'vscode-insiders', evalFilePath),\n };\n case 'agentv': {\n const model = typeof parsed.model === 'string' ? parsed.model : undefined;\n if (!model) {\n throw new Error(\n `Target \"${parsed.name}\" (provider: agentv) requires a \"model\" field (e.g., \"openai:gpt-5-mini\")`,\n );\n }\n const temperature = typeof parsed.temperature === 'number' ? parsed.temperature : 0;\n return {\n kind: 'agentv',\n ...base,\n workers: typeof parsed.workers === 'number' ? parsed.workers : undefined,\n config: { model, temperature },\n };\n }\n case 'cli':\n return {\n kind: 'cli',\n ...base,\n config: resolveCliConfig(parsed, env, evalFilePath),\n };\n default:\n // Unknown provider kind — resolve as CLI target.\n // This enables convention-based provider discovery: scripts in\n // .agentv/providers/ are registered in the ProviderRegistry under\n // their filename, and users can reference them by name directly.\n // The ProviderRegistry factory handles creating the appropriate\n // CliProvider with the discovered script path.\n return {\n kind: 'cli',\n ...base,\n config: resolveDiscoveredProviderConfig(parsed, provider, env, evalFilePath),\n };\n }\n}\n\nfunction normalizeOpenAIBaseUrl(value: string | undefined): string {\n if (!value) {\n return DEFAULT_OPENAI_BASE_URL;\n }\n\n const trimmed = value.trim().replace(/\\/+$/, '');\n if (trimmed.length === 0) {\n return DEFAULT_OPENAI_BASE_URL;\n }\n\n return trimmed.endsWith('/v1') ? trimmed : `${trimmed}/v1`;\n}\n\nfunction resolveAzureConfig(\n target: z.infer<typeof BASE_TARGET_SCHEMA>,\n env: EnvLookup,\n): AzureResolvedConfig {\n const endpointSource = target.endpoint ?? target.resource;\n const apiKeySource = target.api_key;\n const deploymentSource = target.deployment ?? target.model;\n const versionSource = target.version ?? target.api_version;\n const temperatureSource = target.temperature;\n const maxTokensSource = target.max_output_tokens;\n\n const resourceName = resolveString(endpointSource, env, `${target.name} endpoint`);\n const apiKey = resolveString(apiKeySource, env, `${target.name} api key`);\n const deploymentName = resolveString(deploymentSource, env, `${target.name} deployment`);\n const apiFormat = resolveApiFormat(target, env, target.name);\n const version = normalizeAzureApiVersion(\n resolveOptionalString(versionSource, env, `${target.name} api version`, {\n allowLiteral: true,\n optionalEnv: true,\n }),\n apiFormat,\n );\n const temperature = resolveOptionalNumber(temperatureSource, `${target.name} temperature`);\n const maxOutputTokens = resolveOptionalNumber(\n maxTokensSource,\n `${target.name} max output tokens`,\n );\n const retry = resolveRetryConfig(target);\n\n return {\n resourceName,\n deploymentName,\n apiKey,\n version,\n apiFormat,\n temperature,\n maxOutputTokens,\n retry,\n };\n}\n\nfunction resolveApiFormat(\n target: z.infer<typeof BASE_TARGET_SCHEMA>,\n env: EnvLookup,\n targetName: string,\n): ApiFormat | undefined {\n const raw = resolveOptionalString(target.api_format, env, `${targetName} api format`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n if (raw === undefined) return undefined;\n if (raw === 'chat' || raw === 'responses') return raw;\n throw new Error(\n `Invalid api_format '${raw}' for target '${targetName}'. Must be 'chat' or 'responses'.`,\n );\n}\n\nfunction resolveOpenAIConfig(\n target: z.infer<typeof BASE_TARGET_SCHEMA>,\n env: EnvLookup,\n): OpenAIResolvedConfig {\n const endpointSource = target.endpoint ?? target.base_url;\n const apiKeySource = target.api_key;\n const modelSource = target.model ?? target.deployment ?? target.variant;\n const temperatureSource = target.temperature;\n const maxTokensSource = target.max_output_tokens;\n\n const baseURL = normalizeOpenAIBaseUrl(\n resolveOptionalString(endpointSource, env, `${target.name} endpoint`, {\n allowLiteral: true,\n optionalEnv: true,\n }),\n );\n const apiKey = resolveString(apiKeySource, env, `${target.name} api key`);\n const model = resolveString(modelSource, env, `${target.name} model`);\n const retry = resolveRetryConfig(target);\n\n return {\n baseURL,\n apiKey,\n model,\n apiFormat: resolveApiFormat(target, env, target.name),\n temperature: resolveOptionalNumber(temperatureSource, `${target.name} temperature`),\n maxOutputTokens: resolveOptionalNumber(maxTokensSource, `${target.name} max output tokens`),\n retry,\n };\n}\n\nfunction resolveOpenRouterConfig(\n target: z.infer<typeof BASE_TARGET_SCHEMA>,\n env: EnvLookup,\n): OpenRouterResolvedConfig {\n const apiKeySource = target.api_key;\n const modelSource = target.model ?? target.deployment ?? target.variant;\n const temperatureSource = target.temperature;\n const maxTokensSource = target.max_output_tokens;\n const retry = resolveRetryConfig(target);\n\n return {\n apiKey: resolveString(apiKeySource, env, `${target.name} OpenRouter api key`),\n model: resolveString(modelSource, env, `${target.name} OpenRouter model`),\n temperature: resolveOptionalNumber(temperatureSource, `${target.name} temperature`),\n maxOutputTokens: resolveOptionalNumber(maxTokensSource, `${target.name} max output tokens`),\n retry,\n };\n}\n\nfunction resolveAnthropicConfig(\n target: z.infer<typeof BASE_TARGET_SCHEMA>,\n env: EnvLookup,\n): AnthropicResolvedConfig {\n const apiKeySource = target.api_key;\n const modelSource = target.model ?? target.deployment ?? target.variant;\n const temperatureSource = target.temperature;\n const maxTokensSource = target.max_output_tokens;\n const thinkingBudgetSource = target.thinking_budget;\n\n const apiKey = resolveString(apiKeySource, env, `${target.name} Anthropic api key`);\n const model = resolveString(modelSource, env, `${target.name} Anthropic model`);\n const retry = resolveRetryConfig(target);\n\n return {\n apiKey,\n model,\n temperature: resolveOptionalNumber(temperatureSource, `${target.name} temperature`),\n maxOutputTokens: resolveOptionalNumber(maxTokensSource, `${target.name} max output tokens`),\n thinkingBudget: resolveOptionalNumber(thinkingBudgetSource, `${target.name} thinking budget`),\n retry,\n };\n}\n\nfunction resolveGeminiConfig(\n target: z.infer<typeof BASE_TARGET_SCHEMA>,\n env: EnvLookup,\n): GeminiResolvedConfig {\n const apiKeySource = target.api_key;\n const modelSource = target.model ?? target.deployment ?? target.variant;\n const temperatureSource = target.temperature;\n const maxTokensSource = target.max_output_tokens;\n\n const apiKey = resolveString(apiKeySource, env, `${target.name} Google API key`);\n const model =\n resolveOptionalString(modelSource, env, `${target.name} Gemini model`, {\n allowLiteral: true,\n optionalEnv: true,\n }) ?? 'gemini-2.5-flash';\n const retry = resolveRetryConfig(target);\n\n return {\n apiKey,\n model,\n temperature: resolveOptionalNumber(temperatureSource, `${target.name} temperature`),\n maxOutputTokens: resolveOptionalNumber(maxTokensSource, `${target.name} max output tokens`),\n retry,\n };\n}\n\nfunction resolveCodexConfig(\n target: z.infer<typeof BASE_TARGET_SCHEMA>,\n env: EnvLookup,\n evalFilePath?: string,\n): CodexResolvedConfig {\n const modelSource = target.model;\n const executableSource = target.executable ?? target.command ?? target.binary;\n const argsSource = target.args ?? target.arguments;\n const cwdSource = target.cwd;\n const workspaceTemplateSource = target.workspace_template;\n const timeoutSource = target.timeout_seconds;\n const logDirSource = target.log_dir ?? target.log_directory;\n const logFormatSource =\n target.log_format ?? target.log_output_format ?? env.AGENTV_CODEX_LOG_FORMAT;\n const systemPromptSource = target.system_prompt;\n\n const model = resolveOptionalString(modelSource, env, `${target.name} codex model`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n const executable =\n resolveOptionalString(executableSource, env, `${target.name} codex executable`, {\n allowLiteral: true,\n optionalEnv: true,\n }) ?? 'codex';\n\n const args = resolveOptionalStringArray(argsSource, env, `${target.name} codex args`);\n\n const cwd = resolveOptionalString(cwdSource, env, `${target.name} codex cwd`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n let workspaceTemplate = resolveOptionalString(\n workspaceTemplateSource,\n env,\n `${target.name} codex workspace template`,\n {\n allowLiteral: true,\n optionalEnv: true,\n },\n );\n\n // Resolve relative workspace template paths against eval file directory\n if (workspaceTemplate && evalFilePath && !path.isAbsolute(workspaceTemplate)) {\n workspaceTemplate = path.resolve(path.dirname(path.resolve(evalFilePath)), workspaceTemplate);\n }\n\n // Validate mutual exclusivity of cwd and workspace_template\n if (cwd && workspaceTemplate) {\n throw new Error(\n `${target.name}: 'cwd' and 'workspace_template' are mutually exclusive. Use 'cwd' to run in an existing directory, or 'workspace_template' to copy a template to a temp location.`,\n );\n }\n\n const timeoutMs = resolveTimeoutMs(timeoutSource, `${target.name} codex timeout`);\n const logDir = resolveOptionalString(logDirSource, env, `${target.name} codex log directory`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n const logFormat = normalizeCodexLogFormat(logFormatSource);\n\n const systemPrompt =\n typeof systemPromptSource === 'string' && systemPromptSource.trim().length > 0\n ? systemPromptSource.trim()\n : undefined;\n\n return {\n model,\n executable,\n args,\n cwd,\n workspaceTemplate,\n timeoutMs,\n logDir,\n logFormat,\n systemPrompt,\n };\n}\n\nfunction normalizeCodexLogFormat(value: unknown): 'summary' | 'json' | undefined {\n if (value === undefined || value === null) {\n return undefined;\n }\n if (typeof value !== 'string') {\n throw new Error(\"codex log format must be 'summary' or 'json'\");\n }\n const normalized = value.trim().toLowerCase();\n if (normalized === 'json' || normalized === 'summary') {\n return normalized;\n }\n throw new Error(\"codex log format must be 'summary' or 'json'\");\n}\n\nfunction resolveCopilotSdkConfig(\n target: z.infer<typeof BASE_TARGET_SCHEMA>,\n env: EnvLookup,\n evalFilePath?: string,\n): CopilotSdkResolvedConfig {\n const cliUrlSource = target.cli_url;\n const cliPathSource = target.cli_path;\n const githubTokenSource = target.github_token;\n const modelSource = target.model;\n const cwdSource = target.cwd;\n const workspaceTemplateSource = target.workspace_template;\n const timeoutSource = target.timeout_seconds;\n const logDirSource = target.log_dir ?? target.log_directory;\n const logFormatSource = target.log_format;\n const systemPromptSource = target.system_prompt;\n\n const cliUrl = resolveOptionalString(cliUrlSource, env, `${target.name} copilot-sdk cli URL`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n const cliPath = resolveOptionalString(cliPathSource, env, `${target.name} copilot-sdk cli path`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n const githubToken = resolveOptionalString(\n githubTokenSource,\n env,\n `${target.name} copilot-sdk github token`,\n {\n allowLiteral: false,\n optionalEnv: true,\n },\n );\n\n const model = resolveOptionalString(modelSource, env, `${target.name} copilot-sdk model`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n const cwd = resolveOptionalString(cwdSource, env, `${target.name} copilot-sdk cwd`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n let workspaceTemplate = resolveOptionalString(\n workspaceTemplateSource,\n env,\n `${target.name} copilot-sdk workspace template`,\n {\n allowLiteral: true,\n optionalEnv: true,\n },\n );\n\n // Resolve relative workspace template paths against eval file directory\n if (workspaceTemplate && evalFilePath && !path.isAbsolute(workspaceTemplate)) {\n workspaceTemplate = path.resolve(path.dirname(path.resolve(evalFilePath)), workspaceTemplate);\n }\n\n // Validate mutual exclusivity of cwd and workspace_template\n if (cwd && workspaceTemplate) {\n throw new Error(\n `${target.name}: 'cwd' and 'workspace_template' are mutually exclusive. Use 'cwd' to run in an existing directory, or 'workspace_template' to copy a template to a temp location.`,\n );\n }\n\n const timeoutMs = resolveTimeoutMs(timeoutSource, `${target.name} copilot-sdk timeout`);\n\n const logDir = resolveOptionalString(\n logDirSource,\n env,\n `${target.name} copilot-sdk log directory`,\n {\n allowLiteral: true,\n optionalEnv: true,\n },\n );\n\n const logFormat = normalizeCopilotLogFormat(logFormatSource);\n\n const systemPrompt =\n typeof systemPromptSource === 'string' && systemPromptSource.trim().length > 0\n ? systemPromptSource.trim()\n : undefined;\n\n // BYOK (Bring Your Own Key) — allows routing through a user-provided endpoint\n // instead of GitHub's Copilot infrastructure. The byok block maps to the SDK's\n // `provider` option on createSession(). See copilot-sdk docs/auth/byok.md.\n const byok = target.byok as Record<string, unknown> | undefined;\n let byokType: string | undefined;\n let byokBaseUrl: string | undefined;\n let byokApiKey: string | undefined;\n let byokBearerToken: string | undefined;\n let byokApiVersion: string | undefined;\n let byokWireApi: string | undefined;\n\n if (byok && typeof byok === 'object') {\n byokType = resolveOptionalString(byok.type, env, `${target.name} byok type`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n byokBaseUrl = resolveOptionalString(byok.base_url, env, `${target.name} byok base URL`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n byokApiKey = resolveOptionalString(byok.api_key, env, `${target.name} byok API key`, {\n allowLiteral: false,\n optionalEnv: true,\n });\n\n byokBearerToken = resolveOptionalString(\n byok.bearer_token,\n env,\n `${target.name} byok bearer token`,\n {\n allowLiteral: false,\n optionalEnv: true,\n },\n );\n\n byokApiVersion = resolveOptionalString(\n byok.api_version,\n env,\n `${target.name} byok API version`,\n {\n allowLiteral: true,\n optionalEnv: true,\n },\n );\n\n byokWireApi = resolveOptionalString(byok.wire_api, env, `${target.name} byok wire API`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n // base_url is required when byok is specified\n if (!byokBaseUrl) {\n throw new Error(`${target.name}: 'byok.base_url' is required when 'byok' is specified`);\n }\n }\n\n return {\n cliUrl,\n cliPath,\n githubToken,\n model,\n cwd,\n workspaceTemplate,\n timeoutMs,\n logDir,\n logFormat,\n systemPrompt,\n byokType,\n byokBaseUrl,\n byokApiKey,\n byokBearerToken,\n byokApiVersion,\n byokWireApi,\n };\n}\n\nfunction resolveCopilotCliConfig(\n target: z.infer<typeof BASE_TARGET_SCHEMA>,\n env: EnvLookup,\n evalFilePath?: string,\n): CopilotCliResolvedConfig {\n const executableSource = target.executable ?? target.command ?? target.binary;\n const modelSource = target.model;\n const argsSource = target.args ?? target.arguments;\n const cwdSource = target.cwd;\n const workspaceTemplateSource = target.workspace_template;\n const timeoutSource = target.timeout_seconds;\n const logDirSource = target.log_dir ?? target.log_directory;\n const logFormatSource = target.log_format;\n const systemPromptSource = target.system_prompt;\n\n const executable =\n resolveOptionalString(executableSource, env, `${target.name} copilot-cli executable`, {\n allowLiteral: true,\n optionalEnv: true,\n }) ?? 'copilot';\n\n const model = resolveOptionalString(modelSource, env, `${target.name} copilot-cli model`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n const args = resolveOptionalStringArray(argsSource, env, `${target.name} copilot-cli args`);\n\n const cwd = resolveOptionalString(cwdSource, env, `${target.name} copilot-cli cwd`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n let workspaceTemplate = resolveOptionalString(\n workspaceTemplateSource,\n env,\n `${target.name} copilot-cli workspace template`,\n {\n allowLiteral: true,\n optionalEnv: true,\n },\n );\n\n // Resolve relative workspace template paths against eval file directory\n if (workspaceTemplate && evalFilePath && !path.isAbsolute(workspaceTemplate)) {\n workspaceTemplate = path.resolve(path.dirname(path.resolve(evalFilePath)), workspaceTemplate);\n }\n\n // Validate mutual exclusivity of cwd and workspace_template\n if (cwd && workspaceTemplate) {\n throw new Error(\n `${target.name}: 'cwd' and 'workspace_template' are mutually exclusive. Use 'cwd' to run in an existing directory, or 'workspace_template' to copy a template to a temp location.`,\n );\n }\n\n const timeoutMs = resolveTimeoutMs(timeoutSource, `${target.name} copilot-cli timeout`);\n\n const logDir = resolveOptionalString(\n logDirSource,\n env,\n `${target.name} copilot-cli log directory`,\n {\n allowLiteral: true,\n optionalEnv: true,\n },\n );\n\n const logFormat = normalizeCopilotLogFormat(logFormatSource);\n\n const systemPrompt =\n typeof systemPromptSource === 'string' && systemPromptSource.trim().length > 0\n ? systemPromptSource.trim()\n : undefined;\n\n return {\n executable,\n model,\n args,\n cwd,\n workspaceTemplate,\n timeoutMs,\n logDir,\n logFormat,\n systemPrompt,\n };\n}\n\nfunction normalizeCopilotLogFormat(value: unknown): 'summary' | 'json' | undefined {\n if (value === undefined || value === null) return undefined;\n if (typeof value !== 'string') throw new Error(\"copilot log format must be 'summary' or 'json'\");\n const normalized = value.trim().toLowerCase();\n if (normalized === 'json' || normalized === 'summary') return normalized;\n throw new Error(\"copilot log format must be 'summary' or 'json'\");\n}\n\nfunction resolvePiCodingAgentConfig(\n target: z.infer<typeof BASE_TARGET_SCHEMA>,\n env: EnvLookup,\n evalFilePath?: string,\n): PiCodingAgentResolvedConfig {\n const subproviderSource = target.subprovider;\n const modelSource = target.model ?? target.pi_model;\n const apiKeySource = target.api_key;\n const toolsSource = target.tools ?? target.pi_tools;\n const thinkingSource = target.thinking ?? target.pi_thinking;\n const cwdSource = target.cwd;\n const workspaceTemplateSource = target.workspace_template;\n const timeoutSource = target.timeout_seconds;\n const logDirSource = target.log_dir ?? target.log_directory;\n const logFormatSource = target.log_format;\n const systemPromptSource = target.system_prompt;\n\n const subprovider = resolveOptionalString(\n subproviderSource,\n env,\n `${target.name} pi subprovider`,\n {\n allowLiteral: true,\n optionalEnv: true,\n },\n );\n\n const model = resolveOptionalString(modelSource, env, `${target.name} pi model`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n const apiKey = resolveOptionalString(apiKeySource, env, `${target.name} pi api key`, {\n allowLiteral: false,\n optionalEnv: true,\n });\n\n const baseUrlSource = target.base_url ?? target.endpoint;\n const baseUrl = resolveOptionalString(baseUrlSource, env, `${target.name} pi base url`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n const tools = resolveOptionalString(toolsSource, env, `${target.name} pi tools`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n const thinking = resolveOptionalString(thinkingSource, env, `${target.name} pi thinking`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n const cwd = resolveOptionalString(cwdSource, env, `${target.name} pi cwd`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n let workspaceTemplate = resolveOptionalString(\n workspaceTemplateSource,\n env,\n `${target.name} pi workspace template`,\n {\n allowLiteral: true,\n optionalEnv: true,\n },\n );\n\n // Resolve relative workspace template paths against eval file directory\n if (workspaceTemplate && evalFilePath && !path.isAbsolute(workspaceTemplate)) {\n workspaceTemplate = path.resolve(path.dirname(path.resolve(evalFilePath)), workspaceTemplate);\n }\n\n // Validate mutual exclusivity of cwd and workspace_template\n if (cwd && workspaceTemplate) {\n throw new Error(\n `${target.name}: 'cwd' and 'workspace_template' are mutually exclusive. Use 'cwd' to run in an existing directory, or 'workspace_template' to copy a template to a temp location.`,\n );\n }\n\n const timeoutMs = resolveTimeoutMs(timeoutSource, `${target.name} pi timeout`);\n\n const logDir = resolveOptionalString(logDirSource, env, `${target.name} pi log directory`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n const logFormat =\n logFormatSource === 'json' || logFormatSource === 'summary' ? logFormatSource : undefined;\n\n const systemPrompt =\n typeof systemPromptSource === 'string' && systemPromptSource.trim().length > 0\n ? systemPromptSource.trim()\n : undefined;\n\n return {\n subprovider,\n model,\n apiKey,\n baseUrl,\n tools,\n thinking,\n cwd,\n workspaceTemplate,\n timeoutMs,\n logDir,\n logFormat,\n systemPrompt,\n };\n}\n\nfunction resolvePiCliConfig(\n target: z.infer<typeof BASE_TARGET_SCHEMA>,\n env: EnvLookup,\n evalFilePath?: string,\n): PiCliResolvedConfig {\n const executableSource = target.executable ?? target.command ?? target.binary;\n const subproviderSource = target.subprovider;\n const modelSource = target.model ?? target.pi_model;\n const apiKeySource = target.api_key;\n const toolsSource = target.tools ?? target.pi_tools;\n const thinkingSource = target.thinking ?? target.pi_thinking;\n const cwdSource = target.cwd;\n const workspaceTemplateSource = target.workspace_template;\n const timeoutSource = target.timeout_seconds;\n const logDirSource = target.log_dir ?? target.log_directory;\n const logFormatSource = target.log_format;\n const systemPromptSource = target.system_prompt;\n\n const executable =\n resolveOptionalString(executableSource, env, `${target.name} pi-cli executable`, {\n allowLiteral: true,\n optionalEnv: true,\n }) ?? 'pi';\n\n const subprovider = resolveOptionalString(\n subproviderSource,\n env,\n `${target.name} pi-cli subprovider`,\n { allowLiteral: true, optionalEnv: true },\n );\n\n const model = resolveOptionalString(modelSource, env, `${target.name} pi-cli model`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n const apiKey = resolveOptionalString(apiKeySource, env, `${target.name} pi-cli api key`, {\n allowLiteral: false,\n optionalEnv: true,\n });\n\n const baseUrlSource = target.base_url ?? target.endpoint;\n const baseUrl = resolveOptionalString(baseUrlSource, env, `${target.name} pi-cli base url`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n const tools = resolveOptionalString(toolsSource, env, `${target.name} pi-cli tools`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n const thinking = resolveOptionalString(thinkingSource, env, `${target.name} pi-cli thinking`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n const rawArgs = target.args ?? target.arguments;\n const args = resolveOptionalStringArray(rawArgs, env, `${target.name} pi-cli args`);\n\n const cwd = resolveOptionalString(cwdSource, env, `${target.name} pi-cli cwd`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n let workspaceTemplate = resolveOptionalString(\n workspaceTemplateSource,\n env,\n `${target.name} pi-cli workspace template`,\n { allowLiteral: true, optionalEnv: true },\n );\n\n if (workspaceTemplate && evalFilePath && !path.isAbsolute(workspaceTemplate)) {\n workspaceTemplate = path.resolve(path.dirname(path.resolve(evalFilePath)), workspaceTemplate);\n }\n\n if (cwd && workspaceTemplate) {\n throw new Error(`${target.name}: 'cwd' and 'workspace_template' are mutually exclusive.`);\n }\n\n const timeoutMs = resolveTimeoutMs(timeoutSource, `${target.name} pi-cli timeout`);\n\n const logDir = resolveOptionalString(logDirSource, env, `${target.name} pi-cli log directory`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n const logFormat =\n logFormatSource === 'json' || logFormatSource === 'summary' ? logFormatSource : undefined;\n\n const systemPrompt =\n typeof systemPromptSource === 'string' && systemPromptSource.trim().length > 0\n ? systemPromptSource.trim()\n : undefined;\n\n return {\n executable,\n subprovider,\n model,\n apiKey,\n baseUrl,\n tools,\n thinking,\n args,\n cwd,\n workspaceTemplate,\n timeoutMs,\n logDir,\n logFormat,\n systemPrompt,\n };\n}\n\nfunction resolveClaudeConfig(\n target: z.infer<typeof BASE_TARGET_SCHEMA>,\n env: EnvLookup,\n evalFilePath?: string,\n): ClaudeResolvedConfig {\n const modelSource = target.model;\n const cwdSource = target.cwd;\n const workspaceTemplateSource = target.workspace_template;\n const timeoutSource = target.timeout_seconds;\n const logDirSource = target.log_dir ?? target.log_directory;\n const logFormatSource =\n target.log_format ?? target.log_output_format ?? env.AGENTV_CLAUDE_LOG_FORMAT;\n const systemPromptSource = target.system_prompt;\n\n const model = resolveOptionalString(modelSource, env, `${target.name} claude model`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n const cwd = resolveOptionalString(cwdSource, env, `${target.name} claude cwd`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n let workspaceTemplate = resolveOptionalString(\n workspaceTemplateSource,\n env,\n `${target.name} claude workspace template`,\n {\n allowLiteral: true,\n optionalEnv: true,\n },\n );\n\n // Resolve relative workspace template paths against eval file directory\n if (workspaceTemplate && evalFilePath && !path.isAbsolute(workspaceTemplate)) {\n workspaceTemplate = path.resolve(path.dirname(path.resolve(evalFilePath)), workspaceTemplate);\n }\n\n // Validate mutual exclusivity of cwd and workspace_template\n if (cwd && workspaceTemplate) {\n throw new Error(\n `${target.name}: 'cwd' and 'workspace_template' are mutually exclusive. Use 'cwd' to run in an existing directory, or 'workspace_template' to copy a template to a temp location.`,\n );\n }\n\n const timeoutMs = resolveTimeoutMs(timeoutSource, `${target.name} claude timeout`);\n\n const logDir = resolveOptionalString(logDirSource, env, `${target.name} claude log directory`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n const logFormat = normalizeClaudeLogFormat(logFormatSource);\n\n const systemPrompt =\n typeof systemPromptSource === 'string' && systemPromptSource.trim().length > 0\n ? systemPromptSource.trim()\n : undefined;\n\n const maxTurns = typeof target.max_turns === 'number' ? target.max_turns : undefined;\n\n const maxBudgetUsd =\n typeof target.max_budget_usd === 'number' ? target.max_budget_usd : undefined;\n\n return {\n model,\n systemPrompt,\n cwd,\n workspaceTemplate,\n timeoutMs,\n maxTurns,\n maxBudgetUsd,\n logDir,\n logFormat,\n };\n}\n\nfunction normalizeClaudeLogFormat(value: unknown): 'summary' | 'json' | undefined {\n if (value === undefined || value === null) {\n return undefined;\n }\n if (typeof value !== 'string') {\n throw new Error(\"claude log format must be 'summary' or 'json'\");\n }\n const normalized = value.trim().toLowerCase();\n if (normalized === 'json' || normalized === 'summary') {\n return normalized;\n }\n throw new Error(\"claude log format must be 'summary' or 'json'\");\n}\n\nfunction resolveMockConfig(target: z.infer<typeof BASE_TARGET_SCHEMA>): MockResolvedConfig {\n const response = typeof target.response === 'string' ? target.response : undefined;\n return { response };\n}\n\nfunction resolveVSCodeConfig(\n target: z.infer<typeof BASE_TARGET_SCHEMA>,\n env: EnvLookup,\n insiders: boolean,\n evalFilePath?: string,\n): VSCodeResolvedConfig {\n const workspaceTemplateEnvVar = resolveOptionalLiteralString(target.workspace_template);\n let workspaceTemplate = workspaceTemplateEnvVar\n ? resolveOptionalString(\n workspaceTemplateEnvVar,\n env,\n `${target.name} workspace template path`,\n {\n allowLiteral: true,\n optionalEnv: true,\n },\n )\n : undefined;\n\n // Resolve relative workspace template paths against eval file directory\n if (workspaceTemplate && evalFilePath && !path.isAbsolute(workspaceTemplate)) {\n workspaceTemplate = path.resolve(path.dirname(path.resolve(evalFilePath)), workspaceTemplate);\n }\n\n const executableSource = target.executable;\n const waitSource = target.wait;\n const dryRunSource = target.dry_run;\n const subagentRootSource = target.subagent_root;\n const timeoutSource = target.timeout_seconds;\n\n const defaultCommand = insiders ? 'code-insiders' : 'code';\n const executable =\n resolveOptionalString(executableSource, env, `${target.name} vscode executable`, {\n allowLiteral: true,\n optionalEnv: true,\n }) ?? defaultCommand;\n\n const timeoutMs = resolveTimeoutMs(timeoutSource, `${target.name} vscode timeout`);\n\n return {\n executable,\n waitForResponse: resolveOptionalBoolean(waitSource) ?? true,\n dryRun: resolveOptionalBoolean(dryRunSource) ?? false,\n subagentRoot: resolveOptionalString(subagentRootSource, env, `${target.name} subagent root`, {\n allowLiteral: true,\n optionalEnv: true,\n }),\n workspaceTemplate,\n timeoutMs,\n };\n}\n\n/**\n * Custom Zod error map for CLI provider validation.\n * Provides clear, user-friendly error messages for common validation failures.\n */\nconst cliErrorMap: z.ZodErrorMap = (issue, ctx) => {\n if (issue.code === z.ZodIssueCode.unrecognized_keys) {\n return { message: `Unknown CLI provider settings: ${issue.keys.join(', ')}` };\n }\n if (issue.code === z.ZodIssueCode.invalid_union) {\n return { message: \"healthcheck must have either 'url' (HTTP) or 'command' (command)\" };\n }\n if (issue.code === z.ZodIssueCode.invalid_type && issue.expected === 'string') {\n return { message: `${ctx.defaultError} (expected a string value)` };\n }\n return { message: ctx.defaultError };\n};\n\n/**\n * Resolves a CLI target configuration using Zod schema validation and normalization.\n *\n * This function:\n * 1. Parses the raw target with CliTargetInputSchema for structural validation\n * 2. Normalizes the input using normalizeCliTargetInput() for env var resolution and casing\n * 3. Validates CLI placeholders in the command\n *\n * @param target - The raw target definition from YAML\n * @param env - Environment variable lookup for ${{ VAR }} resolution\n * @param evalFilePath - Optional path to eval file for relative path resolution\n * @returns Normalized CLI configuration matching CliResolvedConfig\n */\nfunction resolveCliConfig(\n target: z.infer<typeof BASE_TARGET_SCHEMA>,\n env: EnvLookup,\n evalFilePath?: string,\n): CliResolvedConfig {\n // Parse with Zod schema for structural validation with custom error messages\n const parseResult = CliTargetInputSchema.safeParse(target, { errorMap: cliErrorMap });\n if (!parseResult.success) {\n const firstError = parseResult.error.errors[0];\n const path = firstError?.path.join('.') || '';\n const prefix = path ? `${target.name} ${path}: ` : `${target.name}: `;\n throw new Error(`${prefix}${firstError?.message}`);\n }\n\n // Normalize the parsed input (handles env var resolution, casing, path resolution)\n const normalized = normalizeCliTargetInput(parseResult.data, env, evalFilePath);\n\n // Validate CLI placeholders in command\n assertSupportedCliPlaceholders(normalized.command, `${target.name} CLI command`);\n\n // Validate CLI placeholders in healthcheck command if present\n if (\n 'command' in (normalized.healthcheck ?? {}) &&\n (normalized.healthcheck as { command: string }).command\n ) {\n assertSupportedCliPlaceholders(\n (normalized.healthcheck as { command: string }).command,\n `${target.name} healthcheck command`,\n );\n }\n\n return normalized;\n}\n\n/**\n * Resolves configuration for a discovered (convention-based) provider.\n *\n * When the provider kind doesn't match any built-in provider, it is assumed\n * to be a convention-based provider discovered from `.agentv/providers/`.\n * The command defaults to `bun run .agentv/providers/<kind>.ts {PROMPT}`\n * but can be overridden via `command` in the target definition.\n */\nfunction resolveDiscoveredProviderConfig(\n target: z.infer<typeof BASE_TARGET_SCHEMA>,\n providerKind: string,\n env: EnvLookup,\n evalFilePath?: string,\n): CliResolvedConfig {\n // Use explicit command if provided, otherwise derive from convention\n const command = target.command\n ? resolveString(target.command, env, `${target.name} command`, true)\n : `bun run .agentv/providers/${providerKind}.ts {PROMPT}`;\n\n // Resolve optional fields using the same patterns as CLI providers\n const timeoutSeconds = target.timeout_seconds;\n const timeoutMs = resolveTimeoutMs(timeoutSeconds, `${target.name} timeout`);\n\n let cwd = resolveOptionalString(target.cwd, env, `${target.name} working directory`, {\n allowLiteral: true,\n optionalEnv: true,\n });\n\n // Resolve relative cwd paths against eval file directory\n if (cwd && evalFilePath && !path.isAbsolute(cwd)) {\n cwd = path.resolve(path.dirname(path.resolve(evalFilePath)), cwd);\n }\n\n // Fallback: if cwd is not set and we have an eval file path, use the eval directory\n if (!cwd && evalFilePath) {\n cwd = path.dirname(path.resolve(evalFilePath));\n }\n\n return {\n command,\n cwd,\n timeoutMs,\n };\n}\n\nfunction resolveTimeoutMs(source: unknown, description: string): number | undefined {\n const seconds = resolveOptionalNumber(source, `${description} (seconds)`);\n if (seconds === undefined) {\n return undefined;\n }\n if (seconds <= 0) {\n throw new Error(`${description} must be greater than zero seconds`);\n }\n return Math.floor(seconds * 1000);\n}\n\nfunction assertSupportedCliPlaceholders(template: string, description: string): void {\n const placeholders = extractCliPlaceholders(template);\n for (const placeholder of placeholders) {\n if (!CLI_PLACEHOLDERS.has(placeholder)) {\n throw new Error(\n `${description} includes unsupported placeholder '{${placeholder}}'. Supported placeholders: ${Array.from(CLI_PLACEHOLDERS).join(', ')}`,\n );\n }\n }\n}\n\nfunction extractCliPlaceholders(template: string): string[] {\n const matches = template.matchAll(/\\{([A-Z_]+)\\}/g);\n const results: string[] = [];\n for (const match of matches) {\n if (match[1]) {\n results.push(match[1]);\n }\n }\n return results;\n}\n\nfunction resolveString(\n source: unknown,\n env: EnvLookup,\n description: string,\n allowLiteral = false,\n): string {\n const value = resolveOptionalString(source, env, description, {\n allowLiteral,\n optionalEnv: false,\n });\n if (value === undefined) {\n throw new Error(`${description} is required`);\n }\n return value;\n}\n\nfunction resolveDiscover(value: unknown, targetName: string): 'latest' | undefined {\n if (value === undefined || value === null) return undefined;\n if (value === 'latest') return 'latest';\n throw new Error(`Target \"${targetName}\": discover must be \"latest\" (got \"${String(value)}\")`);\n}\n\nfunction resolveCopilotLogConfig(\n target: z.infer<typeof BASE_TARGET_SCHEMA>,\n env: EnvLookup,\n): CopilotLogResolvedConfig {\n const sessionDirSource = target.session_dir;\n const sessionIdSource = target.session_id;\n const discoverSource = target.discover;\n const sessionStateDirSource = target.session_state_dir;\n const cwdSource = target.cwd;\n\n return {\n sessionDir: resolveOptionalString(\n sessionDirSource,\n env,\n `${target.name} copilot-log session_dir`,\n { allowLiteral: true, optionalEnv: true },\n ),\n sessionId: resolveOptionalString(\n sessionIdSource,\n env,\n `${target.name} copilot-log session_id`,\n { allowLiteral: true, optionalEnv: true },\n ),\n discover: resolveDiscover(discoverSource, target.name),\n sessionStateDir: resolveOptionalString(\n sessionStateDirSource,\n env,\n `${target.name} copilot-log session_state_dir`,\n { allowLiteral: true, optionalEnv: true },\n ),\n cwd: resolveOptionalString(cwdSource, env, `${target.name} copilot-log cwd`, {\n allowLiteral: true,\n optionalEnv: true,\n }),\n };\n}\n\n/**\n * Resolve a string value from targets.yaml, supporting `${{ VARIABLE }}` env var syntax.\n *\n * Security: By default (`allowLiteral: false`), values MUST use the `${{ VARIABLE_NAME }}`\n * syntax to reference environment variables. Literal strings are rejected to prevent\n * secrets (API keys, tokens) from being committed in plaintext to targets.yaml.\n * Only non-sensitive fields like `cwd` or `model` use `allowLiteral: true`.\n */\nfunction resolveOptionalString(\n source: unknown,\n env: EnvLookup,\n description: string,\n options?: { allowLiteral?: boolean; optionalEnv?: boolean },\n): string | undefined {\n if (source === undefined || source === null) {\n return undefined;\n }\n if (typeof source !== 'string') {\n throw new Error(`${description} must be a string`);\n }\n const trimmed = source.trim();\n if (trimmed.length === 0) {\n return undefined;\n }\n\n // Check for ${{ variable }} syntax\n const envVarMatch = trimmed.match(/^\\$\\{\\{\\s*([A-Z0-9_]+)\\s*\\}\\}$/i);\n if (envVarMatch) {\n const varName = envVarMatch[1];\n const envValue = env[varName];\n const optionalEnv = options?.optionalEnv ?? false;\n\n // Treat empty or undefined env vars the same way\n if (envValue === undefined || envValue.trim().length === 0) {\n if (optionalEnv) {\n return undefined;\n }\n const status = envValue === undefined ? 'is not set' : 'is empty';\n throw new Error(`Environment variable '${varName}' required for ${description} ${status}`);\n }\n return envValue;\n }\n\n // Return as literal value\n const allowLiteral = options?.allowLiteral ?? false;\n if (!allowLiteral) {\n throw new Error(\n `${description} must use \\${{ VARIABLE_NAME }} syntax for environment variables or be marked as allowing literals`,\n );\n }\n return trimmed;\n}\n\nfunction resolveOptionalLiteralString(source: unknown): string | undefined {\n if (source === undefined || source === null) {\n return undefined;\n }\n if (typeof source !== 'string') {\n throw new Error('expected string value');\n }\n const trimmed = source.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction resolveOptionalNumber(source: unknown, description: string): number | undefined {\n if (source === undefined || source === null || source === '') {\n return undefined;\n }\n if (typeof source === 'number') {\n return Number.isFinite(source) ? source : undefined;\n }\n if (typeof source === 'string') {\n const numeric = Number(source);\n if (Number.isFinite(numeric)) {\n return numeric;\n }\n }\n throw new Error(`${description} must be a number`);\n}\n\nfunction resolveOptionalBoolean(source: unknown): boolean | undefined {\n if (source === undefined || source === null || source === '') {\n return undefined;\n }\n if (typeof source === 'boolean') {\n return source;\n }\n if (typeof source === 'string') {\n const lowered = source.trim().toLowerCase();\n if (lowered === 'true' || lowered === '1') {\n return true;\n }\n if (lowered === 'false' || lowered === '0') {\n return false;\n }\n }\n throw new Error('expected boolean value');\n}\n\nfunction resolveOptionalStringArray(\n source: unknown,\n env: EnvLookup,\n description: string,\n): readonly string[] | undefined {\n if (source === undefined || source === null) {\n return undefined;\n }\n if (!Array.isArray(source)) {\n throw new Error(`${description} must be an array of strings`);\n }\n if (source.length === 0) {\n return undefined;\n }\n const resolved: string[] = [];\n for (let i = 0; i < source.length; i++) {\n const item = source[i];\n if (typeof item !== 'string') {\n throw new Error(`${description}[${i}] must be a string`);\n }\n const trimmed = item.trim();\n if (trimmed.length === 0) {\n throw new Error(`${description}[${i}] cannot be empty`);\n }\n\n // Check for ${{ variable }} syntax\n const envVarMatch = trimmed.match(/^\\$\\{\\{\\s*([A-Z0-9_]+)\\s*\\}\\}$/i);\n if (envVarMatch) {\n const varName = envVarMatch[1];\n const envValue = env[varName];\n if (envValue !== undefined) {\n if (envValue.trim().length === 0) {\n throw new Error(`Environment variable '${varName}' for ${description}[${i}] is empty`);\n }\n resolved.push(envValue);\n continue;\n }\n throw new Error(`Environment variable '${varName}' for ${description}[${i}] is not set`);\n }\n\n // Treat as literal value\n resolved.push(trimmed);\n }\n return resolved.length > 0 ? resolved : undefined;\n}\n\nfunction resolveOptionalNumberArray(\n source: unknown,\n description: string,\n): readonly number[] | undefined {\n if (source === undefined || source === null) {\n return undefined;\n }\n if (!Array.isArray(source)) {\n throw new Error(`${description} must be an array of numbers`);\n }\n if (source.length === 0) {\n return undefined;\n }\n const resolved: number[] = [];\n for (let i = 0; i < source.length; i++) {\n const item = source[i];\n if (typeof item !== 'number' || !Number.isFinite(item)) {\n throw new Error(`${description}[${i}] must be a number`);\n }\n resolved.push(item);\n }\n return resolved.length > 0 ? resolved : undefined;\n}\n","import type { Content } from '../content.js';\nimport { getTextContent, isContentArray } from '../content.js';\nimport type { JsonObject } from '../types.js';\n\nexport type ChatMessageRole = 'system' | 'user' | 'assistant' | 'tool' | 'function';\n\nexport interface ChatMessage {\n readonly role: ChatMessageRole;\n readonly content: string;\n readonly name?: string;\n}\n\nexport type ChatPrompt = readonly ChatMessage[];\n\nexport type ProviderKind =\n | 'openai'\n | 'openrouter'\n | 'azure'\n | 'anthropic'\n | 'gemini'\n | 'codex'\n | 'copilot-sdk'\n | 'copilot-cli'\n | 'copilot-log'\n | 'pi-coding-agent'\n | 'pi-cli'\n | 'claude'\n | 'claude-cli'\n | 'claude-sdk'\n | 'cli'\n | 'mock'\n | 'vscode'\n | 'vscode-insiders'\n | 'agentv'\n | 'transcript';\n\n/**\n * Agent providers that spawn interactive sessions with filesystem access.\n * These providers read files directly from the filesystem using file:// URIs.\n *\n * Note: copilot-log is intentionally excluded — it is a passive transcript\n * reader, not an interactive agent. This allows deterministic-only evals\n * (e.g., skill-trigger) to run without a grader_target or LLM API key.\n */\nexport const AGENT_PROVIDER_KINDS: readonly ProviderKind[] = [\n 'codex',\n 'copilot-sdk',\n 'copilot-cli',\n 'pi-coding-agent',\n 'pi-cli',\n 'claude',\n 'claude-cli',\n 'claude-sdk',\n 'vscode',\n 'vscode-insiders',\n] as const;\n\n/**\n * Provider kinds that can return structured JSON for LLM grading.\n * Used by the orchestrator to decide whether a target can double as its own\n * grader when no explicit grader_target is configured.\n *\n * Providers NOT in this list (agent providers, transcript, cli, copilot-log)\n * cannot produce grader responses and should not be used as graders.\n */\nexport const LLM_GRADER_CAPABLE_KINDS: readonly ProviderKind[] = [\n 'openai',\n 'openrouter',\n 'azure',\n 'anthropic',\n 'gemini',\n 'agentv',\n 'mock',\n] as const;\n\n/**\n * List of all supported provider kinds.\n * This is the source of truth for provider validation.\n */\nexport const KNOWN_PROVIDERS: readonly ProviderKind[] = [\n 'openai',\n 'openrouter',\n 'azure',\n 'anthropic',\n 'gemini',\n 'codex',\n 'copilot-sdk',\n 'copilot-cli',\n 'copilot-log',\n 'pi-coding-agent',\n 'pi-cli',\n 'claude',\n 'claude-cli',\n 'claude-sdk',\n 'cli',\n 'mock',\n 'vscode',\n 'vscode-insiders',\n 'agentv',\n 'transcript',\n] as const;\n\n/**\n * Provider aliases that are accepted in target definitions.\n * These map to the canonical ProviderKind values.\n */\nexport const PROVIDER_ALIASES: readonly string[] = [\n 'azure-openai', // alias for \"azure\"\n 'google', // alias for \"gemini\"\n 'google-gemini', // alias for \"gemini\"\n 'codex-cli', // alias for \"codex\"\n 'copilot', // alias for \"copilot-cli\" (default copilot experience)\n 'copilot_sdk', // alias for \"copilot-sdk\" (underscore variant)\n\n 'pi', // alias for \"pi-coding-agent\"\n 'claude-code', // alias for \"claude\" (legacy)\n 'bedrock', // legacy/future support\n 'vertex', // legacy/future support\n] as const;\n\n/**\n * Schema identifier for targets.yaml files (version 2).\n */\nexport const TARGETS_SCHEMA_V2 = 'agentv-targets-v2.2';\n\n/** Callbacks for real-time observability during provider execution */\nexport interface ProviderStreamCallbacks {\n onToolCallStart?: (toolName: string, toolCallId?: string) => void;\n onToolCallEnd?: (\n toolName: string,\n input: unknown,\n output: unknown,\n durationMs: number,\n toolCallId?: string,\n ) => void;\n onLlmCallEnd?: (model: string, tokenUsage?: ProviderTokenUsage) => void;\n /** Returns active OTel span IDs for Braintrust trace bridging (optional) */\n getActiveSpanIds?: () => { parentSpanId: string; rootSpanId: string } | null;\n}\n\nexport interface ProviderRequest {\n readonly question: string;\n readonly systemPrompt?: string;\n readonly chatPrompt?: ChatPrompt;\n readonly inputFiles?: readonly string[];\n readonly evalCaseId?: string;\n readonly attempt?: number;\n readonly maxOutputTokens?: number;\n readonly temperature?: number;\n readonly metadata?: JsonObject;\n readonly signal?: AbortSignal;\n /** Working directory override (e.g., from workspace_template) */\n readonly cwd?: string;\n /** VS Code .code-workspace file (resolved from workspace.template) */\n readonly workspaceFile?: string;\n /** When true, AgentV captures file changes from workspace — provider should skip forced diff prompt */\n readonly captureFileChanges?: boolean;\n /** Real-time observability callbacks (optional) */\n readonly streamCallbacks?: ProviderStreamCallbacks;\n /** Braintrust span IDs for trace-claude-code plugin (optional) */\n readonly braintrustSpanIds?: { readonly parentSpanId: string; readonly rootSpanId: string };\n}\n\n/**\n * A tool call within an output message.\n * Represents a single tool invocation with its input and optional output.\n */\nexport interface ToolCall {\n /** Tool name */\n readonly tool: string;\n /** Tool input arguments */\n readonly input?: unknown;\n /** Tool output result */\n readonly output?: unknown;\n /** Stable identifier for pairing tool calls */\n readonly id?: string;\n /** ISO 8601 timestamp when the tool call started */\n readonly startTime?: string;\n /** ISO 8601 timestamp when the tool call ended */\n readonly endTime?: string;\n /** Duration of the tool call in milliseconds */\n readonly durationMs?: number;\n}\n\n/**\n * An output message from agent execution.\n * Represents a single message in the conversation with optional tool calls.\n */\nexport interface Message {\n /** Message role (e.g., 'assistant', 'user', 'tool') */\n readonly role: string;\n /** Optional name for the message sender */\n readonly name?: string;\n /** Message content — plain string or structured content blocks for multimodal data. */\n readonly content?: string | Content[];\n /** Tool calls made in this message */\n readonly toolCalls?: readonly ToolCall[];\n /** ISO 8601 timestamp when the message started */\n readonly startTime?: string;\n /** ISO 8601 timestamp when the message ended */\n readonly endTime?: string;\n /** Duration of the message in milliseconds */\n readonly durationMs?: number;\n /** Provider-specific metadata */\n readonly metadata?: Record<string, unknown>;\n /** Per-message token usage metrics (optional) */\n readonly tokenUsage?: ProviderTokenUsage;\n}\n\n/** @deprecated Use Message instead */\nexport type OutputMessage = Message;\n\n/**\n * Token usage metrics reported by provider.\n */\nexport interface ProviderTokenUsage {\n /** Input/prompt tokens consumed */\n readonly input: number;\n /** Output/completion tokens generated */\n readonly output: number;\n /** Cached tokens (optional, provider-specific) */\n readonly cached?: number;\n /** Reasoning/thinking tokens (optional, provider-specific) */\n readonly reasoning?: number;\n}\n\nexport interface ProviderResponse {\n readonly raw?: unknown;\n readonly usage?: JsonObject;\n /** Output messages from agent execution (primary source for tool trajectory) */\n readonly output?: readonly Message[];\n /** Token usage metrics (optional) */\n readonly tokenUsage?: ProviderTokenUsage;\n /** Total cost in USD (optional) */\n readonly costUsd?: number;\n /** Execution duration in milliseconds (optional) */\n readonly durationMs?: number;\n /** ISO 8601 timestamp when execution started (optional) */\n readonly startTime?: string;\n /** ISO 8601 timestamp when execution ended (optional) */\n readonly endTime?: string;\n}\n\n/**\n * Extract the content from the last assistant message in an output message array.\n * Returns empty string if no assistant message found.\n *\n * Handles both plain-string content and Content[] (extracts text blocks).\n */\nexport function extractLastAssistantContent(messages: readonly Message[] | undefined): string {\n if (!messages || messages.length === 0) {\n return '';\n }\n\n // Find the last assistant message (reverse search)\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.role === 'assistant' && msg.content !== undefined) {\n if (typeof msg.content === 'string') {\n return msg.content;\n }\n if (isContentArray(msg.content)) {\n return getTextContent(msg.content);\n }\n return JSON.stringify(msg.content);\n }\n }\n\n return '';\n}\n\n/**\n * Type guard to check if a provider is an agent provider with filesystem access.\n * Agent providers read files directly from the filesystem.\n */\nexport function isAgentProvider(provider: Provider | undefined): boolean {\n return provider ? AGENT_PROVIDER_KINDS.includes(provider.kind) : false;\n}\n\nexport interface Provider {\n readonly id: string;\n readonly kind: ProviderKind;\n readonly targetName: string;\n invoke(request: ProviderRequest): Promise<ProviderResponse>;\n /**\n * Optional capability marker for provider-managed batching (single session handling multiple requests).\n */\n readonly supportsBatch?: boolean;\n /**\n * Optional batch invocation hook. When defined alongside supportsBatch=true,\n * the orchestrator may send multiple requests in a single provider session.\n */\n invokeBatch?(requests: readonly ProviderRequest[]): Promise<readonly ProviderResponse[]>;\n /**\n * Optional method to get a Vercel AI SDK LanguageModel instance for structured output generation.\n * Used by evaluators that need generateObject/generateText from the AI SDK.\n */\n asLanguageModel?(): import('ai').LanguageModel;\n}\n\nexport type EnvLookup = Readonly<Record<string, string | undefined>>;\n\nexport interface TargetDefinition {\n readonly name: string;\n readonly provider?: ProviderKind | string;\n // Delegation: resolve this target as another named target.\n // Supports ${{ ENV_VAR }} syntax (e.g., use_target: ${{ AGENT_TARGET }}).\n readonly use_target?: string | unknown | undefined;\n readonly grader_target?: string | undefined;\n /** @deprecated Use `grader_target` instead */\n readonly judge_target?: string | undefined;\n readonly workers?: number | undefined;\n // Provider batching\n readonly provider_batching?: boolean | undefined;\n readonly subagent_mode_allowed?: boolean | undefined;\n // Azure fields\n readonly endpoint?: string | unknown | undefined;\n readonly base_url?: string | unknown | undefined;\n readonly resource?: string | unknown | undefined;\n readonly api_key?: string | unknown | undefined;\n readonly deployment?: string | unknown | undefined;\n readonly model?: string | unknown | undefined;\n readonly version?: string | unknown | undefined;\n readonly api_version?: string | unknown | undefined;\n // Anthropic fields\n readonly variant?: string | unknown | undefined;\n readonly thinking_budget?: number | unknown | undefined;\n // Common fields\n readonly temperature?: number | unknown | undefined;\n readonly max_output_tokens?: number | unknown | undefined;\n // Codex fields\n readonly executable?: string | unknown | undefined;\n readonly command?: string | unknown | undefined;\n readonly binary?: string | unknown | undefined;\n readonly args?: unknown | undefined;\n readonly arguments?: unknown | undefined;\n readonly cwd?: string | unknown | undefined;\n readonly timeout_seconds?: number | unknown | undefined;\n readonly log_dir?: string | unknown | undefined;\n readonly log_directory?: string | unknown | undefined;\n readonly log_format?: string | unknown | undefined;\n readonly log_output_format?: string | unknown | undefined;\n // System prompt (codex, copilot, claude, pi-coding-agent)\n readonly system_prompt?: string | unknown | undefined;\n // Claude Agent SDK fields\n readonly max_turns?: number | unknown | undefined;\n readonly max_budget_usd?: number | unknown | undefined;\n // Mock fields\n readonly response?: string | unknown | undefined;\n // VSCode fields\n readonly wait?: boolean | unknown | undefined;\n readonly dry_run?: boolean | unknown | undefined;\n readonly subagent_root?: string | unknown | undefined;\n readonly workspace_template?: string | unknown | undefined;\n // CLI fields\n readonly files_format?: string | unknown | undefined;\n readonly attachments_format?: string | unknown | undefined;\n readonly env?: unknown | undefined;\n readonly healthcheck?: unknown | undefined;\n // Copilot-log fields\n readonly session_dir?: string | unknown | undefined;\n readonly session_id?: string | unknown | undefined;\n readonly discover?: string | unknown | undefined;\n readonly session_state_dir?: string | unknown | undefined;\n // Copilot SDK fields\n readonly cli_url?: string | unknown | undefined;\n readonly cli_path?: string | unknown | undefined;\n readonly github_token?: string | unknown | undefined;\n // Copilot SDK BYOK (Bring Your Own Key) — routes through a user-provided endpoint\n readonly byok?: Record<string, unknown> | undefined;\n // Retry configuration fields\n readonly max_retries?: number | unknown | undefined;\n readonly retry_initial_delay_ms?: number | unknown | undefined;\n readonly retry_max_delay_ms?: number | unknown | undefined;\n readonly retry_backoff_factor?: number | unknown | undefined;\n readonly retry_status_codes?: unknown | undefined;\n // Fallback targets for provider errors\n readonly fallback_targets?: readonly string[] | unknown | undefined;\n}\n","import type { EnvLookup } from './providers/types.js';\n\nconst ENV_VAR_PATTERN = /\\$\\{\\{\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*\\}\\}/g;\n\n/**\n * Recursively interpolate `${{ VAR }}` references in all string values.\n * Missing variables resolve to empty string.\n * Non-string values pass through unchanged. Returns a new object (no mutation).\n */\nexport function interpolateEnv(value: unknown, env: EnvLookup): unknown {\n if (typeof value === 'string') {\n return value.replace(ENV_VAR_PATTERN, (_, varName: string) => env[varName] ?? '');\n }\n if (Array.isArray(value)) {\n return value.map((item) => interpolateEnv(item, env));\n }\n if (value !== null && typeof value === 'object') {\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n result[key] = interpolateEnv(val, env);\n }\n return result;\n }\n return value;\n}\n","import { readFile } from 'node:fs/promises';\nimport path from 'node:path';\nimport fg from 'fast-glob';\nimport { parse as parseYaml } from 'yaml';\n\nimport { interpolateEnv } from '../interpolation.js';\nimport type { JsonObject, JsonValue } from '../types.js';\nimport { isJsonObject } from '../types.js';\n\nconst ANSI_YELLOW = '\\u001b[33m';\nconst ANSI_RESET = '\\u001b[0m';\n\nconst FILE_PROTOCOL = 'file://';\n\n/**\n * Check if a value in the tests array is a file:// reference string.\n */\nexport function isFileReference(value: JsonValue): value is string {\n return typeof value === 'string' && value.startsWith(FILE_PROTOCOL);\n}\n\n/**\n * Extract the path portion from a file:// reference.\n */\nfunction extractFilePath(ref: string): string {\n return ref.slice(FILE_PROTOCOL.length);\n}\n\n/**\n * Check if a path contains glob pattern characters.\n */\nfunction isGlobPattern(filePath: string): boolean {\n return filePath.includes('*') || filePath.includes('?') || filePath.includes('{');\n}\n\n/**\n * Parse test objects from a YAML file.\n * Expects the file to contain an array of test objects.\n */\nfunction parseYamlCases(content: string, filePath: string): JsonObject[] {\n const raw = parseYaml(content) as unknown;\n const parsed = interpolateEnv(raw, process.env);\n if (!Array.isArray(parsed)) {\n throw new Error(\n `External test file must contain a YAML array, got ${typeof parsed}: ${filePath}`,\n );\n }\n const results: JsonObject[] = [];\n for (const item of parsed) {\n if (!isJsonObject(item)) {\n throw new Error(`External test file contains non-object entry: ${filePath}`);\n }\n results.push(item);\n }\n return results;\n}\n\n/**\n * Parse test objects from a JSONL file.\n * Each non-empty line must be a valid JSON object.\n */\nfunction parseJsonlCases(content: string, filePath: string): JsonObject[] {\n const lines = content.split('\\n');\n const results: JsonObject[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i].trim();\n if (line === '') continue;\n\n try {\n const raw = JSON.parse(line) as unknown;\n const parsed = interpolateEnv(raw, process.env);\n if (!isJsonObject(parsed)) {\n throw new Error('Expected JSON object');\n }\n results.push(parsed);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Malformed JSONL at line ${i + 1}: ${message}\\n File: ${filePath}`);\n }\n }\n\n return results;\n}\n\n/**\n * Load test objects from a single external file (YAML or JSONL).\n */\nexport async function loadCasesFromFile(filePath: string): Promise<JsonObject[]> {\n const ext = path.extname(filePath).toLowerCase();\n let content: string;\n\n try {\n content = await readFile(filePath, 'utf8');\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Cannot read external test file: ${filePath}\\n ${message}`);\n }\n\n if (content.trim() === '') {\n console.warn(\n `${ANSI_YELLOW}Warning: External test file is empty, skipping: ${filePath}${ANSI_RESET}`,\n );\n return [];\n }\n\n if (ext === '.yaml' || ext === '.yml') {\n return parseYamlCases(content, filePath);\n }\n if (ext === '.jsonl') {\n return parseJsonlCases(content, filePath);\n }\n\n throw new Error(\n `Unsupported external test file format '${ext}': ${filePath}. Supported: .yaml, .yml, .jsonl`,\n );\n}\n\n/**\n * Resolve a file:// reference to test objects.\n * Handles both direct file paths and glob patterns.\n * Paths are resolved relative to the eval file directory.\n */\nexport async function resolveFileReference(\n ref: string,\n evalFileDir: string,\n): Promise<JsonObject[]> {\n const rawPath = extractFilePath(ref);\n const absolutePattern = path.resolve(evalFileDir, rawPath);\n\n if (isGlobPattern(rawPath)) {\n // Glob pattern: resolve matching files\n // fast-glob requires forward slashes, even on Windows\n const matches = await fg(absolutePattern.replaceAll('\\\\', '/'), {\n onlyFiles: true,\n absolute: true,\n });\n\n if (matches.length === 0) {\n console.warn(\n `${ANSI_YELLOW}Warning: Glob pattern matched no files: ${ref} (resolved to ${absolutePattern})${ANSI_RESET}`,\n );\n return [];\n }\n\n // Sort for deterministic order\n matches.sort();\n\n const allCases: JsonObject[] = [];\n for (const match of matches) {\n const cases = await loadCasesFromFile(match);\n allCases.push(...cases);\n }\n return allCases;\n }\n\n // Direct file path\n return loadCasesFromFile(absolutePattern);\n}\n\n/**\n * Process a tests array, expanding any file:// references into inline test objects.\n * Returns a flat array of JsonValue where all file:// strings are replaced\n * with the test objects loaded from the referenced files.\n */\nexport async function expandFileReferences(\n tests: readonly JsonValue[],\n evalFileDir: string,\n): Promise<JsonValue[]> {\n const expanded: JsonValue[] = [];\n\n for (const entry of tests) {\n if (isFileReference(entry)) {\n const cases = await resolveFileReference(entry, evalFileDir);\n expanded.push(...cases);\n } else {\n expanded.push(entry);\n }\n }\n\n return expanded;\n}\n"],"mappings":";AA8DA,IAAM,gBAAgB,oBAAI,IAAY,CAAC,QAAQ,SAAS,MAAM,CAAC;AAGxD,SAAS,UAAU,OAAkC;AAC1D,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,IAAI;AACV,SAAO,OAAO,EAAE,SAAS,YAAY,cAAc,IAAI,EAAE,IAAI;AAC/D;AAGO,SAAS,eAAe,OAAoC;AACjE,SAAO,MAAM,QAAQ,KAAK,KAAK,MAAM,SAAS,KAAK,MAAM,MAAM,SAAS;AAC1E;AAgBO,SAAS,eAAe,SAAwD;AACrF,MAAI,WAAW,KAAM,QAAO;AAC5B,MAAI,OAAO,YAAY,SAAU,QAAO;AACxC,MAAI,CAAC,MAAM,QAAQ,OAAO,EAAG,QAAO;AAEpC,QAAM,QAAkB,CAAC;AACzB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