Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,18 @@ All notable changes to SkillEvaluator are documented in this file.
when the catalog has no eligible entries to compare against.
These queries return an empty result without constructing the provider
client, including when that provider is missing or unreachable.
- Validation policy files accept `mcp.allowed_private_hosts`,
`hooks.allowed_urls` and `endpoints.resolve`. These blocks were ignored with an
`Ignoring unknown top-level key(s)` warning; now a malformed block stops
`validate --policy` with an error, and a valid one changes the policy digest
recorded in result metadata and adds entry counts, never the hosts or URLs,
to the policy summary. A hook URL prefix requires an exact host. Use a bare
wildcard host pattern to allow all paths on its matching subdomains.
- `evals/config.yml` accepts `harbor.trial_retries` (0 to 5) and an optional
`plugin` block with `load` and `lift_mode`, which were rejected as unknown
keys. These settings are reserved for prepared runtime packages. Harbor skill
runs warn when they ignore these settings. `--backend nemo-gym` rejects a
config that sets `trial_retries` above 0, `load` or `lift_mode`.

### Documentation

Expand Down
63 changes: 63 additions & 0 deletions src/skillevaluator/evaluation/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@
from pathlib import Path
from typing import Any

# Public dataclass annotations must remain resolvable by API schema consumers.
from skillevaluator.validators.policy import ValidationPolicy

# Bounds on ``PluginOptions.probe_mcp_env``: how many grants, and the length of each.
MAX_PROBE_MCP_ENV_GRANTS = 64
MAX_PROBE_MCP_ENV_GRANT_CHARS = 512


@dataclass
class EvaluationOptions:
Expand Down Expand Up @@ -93,3 +100,59 @@ class DatasetOptions:

def engine_kwargs(self) -> dict[str, Any]:
return {f.name: getattr(self, f.name) for f in fields(self) if f.name != "skill_path"}


@dataclass(frozen=True)
class PluginOptions:
"""Run controls for a prepared runtime package, validated on construction.

Every field is unset by default (``None`` or empty). Construction checks
every field except ``repo_root`` and normalizes the two allowlists by the
validation policy rules. The class only holds these values; it applies
none of them. ``policy`` must be a ``ValidationPolicy`` when given.
"""

plugin_load: str | None = None
lift_mode: str | None = None
probe_mcp: bool | None = None
probe_mcp_env: tuple[str, ...] = ()
trial_retries: int | None = None
repo_root: Path | None = None
allowed_private_hosts: tuple[str, ...] = ()
hook_allowed_urls: tuple[str, ...] = ()
policy: ValidationPolicy | None = None

def __post_init__(self) -> None:
from skillevaluator.validators.plugin_policy import normalize_plugin_allowlist

if self.policy is not None and not isinstance(self.policy, ValidationPolicy):
raise ValueError("policy must be a ValidationPolicy")
object.__setattr__(
self,
"allowed_private_hosts",
normalize_plugin_allowlist(self.allowed_private_hosts, "mcp.allowed_private_hosts", 255),
)
object.__setattr__(
self, "hook_allowed_urls", normalize_plugin_allowlist(self.hook_allowed_urls, "hooks.allowed_urls", 2048)
)
for name, choices in (
("plugin_load", {"wrapper", "native", "auto"}),
("lift_mode", {"effectiveness", "integration", "both", "ladder"}),
):
value = getattr(self, name)
if value is not None and (not isinstance(value, str) or value not in choices):
raise ValueError(f"{name} must be one of: {', '.join(sorted(choices))}")
if self.probe_mcp is not None and type(self.probe_mcp) is not bool:
raise ValueError("probe_mcp must be a boolean")
if self.trial_retries is not None and (type(self.trial_retries) is not int or not 0 <= self.trial_retries <= 5):
raise ValueError("trial_retries must be an integer between 0 and 5")
if (
not isinstance(self.probe_mcp_env, tuple)
Comment thread
rng1995 marked this conversation as resolved.
Resolved
or len(self.probe_mcp_env) > MAX_PROBE_MCP_ENV_GRANTS
or any(
not isinstance(value, str) or len(value) > MAX_PROBE_MCP_ENV_GRANT_CHARS for value in self.probe_mcp_env
)
):
raise ValueError(
f"probe_mcp_env must contain at most {MAX_PROBE_MCP_ENV_GRANTS} bounded environment grants"
)
23 changes: 22 additions & 1 deletion src/skillevaluator/tier3/evals_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,9 @@
}
GRADING_MODES = {"default", "default_plus_custom", "custom_only", *GRADING_MODE_ALIASES}

_TOP_LEVEL_KEYS = {"schema_version", "harbor", "skill_workspace", "grading"}
_TOP_LEVEL_KEYS = {"schema_version", "harbor", "skill_workspace", "grading", "plugin"}
_HARBOR_KEYS = {
"trial_retries",
"task_source",
"custom_dockerfile_mode",
"base_image_mode",
Expand Down Expand Up @@ -247,6 +248,21 @@ def _validate_config(raw: dict[str, Any], config_path: Path) -> dict[str, Any]:
raise EvalsConfigError(f"{config_path}: schema_version must be 1")

out: dict[str, Any] = {"schema_version": 1}
if "plugin" in raw:
plugin_raw = raw["plugin"]
if not isinstance(plugin_raw, dict):
raise EvalsConfigError(f"{config_path}: plugin must be a mapping")
unknown = _unknown_keys(plugin_raw, {"load", "lift_mode"}, config_path, "plugin")
if unknown:
raise EvalsConfigError(f"{config_path}: unknown plugin key(s): {', '.join(sorted(unknown))}")
plugin = {}
for key, choices in (
("load", {"wrapper", "native", "auto"}),
("lift_mode", {"effectiveness", "integration", "both", "ladder"}),
):
if key in plugin_raw:
plugin[key] = _enum(plugin_raw[key], choices, config_path, f"plugin.{key}")
out["plugin"] = plugin
harbor_raw = raw.get("harbor")
if harbor_raw is not None:
if not isinstance(harbor_raw, dict):
Expand All @@ -257,6 +273,11 @@ def _validate_config(raw: dict[str, Any], config_path: Path) -> dict[str, Any]:
raise EvalsConfigError(f"{config_path}: unknown harbor key(s): {', '.join(sorted(unknown_harbor))}")

harbor: dict[str, Any] = {}
if "trial_retries" in harbor_raw:
Comment thread
rng1995 marked this conversation as resolved.
Resolved
retries = _int_at_least(harbor_raw["trial_retries"], 0, config_path, "harbor.trial_retries")
if retries > 5:
Comment thread
rng1995 marked this conversation as resolved.
Resolved
raise EvalsConfigError(f"{config_path}: harbor.trial_retries must be between 0 and 5")
harbor["trial_retries"] = retries
if "task_source" in harbor_raw:
harbor["task_source"] = _enum(
harbor_raw["task_source"],
Expand Down
9 changes: 9 additions & 0 deletions src/skillevaluator/tier3/harbor/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -5571,6 +5571,15 @@ def _run_harbor_eval_impl(
return {"error": [str(exc)]}

harbor_config = config.get("harbor", {})
if _private_runtime_hooks() is None:
plugin_controls = [f"plugin.{name}" for name in sorted(config.get("plugin", {}))]
if harbor_config.get("trial_retries"):
plugin_controls.append("harbor.trial_retries")
if plugin_controls:
logger.warning(
"Only prepared plugin runs use these settings. The skill run ignores %s.",
", ".join(plugin_controls),
)
workspace_config = config.get("skill_workspace", {})
grading_config = config.get("grading", {})
n_attempts = n_attempts if n_attempts is not None else harbor_config.get("n_attempts", 1)
Expand Down
6 changes: 6 additions & 0 deletions src/skillevaluator/tier3/nemo_gym/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,12 @@ def nemo_gym_config_errors(
errors.append("harbor.stop_on_pass is not supported with --backend nemo-gym yet")
if agent_runtime_preflight is None and harbor.get("agent_runtime_preflight"):
errors.append("harbor.agent_runtime_preflight applies to the Harbor backend only")
# No Gym run reads these settings; zero retries is Gym's own behavior.
if harbor.get("trial_retries"):
errors.append("harbor.trial_retries is not supported with --backend nemo-gym yet")
errors.extend(
f"plugin.{name} is not supported with --backend nemo-gym" for name in sorted(config.get("plugin") or {})
)
if mcp_error := mcp_servers_error(skill_path):
errors.append(mcp_error)
if uses_native_harbor_tasks(skill_path, harbor.get("task_source", "auto")) and native_mcp_servers_declared(
Expand Down
8 changes: 8 additions & 0 deletions src/skillevaluator/tier3/results_location.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,14 @@ def legacy_results_root(skill_path: Path) -> Path:
return skill_path.expanduser().resolve() / "evals" / "results"


def plugin_results_directory(plugin_root: Path, requested: Path | None = None) -> Path:
"""Select a public plugin results base without creating an authored evals tree."""
if requested is not None:
return requested
configured = os.environ.get(ENV_RESULTS_DIR)
Comment thread
rng1995 marked this conversation as resolved.
Resolved
return Path(configured).expanduser() if configured else plugin_root / "results"


def skill_results_name(skill_path: Path) -> str:
"""Return the directory name used under an external results root."""
return skill_path.expanduser().resolve().name
Expand Down
104 changes: 104 additions & 0 deletions src/skillevaluator/validators/plugin_policy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# SPDX-License-Identifier: Apache-2.0
"""Bounded operator allowlists shared by component checks and runtime proof."""

from __future__ import annotations

import ipaddress
import unicodedata
from urllib.parse import urlsplit


def normalize_plugin_allowlist(value: object, key: str, max_chars: int) -> tuple[str, ...]:
"""Validate entries without DNS and preserve the existing host matcher rules."""
if value is None:
return ()
if not isinstance(value, (list, tuple)) or len(value) > 64:
raise ValueError(f"{key} must be a list of at most 64 strings")
if not value:
return ()
# Default policies stay cheap for ordinary skills and base installations.
from skillevaluator.plugin_component_risk import hook_url_entry_problem
from skillevaluator.validators.mcp_static import classify_endpoint_host
from skillevaluator.validators.url_policy import url_ambiguities

normalized = []
for raw in value:
if not isinstance(raw, str) or not raw.strip() or len(raw) > max_chars:
raise ValueError(f"{key} entries must be nonempty strings of at most {max_chars} characters")
if any(unicodedata.category(char) in {"Cc", "Cf", "Cs"} for char in raw):
raise ValueError(f"{key} entries cannot contain control or invisible characters")
entry = raw.strip()
if "://" in entry:
if (
key != "hooks.allowed_urls"
or hook_url_entry_problem(entry) is not None
or url_ambiguities(entry, percent_in_host=True)
):
raise ValueError(f"{key} contains an invalid URL prefix")
parsed = urlsplit(entry)
if parsed.scheme.lower() not in {"http", "https"}:
raise ValueError(f"{key} URL prefixes must use HTTP or HTTPS")
host = parsed.hostname
if host:
_check_host_pattern(host, key)
if "*" in host:
raise ValueError(f"{key} URL prefix host must be exact. Use a bare wildcard host pattern instead.")
Comment thread
rng1995 marked this conversation as resolved.
Resolved
else:
# The host matcher percent-decodes an entry, so '%' could spell any rejected character.
# It also folds fullwidth forms to ASCII, so check the folded spelling as well.
folded = unicodedata.normalize("NFKC", entry)
if any(char.isspace() for char in folded) or any(char in folded for char in "%@?#\\"):
raise ValueError(f"{key} contains an invalid host pattern")
if "/" in folded or ":" in folded:
Comment thread
rng1995 marked this conversation as resolved.
Resolved
try:
ipaddress.ip_network(
folded[1:-1] if folded.startswith("[") and folded.endswith("]") else folded, strict=False
)
except ValueError as exc:
raise ValueError(f"{key} contains an invalid IP address or network") from exc
_check_host_pattern(entry, key)
host = entry
endpoint = classify_endpoint_host(host) if host else None
if endpoint is not None and endpoint.kind == "metadata":
raise ValueError(f"{key} cannot allow cloud metadata endpoints")
normalized.append(entry)
return tuple(dict.fromkeys(normalized))
Comment thread
rng1995 marked this conversation as resolved.
Resolved


def _check_host_pattern(host: str, key: str) -> None:
"""Reject a host that the matcher would keep as a name no real host can have."""
from skillevaluator.validators.mcp_static import HostAllowlist

if "*" in host and (not host.startswith("*.") or "*" in host[2:]):
raise ValueError(f"{key} contains an invalid host wildcard")
hosts = HostAllowlist.from_entries((host,))
if not (hosts.names or hosts.suffixes or hosts.networks):
raise ValueError(f"{key} contains an invalid host pattern")
if any(name.startswith(".") for name in hosts.names):
raise ValueError(f"{key} contains a host that starts with '.'; use the '*.suffix' form to allow subdomains")
names = (*hosts.names, *hosts.suffixes)
# Host patterns already had their wildcard removed by the matcher. A
# remaining asterisk is a literal introduced by normalization.
if any("*" in name for name in names):
raise ValueError(f"{key} contains an invalid host wildcard")
if any(".." in name for name in names):
raise ValueError(f"{key} contains a host with an empty label")
if not hosts.networks and any(
label.startswith("-") or label.endswith("-") for name in names for label in name.split(".")
):
raise ValueError(f"{key} contains an invalid host label. Hyphens must be inside a label.")


def plugin_policy_block(data: dict, name: str, known: set[str]) -> dict:
"""Reject misspelled controls instead of silently widening operator intent."""
block = data.get(name)
if block is None:
return {}
if not isinstance(block, dict) or not all(isinstance(key, str) for key in block) or set(block) - known:
raise ValueError(f"{name} policy must be a mapping with only {', '.join(sorted(known))}")
return block


def overlay_sets(data: dict, block: str, key: str) -> bool:
value = data.get(block)
return isinstance(value, dict) and key in value
Loading