Skip to content

Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.

49.4 KB
Raw Blame
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""Harbor agent wrappers that run vendor CLIs in Harbor local mode."""

from __future__ import annotations

import asyncio
import copy
import json
import logging
import os
import re
import secrets
import shlex
import tempfile
import uuid
from collections.abc import Awaitable, Callable, Mapping
from contextlib import suppress
from pathlib import Path, PurePosixPath
from typing import TYPE_CHECKING, Any
from urllib.parse import urlsplit

from harbor.agents.agent_auth_resolution import ResolvedModelConnection, without_inferred_endpoint
from harbor.agents.installed.base import NetworkConnectionError, NonZeroAgentExitCodeError
from harbor.models.trial.paths import EnvironmentPaths
from harbor.utils.env import parse_bool_env_value

from skillevaluator.provider_config import is_claude_5_5_or_later, is_gpt6_model
from skillevaluator.tier3.harbor import LOCAL_CODEX_HOME_DIRNAME, LOCAL_CODEX_SECRETS_DIRNAME
from skillevaluator.tier3.harbor.installed_agents import SkillEvaluatorClaudeCode as _InstalledClaudeCode
from skillevaluator.tier3.harbor.installed_agents import SkillEvaluatorCodex, SkillEvaluatorOpenCode
from skillevaluator.tier3.harbor.nvidia_build_bridge import (
    MAX_REQUESTS_PER_BRIDGE,
    RunningBridge,
    start_in_process_bridge,
)
from skillevaluator.tier3.harbor.sensitive_stdin import (
    NVIDIA_BUILD_STDIN_SENTINEL,
    read_nvidia_build_key_from_stdin,
)

if TYPE_CHECKING:
    from harbor.environments.base import BaseEnvironment

_CODEX_MODEL_ARG_RE = re.compile(r"(?P<prefix>(?:^|\s)--model(?:=|\s+))(?P<model>[^\s]+)(?P<suffix>(?=\s|$))")

_DEFAULT_OPENAI_BASE_URL = "https://api.openai.com/v1"
_NVIDIA_BUILD_BRIDGE_BASE_URL = "https://integrate.api.nvidia.com/v1"
_NVIDIA_BUILD_BRIDGE_HOST = "127.0.0.1"
_NVIDIA_BUILD_BRIDGE_API_KEY_ENV = "SKILLEVALUATOR_NVIDIA_BUILD_BRIDGE_API_KEY"
_NVIDIA_BUILD_BRIDGE_CLIENT_TOKEN_ENV = "SKILLEVALUATOR_NVIDIA_BUILD_BRIDGE_CLIENT_TOKEN"
_NVIDIA_BUILD_FILE_BACKED_SENTINEL_KEY = "skillevaluator-file-backed-nvidia-key"
_NVIDIA_BUILD_HOST_KEY_FILE_ENV = "SKILLEVALUATOR_NVIDIA_API_KEY_FILE"
# Local mode runs the CLI installed on the host, not the release Harbor installs
# in other environments. These are the oldest releases that run each model family.
_CLAUDE_CODE_MIN_VERSION_FOR_CLAUDE_5_5 = (2, 1, 280)
_CODEX_MIN_VERSION_FOR_GPT_6 = (0, 159, 1)
_CLI_VERSION_RE = re.compile(r"(\d+)\.(\d+)\.(\d+)")

logger = logging.getLogger(__name__)


async def _await_task_uninterruptibly(
    task: asyncio.Task[Any],
    *,
    preserve_cancellation: bool = True,
) -> Any:
    """Await cleanup work to completion even if cancellation is repeated."""
    cancellation_requested = False
    while True:
        try:
            result = await asyncio.shield(task)
            break
        except asyncio.CancelledError:
            cancellation_requested = True
            if task.done():
                result = task.result()
                break
    if cancellation_requested and preserve_cancellation:
        raise asyncio.CancelledError
    return result


async def _close_running_bridge(
    running: RunningBridge,
    *,
    preserve_cancellation: bool = True,
) -> None:
    close_task = asyncio.create_task(asyncio.to_thread(running.close))
    await _await_task_uninterruptibly(close_task, preserve_cancellation=preserve_cancellation)


def _merge_codex_openai_compatible_config(
    config: dict[str, Any],
    base_url: str,
    user_config: Mapping[str, Any],
    *,
    env_key: str = "OPENAI_API_KEY",
) -> dict[str, Any]:
    """Apply SkillEvaluator's Responses routing without discarding user config."""
    config["model_provider"] = "openai_compatible"
    config["openai_base_url"] = base_url

    model_providers = config.get("model_providers")
    if not isinstance(model_providers, dict):
        model_providers = {}
        config["model_providers"] = model_providers

    # Harbor 0.25 rewrites the originally selected provider's URL. That provider
    # becomes inactive when we select our Responses route, so retain its config.
    user_providers = user_config.get("model_providers", {})
    if isinstance(user_providers, Mapping):
        for name, value in user_providers.items():
            if name != "openai_compatible":
                model_providers[name] = copy.deepcopy(value)

    provider = model_providers.get("openai_compatible")
    if not isinstance(provider, dict):
        provider = {}
        model_providers["openai_compatible"] = provider

    provider.update(
        {
            "name": "OpenAI-compatible provider",
            "base_url": base_url,
            "env_key": env_key,
            "wire_api": "responses",
        }
    )
    return config


def _require_cli_version(cli: str, version: str, minimum: tuple[int, int, int], model: str) -> None:
    """Fail before the agent starts when the installed ``cli`` is too old for ``model``."""
    match = _CLI_VERSION_RE.search(version)
    if match is None or tuple(int(part) for part in match.groups()) < minimum:
        required = ".".join(str(part) for part in minimum)
        raise RuntimeError(
            f"{model} needs {cli} {required} or newer, but the installed {cli} reports version {version!r}. "
            f"Update the {cli} CLI or use --env-mode docker."
        )


def _rewrite_launcher_segment(command: str, rewrite: Callable[[str], str]) -> str:
    """Apply launcher rewrites before the CLI ``--`` prompt separator only."""
    launcher, separator, prompt = command.partition(" -- ")
    if not separator:
        return rewrite(command)
    return f"{rewrite(launcher)}{separator}{prompt}"


class AgentSetupNetworkError(RuntimeError):
    """A network failure while Harbor set up an agent, before the agent received its task.

    Harbor raises ``NetworkConnectionError`` for a network failure in any agent
    command, during setup and during the task alike. This name marks the
    setup-phase failure only, so a retry policy can rerun it without ever
    rerunning an agent that may already have worked on its task.
    """


class SetupNetworkErrorAgent:
    """Raise a network failure in Harbor's agent ``setup`` as :class:`AgentSetupNetworkError`."""

    async def setup(self, environment: BaseEnvironment) -> None:
        try:
            await super().setup(environment)  # type: ignore[misc]
        except NetworkConnectionError as exc:
            raise AgentSetupNetworkError(f"Agent setup failed with a network error: {exc}") from exc


class SkillEvaluatorClaudeCode(_InstalledClaudeCode):
    """Wrap Claude Code to preserve rich MCP server declarations and Vertex AI routing.

    It extends the installed-agent wrapper, so Harbor's installer still skips
    the distribution Node/npm packages that the native installer does not need.
    """

    def _env_sources(self) -> tuple[Mapping[str, str], ...]:
        """Environment sources in runtime precedence order, safe for partially initialized instances."""
        sources: list[Mapping[str, str]] = []
        resolved = getattr(self, "_resolved_env_vars", None)
        if isinstance(resolved, Mapping):
            sources.append(resolved)
        extra = getattr(self, "_extra_env", None)
        if isinstance(extra, Mapping):
            sources.append(extra)
        sources.append(os.environ)
        return tuple(sources)

    def _uses_vertex_auth(self) -> bool:
        """Return whether Claude Code is configured to route through Vertex AI."""
        try:
            return bool(
                parse_bool_env_value(
                    self._get_env("CLAUDE_CODE_USE_VERTEX"),
                    name="CLAUDE_CODE_USE_VERTEX",
                    default=False,
                )
            )
        except (ValueError, AttributeError):
            logger.debug("Ignoring invalid boolean environment value CLAUDE_CODE_USE_VERTEX")
            return False

    @property
    def model_connection(self) -> ResolvedModelConnection:
        """Suppress Anthropic API endpoint inference when Vertex AI routing is active."""
        access = super().model_connection
        if self._uses_vertex_auth():
            return without_inferred_endpoint(access)
        return access

    def _resolved_model_name(self) -> str | None:
        """Let the native Vertex client select its endpoint after model parsing."""
        if self._uses_vertex_auth() and self.model_name and not self.skip_model_parsing:
            return self._parse_model_name(self.model_name)[1]
        return super()._resolved_model_name()

    def _resolve_auth_env(self) -> dict[str, str]:
        """Resolve Claude Code authentication environment including Vertex AI variables."""
        if not self._uses_vertex_auth():
            return super()._resolve_auth_env()

        env: dict[str, str] = {"CLAUDE_CODE_USE_VERTEX": "1"}
        for vertex_var in (
            "CLOUD_ML_REGION",
            "ANTHROPIC_VERTEX_PROJECT_ID",
            "GOOGLE_CLOUD_PROJECT",
            "GCLOUD_PROJECT",
            "CLOUDSDK_CORE_PROJECT",
            "GOOGLE_APPLICATION_CREDENTIALS",
            "CLOUDSDK_CONFIG",
            "ANTHROPIC_DEFAULT_OPUS_MODEL",
            "ANTHROPIC_DEFAULT_SONNET_MODEL",
            "ANTHROPIC_DEFAULT_HAIKU_MODEL",
            "CLAUDE_CODE_SUBAGENT_MODEL",
        ):
            val = (self._get_env(vertex_var) or "").strip()
            if val:
                env[vertex_var] = val
        if (self._get_env("DISABLE_PROMPT_CACHING") or "").strip() == "1":
            env["DISABLE_PROMPT_CACHING"] = "1"
        return env

    async def exec_as_agent(
        self,
        environment: BaseEnvironment,
        command: str,
        env: dict[str, str] | None = None,
        cwd: str | None = None,
        timeout_sec: int | None = None,
    ):
        if self._uses_vertex_auth():
            command = (
                f"unset ANTHROPIC_API_KEY ANTHROPIC_AUTH_TOKEN ANTHROPIC_BASE_URL CLAUDE_CODE_OAUTH_TOKEN; {command}"
            )
            if env:
                env = {
                    k: v
                    for k, v in env.items()
                    if k
                    not in {
                        "ANTHROPIC_API_KEY",
                        "ANTHROPIC_AUTH_TOKEN",
                        "ANTHROPIC_BASE_URL",
                        "CLAUDE_CODE_OAUTH_TOKEN",
                    }
                }
        return await super().exec_as_agent(
            environment,
            command=command,
            env=env,
            cwd=cwd,
            timeout_sec=timeout_sec,
        )

    def _resolve_task_path(self) -> Path | None:
        """Resolve the task directory path from trial config.json."""
        trial_config_path = self.logs_dir.parent / "config.json"
        if not trial_config_path.is_file():
            trial_config_path = self.logs_dir.parent.parent / "config.json"
            if not trial_config_path.is_file():
                return None
        try:
            config_data = json.loads(trial_config_path.read_text(encoding="utf-8"))
            task_path_str = config_data.get("task", {}).get("path")
            if not task_path_str:
                return None
            task_path = Path(task_path_str)
            if not task_path.is_absolute():
                task_path = (trial_config_path.parent / task_path).resolve()
            return task_path
        except Exception:
            return None

    def _resolve_task_runtime_env(self) -> dict[str, str]:
        """Extract allowed runtime environment from task.toml if available."""
        task_path = self._resolve_task_path()
        if not task_path:
            return {}
        task_toml_path = task_path / "task.toml"
        if not task_toml_path.is_file():
            return {}
        try:
            import tomllib
        except ImportError:
            import tomli as tomllib  # type: ignore[no-redef]
        try:
            task_data = tomllib.loads(task_toml_path.read_text(encoding="utf-8"))
            env_table = task_data.get("environment", {}).get("env", {})
            if isinstance(env_table, dict):
                return {str(k): str(v) for k, v in env_table.items()}
        except Exception:
            pass
        return {}

    def _build_register_mcp_servers_command(self) -> str | None:
        """Build MCP registration command supporting streamable-http and headers from mcp_servers.json."""
        mcp_servers = self._resolve_task_mcp_servers()
        if not mcp_servers:
            return super()._build_register_mcp_servers_command()

        servers: dict[str, dict[str, Any]] = {}
        for server in mcp_servers:
            name = server.get("name")
            if not name:
                continue
            transport = server.get("transport", "stdio")
            if transport == "stdio":
                stdio_entry: dict[str, Any] = {
                    "type": "stdio",
                    "command": server.get("command"),
                    "args": server.get("args", []),
                }
                if "env" in server and isinstance(server["env"], dict):
                    stdio_entry["env"] = server["env"]
                servers[name] = stdio_entry
            else:
                http_type = "http" if transport in ("streamable-http", "http") else transport
                entry: dict[str, Any] = {
                    "type": http_type,
                    "url": server.get("url"),
                }
                if "headers" in server and isinstance(server["headers"], dict):
                    entry["headers"] = server["headers"]
                servers[name] = entry

        if not servers:
            return super()._build_register_mcp_servers_command()

        claude_json = json.dumps({"mcpServers": servers}, indent=2)
        escaped = shlex.quote(claude_json)
        return (
            'CLAUDE_DIR="${CLAUDE_CONFIG_DIR:-$HOME}" && '
            'mkdir -p "$CLAUDE_DIR" && '
            f"printf '%s\\n' {escaped} > \"$CLAUDE_DIR/.claude.json\""
        )

    def _resolve_task_mcp_servers(self) -> list[dict[str, Any]]:
        """Resolve rich MCP declarations from task mcp_servers.json if available."""
        task_path = self._resolve_task_path()
        if not task_path:
            return []
        try:
            mcp_json_path = task_path / "mcp_servers.json"
            if not mcp_json_path.is_file():
                return []
            raw_servers = json.loads(mcp_json_path.read_text(encoding="utf-8"))
            if isinstance(raw_servers, list):
                from skillevaluator.tier3.harbor.adapter import validate_mcp_server_declarations

                runtime_env = self._resolve_task_runtime_env()
                return validate_mcp_server_declarations(
                    raw_servers,
                    allowed_runtime_env=runtime_env,
                    source_label=str(mcp_json_path),
                )
            return []
        except ValueError:
            raise
        except Exception:
            return []


class SkillEvaluatorGatewayClaudeCode(SkillEvaluatorClaudeCode):
    """Preserve an explicit gateway's opaque catalog ID in Claude's model selection."""

    def _resolved_model_name(self) -> str | None:
        # A gateway judge can coexist with independent native/Vertex/Bedrock
        # agent credentials. Preserve those routes' native model parsing.
        access = self.model_connection
        endpoint = access.execution_base_url
        if (
            self._uses_vertex_auth()
            or access.provider is None
            or not endpoint
            or urlsplit(endpoint).hostname == "api.anthropic.com"
        ):
            return super()._resolved_model_name()
        # Harbor normally removes a provider prefix. Gateway catalog IDs can
        # contain several slashes, and every segment belongs to the upstream ID.
        return self.model_name or super()._resolved_model_name()


class SkillEvaluatorLocalClaudeCode(SkillEvaluatorClaudeCode):
    """Claude Code wrapper that skips bootstrap install in local mode."""

    _REMOTE_CLAUDE_TMP = PurePosixPath(EnvironmentPaths.agent_dir / "claude-tmp")

    async def install(self, environment: BaseEnvironment) -> None:
        result = await self.exec_as_agent(environment, command="claude --version")
        self._version = self.parse_version(result.stdout or "")
        model = self.model_name or ""
        if is_claude_5_5_or_later(model):
            _require_cli_version("claude", self._version, _CLAUDE_CODE_MIN_VERSION_FOR_CLAUDE_5_5, model)

    def get_version_command(self) -> str | None:
        return "claude --version"

    async def exec_as_agent(
        self,
        environment: BaseEnvironment,
        command: str,
        env: dict[str, str] | None = None,
        cwd: str | None = None,
        timeout_sec: int | None = None,
    ):
        command = _rewrite_launcher_segment(
            command,
            lambda text: text.replace("--permission-mode=bypassPermissions", "--permission-mode=auto"),
        )
        command = f"mkdir -p {shlex.quote(self._REMOTE_CLAUDE_TMP.as_posix())} && {command}"
        routed_env = dict(env or {})
        routed_env["CLAUDE_CODE_TMPDIR"] = self._REMOTE_CLAUDE_TMP.as_posix()
        return await super().exec_as_agent(
            environment,
            command=command,
            env=routed_env,
            cwd=cwd,
            timeout_sec=timeout_sec,
        )


class SkillEvaluatorLocalGatewayClaudeCode(SkillEvaluatorLocalClaudeCode, SkillEvaluatorGatewayClaudeCode):
    """Use the local CLI while preserving the selected gateway catalog ID."""


class SkillEvaluatorGatewayCodex(SkillEvaluatorCodex):
    """Use an explicit Responses gateway without truncating its catalog model ID."""

    def _build_effective_config(self, openai_base_url: str | None = None) -> dict[str, Any]:
        """Extend Harbor's final user/MCP config with SkillEvaluator routing."""
        config = super()._build_effective_config(openai_base_url)
        base_url = openai_base_url or os.environ.get("OPENAI_BASE_URL") or _DEFAULT_OPENAI_BASE_URL
        # Harbor may project the selected key into a custom provider variable
        # and clear OPENAI_API_KEY before launching the CLI.
        env_key = self.model_connection.api_key_destination_name or "OPENAI_API_KEY"
        return _merge_codex_openai_compatible_config(config, base_url, self._base_config, env_key=env_key)

    def _preserve_gateway_model_name(self, command: str, env: dict[str, str] | None) -> str:
        """Undo Harbor's default Codex model truncation when routing through an OpenAI-compatible gateway."""
        model_name = str(self.model_name or "")
        if not model_name or "/" not in model_name or not (env or {}).get("OPENAI_BASE_URL"):
            return command

        runtime_models = {model_name.rsplit("/", 1)[-1], self._parse_model_name(model_name)[1]}

        def replace(match: re.Match[str]) -> str:
            if match.group("model") not in runtime_models:
                return match.group(0)
            return f"{match.group('prefix')}{shlex.quote(model_name)}{match.group('suffix')}"

        return _rewrite_launcher_segment(command, lambda text: _CODEX_MODEL_ARG_RE.sub(replace, text))

    async def exec_as_agent(
        self,
        environment: BaseEnvironment,
        command: str,
        env: dict[str, str] | None = None,
        cwd: str | None = None,
        timeout_sec: int | None = None,
    ):
        command = self._preserve_gateway_model_name(command, env)
        return await super().exec_as_agent(
            environment,
            command=command,
            env=env,
            cwd=cwd,
            timeout_sec=timeout_sec,
        )


class SkillEvaluatorLocalCodex(SkillEvaluatorGatewayCodex):
    """Use the installed local CLI with per-trial state and gateway routing."""

    _REMOTE_CODEX_HOME = PurePosixPath(EnvironmentPaths.agent_dir / LOCAL_CODEX_HOME_DIRNAME)
    _REMOTE_CODEX_SECRETS_DIR = PurePosixPath(EnvironmentPaths.agent_dir / LOCAL_CODEX_SECRETS_DIRNAME)

    async def install(self, environment: BaseEnvironment) -> None:
        result = await self.exec_as_agent(environment, command="codex --version")
        self._version = self.parse_version(result.stdout or "")
        model = self.model_name or ""
        if is_gpt6_model(model):
            _require_cli_version("codex", self._version, _CODEX_MIN_VERSION_FOR_GPT_6, model)

    def get_version_command(self) -> str | None:
        return "codex --version"

    async def exec_as_agent(
        self,
        environment: BaseEnvironment,
        command: str,
        env: dict[str, str] | None = None,
        cwd: str | None = None,
        timeout_sec: int | None = None,
    ):
        command = _rewrite_launcher_segment(
            command,
            lambda text: text.replace("/tmp/codex-secrets", self._REMOTE_CODEX_SECRETS_DIR.as_posix()),
        )
        return await super().exec_as_agent(environment, command=command, env=env, cwd=cwd, timeout_sec=timeout_sec)


class SkillEvaluatorGatewayOpenCode(SkillEvaluatorOpenCode):
    """Use Chat Completions for an explicitly OpenAI-compatible gateway."""

    def __init__(self, *args: Any, **kwargs: Any) -> None:
        super().__init__(*args, **kwargs)
        namespace, separator, model_id = str(self.model_name or "").partition("/")
        if namespace != "openai" or not separator or not model_id:
            raise ValueError("Gateway OpenCode requires an openai/MODEL identifier")
        # OpenCode's built-in openai loader always selects Responses, even when
        # its npm SDK is overridden. A distinct transport namespace is needed;
        # the gateway's catalog model ID remains unchanged after the first slash.
        self.model_name = f"skillevaluator-gateway/{model_id}"
        self._opencode_config = self._deep_merge(
            copy.deepcopy(self._opencode_config),
            {
                "provider": {
                    "skillevaluator-gateway": {
                        "npm": "@ai-sdk/openai-compatible",
                        "options": {
                            "baseURL": os.environ.get("OPENAI_BASE_URL", ""),
                            "apiKey": "{env:OPENAI_API_KEY}",
                        },
                    }
                }
            },
        )


class SkillEvaluatorLocalOpenCode(SkillEvaluatorOpenCode):
    """OpenCode wrapper that skips nvm/npm bootstrap in local mode."""

    _REMOTE_WORKSPACE = PurePosixPath("/workspace")

    async def install(self, environment: BaseEnvironment) -> None:
        await self.exec_as_agent(environment, command="opencode --version")

    def get_version_command(self) -> str | None:
        return "opencode --version"

    def _confined_project_env(self, env: dict[str, str] | None = None) -> dict[str, str]:
        confined = dict(env or {})
        confined.update(
            {
                "OPENCODE_FAKE_VCS": "git",
                "OPENCODE_TEST_HOME": self._REMOTE_WORKSPACE.as_posix(),
                "OPENCODE_DISABLE_PROJECT_CONFIG": "1",
            }
        )
        return confined

    def _nvidia_provider_config_command(self, model_id: str) -> str:
        config: dict[str, object] = {}
        if self.mcp_servers:
            mcp: dict[str, dict[str, object]] = {}
            for server in self.mcp_servers:
                if server.transport == "stdio":
                    cmd_list = [server.command, *server.args] if server.command else []
                    mcp[server.name] = {"type": "local", "command": cmd_list}
                else:
                    # Match Harbor's OpenCode config: headless trials cannot complete OAuth.
                    mcp[server.name] = {"type": "remote", "url": server.url, "oauth": False}
            config["mcp"] = mcp

        config["provider"] = {
            "nvidia": {
                "npm": "@ai-sdk/openai-compatible",
                "name": "NVIDIA Build",
                "models": {model_id: {"name": model_id}},
                "options": {
                    "baseURL": os.environ.get("OPENAI_BASE_URL", ""),
                    "apiKey": "{env:OPENAI_API_KEY}",
                },
            }
        }
        config = self._deep_merge(copy.deepcopy(self._DEFAULT_CONFIG), config)
        config = self._deep_merge(config, self._opencode_config)
        escaped = shlex.quote(json.dumps(config, indent=2))
        return f"mkdir -p ~/.config/opencode && echo {escaped} > ~/.config/opencode/opencode.json"

    async def run(self, instruction, environment: BaseEnvironment, context) -> None:  # type: ignore[no-untyped-def]
        if not self.model_name or "/" not in self.model_name:
            raise ValueError("Model name must be in the format provider/model_name")

        provider, model_id = self.model_name.split("/", 1)
        confinement_env = self._confined_project_env()

        # OpenCode uses / as the project root when no VCS boundary exists. Set
        # up the isolated workspace before either the upstream provider path or
        # the NVIDIA-compatible path can launch it.
        await self.exec_as_agent(
            environment,
            command=f"git -C {self._REMOTE_WORKSPACE.as_posix()} init -q",
            env=confinement_env,
        )

        if provider != "nvidia":
            await super().run(instruction=instruction, environment=environment, context=context)
            return

        instruction = self.render_instruction(instruction)
        self._instruction = instruction
        env = {key: os.environ[key] for key in ("OPENAI_API_KEY", "OPENAI_BASE_URL") if key in os.environ}
        env = self._confined_project_env(env)

        skills_command = self._build_register_skills_command()
        if skills_command:
            await self.exec_as_agent(environment, command=skills_command, env=env)

        await self.exec_as_agent(
            environment,
            command=self._nvidia_provider_config_command(model_id),
            env=env,
        )

        cli_flags = self.build_cli_flags()
        cli_flags_arg = (cli_flags + " ") if cli_flags else ""
        escaped_instruction = shlex.quote(instruction)
        await self.exec_as_agent(
            environment,
            command=(
                "if [ -f ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; "
                f"opencode run --model={self.model_name} --format=json "
                f"{cli_flags_arg}--thinking -- {escaped_instruction} "
                "2>&1 </dev/null | tee /logs/agent/opencode.txt"
            ),
            env=env,
        )

        if messages := self._error_messages():
            raise NonZeroAgentExitCodeError("OpenCode emitted error event(s): " + "; ".join(messages[:3]))

    async def exec_as_agent(
        self,
        environment: BaseEnvironment,
        command: str,
        env: dict[str, str] | None = None,
        cwd: str | None = None,
        timeout_sec: int | None = None,
    ):
        # Harbor's Docker image has GNU coreutils and a permissive OpenCode
        # wrapper, but trusted local hosts may have a stock CLI. Keep OpenCode's
        # JSON log capture while avoiding host-only argument failures before the
        # agent can run.
        command = command.replace(
            "| stdbuf -oL tee /logs/agent/opencode.txt",
            "| tee /logs/agent/opencode.txt",
        ).replace(" --dangerously-skip-permissions", "", 1)
        env = self._confined_project_env(env)
        return await super().exec_as_agent(
            environment,
            command=command,
            env=env,
            cwd=cwd,
            timeout_sec=timeout_sec,
        )


class _NvidiaBuildBridgeAgent:
    """Run a Docker-only loopback bridge around Harbor's stock vendor agent."""

    _BRIDGE_CLIENT_ENV_UNSET = ("NVIDIA_API_KEY",)
    _BRIDGE_SCRIPT = PurePosixPath(EnvironmentPaths.agent_dir / "nvidia-build-bridge.py")
    _BRIDGE_PID = PurePosixPath(EnvironmentPaths.agent_dir / "nvidia-build-bridge.pid")
    _BRIDGE_READY = PurePosixPath(EnvironmentPaths.agent_dir / "nvidia-build-bridge.ready")
    _BRIDGE_LOG = PurePosixPath(EnvironmentPaths.agent_dir / "nvidia-build-bridge.log")

    def _bridge_client_environment(self) -> dict[str, str]:
        raise NotImplementedError

    def _rewrite_bridge_client_command(self, command: str) -> str:
        return command

    @staticmethod
    def _sensitive_exec(environment: BaseEnvironment) -> Callable[..., Awaitable[Any]]:
        """Require a transport that keeps sensitive values out of host argv and logs."""
        sensitive_exec = getattr(environment, "exec_with_sensitive_env", None)
        if not callable(sensitive_exec):
            raise RuntimeError("NVIDIA Build bridge requires an environment with protected sensitive-value transport")
        return sensitive_exec

    async def _prepare_bridge_client(self, environment: BaseEnvironment) -> None:
        """Perform optional agent-specific setup after the bridge is healthy."""

    async def _bridge_raw_exec(
        self,
        environment: BaseEnvironment,
        command: str,
        env: dict[str, str] | None = None,
    ):
        # Docker tasks may declare a non-root USER. Lifecycle files copied by
        # Docker are not guaranteed to be owned by that user, so the private
        # key handoff and cleanup must run through Harbor's root executor.
        return await super().exec_as_root(environment, command=command, env=env)

    @staticmethod
    def _require_success(result: object, operation: str) -> None:
        if getattr(result, "return_code", 0) != 0:
            raise RuntimeError(f"NVIDIA Build bridge {operation} failed")

    @staticmethod
    def _resolve_bridge_api_key() -> str:
        api_key = os.environ.get("NVIDIA_API_KEY", "").strip()
        if api_key == NVIDIA_BUILD_STDIN_SENTINEL:
            return read_nvidia_build_key_from_stdin()
        host_key_file = os.environ.get(_NVIDIA_BUILD_HOST_KEY_FILE_ENV, "").strip()
        if host_key_file:
            try:
                api_key = Path(host_key_file).read_text(encoding="utf-8").strip()
            except OSError as exc:
                raise RuntimeError("NVIDIA Build bridge key handoff file is unavailable") from exc
            if not api_key:
                raise RuntimeError("NVIDIA Build bridge key handoff file is empty")
            return api_key
        if api_key == _NVIDIA_BUILD_FILE_BACKED_SENTINEL_KEY:
            raise RuntimeError(
                f"NVIDIA Build bridge requires {_NVIDIA_BUILD_HOST_KEY_FILE_ENV} for file-backed credentials"
            )
        if not api_key:
            raise RuntimeError("NVIDIA Build bridge requires NVIDIA_API_KEY")
        return api_key

    @staticmethod
    def _bridge_result_stdout(result: object) -> str:
        stdout = getattr(result, "stdout", "")
        if isinstance(stdout, bytes):
            return stdout.decode("utf-8", errors="strict")
        return str(stdout or "")

    @staticmethod
    def _parse_bridge_origin(value: str) -> str:
        origin = value.strip()
        try:
            parsed = urlsplit(origin)
            port = parsed.port
        except ValueError as exc:
            raise RuntimeError("NVIDIA Build bridge returned an invalid dynamic origin") from exc
        expected_origin = f"http://{_NVIDIA_BUILD_BRIDGE_HOST}:{port}" if port is not None else ""
        if (
            parsed.scheme != "http"
            or parsed.hostname != _NVIDIA_BUILD_BRIDGE_HOST
            or parsed.username is not None
            or parsed.password is not None
            or parsed.path
            or parsed.query
            or parsed.fragment
            or port is None
            or origin != expected_origin
        ):
            raise RuntimeError("NVIDIA Build bridge returned an invalid dynamic origin")
        return origin

    def _bridge_origin(self) -> str:
        origin = getattr(self, "_nvidia_build_bridge_origin", None)
        if not origin:
            raise RuntimeError("NVIDIA Build bridge dynamic origin is unavailable")
        return str(origin)

    def _bridge_api_url(self) -> str:
        return f"{self._bridge_origin()}/v1"

    def _bridge_client_token(self) -> str:
        client_token = getattr(self, "_nvidia_build_bridge_client_token", None)
        if not client_token:
            raise RuntimeError("NVIDIA Build bridge client token is unavailable")
        return str(client_token)

    async def _start_bridge(self, environment: BaseEnvironment) -> None:
        sensitive_exec = self._sensitive_exec(environment)
        api_key = self._resolve_bridge_api_key()
        model_name = str(self.model_name or "").strip()
        if not model_name:
            raise RuntimeError("NVIDIA Build bridge requires a selected model")
        private_file_stem = f"/tmp/.skillevaluator-nvidia-build-{uuid.uuid4().hex}"
        key_file = PurePosixPath(f"{private_file_stem}.key")
        client_token_file = PurePosixPath(f"{private_file_stem}.token")
        client_token = secrets.token_urlsafe(32)
        self._nvidia_build_bridge_key_file = key_file
        self._nvidia_build_bridge_client_token_file = client_token_file
        self._nvidia_build_bridge_client_token = client_token
        # From the first upload onward, every exit path owns cleanup. Mark that
        # responsibility before any await can be cancelled.
        self._nvidia_build_bridge_started = True
        try:
            await environment.upload_file(
                Path(__file__).with_name("nvidia_build_bridge.py"), self._BRIDGE_SCRIPT.as_posix()
            )

            # The selected secure Docker environment streams ``env=`` values
            # over Compose stdin. Materialize both secrets only inside the
            # not-yet-exposed task container, then discard the transient names.
            # Route this through the selected environment's sensitive-exec
            # transport so neither bridge capability enters process arguments
            # or the agent's longer-lived execution environment.
            handoff_result = await sensitive_exec(
                command=(
                    "set -eu; umask 077; "
                    f"printf '%s' \"${{{_NVIDIA_BUILD_BRIDGE_API_KEY_ENV}}}\" > "
                    f"{shlex.quote(key_file.as_posix())}; "
                    f"printf '%s' \"${{{_NVIDIA_BUILD_BRIDGE_CLIENT_TOKEN_ENV}}}\" > "
                    f"{shlex.quote(client_token_file.as_posix())}; "
                    f"unset {_NVIDIA_BUILD_BRIDGE_API_KEY_ENV} {_NVIDIA_BUILD_BRIDGE_CLIENT_TOKEN_ENV}"
                ),
                env={
                    _NVIDIA_BUILD_BRIDGE_API_KEY_ENV: api_key,
                    _NVIDIA_BUILD_BRIDGE_CLIENT_TOKEN_ENV: client_token,
                },
                user="root",
            )
            self._require_success(handoff_result, "secret handoff")

            start_result = await self._bridge_raw_exec(
                environment,
                command=(
                    "set -eu; umask 077; "
                    f"rm -f {shlex.quote(self._BRIDGE_PID.as_posix())} "
                    f"{shlex.quote(self._BRIDGE_READY.as_posix())}; "
                    f"chown 0:0 {shlex.quote(key_file.as_posix())} "
                    f"{shlex.quote(client_token_file.as_posix())}; "
                    f"chmod 600 {shlex.quote(key_file.as_posix())} "
                    f"{shlex.quote(client_token_file.as_posix())}; "
                    "env -u NVIDIA_API_KEY "
                    f"python3 {shlex.quote(self._BRIDGE_SCRIPT.as_posix())} "
                    f"--build-base-url {_NVIDIA_BUILD_BRIDGE_BASE_URL} "
                    f"--api-key-file {shlex.quote(key_file.as_posix())} "
                    f"--client-token-file {shlex.quote(client_token_file.as_posix())} "
                    f"--allowed-model {shlex.quote(model_name)} "
                    f"--max-requests {MAX_REQUESTS_PER_BRIDGE} "
                    "--port 0 "
                    f"--ready-file {shlex.quote(self._BRIDGE_READY.as_posix())} "
                    f"--log-path {shlex.quote(self._BRIDGE_LOG.as_posix())} "
                    ">/dev/null 2>&1 & "
                    f"echo $! > {shlex.quote(self._BRIDGE_PID.as_posix())}"
                ),
                env={},
            )
            self._require_success(start_result, "startup")
            health_result = await self._bridge_raw_exec(
                environment,
                command=(
                    "set -u; "
                    "for attempt in $(seq 1 15); do "
                    f"if [ ! -s {shlex.quote(self._BRIDGE_PID.as_posix())} ]; then exit 1; fi; "
                    f'bridge_pid="$(cat {shlex.quote(self._BRIDGE_PID.as_posix())})"; '
                    'if ! kill -0 "$bridge_pid" 2>/dev/null; then exit 1; fi; '
                    f"if [ -s {shlex.quote(self._BRIDGE_READY.as_posix())} ]; then "
                    "if bridge_origin=$(env -u NVIDIA_API_KEY "
                    f"python3 {shlex.quote(self._BRIDGE_SCRIPT.as_posix())} "
                    f"--check-ready-file {shlex.quote(self._BRIDGE_READY.as_posix())} 2>/dev/null); then "
                    'if ! kill -0 "$bridge_pid" 2>/dev/null; then exit 1; fi; '
                    "printf '%s\n' \"$bridge_origin\"; exit 0; "
                    "fi; fi; "
                    "sleep 1; "
                    "done; echo 'NVIDIA Build bridge health check failed' >&2; exit 1"
                ),
                env={},
            )
            self._require_success(health_result, "health check")
            self._nvidia_build_bridge_origin = self._parse_bridge_origin(self._bridge_result_stdout(health_result))
        except BaseException:
            # Uploads and the detached launch can complete even when their
            # awaiter is cancelled. Complete cleanup despite repeat
            # cancellation, then preserve the original startup failure.
            cleanup_task = asyncio.create_task(self._cleanup_bridge(environment))
            with suppress(BaseException):
                await _await_task_uninterruptibly(cleanup_task, preserve_cancellation=False)
            raise

    async def _cleanup_bridge(self, environment: BaseEnvironment) -> None:
        # The bridge log itself has a fixed sanitized format. Retain it as the
        # sole lifecycle artifact; remove its executable and private metadata.
        key_file = getattr(self, "_nvidia_build_bridge_key_file", None)
        client_token_file = getattr(self, "_nvidia_build_bridge_client_token_file", None)
        private_file_cleanup = "".join(
            f" {shlex.quote(path.as_posix())}" for path in (key_file, client_token_file) if path is not None
        )
        cleanup_complete = False
        try:
            cleanup_result = await self._bridge_raw_exec(
                environment,
                command=(
                    f"if [ -s {shlex.quote(self._BRIDGE_PID.as_posix())} ]; then "
                    f'kill "$(cat {shlex.quote(self._BRIDGE_PID.as_posix())})" 2>/dev/null || true; '
                    "fi; "
                    f"rm -f {shlex.quote(self._BRIDGE_PID.as_posix())} "
                    f"{shlex.quote(self._BRIDGE_READY.as_posix())} "
                    f"{shlex.quote(self._BRIDGE_SCRIPT.as_posix())}{private_file_cleanup}"
                ),
                env={},
            )
            self._require_success(cleanup_result, "cleanup")
            cleanup_complete = True
        finally:
            self._nvidia_build_bridge_origin = None
            if cleanup_complete:
                self._nvidia_build_bridge_started = False
                self._nvidia_build_bridge_key_file = None
                self._nvidia_build_bridge_client_token_file = None
                self._nvidia_build_bridge_client_token = None

    async def exec_as_agent(
        self,
        environment: BaseEnvironment,
        command: str,
        env: dict[str, str] | None = None,
        cwd: str | None = None,
        timeout_sec: int | None = None,
    ):
        client_env = getattr(self, "_nvidia_build_bridge_client_env", None)
        if client_env is None:
            return await super().exec_as_agent(environment, command=command, env=env, cwd=cwd, timeout_sec=timeout_sec)
        routed_env = dict(env or {})
        routed_env.update(client_env)
        for name in self._BRIDGE_CLIENT_ENV_UNSET:
            routed_env.pop(name, None)
        routed_command = self._rewrite_bridge_client_command(command)
        unset_args = " ".join(f"-u {shlex.quote(name)}" for name in self._BRIDGE_CLIENT_ENV_UNSET)
        with environment.scoped_exec_env(client_env):
            return await super().exec_as_agent(
                environment,
                command=f"env {unset_args} bash -o pipefail -c {shlex.quote(routed_command)}",
                env=routed_env,
                cwd=cwd,
                timeout_sec=timeout_sec,
            )

    async def run(self, instruction, environment: BaseEnvironment, context) -> None:  # type: ignore[no-untyped-def]
        self._nvidia_build_bridge_started = False
        self._nvidia_build_bridge_key_file = None
        self._nvidia_build_bridge_client_token_file = None
        self._nvidia_build_bridge_client_token = None
        self._nvidia_build_bridge_origin = None
        run_failed = False
        try:
            await self._start_bridge(environment)
            self._nvidia_build_bridge_client_env = self._bridge_client_environment()
            await self._prepare_bridge_client(environment)
            await super().run(instruction=instruction, environment=environment, context=context)
        except BaseException:
            run_failed = True
            raise
        finally:
            self._nvidia_build_bridge_client_env = None
            if self._nvidia_build_bridge_started:
                try:
                    cleanup_task = asyncio.create_task(self._cleanup_bridge(environment))
                    await _await_task_uninterruptibly(cleanup_task, preserve_cancellation=not run_failed)
                except BaseException:
                    if not run_failed:
                        raise


class SkillEvaluatorNvidiaBuildCodex(_NvidiaBuildBridgeAgent, SkillEvaluatorCodex):
    """Stock Codex CLI routed through the in-trial NVIDIA Build bridge."""

    _BRIDGE_CLIENT_ENV_UNSET = ("NVIDIA_API_KEY", "OPENAI_BASE_URL", "OPENAI_API_BASE")

    def _bridge_client_environment(self) -> dict[str, str]:
        return {
            "OPENAI_API_KEY": self._bridge_client_token(),
        }

    def _get_env(self, key: str, *alternatives: str) -> str | None:
        """Expose the sentinel key while suppressing Codex's legacy base-url config."""
        client_env = getattr(self, "_nvidia_build_bridge_client_env", None)
        if client_env is not None:
            if key == "OPENAI_BASE_URL":
                return None
            for name in (key, *alternatives):
                if name in client_env:
                    return client_env[name]
        return super()._get_env(key, *alternatives)

    def _build_effective_config(self, openai_base_url: str | None = None) -> dict[str, Any]:
        """Make the live bridge the final Codex route after user/MCP merging."""
        _ = openai_base_url
        bridge_api_url = self._bridge_api_url()
        config = super()._build_effective_config(bridge_api_url)
        return _merge_codex_openai_compatible_config(config, bridge_api_url, self._base_config)

    def _rewrite_bridge_client_command(self, command: str) -> str:
        model_name = str(self.model_name or "")
        command = command.replace(
            'openai_base_url = "${OPENAI_BASE_URL}"',
            f'openai_base_url = "{self._bridge_api_url()}"',
        )
        if not model_name or "/" not in model_name:
            return command
        runtime_models = {model_name.rsplit("/", 1)[-1], self._parse_model_name(model_name)[1]}

        def replace(match: re.Match[str]) -> str:
            if match.group("model") not in runtime_models:
                return match.group(0)
            return f"{match.group('prefix')}{model_name}{match.group('suffix')}"

        return _rewrite_launcher_segment(command, lambda text: _CODEX_MODEL_ARG_RE.sub(replace, text))


class SkillEvaluatorNvidiaBuildClaudeCode(_NvidiaBuildBridgeAgent, SkillEvaluatorClaudeCode):
    """Stock Claude Code CLI routed through the in-trial NVIDIA Build bridge."""

    def _bridge_client_environment(self) -> dict[str, str]:
        model_name = str(self.model_name or "")
        environment = {
            "ANTHROPIC_API_KEY": self._bridge_client_token(),
            "ANTHROPIC_BASE_URL": self._bridge_origin(),
        }
        if model_name:
            environment.update(
                {
                    "ANTHROPIC_MODEL": model_name,
                    "ANTHROPIC_DEFAULT_SONNET_MODEL": model_name,
                    "ANTHROPIC_DEFAULT_OPUS_MODEL": model_name,
                    "ANTHROPIC_DEFAULT_HAIKU_MODEL": model_name,
                    "CLAUDE_CODE_SUBAGENT_MODEL": model_name,
                }
            )
        return environment


class _LocalHostNvidiaBuildBridgeAgent:
    """Run the authenticated bridge in Harbor's trusted local parent process."""

    async def _start_bridge(self, environment: BaseEnvironment) -> None:
        _ = environment
        api_key = self._resolve_bridge_api_key()
        temp_dir = tempfile.TemporaryDirectory(prefix="skillevaluator-local-nvidia-build-")
        self._nvidia_build_local_temp_dir = temp_dir
        log_path = Path(temp_dir.name) / "nvidia-build-bridge.log"
        self._nvidia_build_local_log_path = log_path
        startup_task = asyncio.create_task(
            asyncio.to_thread(
                start_in_process_bridge,
                api_key=api_key,
                build_base_url=_NVIDIA_BUILD_BRIDGE_BASE_URL,
                log_path=log_path,
                allowed_model=str(self.model_name or "").strip(),
            )
        )
        try:
            running = await asyncio.shield(startup_task)
        except BaseException:
            # ``to_thread`` keeps running if its awaiter is cancelled. Recover
            # the eventual handle and close it before propagating cancellation
            # so no authenticated listener or temporary directory is orphaned.
            try:
                abandoned = await _await_task_uninterruptibly(startup_task, preserve_cancellation=False)
            except BaseException:
                temp_dir.cleanup()
                self._nvidia_build_local_temp_dir = None
                self._nvidia_build_local_log_path = None
            else:
                self._nvidia_build_running_bridge = abandoned
                self._nvidia_build_bridge_client_token = abandoned.client_token
                self._nvidia_build_bridge_origin = abandoned.origin
                self._nvidia_build_bridge_started = True
                try:
                    await _close_running_bridge(abandoned, preserve_cancellation=False)
                except BaseException:
                    # Retain the handle and temp directory so the outer run
                    # finalizer can retry cleanup instead of hiding a listener.
                    pass
                else:
                    temp_dir.cleanup()
                    self._nvidia_build_running_bridge = None
                    self._nvidia_build_local_temp_dir = None
                    self._nvidia_build_local_log_path = None
                    self._nvidia_build_bridge_client_token = None
                    self._nvidia_build_bridge_origin = None
                    self._nvidia_build_bridge_started = False
            raise
        self._nvidia_build_running_bridge = running
        self._nvidia_build_bridge_client_token = running.client_token
        self._nvidia_build_bridge_origin = running.origin
        self._nvidia_build_bridge_started = True

    async def _cleanup_bridge(self, environment: BaseEnvironment) -> None:
        running: RunningBridge | None = getattr(self, "_nvidia_build_running_bridge", None)
        log_path: Path | None = getattr(self, "_nvidia_build_local_log_path", None)
        temp_dir: tempfile.TemporaryDirectory[str] | None = getattr(self, "_nvidia_build_local_temp_dir", None)
        bridge_closed = running is None
        try:
            if running is not None:
                try:
                    await _close_running_bridge(running)
                except asyncio.CancelledError:
                    bridge_closed = running._closed
                    raise
                else:
                    bridge_closed = True
            if log_path is not None and log_path.is_file():
                await environment.upload_file(log_path, _NvidiaBuildBridgeAgent._BRIDGE_LOG.as_posix())
        finally:
            if bridge_closed:
                if temp_dir is not None:
                    temp_dir.cleanup()
                self._nvidia_build_running_bridge = None
                self._nvidia_build_local_log_path = None
                self._nvidia_build_local_temp_dir = None
                self._nvidia_build_bridge_client_token = None
                self._nvidia_build_bridge_origin = None
                self._nvidia_build_bridge_started = False


class SkillEvaluatorLocalNvidiaBuildCodex(
    _LocalHostNvidiaBuildBridgeAgent,
    SkillEvaluatorNvidiaBuildCodex,
    SkillEvaluatorLocalCodex,
):
    """Managed local Codex CLI routed through an authenticated host bridge."""


class SkillEvaluatorLocalNvidiaBuildClaudeCode(
    _LocalHostNvidiaBuildBridgeAgent,
    SkillEvaluatorNvidiaBuildClaudeCode,
    SkillEvaluatorLocalClaudeCode,
):
    """Managed local Claude Code CLI routed through an authenticated host bridge."""


from skillevaluator.tier3.harbor import (  # noqa: F401
    CONTAINER_AGENT_IMPORT_PATHS,
    LOCAL_AGENT_IMPORT_PATHS,
)

NVIDIA_BUILD_AGENT_IMPORT_PATHS = {
    "claude-code": "skillevaluator.tier3.harbor.local_agents:SkillEvaluatorNvidiaBuildClaudeCode",
    "codex": "skillevaluator.tier3.harbor.local_agents:SkillEvaluatorNvidiaBuildCodex",
}

NVIDIA_BUILD_LOCAL_AGENT_IMPORT_PATHS = {
    "claude-code": "skillevaluator.tier3.harbor.local_agents:SkillEvaluatorLocalNvidiaBuildClaudeCode",
    "codex": "skillevaluator.tier3.harbor.local_agents:SkillEvaluatorLocalNvidiaBuildCodex",
}