Spaces:
Configuration error
Configuration error
File size: 21,139 Bytes
a37e1b9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 | """Compatibility helpers for Agent Plugins v1 portable directory packages.
This module validates the versioned portable format locally and translates its
supported components into records consumed by Hermes' existing skill and MCP
runtimes. It deliberately performs no schema fetching and imports no plugin
Python code.
"""
from __future__ import annotations
import json
import os
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Mapping, Tuple
from agent.skill_utils import yaml_load
PLUGIN_SCHEMA_V1 = "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json"
MCP_SCHEMA_V1 = "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"
_PLUGIN_FIELDS = {
"$schema",
"name",
"version",
"description",
"author",
"homepage",
"repository",
"license",
"keywords",
"extensions",
}
_AUTHOR_FIELDS = {"name", "email", "url"}
_STDIO_FIELDS = {"type", "command", "args", "env", "cwd"}
_REMOTE_FIELDS = {"type", "url", "headers"}
_PLUGIN_NAME_RE = re.compile(
r"^(?!.*(?:--|\.\.))[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$"
)
_SKILL_NAME_RE = re.compile(r"^(?!.*--)[a-z0-9]+(?:-[a-z0-9]+)*$")
_PLACEHOLDER_RE = re.compile(r"\$\{(PLUGIN_ROOT|PLUGIN_DATA)\}")
_HEADER_NAME_RE = re.compile(r"^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$")
class AgentPluginError(ValueError):
"""Fatal portable manifest validation failure."""
@dataclass(frozen=True)
class AgentPluginDiagnostic:
scope: str
message: str
@dataclass(frozen=True)
class AgentPluginSkill:
name: str
description: str
root: Path
skill_md: Path
frontmatter: Mapping[str, Any]
@dataclass(frozen=True)
class AgentPluginPackage:
name: str
version: str
description: str
root: Path
data_root: Path
manifest: Mapping[str, Any]
skills: Tuple[AgentPluginSkill, ...]
mcp_servers: Mapping[str, Dict[str, Any]]
diagnostics: Tuple[AgentPluginDiagnostic, ...]
def _inside(path: Path, root: Path) -> bool:
try:
path.resolve(strict=False).relative_to(root.resolve(strict=True))
return True
except (OSError, RuntimeError, ValueError):
return False
def _read_json_object(path: Path, *, label: str) -> dict:
try:
value = json.loads(path.read_text(encoding="utf-8"))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
raise AgentPluginError(f"{label} is not valid readable JSON: {exc}") from exc
if not isinstance(value, dict):
raise AgentPluginError(f"{label} must contain a JSON object")
return value
def _validate_manifest(root: Path) -> tuple[dict, list[AgentPluginDiagnostic]]:
manifest_path = root / "plugin.json"
if not _inside(manifest_path, root) or not manifest_path.is_file():
raise AgentPluginError("plugin.json must be a regular file within the plugin root")
manifest = _read_json_object(manifest_path, label="plugin.json")
diagnostics: list[AgentPluginDiagnostic] = []
for field in sorted(set(manifest) - _PLUGIN_FIELDS):
diagnostics.append(
AgentPluginDiagnostic("manifest", f"ignored unknown top-level field: {field}")
)
manifest.pop(field)
if manifest.get("$schema") != PLUGIN_SCHEMA_V1:
raise AgentPluginError(
"plugin.json declares an unsupported or missing Agent Plugins schema"
)
name = manifest.get("name")
if (
not isinstance(name, str)
or not 1 <= len(name) <= 64
or _PLUGIN_NAME_RE.fullmatch(name) is None
):
raise AgentPluginError("plugin.json name does not satisfy v1 constraints")
for field in ("version", "description", "homepage", "repository", "license"):
if field in manifest and not isinstance(manifest[field], str):
raise AgentPluginError(f"plugin.json {field} must be a string")
if "keywords" in manifest:
keywords = manifest["keywords"]
if not isinstance(keywords, list) or any(
not isinstance(value, str) for value in keywords
):
raise AgentPluginError("plugin.json keywords must be an array of strings")
if "author" in manifest:
author = manifest["author"]
if not isinstance(author, dict):
raise AgentPluginError("plugin.json author must be an object")
unknown = set(author) - _AUTHOR_FIELDS
if unknown or any(not isinstance(value, str) for value in author.values()):
raise AgentPluginError(
"plugin.json author may contain only string name, email, and url fields"
)
if "extensions" in manifest:
extensions = manifest["extensions"]
if not isinstance(extensions, dict):
diagnostics.append(
AgentPluginDiagnostic(
"manifest", "ignored non-object extensions field"
)
)
manifest.pop("extensions")
elif any(not isinstance(value, dict) for value in extensions.values()):
raise AgentPluginError("plugin.json extension namespace values must be objects")
return manifest, diagnostics
def _valid_skill_frontmatter(
frontmatter: Mapping[str, Any], directory_name: str
) -> str | None:
name = frontmatter.get("name")
if (
not isinstance(name, str)
or name != directory_name
or not 1 <= len(name) <= 64
or _SKILL_NAME_RE.fullmatch(name) is None
):
return "name must match the directory and satisfy Agent Skills constraints"
description = frontmatter.get("description")
if not isinstance(description, str) or not 1 <= len(description) <= 1024:
return "description must be a non-empty string of at most 1024 characters"
if "license" in frontmatter and not isinstance(frontmatter["license"], str):
return "license must be a string"
if "compatibility" in frontmatter:
compatibility = frontmatter["compatibility"]
if not isinstance(compatibility, str) or not 1 <= len(compatibility) <= 500:
return "compatibility must be a string of 1 to 500 characters"
if "metadata" in frontmatter:
metadata = frontmatter["metadata"]
if not isinstance(metadata, dict) or any(
not isinstance(key, str) or not isinstance(value, str)
for key, value in metadata.items()
):
return "metadata must map string keys to string values"
if "allowed-tools" in frontmatter and not isinstance(
frontmatter["allowed-tools"], str
):
return "allowed-tools must be a string"
return None
def _discover_skills(
root: Path, diagnostics: list[AgentPluginDiagnostic]
) -> tuple[AgentPluginSkill, ...]:
skills_root = root / "skills"
if not skills_root.exists() and not skills_root.is_symlink():
return ()
if not _inside(skills_root, root) or not skills_root.is_dir():
diagnostics.append(
AgentPluginDiagnostic("skills", "skills must be an in-root directory")
)
return ()
skills: list[AgentPluginSkill] = []
try:
children = sorted(skills_root.iterdir(), key=lambda path: path.name)
except OSError as exc:
diagnostics.append(AgentPluginDiagnostic("skills", f"cannot list skills: {exc}"))
return ()
for child in children:
skill_md = child / "SKILL.md"
if not child.is_dir() or not skill_md.exists():
continue
scope = f"skill:{child.name}"
if not _inside(skill_md, root) or not skill_md.is_file():
diagnostics.append(
AgentPluginDiagnostic(scope, "SKILL.md must be a regular in-root file")
)
continue
try:
content = skill_md.read_text(encoding="utf-8")
content = content.lstrip("\ufeff")
if not content.startswith("---"):
raise ValueError("missing YAML frontmatter")
end_match = re.search(r"\n---\s*\n", content[3:])
if end_match is None:
raise ValueError("unterminated YAML frontmatter")
try:
parsed = yaml_load(content[3 : end_match.start() + 3])
except Exception as exc:
raise ValueError(f"invalid YAML frontmatter: {exc}") from exc
if not isinstance(parsed, dict):
raise ValueError("YAML frontmatter must be an object")
frontmatter = parsed
except (OSError, UnicodeError, ValueError) as exc:
diagnostics.append(AgentPluginDiagnostic(scope, f"invalid SKILL.md: {exc}"))
continue
error = _valid_skill_frontmatter(frontmatter, child.name)
if error:
diagnostics.append(AgentPluginDiagnostic(scope, error))
continue
skills.append(
AgentPluginSkill(
name=child.name,
description=frontmatter["description"],
root=child.resolve(strict=True),
skill_md=skill_md.resolve(strict=True),
frontmatter=dict(frontmatter),
)
)
return tuple(skills)
def _expand(value: str, plugin_root: Path, data_root: Path) -> str:
replacements = {
"PLUGIN_ROOT": str(plugin_root),
"PLUGIN_DATA": str(data_root),
}
return _PLACEHOLDER_RE.sub(lambda match: replacements[match.group(1)], value)
def _resolve_scoped_path(
value: str,
plugin_root: Path,
data_root: Path,
*,
expand_placeholders: bool = True,
) -> Path:
expanded = _expand(value, plugin_root, data_root) if expand_placeholders else value
if value.startswith("./"):
base = plugin_root
candidate = base / expanded[2:]
elif value == "${PLUGIN_ROOT}" or value.startswith("${PLUGIN_ROOT}/"):
base = plugin_root
candidate = Path(expanded)
elif value == "${PLUGIN_DATA}" or value.startswith("${PLUGIN_DATA}/"):
base = data_root
candidate = Path(expanded)
else:
raise ValueError("path must start with ./, ${PLUGIN_ROOT}, or ${PLUGIN_DATA}")
resolved = candidate.resolve(strict=False)
try:
resolved.relative_to(base.resolve(strict=False))
except (OSError, RuntimeError, ValueError) as exc:
raise ValueError("path escapes its resolved root") from exc
return resolved
def _validate_headers(headers: object) -> bool:
if headers is None:
return True
if not isinstance(headers, dict):
return False
seen: set[str] = set()
for name, value in headers.items():
if (
not isinstance(name, str)
or _HEADER_NAME_RE.fullmatch(name) is None
or not isinstance(value, str)
or "\r" in value
or "\n" in value
or name.lower() in seen
):
return False
seen.add(name.lower())
return True
def _validate_remote_url(url: object) -> str:
"""Validate a portable remote MCP URL per the v1 spec and return it.
Rules (Agent Plugins v1 §7.2.1): absolute http(s) URL, no user
information, no fragment; non-loopback endpoints must use HTTPS. HTTP is
allowed only when the host is exactly ``localhost`` or an IP literal in a
loopback range. No placeholder or environment expansion is performed.
"""
from urllib.parse import urlsplit
if not isinstance(url, str) or not url:
raise ValueError("url must be a non-empty string")
try:
parsed = urlsplit(url)
except ValueError as exc:
raise ValueError(f"url is not parseable: {exc}") from exc
scheme = parsed.scheme.lower()
if scheme not in {"http", "https"}:
raise ValueError("url scheme must be http or https")
if parsed.username is not None or parsed.password is not None:
raise ValueError("url must not contain user information")
if parsed.fragment:
raise ValueError("url must not contain a fragment")
host = parsed.hostname
if not host:
raise ValueError("url must have a host")
if scheme == "http":
loopback = False
if host == "localhost":
loopback = True
else:
import ipaddress
try:
loopback = ipaddress.ip_address(host).is_loopback
except ValueError:
loopback = False
if not loopback:
raise ValueError("non-loopback url must use https")
return url
def _translate_remote(config: Mapping[str, Any]) -> Dict[str, Any]:
"""Translate a portable ``streamable-http`` entry into native MCP config.
The returned record targets Hermes' existing URL-based MCP runtime.
``strict_redirect_headers`` instructs the runtime to drop the configured
headers on any cross-origin redirect, which the v1 spec requires for
portable packages (configured headers must not be forwarded to a
different origin without explicit user authorization).
"""
if set(config) - _REMOTE_FIELDS:
raise ValueError("unknown remote field")
url = _validate_remote_url(config.get("url"))
if not _validate_headers(config.get("headers")):
raise ValueError("invalid headers")
translated: Dict[str, Any] = {
"url": url,
"strict_redirect_headers": True,
}
headers = config.get("headers")
if headers:
translated["headers"] = dict(headers)
return translated
def _translate_stdio(
config: Mapping[str, Any], plugin_root: Path, data_root: Path
) -> Dict[str, Any]:
if set(config) - _STDIO_FIELDS:
raise ValueError("unknown stdio field")
command = config.get("command")
if not isinstance(command, str) or not command or "\x00" in command:
raise ValueError("command must be a non-empty executable token")
if command.startswith("./"):
command_value = str(
_resolve_scoped_path(
command,
plugin_root,
data_root,
expand_placeholders=False,
)
)
elif any(character.isspace() for character in command):
raise ValueError("command must contain one executable token")
elif "/" in command or "\\" in command or command in {".", ".."}:
raise ValueError("command must be a bare executable or begin with ./")
else:
command_value = command
args = config.get("args", [])
if not isinstance(args, list) or any(not isinstance(value, str) for value in args):
raise ValueError("args must be an array of strings")
env = config.get("env", {})
if not isinstance(env, dict) or any(
not isinstance(key, str) or not isinstance(value, str)
for key, value in env.items()
):
raise ValueError("env must map string keys to string values")
env_keys = {key.upper() if os.name == "nt" else key for key in env}
if "PLUGIN_ROOT" in env_keys or "PLUGIN_DATA" in env_keys:
raise ValueError("PLUGIN_ROOT and PLUGIN_DATA are reserved")
cwd = config.get("cwd")
if cwd is None:
cwd_value = plugin_root
elif not isinstance(cwd, str):
raise ValueError("cwd must be a string")
else:
cwd_value = _resolve_scoped_path(cwd, plugin_root, data_root)
translated_env = {
key: _expand(value, plugin_root, data_root) for key, value in env.items()
}
translated_env["PLUGIN_ROOT"] = str(plugin_root)
translated_env["PLUGIN_DATA"] = str(data_root)
return {
"command": command_value,
"args": [_expand(value, plugin_root, data_root) for value in args],
"env": translated_env,
"cwd": str(cwd_value),
}
def _discover_mcp(
root: Path,
data_root: Path,
diagnostics: list[AgentPluginDiagnostic],
*,
create_data: bool = True,
) -> Dict[str, Dict[str, Any]]:
mcp_path = root / "mcp.json"
if not mcp_path.exists() and not mcp_path.is_symlink():
return {}
if not _inside(mcp_path, root) or not mcp_path.is_file():
diagnostics.append(
AgentPluginDiagnostic("mcp", "mcp.json must be a regular in-root file")
)
return {}
try:
config = _read_json_object(mcp_path, label="mcp.json")
except AgentPluginError as exc:
diagnostics.append(AgentPluginDiagnostic("mcp", str(exc)))
return {}
if set(config) != {"$schema", "mcpServers"}:
diagnostics.append(
AgentPluginDiagnostic("mcp", "mcp.json has an invalid top-level shape")
)
return {}
if config.get("$schema") != MCP_SCHEMA_V1:
diagnostics.append(
AgentPluginDiagnostic("mcp", "mcp.json declares an unsupported schema")
)
return {}
servers = config.get("mcpServers")
if not isinstance(servers, dict):
diagnostics.append(
AgentPluginDiagnostic("mcp", "mcpServers must be an object")
)
return {}
translated: Dict[str, Dict[str, Any]] = {}
for name, server in servers.items():
scope = f"mcp:{name}"
if not isinstance(name, str) or not name or not isinstance(server, dict):
diagnostics.append(AgentPluginDiagnostic(scope, "invalid server entry"))
continue
server_type = server.get("type")
if server_type == "stdio":
try:
translated_server = _translate_stdio(server, root, data_root)
if create_data:
data_root.mkdir(parents=True, exist_ok=True)
cwd_path = Path(translated_server["cwd"])
try:
cwd_path.relative_to(data_root)
except ValueError:
pass
else:
# The MCP client starts stdio servers with this cwd.
# Create only data-root descendants; plugin-root paths
# remain package-owned and are never made writable as a
# side effect of discovery.
cwd_path.mkdir(parents=True, exist_ok=True)
translated[name] = translated_server
except (OSError, ValueError) as exc:
diagnostics.append(AgentPluginDiagnostic(scope, str(exc)))
elif server_type == "streamable-http":
try:
translated[name] = _translate_remote(server)
except ValueError as exc:
diagnostics.append(AgentPluginDiagnostic(scope, str(exc)))
elif server_type == "sse":
if (
set(server) - _REMOTE_FIELDS
or not isinstance(server.get("url"), str)
or not server.get("url")
or not _validate_headers(server.get("headers"))
):
diagnostics.append(AgentPluginDiagnostic(scope, "invalid remote entry"))
else:
diagnostics.append(
AgentPluginDiagnostic(
scope,
f"portable {server_type} transport is not supported",
)
)
else:
diagnostics.append(AgentPluginDiagnostic(scope, "unknown MCP server type"))
return translated
def load_agent_plugin(plugin_root: Path, data_root: Path) -> AgentPluginPackage:
"""Validate and translate one installed Agent Plugins v1 package.
Fatal manifest errors raise :class:`AgentPluginError`. Component and entry
failures are returned as diagnostics and isolated to their owning scope.
"""
root = Path(plugin_root).resolve(strict=True)
if not root.is_dir():
raise AgentPluginError("plugin root must be a directory")
manifest, diagnostics = _validate_manifest(root)
resolved_data = Path(data_root).resolve(strict=False)
skills = _discover_skills(root, diagnostics)
mcp_servers = _discover_mcp(root, resolved_data, diagnostics)
return AgentPluginPackage(
name=manifest["name"],
version=manifest.get("version", ""),
description=manifest.get("description", ""),
root=root,
data_root=resolved_data,
manifest=dict(manifest),
skills=skills,
mcp_servers=mcp_servers,
diagnostics=tuple(diagnostics),
)
def read_agent_plugin_manifest(plugin_root: Path) -> tuple[dict, tuple[AgentPluginDiagnostic, ...]]:
"""Validate only root ``plugin.json`` without discovering components."""
root = Path(plugin_root).resolve(strict=True)
if not root.is_dir():
raise AgentPluginError("plugin root must be a directory")
manifest, diagnostics = _validate_manifest(root)
return manifest, tuple(diagnostics)
def has_enabled_agent_plugin_mcp(raw_config: Mapping[str, Any]) -> bool:
"""Compatibility wrapper for the shared PluginManager MCP probe.
Directory scanning belongs to :mod:`hermes_cli.plugins` so startup gating
and full plugin discovery cannot drift apart. Keep this import-compatible
entry point for callers that used the original helper.
"""
from hermes_cli.plugins import has_enabled_agent_plugin_mcp as _probe
return _probe(raw_config)
|