Merge branch 'simp/r2-tools-b-termhub' into simp/integration2

This commit is contained in:
Teknium
2026-09-02 17:05:25 -07:00
10 changed files with 2534 additions and 2281 deletions
+9 -9
View File
@@ -88,7 +88,7 @@ def test_modal_backend_managed_mode_without_feature_flag_logs_clear_error(monkey
def test_vercel_backend_without_sdk_logs_specific_error(monkeypatch, caplog):
_clear_terminal_env(monkeypatch)
monkeypatch.setenv("TERMINAL_ENV", "vercel_sandbox")
monkeypatch.setattr(terminal_tool_module.importlib.util, "find_spec", lambda _name: None)
monkeypatch.setattr(importlib.util, "find_spec", lambda _name: None)
with caplog.at_level(logging.ERROR):
ok = terminal_tool_module.check_terminal_requirements()
@@ -103,7 +103,7 @@ def test_vercel_backend_without_sdk_logs_specific_error(monkeypatch, caplog):
def test_vercel_backend_without_auth_logs_specific_error(monkeypatch, caplog):
_clear_terminal_env(monkeypatch)
monkeypatch.setenv("TERMINAL_ENV", "vercel_sandbox")
monkeypatch.setattr(terminal_tool_module.importlib.util, "find_spec", lambda _name: object())
monkeypatch.setattr(importlib.util, "find_spec", lambda _name: object())
with caplog.at_level(logging.ERROR):
ok = terminal_tool_module.check_terminal_requirements()
@@ -119,7 +119,7 @@ def test_vercel_backend_accepts_oidc_auth(monkeypatch):
_clear_terminal_env(monkeypatch)
monkeypatch.setenv("TERMINAL_ENV", "vercel_sandbox")
monkeypatch.setenv("VERCEL_OIDC_TOKEN", "oidc-token")
monkeypatch.setattr(terminal_tool_module.importlib.util, "find_spec", lambda _name: object())
monkeypatch.setattr(importlib.util, "find_spec", lambda _name: object())
assert terminal_tool_module.check_terminal_requirements() is True
@@ -130,7 +130,7 @@ def test_vercel_backend_accepts_token_tuple_auth(monkeypatch):
monkeypatch.setenv("VERCEL_TOKEN", "token")
monkeypatch.setenv("VERCEL_PROJECT_ID", "project")
monkeypatch.setenv("VERCEL_TEAM_ID", "team")
monkeypatch.setattr(terminal_tool_module.importlib.util, "find_spec", lambda _name: object())
monkeypatch.setattr(importlib.util, "find_spec", lambda _name: object())
assert terminal_tool_module.check_terminal_requirements() is True
@@ -141,7 +141,7 @@ def test_vercel_backend_accepts_supported_runtimes(monkeypatch, runtime):
monkeypatch.setenv("TERMINAL_ENV", "vercel_sandbox")
monkeypatch.setenv("TERMINAL_VERCEL_RUNTIME", runtime)
monkeypatch.setenv("VERCEL_OIDC_TOKEN", "oidc-token")
monkeypatch.setattr(terminal_tool_module.importlib.util, "find_spec", lambda _name: object())
monkeypatch.setattr(importlib.util, "find_spec", lambda _name: object())
assert terminal_tool_module.check_terminal_requirements() is True
@@ -151,7 +151,7 @@ def test_vercel_backend_accepts_blank_runtime(monkeypatch):
monkeypatch.setenv("TERMINAL_ENV", "vercel_sandbox")
monkeypatch.setenv("TERMINAL_VERCEL_RUNTIME", " ")
monkeypatch.setenv("VERCEL_OIDC_TOKEN", "oidc-token")
monkeypatch.setattr(terminal_tool_module.importlib.util, "find_spec", lambda _name: object())
monkeypatch.setattr(importlib.util, "find_spec", lambda _name: object())
assert terminal_tool_module.check_terminal_requirements() is True
@@ -161,7 +161,7 @@ def test_vercel_backend_rejects_unsupported_runtime(monkeypatch, caplog):
monkeypatch.setenv("TERMINAL_ENV", "vercel_sandbox")
monkeypatch.setenv("TERMINAL_VERCEL_RUNTIME", "node20")
monkeypatch.setenv("VERCEL_OIDC_TOKEN", "oidc-token")
monkeypatch.setattr(terminal_tool_module.importlib.util, "find_spec", lambda _name: object())
monkeypatch.setattr(importlib.util, "find_spec", lambda _name: object())
with caplog.at_level(logging.ERROR):
ok = terminal_tool_module.check_terminal_requirements()
@@ -179,7 +179,7 @@ def test_vercel_backend_rejects_nondefault_disk(monkeypatch, caplog):
monkeypatch.setenv("TERMINAL_ENV", "vercel_sandbox")
monkeypatch.setenv("TERMINAL_CONTAINER_DISK", "8192")
monkeypatch.setenv("VERCEL_OIDC_TOKEN", "oidc-token")
monkeypatch.setattr(terminal_tool_module.importlib.util, "find_spec", lambda _name: object())
monkeypatch.setattr(importlib.util, "find_spec", lambda _name: object())
with caplog.at_level(logging.ERROR):
ok = terminal_tool_module.check_terminal_requirements()
@@ -196,7 +196,7 @@ def test_vercel_backend_rejects_malformed_disk_without_raising(monkeypatch, capl
monkeypatch.setenv("TERMINAL_ENV", "vercel_sandbox")
monkeypatch.setenv("TERMINAL_CONTAINER_DISK", "large")
monkeypatch.setenv("VERCEL_OIDC_TOKEN", "oidc-token")
monkeypatch.setattr(terminal_tool_module.importlib.util, "find_spec", lambda _name: object())
monkeypatch.setattr(importlib.util, "find_spec", lambda _name: object())
with caplog.at_level(logging.ERROR):
ok = terminal_tool_module.check_terminal_requirements()
@@ -304,7 +304,7 @@ class TestCheckFnTransientFailureSuppression:
lambda: {"env_type": "vercel_sandbox", "container_disk": 51200},
)
monkeypatch.setattr(
terminal_tool_module.importlib.util,
importlib.util,
"find_spec",
lambda _name: object(),
)
@@ -326,7 +326,7 @@ class TestCheckFnTransientFailureSuppression:
},
)
monkeypatch.setattr(
terminal_tool_module.importlib.util,
importlib.util,
"find_spec",
lambda _name: object(),
)
@@ -351,7 +351,7 @@ class TestCheckFnTransientFailureSuppression:
},
)
monkeypatch.setattr(
terminal_tool_module.importlib.util,
importlib.util,
"find_spec",
lambda _name: object(),
)
+36 -562
View File
@@ -2,37 +2,34 @@
"""
Skills Hub — hub state management and the public facade for the source adapters.
Library module (not an agent tool). Owns the hub paths, index cache, lock file,
taps, audit log, quarantine/install/uninstall, update checks, and the source
router; the adapters live in the ``tools.skills_hub_*`` siblings and are
re-exported here so ``from tools.skills_hub import X`` keeps working.
Library module (not an agent tool). Owns the hub paths, guarded HTTP, index
cache, lock file, taps and audit log. Install/uninstall/update live in
``skills_hub_install``, the index fetch/source router/search in
``skills_hub_search``, and the adapters in the other ``tools.skills_hub_*``
siblings; all are re-exported here so ``from tools.skills_hub import X`` keeps
working (and stays the test patch target).
Used by hermes_cli/skills_hub.py for CLI commands and the /skills slash command.
"""
import hashlib
import json
import logging
import shutil
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
from typing import Any, Dict, List, Optional
from urllib.parse import urljoin
import httpx
from hermes_constants import get_hermes_home
from agent.skill_utils import is_excluded_skill_path
from tools.skills_guard import ScanResult, content_hash
from tools.url_safety import is_safe_url
from tools.website_policy import check_website_access
from tools.skills_hub_models import ( # noqa: F401 (re-exported public API)
SkillMeta, SkillBundle, SkillSource, source_url_for_bundle,
_referenced_support_paths, _normalize_bundle_path, _validate_skill_name,
_validate_install_parent_path, _normalize_lock_install_path,
_validate_bundle_rel_path, _skill_meta_to_dict, _parse_frontmatter,
_dedupe_by_trust, TRUST_RANK,
SkillMeta, SkillBundle, SkillSource, source_url_for_bundle, _referenced_support_paths,
_normalize_bundle_path, _validate_skill_name, _validate_install_parent_path,
_normalize_lock_install_path, _validate_bundle_rel_path, _skill_meta_to_dict,
_parse_frontmatter, _dedupe_by_trust, TRUST_RANK,
)
from tools.skills_hub_github import ( # noqa: F401
GITHUB_TAP_PROVIDERS, github_provider_for, _PROVIDER_FILTER_VALUES,
@@ -44,6 +41,16 @@ from tools.skills_hub_sources import ( # noqa: F401
WellKnownSkillSource, UrlSource, LobeHubSource, BrowseShSource,
)
from tools.skills_hub_official import OptionalSkillSource, HermesIndexSource # noqa: F401
from tools.skills_hub_search import ( # noqa: F401 (re-exported; tests patch tools.skills_hub.<name>)
HERMES_INDEX_TTL, HERMES_INDEX_URL, _API_SOURCE_IDS, _hermes_index_cache_file,
_load_hermes_index, _load_stale_index_cache, _search_one_source, _select_active_sources,
create_source_router, parallel_search_sources, unified_search,
)
from tools.skills_hub_install import ( # noqa: F401 (re-exported; tests patch tools.skills_hub.<name>)
_SOURCE_ID_ALIASES, _category_skill_dirs, _check_install_target, _is_path_redirect,
_resolve_lock_install_path, _source_matches, bundle_content_hash, check_for_skill_updates,
install_from_quarantine, quarantine_bundle, uninstall_skill,
)
logger = logging.getLogger(__name__)
@@ -59,44 +66,27 @@ logger = logging.getLogger(__name__)
INDEX_CACHE_TTL = 3600 # 1 hour
def _path(name: str, default):
"""A test-injected real module attribute (patch.object/monkeypatch on
SKILLS_DIR etc.) wins over live resolution."""
forced = globals().get(name)
return Path(forced) if forced is not None else default()
def _path_resolver(name: str, default):
"""Resolver for a hub path: a test-injected real module attribute
(patch.object/monkeypatch on SKILLS_DIR etc.) wins over live resolution."""
def resolve() -> Path:
forced = globals().get(name)
return Path(forced) if forced is not None else default()
resolve.__name__ = f"_{name.lower()}"
return resolve
def _hermes_home() -> Path:
return get_hermes_home()
def _skills_dir() -> Path:
return _path("SKILLS_DIR", lambda: _hermes_home() / "skills")
def _hub_dir() -> Path:
return _path("HUB_DIR", lambda: _skills_dir() / ".hub")
def _lock_file() -> Path:
return _path("LOCK_FILE", lambda: _hub_dir() / "lock.json")
def _quarantine_dir() -> Path:
return _path("QUARANTINE_DIR", lambda: _hub_dir() / "quarantine")
def _audit_log() -> Path:
return _path("AUDIT_LOG", lambda: _hub_dir() / "audit.log")
def _taps_file() -> Path:
return _path("TAPS_FILE", lambda: _hub_dir() / "taps.json")
def _index_cache_dir() -> Path:
return _path("INDEX_CACHE_DIR", lambda: _hub_dir() / "index-cache")
_skills_dir = _path_resolver("SKILLS_DIR", lambda: _hermes_home() / "skills")
_hub_dir = _path_resolver("HUB_DIR", lambda: _skills_dir() / ".hub")
_lock_file = _path_resolver("LOCK_FILE", lambda: _hub_dir() / "lock.json")
_quarantine_dir = _path_resolver("QUARANTINE_DIR", lambda: _hub_dir() / "quarantine")
_audit_log = _path_resolver("AUDIT_LOG", lambda: _hub_dir() / "audit.log")
_taps_file = _path_resolver("TAPS_FILE", lambda: _hub_dir() / "taps.json")
_index_cache_dir = _path_resolver("INDEX_CACHE_DIR", lambda: _hub_dir() / "index-cache")
_DYNAMIC_PATH_RESOLVERS = {
"HERMES_HOME": _hermes_home,
@@ -127,37 +117,6 @@ _REDIRECT_STATUS_CODES = {301, 302, 303, 307, 308}
_MAX_SKILL_FETCH_REDIRECTS = 5
def _is_path_redirect(path: Path) -> bool:
"""True when ``path`` is a symlink or (on Windows) a directory junction —
either lets a writer in ``skills/`` redirect a later ``rmtree`` outside it.
``is_junction`` only exists on Python 3.12+ Windows; gate with ``hasattr``."""
return path.is_symlink() or (hasattr(path, "is_junction") and path.is_junction())
def _resolve_lock_install_path(install_path: str, skill_name: str) -> Path:
"""Resolve a lock-file install path without allowing escapes from ``SKILLS_DIR``.
Walks component-by-component refusing symlink/junction redirects (which
``Path.resolve`` would silently follow), then rejects both escape-out and
``resolved == SKILLS_DIR`` — an empty/``"."`` install_path resolves to the
skills root and ``rmtree`` there would wipe every installed skill.
"""
normalized = _normalize_lock_install_path(install_path, skill_name)
skills_dir = _skills_dir()
skills_root = skills_dir.resolve()
target = skills_dir
for part in normalized.split("/"):
target = target / part
if _is_path_redirect(target):
raise ValueError(f"Unsafe install path: {install_path}")
target = target.resolve()
if target == skills_root or not target.is_relative_to(skills_root):
raise ValueError(f"Unsafe install path: {install_path}")
return target
def _ssrf_safe_http_get(url: str, *, timeout: int = 20) -> httpx.Response:
"""Fetch one URL with connect-time SSRF validation and no automatic redirects."""
from tools.url_safety import create_ssrf_safe_client
@@ -402,497 +361,12 @@ def ensure_hub_dirs() -> None:
path.write_text(initial, encoding="utf-8")
def quarantine_bundle(bundle: SkillBundle) -> Path:
"""Write a skill bundle to the quarantine directory for scanning."""
ensure_hub_dirs()
skill_name = _validate_skill_name(bundle.name)
# Validate every path before touching disk so a bad member aborts cleanly.
validated_files = [
(_validate_bundle_rel_path(rel_path), file_content)
for rel_path, file_content in bundle.files.items()
]
dest = _quarantine_dir() / skill_name
if dest.exists():
shutil.rmtree(dest)
dest.mkdir(parents=True)
for rel_path, file_content in validated_files:
file_dest = dest.joinpath(*rel_path.split("/"))
file_dest.parent.mkdir(parents=True, exist_ok=True)
if isinstance(file_content, bytes):
file_dest.write_bytes(file_content)
else:
file_dest.write_text(file_content, encoding="utf-8")
return dest
def _category_skill_dirs(directory: Path) -> List[str]:
"""Names of non-hidden child dirs holding at least one active SKILL.md
anywhere below (nested layouts like ``mlops/training/<skill>`` count).
Vendored/cache/progressive-disclosure paths are pruned via
:func:`is_excluded_skill_path` so a lone ``node_modules`` or
``references/pkg/SKILL.md`` does not make the directory a category.
Shared with ``hermes_cli.skills_hub._existing_categories``.
"""
skill_dirs: List[str] = []
for entry in directory.iterdir():
if not entry.is_dir() or entry.name.startswith("."):
continue
if any(
not is_excluded_skill_path(skill_md.relative_to(directory), root=directory)
for skill_md in entry.rglob("SKILL.md")
):
skill_dirs.append(entry.name)
return skill_dirs
def _check_install_target(install_dir: Path) -> None:
"""Raise ValueError when installing at ``install_dir`` would destroy other skills.
- Nesting inside an existing skill dir (``--category <existing-skill>``)
would make a later update/uninstall of the outer skill rmtree the inner one.
- A stray regular file at the target: rmtree would raise NotADirectoryError.
- A category bucket (dir without SKILL.md that holds other skills) must never
be silently wiped; a dir that directly contains SKILL.md is an existing
install and stays overwritable (hub installs are lock-guarded in do_install).
"""
skills_root = _skills_dir().resolve()
ancestor = install_dir.parent
while ancestor != skills_root and ancestor.is_relative_to(skills_root):
if (ancestor / "SKILL.md").is_file():
raise ValueError(
f"Refusing to install into '{ancestor.name}': it is an "
f"existing skill directory, not a category. Choose a "
f"different category."
)
ancestor = ancestor.parent
if not install_dir.exists():
return
if not install_dir.is_dir():
raise ValueError(
f"Refusing to install: '{install_dir.name}' already exists "
f"and is not a directory. Remove it or choose a different "
f"skill name."
)
if not (install_dir / "SKILL.md").exists():
skill_dirs_in = _category_skill_dirs(install_dir)
if skill_dirs_in:
raise ValueError(
f"Refusing to overwrite category directory '{install_dir}' "
f"which contains {len(skill_dirs_in)} skill(s): "
f"{', '.join(sorted(skill_dirs_in))}. "
f"Use a different --name or install into a subcategory."
)
def install_from_quarantine(
quarantine_path: Path,
skill_name: str,
category: str,
bundle: SkillBundle,
scan_result: ScanResult,
scan_provenance: Optional[Dict[str, Any]] = None,
) -> Path:
"""Move a scanned skill from quarantine into the skills directory."""
safe_skill_name = _validate_skill_name(skill_name)
safe_category = _validate_install_parent_path(category) if category else ""
quarantine_resolved = quarantine_path.resolve()
if not quarantine_resolved.is_relative_to(_quarantine_dir().resolve()):
raise ValueError(f"Unsafe quarantine path: {quarantine_path}")
install_rel_path = f"{safe_category}/{safe_skill_name}" if safe_category else safe_skill_name
# Same validator the uninstaller uses, so a lock entry can never point at a
# symlink-redirected target.
install_dir = _resolve_lock_install_path(install_rel_path, safe_skill_name)
_check_install_target(install_dir)
if install_dir.exists():
shutil.rmtree(install_dir)
skill_md = quarantine_path / "SKILL.md"
if skill_md.exists():
try:
skill_size = skill_md.stat().st_size
if skill_size > 100_000:
logger.warning(
"Skill '%s' has a large SKILL.md (%s chars). "
"Large skills consume significant context when loaded. "
"Consider asking the author to split it into smaller files.",
safe_skill_name,
f"{skill_size:,}",
)
except OSError:
pass
# A symlink in the bundle would copy its target into skills/ and leak it
# to the agent on the next skill_view.
for entry in quarantine_path.rglob("*"):
if not _is_path_redirect(entry):
continue
try:
rel = entry.relative_to(quarantine_resolved)
except ValueError:
rel = entry
raise ValueError(
f"Installed skill contains symlinks, which is not allowed: {rel}"
)
install_dir.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(quarantine_path), str(install_dir))
installed_hash = content_hash(install_dir)
HubLockFile().record_install(
name=safe_skill_name,
source=bundle.source,
identifier=bundle.identifier,
trust_level=bundle.trust_level,
scan_verdict=scan_result.verdict,
skill_hash=installed_hash,
install_path=install_dir.resolve().relative_to(_skills_dir().resolve()).as_posix(),
files=list(bundle.files.keys()),
metadata=bundle.metadata,
scan_provenance=scan_provenance or getattr(scan_result, "scan_provenance", None),
)
append_audit_log(
"INSTALL", safe_skill_name, bundle.source,
bundle.trust_level, scan_result.verdict,
installed_hash,
)
try:
from tools.skill_usage import record_installed
record_installed(safe_skill_name)
except Exception:
logger.debug(
"Unable to record skill install lifecycle for %s",
safe_skill_name,
exc_info=True,
)
return install_dir
def uninstall_skill(skill_name: str) -> Tuple[bool, str]:
"""Remove a hub-installed skill. Refuses to remove builtins."""
lock = HubLockFile()
entry = lock.get_installed(skill_name)
if not entry:
return False, f"'{skill_name}' is not a hub-installed skill (may be a builtin)"
# The destructive boundary: whatever reaches rmtree MUST be inside
# SKILLS_DIR and MUST NOT be SKILLS_DIR itself (see _resolve_lock_install_path).
try:
install_path = _resolve_lock_install_path(entry.get("install_path", ""), skill_name)
except ValueError as exc:
return False, f"Refusing to uninstall '{skill_name}': {exc}"
if install_path.exists():
shutil.rmtree(install_path)
lock.record_uninstall(skill_name)
append_audit_log("UNINSTALL", skill_name, entry["source"], entry["trust_level"], "n/a", "user_request")
return True, f"Uninstalled '{skill_name}' from {entry['install_path']}"
def bundle_content_hash(bundle: SkillBundle) -> str:
"""Deterministic hash of an in-memory bundle.
MUST stay symmetric with ``tools.skills_guard.content_hash`` (same skill
from disk), which keys files by POSIX relative path. Windows bundle keys
carry backslashes, which changed both bytes and sort order and made every
skill report ``update_available`` forever — normalize before hashing. The
path is hashed too so swapping contents between two files changes the hash.
"""
h = hashlib.sha256()
normalized = {
rel_path.replace("\\", "/"): content
for rel_path, content in bundle.files.items()
}
for rel_path in sorted(normalized):
h.update(rel_path.encode("utf-8"))
h.update(b"\x00")
content = normalized[rel_path]
h.update(content if isinstance(content, bytes) else content.encode("utf-8"))
return f"sha256:{h.hexdigest()[:16]}"
_SOURCE_ID_ALIASES = {"skills.sh": "skills-sh"}
def _source_matches(source: SkillSource, source_name: str) -> bool:
return source.source_id() == _SOURCE_ID_ALIASES.get(source_name, source_name)
def check_for_skill_updates(
name: Optional[str] = None,
*,
lock: Optional[HubLockFile] = None,
sources: Optional[List[SkillSource]] = None,
auth: Optional[GitHubAuth] = None,
) -> List[dict]:
"""Check installed hub skills for upstream changes.
Each entry is fetched ONLY from adapters matching its recorded source.
Falling back to all sources let a same-named skill in a different registry
satisfy the fetch and silently reassign provenance (names are not
namespaced across registries), so a missing adapter reports "unavailable".
"""
lock = lock or HubLockFile()
installed = lock.list_installed()
if name:
installed = [entry for entry in installed if entry.get("name") == name]
if sources is None:
sources = create_source_router(auth=auth)
results: List[dict] = []
for entry in installed:
identifier = entry.get("identifier", "")
source_name = entry.get("source", "")
row = {"name": entry.get("name", ""), "identifier": identifier, "source": source_name}
bundle = None
for src in sources:
if not _source_matches(src, source_name):
continue
try:
bundle = src.fetch(identifier)
except Exception:
bundle = None
if bundle:
break
if not bundle:
results.append({**row, "status": "unavailable"})
continue
current_hash = entry.get("content_hash", "")
latest_hash = bundle_content_hash(bundle)
results.append({
**row,
"status": "up_to_date" if current_hash == latest_hash else "update_available",
"current_hash": current_hash,
"latest_hash": latest_hash,
"bundle": bundle,
})
return results
# ---------------------------------------------------------------------------
# Hermes centralized index (data source for HermesIndexSource)
# ---------------------------------------------------------------------------
HERMES_INDEX_URL = "https://hermes-agent.nousresearch.com/docs/api/skills-index.json"
HERMES_INDEX_TTL = 6 * 3600 # 6 hours
def _hermes_index_cache_file() -> Path:
return _index_cache_dir() / "hermes-index.json"
def _load_hermes_index() -> Optional[dict]:
"""Fetch the centralized skills index (docs site, rebuilt daily), cached
locally for HERMES_INDEX_TTL; on any failure serve the stale cache.
Brotli is deliberately NOT negotiated: the index is tens of MB and httpx's
streaming Brotli decoder (brotlicffi, pinned for Discord attachments) raises
DecodingError on payloads this size — which surfaced as a silently empty
Skills Hub. gzip/deflate first; the identity retry covers proxies that
ignore the header and return Brotli anyway.
"""
cache_file = _hermes_index_cache_file()
cached = _read_json_if_fresh(cache_file, HERMES_INDEX_TTL)
if cached is not None:
return cached
data = None
for accept_encoding in ("gzip, deflate", "identity"):
try:
resp = httpx.get(
HERMES_INDEX_URL,
timeout=15,
follow_redirects=True,
headers={"Accept-Encoding": accept_encoding},
)
if resp.status_code != 200:
logger.debug("Hermes index fetch returned %d", resp.status_code)
return _load_stale_index_cache()
data = resp.json()
break
except httpx.DecodingError as e:
logger.debug(
"Hermes index decode failed (Accept-Encoding=%s): %s",
accept_encoding,
e,
)
continue
except (httpx.HTTPError, json.JSONDecodeError) as e:
logger.debug("Hermes index fetch failed: %s", e)
return _load_stale_index_cache()
if not isinstance(data, dict) or "skills" not in data:
return _load_stale_index_cache()
try:
cache_file.parent.mkdir(parents=True, exist_ok=True)
cache_file.write_text(json.dumps(data), encoding="utf-8")
except OSError:
pass
return data
def _load_stale_index_cache() -> Optional[dict]:
"""Fall back to the cache regardless of age when the network fetch fails."""
return _read_json_if_fresh(_hermes_index_cache_file(), float("inf"))
# ---------------------------------------------------------------------------
# Source router + parallel search
# ---------------------------------------------------------------------------
# External API sources the centralized index already covers; skipped when the
# index is available and no source filter is active (~70 GitHub calls/search
# for unauthenticated users otherwise).
_API_SOURCE_IDS = frozenset({"github", "skills-sh", "clawhub", "lobehub", "well-known"})
def create_source_router(auth: Optional[GitHubAuth] = None) -> List[SkillSource]:
"""All configured source adapters, in priority order."""
if auth is None:
auth = GitHubAuth()
return [
OptionalSkillSource(auth=auth), # official optional skills (highest priority)
HermesIndexSource(auth=auth), # centralized index (search + resolved install paths)
SkillsShSource(auth=auth),
WellKnownSkillSource(),
UrlSource(), # direct HTTP(S) URL to a SKILL.md
GitHubSource(auth=auth, extra_taps=TapsManager().list_taps()),
ClawHubSource(),
LobeHubSource(),
BrowseShSource(), # browse.sh site-specific browser skills
]
def _search_one_source(
src: SkillSource, query: str, limit: int
) -> Tuple[str, List[SkillMeta]]:
"""Search a single source. Runs in a thread for parallelism."""
try:
return src.source_id(), src.search(query, limit=limit)
except Exception as e:
logger.debug("Search failed for %s: %s", src.source_id(), e)
return src.source_id(), []
def _select_active_sources(sources: List[SkillSource], source_filter: str) -> List[SkillSource]:
"""Sources to query for ``source_filter``.
A provider filter (nvidia/openai/...) is not a source id — the data lives
in the index/github source under ``extra.provider`` — so it selects like
"all"; the narrowing happens later on the merged results. "official" is
always included alongside an explicit source filter.
"""
effective = "all" if source_filter.strip().lower() in _PROVIDER_FILTER_VALUES else source_filter
index_available = effective == "all" and any(
src.source_id() == "hermes-index" and getattr(src, "is_available", False)
for src in sources
)
active: List[SkillSource] = []
for src in sources:
sid = src.source_id()
if effective != "all" and sid != effective and sid != "official":
continue
if index_available and sid in _API_SOURCE_IDS:
continue
active.append(src)
return active
def parallel_search_sources(
sources: List[SkillSource],
query: str = "",
per_source_limits: Optional[Dict[str, int]] = None,
source_filter: str = "all",
overall_timeout: float = 30,
on_source_done: Optional[Any] = None,
) -> Tuple[List[SkillMeta], Dict[str, int], List[str]]:
"""Search all sources in parallel with an overall timeout.
Returns ``(all_results, source_counts, timed_out_ids)``. *on_source_done*
is an optional ``(source_id, count) -> None`` progress callback.
"""
from concurrent.futures import as_completed
per_source_limits = per_source_limits or {}
active = _select_active_sources(sources, source_filter)
all_results: List[SkillMeta] = []
source_counts: Dict[str, int] = {}
timed_out_ids: List[str] = []
if not active:
return all_results, source_counts, timed_out_ids
# Not a ``with`` block: its shutdown(wait=True) would block on a slow source
# (ClawHub) for minutes and defeat ``overall_timeout``. Daemon workers so an
# abandoned source cannot block interpreter exit either.
from tools.daemon_pool import DaemonThreadPoolExecutor
pool = DaemonThreadPoolExecutor(max_workers=min(len(active), 8))
futures = {
pool.submit(_search_one_source, src, query, per_source_limits.get(src.source_id(), 50)): src.source_id()
for src in active
}
try:
try:
for fut in as_completed(futures, timeout=overall_timeout):
try:
sid, results = fut.result(timeout=0)
source_counts[sid] = len(results)
all_results.extend(results)
if on_source_done:
on_source_done(sid, len(results))
except Exception:
pass
except TimeoutError:
timed_out_ids = [futures[f] for f in futures if not f.done()]
if timed_out_ids:
logger.debug(
"Skills browse timed out waiting for: %s",
", ".join(timed_out_ids),
)
finally:
pool.shutdown(wait=False, cancel_futures=True)
return all_results, source_counts, timed_out_ids
def unified_search(query: str, sources: List[SkillSource],
source_filter: str = "all", limit: int = 10) -> List[SkillMeta]:
"""Search all sources (in parallel) and merge results."""
all_results, _, _ = parallel_search_sources(
sources,
query=query,
source_filter=source_filter,
overall_timeout=30,
)
# Provider filters target ``extra.provider`` on the merged set, not a source id.
if source_filter.strip().lower() in _PROVIDER_FILTER_VALUES:
all_results = _filter_results_by_provider(all_results, source_filter)
deduped = _dedupe_by_trust(all_results)
# Stable-sort by trust before truncating so the limit cut never drops a
# builtin/official entry because a high-volume community source finished
# first; insertion order is preserved within each rank.
deduped.sort(key=lambda r: -TRUST_RANK.get(r.trust_level, 0))
return deduped[:limit]
+352
View File
@@ -0,0 +1,352 @@
"""Skills Hub install/uninstall/update operations: quarantine staging, install-
target safety (symlink/junction, category-bucket and nested-skill checks),
lock-file-backed uninstall, bundle hashing and upstream update checks.
Split out of ``tools/skills_hub.py``; every public/patched name is re-imported there,
so ``tools.skills_hub.<name>`` keeps resolving (and monkeypatching) as before.
"""
from __future__ import annotations
import logging
import hashlib
import shutil
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
from agent.skill_utils import is_excluded_skill_path
from tools.skills_guard import ScanResult, content_hash
from tools.skills_hub_github import GitHubAuth
from tools.skills_hub_models import (
SkillBundle,
SkillSource,
_normalize_lock_install_path,
_validate_bundle_rel_path,
_validate_install_parent_path,
_validate_skill_name,
)
if TYPE_CHECKING: # origin class; runtime use is via the lazy origin import
from tools.skills_hub import HubLockFile
# Log-record parity with the origin module.
logger = logging.getLogger("tools.skills_hub")
def _is_path_redirect(path: Path) -> bool:
"""True when ``path`` is a symlink or (on Windows) a directory junction —
either lets a writer in ``skills/`` redirect a later ``rmtree`` outside it.
``is_junction`` only exists on Python 3.12+ Windows; gate with ``hasattr``."""
return path.is_symlink() or (hasattr(path, "is_junction") and path.is_junction())
def _resolve_lock_install_path(install_path: str, skill_name: str) -> Path:
"""Resolve a lock-file install path without allowing escapes from ``SKILLS_DIR``.
Walks component-by-component refusing symlink/junction redirects (which
``Path.resolve`` would silently follow), then rejects both escape-out and
``resolved == SKILLS_DIR`` — an empty/``"."`` install_path resolves to the
skills root and ``rmtree`` there would wipe every installed skill.
"""
from tools.skills_hub import _skills_dir
normalized = _normalize_lock_install_path(install_path, skill_name)
skills_dir = _skills_dir()
skills_root = skills_dir.resolve()
target = skills_dir
for part in normalized.split("/"):
target = target / part
if _is_path_redirect(target):
raise ValueError(f"Unsafe install path: {install_path}")
target = target.resolve()
if target == skills_root or not target.is_relative_to(skills_root):
raise ValueError(f"Unsafe install path: {install_path}")
return target
def quarantine_bundle(bundle: SkillBundle) -> Path:
"""Write a skill bundle to the quarantine directory for scanning."""
from tools.skills_hub import _quarantine_dir, ensure_hub_dirs
ensure_hub_dirs()
skill_name = _validate_skill_name(bundle.name)
# Validate every path before touching disk so a bad member aborts cleanly.
validated_files = [
(_validate_bundle_rel_path(rel_path), file_content)
for rel_path, file_content in bundle.files.items()
]
dest = _quarantine_dir() / skill_name
if dest.exists():
shutil.rmtree(dest)
dest.mkdir(parents=True)
for rel_path, file_content in validated_files:
file_dest = dest.joinpath(*rel_path.split("/"))
file_dest.parent.mkdir(parents=True, exist_ok=True)
if isinstance(file_content, bytes):
file_dest.write_bytes(file_content)
else:
file_dest.write_text(file_content, encoding="utf-8")
return dest
def _category_skill_dirs(directory: Path) -> List[str]:
"""Names of non-hidden child dirs holding at least one active SKILL.md
anywhere below (nested layouts like ``mlops/training/<skill>`` count).
Vendored/cache/progressive-disclosure paths are pruned via
:func:`is_excluded_skill_path` so a lone ``node_modules`` or
``references/pkg/SKILL.md`` does not make the directory a category.
Shared with ``hermes_cli.skills_hub._existing_categories``.
"""
skill_dirs: List[str] = []
for entry in directory.iterdir():
if not entry.is_dir() or entry.name.startswith("."):
continue
if any(
not is_excluded_skill_path(skill_md.relative_to(directory), root=directory)
for skill_md in entry.rglob("SKILL.md")
):
skill_dirs.append(entry.name)
return skill_dirs
def _check_install_target(install_dir: Path) -> None:
"""Raise ValueError when installing at ``install_dir`` would destroy other skills.
- Nesting inside an existing skill dir (``--category <existing-skill>``)
would make a later update/uninstall of the outer skill rmtree the inner one.
- A stray regular file at the target: rmtree would raise NotADirectoryError.
- A category bucket (dir without SKILL.md that holds other skills) must never
be silently wiped; a dir that directly contains SKILL.md is an existing
install and stays overwritable (hub installs are lock-guarded in do_install).
"""
from tools.skills_hub import _skills_dir
skills_root = _skills_dir().resolve()
ancestor = install_dir.parent
while ancestor != skills_root and ancestor.is_relative_to(skills_root):
if (ancestor / "SKILL.md").is_file():
raise ValueError(
f"Refusing to install into '{ancestor.name}': it is an "
f"existing skill directory, not a category. Choose a "
f"different category."
)
ancestor = ancestor.parent
if not install_dir.exists():
return
if not install_dir.is_dir():
raise ValueError(
f"Refusing to install: '{install_dir.name}' already exists "
f"and is not a directory. Remove it or choose a different "
f"skill name."
)
if not (install_dir / "SKILL.md").exists():
skill_dirs_in = _category_skill_dirs(install_dir)
if skill_dirs_in:
raise ValueError(
f"Refusing to overwrite category directory '{install_dir}' "
f"which contains {len(skill_dirs_in)} skill(s): "
f"{', '.join(sorted(skill_dirs_in))}. "
f"Use a different --name or install into a subcategory."
)
def install_from_quarantine(
quarantine_path: Path,
skill_name: str,
category: str,
bundle: SkillBundle,
scan_result: ScanResult,
scan_provenance: Optional[Dict[str, Any]] = None,
) -> Path:
"""Move a scanned skill from quarantine into the skills directory."""
from tools.skills_hub import HubLockFile, _quarantine_dir, _skills_dir, append_audit_log
safe_skill_name = _validate_skill_name(skill_name)
safe_category = _validate_install_parent_path(category) if category else ""
quarantine_resolved = quarantine_path.resolve()
if not quarantine_resolved.is_relative_to(_quarantine_dir().resolve()):
raise ValueError(f"Unsafe quarantine path: {quarantine_path}")
install_rel_path = f"{safe_category}/{safe_skill_name}" if safe_category else safe_skill_name
# Same validator the uninstaller uses, so a lock entry can never point at a
# symlink-redirected target.
install_dir = _resolve_lock_install_path(install_rel_path, safe_skill_name)
_check_install_target(install_dir)
if install_dir.exists():
shutil.rmtree(install_dir)
skill_md = quarantine_path / "SKILL.md"
if skill_md.exists():
try:
skill_size = skill_md.stat().st_size
if skill_size > 100_000:
logger.warning(
"Skill '%s' has a large SKILL.md (%s chars). "
"Large skills consume significant context when loaded. "
"Consider asking the author to split it into smaller files.",
safe_skill_name,
f"{skill_size:,}",
)
except OSError:
pass
# A symlink in the bundle would copy its target into skills/ and leak it
# to the agent on the next skill_view.
for entry in quarantine_path.rglob("*"):
if not _is_path_redirect(entry):
continue
try:
rel = entry.relative_to(quarantine_resolved)
except ValueError:
rel = entry
raise ValueError(
f"Installed skill contains symlinks, which is not allowed: {rel}"
)
install_dir.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(quarantine_path), str(install_dir))
installed_hash = content_hash(install_dir)
HubLockFile().record_install(
name=safe_skill_name,
source=bundle.source,
identifier=bundle.identifier,
trust_level=bundle.trust_level,
scan_verdict=scan_result.verdict,
skill_hash=installed_hash,
install_path=install_dir.resolve().relative_to(_skills_dir().resolve()).as_posix(),
files=list(bundle.files.keys()),
metadata=bundle.metadata,
scan_provenance=scan_provenance or getattr(scan_result, "scan_provenance", None),
)
append_audit_log(
"INSTALL", safe_skill_name, bundle.source,
bundle.trust_level, scan_result.verdict,
installed_hash,
)
try:
from tools.skill_usage import record_installed
record_installed(safe_skill_name)
except Exception:
logger.debug(
"Unable to record skill install lifecycle for %s",
safe_skill_name,
exc_info=True,
)
return install_dir
def uninstall_skill(skill_name: str) -> Tuple[bool, str]:
"""Remove a hub-installed skill. Refuses to remove builtins."""
from tools.skills_hub import HubLockFile, append_audit_log
lock = HubLockFile()
entry = lock.get_installed(skill_name)
if not entry:
return False, f"'{skill_name}' is not a hub-installed skill (may be a builtin)"
# The destructive boundary: whatever reaches rmtree MUST be inside
# SKILLS_DIR and MUST NOT be SKILLS_DIR itself (see _resolve_lock_install_path).
try:
install_path = _resolve_lock_install_path(entry.get("install_path", ""), skill_name)
except ValueError as exc:
return False, f"Refusing to uninstall '{skill_name}': {exc}"
if install_path.exists():
shutil.rmtree(install_path)
lock.record_uninstall(skill_name)
append_audit_log("UNINSTALL", skill_name, entry["source"], entry["trust_level"], "n/a", "user_request")
return True, f"Uninstalled '{skill_name}' from {entry['install_path']}"
def bundle_content_hash(bundle: SkillBundle) -> str:
"""Deterministic hash of an in-memory bundle.
MUST stay symmetric with ``tools.skills_guard.content_hash`` (same skill
from disk), which keys files by POSIX relative path. Windows bundle keys
carry backslashes, which changed both bytes and sort order and made every
skill report ``update_available`` forever — normalize before hashing. The
path is hashed too so swapping contents between two files changes the hash.
"""
h = hashlib.sha256()
normalized = {
rel_path.replace("\\", "/"): content
for rel_path, content in bundle.files.items()
}
for rel_path in sorted(normalized):
h.update(rel_path.encode("utf-8"))
h.update(b"\x00")
content = normalized[rel_path]
h.update(content if isinstance(content, bytes) else content.encode("utf-8"))
return f"sha256:{h.hexdigest()[:16]}"
_SOURCE_ID_ALIASES = {"skills.sh": "skills-sh"}
def _source_matches(source: SkillSource, source_name: str) -> bool:
return source.source_id() == _SOURCE_ID_ALIASES.get(source_name, source_name)
def check_for_skill_updates(
name: Optional[str] = None,
*,
lock: Optional[HubLockFile] = None,
sources: Optional[List[SkillSource]] = None,
auth: Optional[GitHubAuth] = None,
) -> List[dict]:
"""Check installed hub skills for upstream changes.
Each entry is fetched ONLY from adapters matching its recorded source.
Falling back to all sources let a same-named skill in a different registry
satisfy the fetch and silently reassign provenance (names are not
namespaced across registries), so a missing adapter reports "unavailable".
"""
from tools.skills_hub import HubLockFile, create_source_router
lock = lock or HubLockFile()
installed = lock.list_installed()
if name:
installed = [entry for entry in installed if entry.get("name") == name]
if sources is None:
sources = create_source_router(auth=auth)
results: List[dict] = []
for entry in installed:
identifier = entry.get("identifier", "")
source_name = entry.get("source", "")
row = {"name": entry.get("name", ""), "identifier": identifier, "source": source_name}
bundle = None
for src in sources:
if not _source_matches(src, source_name):
continue
try:
bundle = src.fetch(identifier)
except Exception:
bundle = None
if bundle:
break
if not bundle:
results.append({**row, "status": "unavailable"})
continue
current_hash = entry.get("content_hash", "")
latest_hash = bundle_content_hash(bundle)
results.append({
**row,
"status": "up_to_date" if current_hash == latest_hash else "update_available",
"current_hash": current_hash,
"latest_hash": latest_hash,
"bundle": bundle,
})
return results
+238
View File
@@ -0,0 +1,238 @@
"""Skills Hub discovery: the centralized Hermes index fetch (cached, stale-
fallback), the source router, and parallel/unified search across source
adapters.
Split out of ``tools/skills_hub.py``; every public/patched name is re-imported there,
so ``tools.skills_hub.<name>`` keeps resolving (and monkeypatching) as before.
"""
from __future__ import annotations
import logging
import httpx
import json
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
from tools.skills_hub_github import _PROVIDER_FILTER_VALUES
from tools.skills_hub_models import SkillMeta, SkillSource, TRUST_RANK, _dedupe_by_trust
from tools.skills_hub_skillssh import SkillsShSource
from tools.skills_hub_sources import LobeHubSource, WellKnownSkillSource
if TYPE_CHECKING: # runtime use resolves through the origin (test patch target)
from tools.skills_hub_github import GitHubAuth
# Log-record parity with the origin module.
logger = logging.getLogger("tools.skills_hub")
HERMES_INDEX_URL = "https://hermes-agent.nousresearch.com/docs/api/skills-index.json"
HERMES_INDEX_TTL = 6 * 3600 # 6 hours
def _hermes_index_cache_file() -> Path:
from tools.skills_hub import _index_cache_dir
return _index_cache_dir() / "hermes-index.json"
def _load_hermes_index() -> Optional[dict]:
"""Fetch the centralized skills index (docs site, rebuilt daily), cached
locally for HERMES_INDEX_TTL; on any failure serve the stale cache.
Brotli is deliberately NOT negotiated: the index is tens of MB and httpx's
streaming Brotli decoder (brotlicffi, pinned for Discord attachments) raises
DecodingError on payloads this size — which surfaced as a silently empty
Skills Hub. gzip/deflate first; the identity retry covers proxies that
ignore the header and return Brotli anyway.
"""
from tools.skills_hub import _hermes_index_cache_file, _read_json_if_fresh
cache_file = _hermes_index_cache_file()
cached = _read_json_if_fresh(cache_file, HERMES_INDEX_TTL)
if cached is not None:
return cached
data = None
for accept_encoding in ("gzip, deflate", "identity"):
try:
resp = httpx.get(
HERMES_INDEX_URL,
timeout=15,
follow_redirects=True,
headers={"Accept-Encoding": accept_encoding},
)
if resp.status_code != 200:
logger.debug("Hermes index fetch returned %d", resp.status_code)
return _load_stale_index_cache()
data = resp.json()
break
except httpx.DecodingError as e:
logger.debug(
"Hermes index decode failed (Accept-Encoding=%s): %s",
accept_encoding,
e,
)
continue
except (httpx.HTTPError, json.JSONDecodeError) as e:
logger.debug("Hermes index fetch failed: %s", e)
return _load_stale_index_cache()
if not isinstance(data, dict) or "skills" not in data:
return _load_stale_index_cache()
try:
cache_file.parent.mkdir(parents=True, exist_ok=True)
cache_file.write_text(json.dumps(data), encoding="utf-8")
except OSError:
pass
return data
def _load_stale_index_cache() -> Optional[dict]:
"""Fall back to the cache regardless of age when the network fetch fails."""
from tools.skills_hub import _hermes_index_cache_file, _read_json_if_fresh
return _read_json_if_fresh(_hermes_index_cache_file(), float("inf"))
# External API sources the centralized index already covers; skipped when the
# index is available and no source filter is active (~70 GitHub calls/search
# for unauthenticated users otherwise).
_API_SOURCE_IDS = frozenset({"github", "skills-sh", "clawhub", "lobehub", "well-known"})
def create_source_router(auth: Optional[GitHubAuth] = None) -> List[SkillSource]:
"""All configured source adapters, in priority order."""
from tools.skills_hub import ( # adapters resolve via origin: tests patch them there
BrowseShSource, ClawHubSource, GitHubAuth, GitHubSource, HermesIndexSource,
OptionalSkillSource, TapsManager, UrlSource,
)
if auth is None:
auth = GitHubAuth()
return [
OptionalSkillSource(auth=auth), # official optional skills (highest priority)
HermesIndexSource(auth=auth), # centralized index (search + resolved install paths)
SkillsShSource(auth=auth),
WellKnownSkillSource(),
UrlSource(), # direct HTTP(S) URL to a SKILL.md
GitHubSource(auth=auth, extra_taps=TapsManager().list_taps()),
ClawHubSource(),
LobeHubSource(),
BrowseShSource(), # browse.sh site-specific browser skills
]
def _search_one_source(
src: SkillSource, query: str, limit: int
) -> Tuple[str, List[SkillMeta]]:
"""Search a single source. Runs in a thread for parallelism."""
try:
return src.source_id(), src.search(query, limit=limit)
except Exception as e:
logger.debug("Search failed for %s: %s", src.source_id(), e)
return src.source_id(), []
def _select_active_sources(sources: List[SkillSource], source_filter: str) -> List[SkillSource]:
"""Sources to query for ``source_filter``.
A provider filter (nvidia/openai/...) is not a source id — the data lives
in the index/github source under ``extra.provider`` — so it selects like
"all"; the narrowing happens later on the merged results. "official" is
always included alongside an explicit source filter.
"""
effective = "all" if source_filter.strip().lower() in _PROVIDER_FILTER_VALUES else source_filter
index_available = effective == "all" and any(
src.source_id() == "hermes-index" and getattr(src, "is_available", False)
for src in sources
)
active: List[SkillSource] = []
for src in sources:
sid = src.source_id()
if effective != "all" and sid != effective and sid != "official":
continue
if index_available and sid in _API_SOURCE_IDS:
continue
active.append(src)
return active
def parallel_search_sources(
sources: List[SkillSource],
query: str = "",
per_source_limits: Optional[Dict[str, int]] = None,
source_filter: str = "all",
overall_timeout: float = 30,
on_source_done: Optional[Any] = None,
) -> Tuple[List[SkillMeta], Dict[str, int], List[str]]:
"""Search all sources in parallel with an overall timeout.
Returns ``(all_results, source_counts, timed_out_ids)``. *on_source_done*
is an optional ``(source_id, count) -> None`` progress callback.
"""
from concurrent.futures import as_completed
per_source_limits = per_source_limits or {}
active = _select_active_sources(sources, source_filter)
all_results: List[SkillMeta] = []
source_counts: Dict[str, int] = {}
timed_out_ids: List[str] = []
if not active:
return all_results, source_counts, timed_out_ids
# Not a ``with`` block: its shutdown(wait=True) would block on a slow source
# (ClawHub) for minutes and defeat ``overall_timeout``. Daemon workers so an
# abandoned source cannot block interpreter exit either.
from tools.daemon_pool import DaemonThreadPoolExecutor
pool = DaemonThreadPoolExecutor(max_workers=min(len(active), 8))
futures = {
pool.submit(_search_one_source, src, query, per_source_limits.get(src.source_id(), 50)): src.source_id()
for src in active
}
try:
try:
for fut in as_completed(futures, timeout=overall_timeout):
try:
sid, results = fut.result(timeout=0)
source_counts[sid] = len(results)
all_results.extend(results)
if on_source_done:
on_source_done(sid, len(results))
except Exception:
pass
except TimeoutError:
timed_out_ids = [futures[f] for f in futures if not f.done()]
if timed_out_ids:
logger.debug(
"Skills browse timed out waiting for: %s",
", ".join(timed_out_ids),
)
finally:
pool.shutdown(wait=False, cancel_futures=True)
return all_results, source_counts, timed_out_ids
def unified_search(query: str, sources: List[SkillSource],
source_filter: str = "all", limit: int = 10) -> List[SkillMeta]:
"""Search all sources (in parallel) and merge results."""
from tools.skills_hub import _filter_results_by_provider, parallel_search_sources
all_results, _, _ = parallel_search_sources(
sources,
query=query,
source_filter=source_filter,
overall_timeout=30,
)
# Provider filters target ``extra.provider`` on the merged set, not a source id.
if source_filter.strip().lower() in _PROVIDER_FILTER_VALUES:
all_results = _filter_results_by_provider(all_results, source_filter)
deduped = _dedupe_by_trust(all_results)
# Stable-sort by trust before truncating so the limit cut never drops a
# builtin/official entry because a high-volume community source finished
# first; insertion order is preserved within each rank.
deduped.sort(key=lambda r: -TRUST_RANK.get(r.trust_level, 0))
return deduped[:limit]
+343 -1707
View File
File diff suppressed because it is too large Load Diff
+482
View File
@@ -0,0 +1,482 @@
"""Execution-environment backends for the terminal tool: per-backend builders
(local/docker/singularity/modal/daytona/vercel/ssh/plugin), the config-to-
kwargs shapers, and the per-backend requirement checkers, both routed by
dispatch table.
Split out of ``tools/terminal_tool.py``; every public/patched name is re-imported there,
so ``tools.terminal_tool.<name>`` keeps resolving (and monkeypatching) as before.
"""
import logging
import importlib.util
import inspect
import shutil
import subprocess
from typing import Any, Dict, Optional
from tools.environments.local import LocalEnvironment as _LocalEnvironment
from tools.environments.managed_modal import (
ManagedModalEnvironment as _ManagedModalEnvironment,
)
from tools.environments.modal import ModalEnvironment as _ModalEnvironment
from tools.environments.singularity import (
SingularityEnvironment as _SingularityEnvironment,
)
from tools.environments.ssh import SSHEnvironment as _SSHEnvironment
from tools.tool_backend_helpers import (
has_direct_modal_credentials,
nous_tool_gateway_unavailable_message,
resolve_modal_backend_state,
)
# Log-record parity with the origin module.
logger = logging.getLogger("tools.terminal_tool")
_VERCEL_SANDBOX_DEFAULT_CWD = "/vercel/sandbox"
_SUPPORTED_VERCEL_RUNTIMES = ("node24", "node22", "python3.13")
def _is_supported_vercel_runtime(runtime: str) -> bool:
return not runtime or runtime in _SUPPORTED_VERCEL_RUNTIMES
def _check_vercel_sandbox_requirements(config: dict[str, Any]) -> bool:
"""Validate Vercel Sandbox terminal backend requirements."""
runtime = (config.get("vercel_runtime") or "").strip()
if not _is_supported_vercel_runtime(runtime):
supported = ", ".join(_SUPPORTED_VERCEL_RUNTIMES)
logger.error(
"Vercel Sandbox runtime %r is not supported. "
"Set TERMINAL_VERCEL_RUNTIME to one of: %s.",
runtime,
supported,
)
return False
disk = config.get("container_disk", 51200)
if disk not in {0, 51200}:
logger.error(
"Vercel Sandbox does not support custom TERMINAL_CONTAINER_DISK=%s. "
"Use the default shared setting (51200 MB).",
disk,
)
return False
if importlib.util.find_spec("vercel") is None:
logger.error(
"vercel is required for the Vercel Sandbox terminal backend: pip install vercel"
)
return False
from agent.secret_scope import get_secret
has_oidc = bool(get_secret("VERCEL_OIDC_TOKEN"))
has_token = bool(get_secret("VERCEL_TOKEN"))
has_project = bool(get_secret("VERCEL_PROJECT_ID"))
has_team = bool(get_secret("VERCEL_TEAM_ID"))
if has_oidc:
return True
if has_token or has_project or has_team:
if has_token and has_project and has_team:
return True
logger.error(
"Vercel Sandbox backend selected with token auth, but "
"VERCEL_TOKEN, VERCEL_PROJECT_ID, and VERCEL_TEAM_ID must all "
"be set together. VERCEL_OIDC_TOKEN is supported for one-off "
"local development only."
)
return False
logger.error(
"Vercel Sandbox backend selected but no supported auth configuration "
"was found. Set VERCEL_TOKEN, VERCEL_PROJECT_ID, and VERCEL_TEAM_ID "
"for normal use. VERCEL_OIDC_TOKEN is supported for one-off local "
"development only."
)
return False
def _get_modal_backend_state(modal_mode: object | None) -> Dict[str, Any]:
"""Resolve direct vs managed Modal backend selection."""
from tools.terminal_tool import is_managed_tool_gateway_ready
return resolve_modal_backend_state(
modal_mode,
has_direct=has_direct_modal_credentials(),
managed_ready=is_managed_tool_gateway_ready("modal"),
)
def _ssh_config_from_config(config: Dict[str, Any]) -> dict:
"""``ssh_config`` for :func:`_create_environment` (shared by terminal_tool
and the lazy :func:`ensure_task_env` bring-up)."""
return {
"host": config.get("ssh_host", ""),
"user": config.get("ssh_user", ""),
"port": config.get("ssh_port", 22),
"key": config.get("ssh_key", ""),
"persistent": config.get("ssh_persistent", False),
}
def _container_config_from_config(config: Dict[str, Any]) -> dict:
"""``container_config`` for :func:`_create_environment` (shared by
terminal_tool and the lazy :func:`ensure_task_env` bring-up)."""
return {
"container_cpu": config.get("container_cpu", 1),
"container_memory": config.get("container_memory", 5120),
"container_disk": config.get("container_disk", 51200),
"container_persistent": config.get("container_persistent", True),
"modal_mode": config.get("modal_mode", "auto"),
"vercel_runtime": config.get("vercel_runtime", ""),
"docker_volumes": config.get("docker_volumes", []),
"docker_mount_cwd_to_workspace": config.get("docker_mount_cwd_to_workspace", False),
"docker_forward_env": config.get("docker_forward_env", []),
"docker_env": config.get("docker_env", {}),
"docker_run_as_host_user": config.get("docker_run_as_host_user", False),
"docker_extra_args": config.get("docker_extra_args", []),
"docker_shm_size": config.get("docker_shm_size", "1g"),
"docker_network": config.get("docker_network", True),
"docker_persist_across_processes": config.get("docker_persist_across_processes", True),
"docker_shared_container_key": config.get("docker_shared_container_key", ""),
"docker_orphan_reaper": config.get("docker_orphan_reaper", True),
}
def _resources(cc: Dict[str, Any]) -> dict:
"""Common sandbox resource kwargs (cpu/memory in MB/disk in MB/persistence)."""
return {
"cpu": cc.get("container_cpu", 1),
"memory": cc.get("container_memory", 5120),
"disk": cc.get("container_disk", 51200),
"persistent_filesystem": cc.get("container_persistent", True),
}
def _build_local_env(*, cwd, timeout, **_):
return _LocalEnvironment(cwd=cwd, timeout=timeout)
def _build_docker_env(*, image, cwd, timeout, cc, task_id, host_cwd, **_):
# One-shot orphan reaper for labeled containers left behind by prior
# Hermes processes that died before atexit (SIGKILL / OOM / closed
# terminal); once per process, ``terminal.docker_orphan_reaper: false``
# disables it.
from tools.terminal_tool import _DockerEnvironment, _docker_session_isolation_enabled, _has_isolation_overrides, _maybe_reap_docker_orphans
_maybe_reap_docker_orphans(cc)
# Per-session container isolation: a session-keyed container must not
# outlive its session, so cross-process reuse/persist is disabled for it —
# cleanup_vm()/the idle reaper stop+rm it. The shared "default" container
# and RL/benchmark override sandboxes keep their existing lifecycle.
session_scoped = (
_docker_session_isolation_enabled()
and task_id != "default"
and not _has_isolation_overrides(task_id)
)
docker_env_obj = _DockerEnvironment(
image=image, cwd=cwd, timeout=timeout, task_id=task_id,
**_resources(cc),
volumes=cc.get("docker_volumes", []),
host_cwd=host_cwd,
auto_mount_cwd=cc.get("docker_mount_cwd_to_workspace", False),
forward_env=cc.get("docker_forward_env", []),
env=cc.get("docker_env", {}),
run_as_host_user=cc.get("docker_run_as_host_user", False),
network=cc.get("docker_network", True),
extra_args=cc.get("docker_extra_args", []),
persist_across_processes=(
False if session_scoped
else cc.get("docker_persist_across_processes", True)
),
shared_container_key=cc.get("docker_shared_container_key", ""),
shm_size=cc.get("docker_shm_size", "1g"),
)
# Marker read by is_persistent_env(): a session-scoped container survives
# BETWEEN turns (skip per-turn teardown) but is removed at session close /
# idle timeout. Guarded: test doubles may not accept attributes.
if session_scoped:
try:
docker_env_obj._session_scoped = True
except AttributeError:
pass
return docker_env_obj
def _build_singularity_env(*, image, cwd, timeout, cc, task_id, **_):
return _SingularityEnvironment(
image=image, cwd=cwd, timeout=timeout, task_id=task_id, **_resources(cc),
)
def _build_modal_env(*, image, cwd, timeout, cc, task_id, **_):
from tools.terminal_tool import managed_nous_tools_enabled
res = _resources(cc)
persistent = res["persistent_filesystem"]
sandbox_kwargs = {k: res[k] for k in ("cpu", "memory") if res[k] > 0}
if res["disk"] > 0:
try:
import modal
if "ephemeral_disk" in inspect.signature(modal.Sandbox.create).parameters:
sandbox_kwargs["ephemeral_disk"] = res["disk"]
except Exception:
pass
modal_state = _get_modal_backend_state(cc.get("modal_mode"))
if modal_state["selected_backend"] == "managed":
return _ManagedModalEnvironment(
image=image, cwd=cwd, timeout=timeout,
modal_sandbox_kwargs=sandbox_kwargs,
persistent_filesystem=persistent, task_id=task_id,
)
if modal_state["selected_backend"] != "direct":
if modal_state["managed_mode_blocked"]:
raise ValueError(
"Modal backend is configured for managed mode, but "
"Nous Tool Gateway access is not currently available and no direct "
"Modal credentials/config were found. "
+ nous_tool_gateway_unavailable_message(
"managed Modal execution",
)
+ " Choose TERMINAL_MODAL_MODE=direct/auto to use direct Modal credentials."
)
if modal_state["mode"] == "managed":
raise ValueError(
"Modal backend is configured for managed mode, but the managed tool gateway is unavailable. "
+ nous_tool_gateway_unavailable_message(
"managed Modal execution",
)
)
if modal_state["mode"] == "direct":
raise ValueError(
"Modal backend is configured for direct mode, but no direct Modal credentials/config were found."
)
message = "Modal backend selected but no direct Modal credentials/config was found."
if managed_nous_tools_enabled():
message = (
"Modal backend selected but no direct Modal credentials/config or managed tool gateway was found."
)
raise ValueError(message)
return _ModalEnvironment(
image=image, cwd=cwd, timeout=timeout,
modal_sandbox_kwargs=sandbox_kwargs,
persistent_filesystem=persistent, task_id=task_id,
)
def _build_daytona_env(*, image, cwd, timeout, cc, task_id, **_):
# Lazy import so daytona SDK is only required when backend is selected.
from tools.environments.daytona import DaytonaEnvironment as _DaytonaEnvironment
res = _resources(cc)
res["cpu"] = int(res["cpu"])
return _DaytonaEnvironment(image=image, cwd=cwd, timeout=timeout, task_id=task_id, **res)
def _build_vercel_env(*, cwd, timeout, cc, task_id, **_):
from tools.environments.vercel_sandbox import (
VercelSandboxEnvironment as _VercelSandboxEnvironment,
)
return _VercelSandboxEnvironment(
runtime=cc.get("vercel_runtime") or None,
cwd=cwd, timeout=timeout, task_id=task_id, **_resources(cc),
)
def _build_ssh_env(*, cwd, timeout, ssh_config, **_):
if not ssh_config or not ssh_config.get("host") or not ssh_config.get("user"):
raise ValueError("SSH environment requires ssh_host and ssh_user to be configured")
return _SSHEnvironment(
host=ssh_config["host"],
user=ssh_config["user"],
port=ssh_config.get("port", 22),
key_path=ssh_config.get("key", ""),
cwd=cwd,
timeout=timeout,
)
def _build_plugin_env(*, env_type, image, cwd, timeout, cc, task_id, **_):
from tools.terminal_tool import _get_plugin_env_provider
provider = _get_plugin_env_provider(env_type)
if provider is not None:
env_obj = provider.create_environment(
cwd=cwd, timeout=timeout, task_id=task_id,
image=image, container_config=cc,
)
# Stamp the backend name so path-resolution and progress surfaces
# can identify plugin backends without class-name sniffing.
try:
env_obj._hermes_backend_name = provider.name.strip().lower()
except AttributeError:
pass # test doubles may reject attributes
return env_obj
try:
from agent.terminal_env_registry import plugin_backend_names
plugin_names = plugin_backend_names()
except Exception:
plugin_names = []
extra = (
", " + ", ".join(f"'{n}'" for n in plugin_names) if plugin_names else ""
)
raise ValueError(
f"Unknown environment type: {env_type}. Use 'local', 'docker', "
f"'singularity', 'modal', 'daytona', 'vercel_sandbox', 'ssh'{extra}"
)
# Built-in backend -> builder. Anything else is looked up in the plugin registry.
_ENV_BUILDERS = {
"local": _build_local_env,
"docker": _build_docker_env,
"singularity": _build_singularity_env,
"modal": _build_modal_env,
"daytona": _build_daytona_env,
"vercel_sandbox": _build_vercel_env,
"ssh": _build_ssh_env,
}
def _create_environment(env_type: str, image: str, cwd: str, timeout: int,
ssh_config: dict = None, container_config: dict = None,
local_config: dict = None,
task_id: str = "default",
host_cwd: Optional[str] = None):
"""Create an execution environment (instance with ``execute()``) for *env_type*.
``image`` is ignored for local/ssh/vercel; ``container_config`` carries the
container_*/docker_* resource keys; ``host_cwd`` is the host directory to
bind into Docker when cwd mounting is explicitly enabled. Unknown
``env_type`` values fall through to plugin-registered backends.
"""
builder = _ENV_BUILDERS.get(env_type, _build_plugin_env)
return builder(
env_type=env_type, image=image, cwd=cwd, timeout=timeout,
cc=container_config or {}, task_id=task_id,
ssh_config=ssh_config, host_cwd=host_cwd,
)
def _check_docker_requirements(config: Dict[str, Any]) -> bool:
from tools.environments.docker import find_docker
docker = find_docker()
if not docker:
logger.error("Docker executable not found in PATH or common install locations")
return False
result = subprocess.run([docker, "version"], capture_output=True, timeout=5, stdin=subprocess.DEVNULL)
return result.returncode == 0
def _check_singularity_requirements(config: Dict[str, Any]) -> bool:
executable = shutil.which("apptainer") or shutil.which("singularity")
if executable:
result = subprocess.run([executable, "--version"], capture_output=True, timeout=5, stdin=subprocess.DEVNULL)
return result.returncode == 0
return False
def _check_ssh_requirements(config: Dict[str, Any]) -> bool:
if not config.get("ssh_host") or not config.get("ssh_user"):
logger.error(
"SSH backend selected but TERMINAL_SSH_HOST and TERMINAL_SSH_USER "
"are not both set. Configure both or switch TERMINAL_ENV to 'local'."
)
return False
return True
def _check_modal_requirements(config: Dict[str, Any]) -> bool:
from tools.terminal_tool import managed_nous_tools_enabled
modal_state = _get_modal_backend_state(config.get("modal_mode"))
if modal_state["selected_backend"] == "managed":
return True
if modal_state["selected_backend"] != "direct":
if modal_state["managed_mode_blocked"]:
logger.error(
"Modal backend selected with TERMINAL_MODAL_MODE=managed, but "
"Nous Tool Gateway access is not currently available and no direct "
"Modal credentials/config were found. %s Choose "
"TERMINAL_MODAL_MODE=direct/auto to use direct Modal credentials.",
nous_tool_gateway_unavailable_message(
"managed Modal execution",
),
)
return False
if modal_state["mode"] == "managed":
logger.error(
"Modal backend selected with TERMINAL_MODAL_MODE=managed, but the managed "
"tool gateway is unavailable. %s",
nous_tool_gateway_unavailable_message(
"managed Modal execution",
),
)
return False
elif modal_state["mode"] == "direct":
if managed_nous_tools_enabled():
logger.error(
"Modal backend selected with TERMINAL_MODAL_MODE=direct, but no direct "
"Modal credentials/config were found. Configure Modal or choose "
"TERMINAL_MODAL_MODE=managed/auto."
)
else:
logger.error(
"Modal backend selected with TERMINAL_MODAL_MODE=direct, but no direct "
"Modal credentials/config were found. Configure Modal or choose "
"TERMINAL_MODAL_MODE=auto."
)
return False
else:
if managed_nous_tools_enabled():
logger.error(
"Modal backend selected but no direct Modal credentials/config or managed "
"tool gateway was found. Configure Modal, set up the managed gateway, "
"or choose a different TERMINAL_ENV."
)
else:
logger.error(
"Modal backend selected but no direct Modal credentials/config was found. "
"Configure Modal or choose a different TERMINAL_ENV."
)
return False
if importlib.util.find_spec("modal") is None:
logger.error("modal is required for direct modal terminal backend: pip install modal")
return False
return True
def _check_daytona_requirements(config: Dict[str, Any]) -> bool:
from daytona import Daytona # noqa: F401 — SDK presence check
from agent.secret_scope import get_secret
return get_secret("DAYTONA_API_KEY") is not None
def _check_plugin_requirements(config: Dict[str, Any]) -> bool:
from tools.terminal_tool import _get_plugin_env_provider
env_type = config["env_type"]
provider = _get_plugin_env_provider(env_type)
if provider is not None:
return bool(provider.check_requirements(config))
logger.error(
"Unknown TERMINAL_ENV '%s'. Use one of: local, docker, singularity, "
"modal, daytona, vercel_sandbox, ssh, or a plugin-registered backend.",
env_type,
)
return False
# Built-in backend -> requirements checker; unknown backends go to the plugin registry.
_REQUIREMENT_CHECKERS = {
"local": lambda config: True,
"docker": _check_docker_requirements,
"singularity": _check_singularity_requirements,
"ssh": _check_ssh_requirements,
"modal": _check_modal_requirements,
"vercel_sandbox": _check_vercel_sandbox_requirements,
"daytona": _check_daytona_requirements,
}
+104
View File
@@ -0,0 +1,104 @@
"""Terminal backend configuration: scope-aware TERMINAL_* reads, env-var parsing,
container-cwd sanity checks, plugin-backend classification and the resolved
config dict (_get_env_config).
Split out of ``tools/terminal_tool.py``; every public/patched name is re-imported there,
so ``tools.terminal_tool.<name>`` keeps resolving (and monkeypatching) as before.
"""
import logging
import json
import os
from typing import Any
# Log-record parity with the origin module.
logger = logging.getLogger("tools.terminal_tool")
def _parse_env_var(name: str, default: str, converter: Any = int, type_label: str = "integer"):
"""Parse an env var with *converter*, raising a clear ValueError on bad
values (e.g. TERMINAL_TIMEOUT=5m) instead of an opaque crash. TERMINAL_*
names are read scope-aware via :func:`_tenv`."""
raw = os.getenv(name, default)
if name.startswith("TERMINAL_"):
raw = _tenv(name, default)
try:
return converter(raw)
except (ValueError, json.JSONDecodeError):
raise ValueError(
f"Invalid value for {name}: {raw!r} (expected {type_label}). "
f"Check ~/.hermes/.env or environment variables."
)
def _safe_getcwd() -> str:
"""``os.getcwd()`` tolerant of a deleted cwd (FileNotFoundError) or a macOS
TCC-protected one without Full Disk Access (PermissionError); falls back
to TERMINAL_CWD, then the home directory."""
try:
return os.getcwd()
except (FileNotFoundError, PermissionError):
return _tenv("TERMINAL_CWD") or os.path.expanduser("~")
# Host-cwd prefixes that cannot exist inside a container sandbox (POSIX user
# dirs and Windows drive paths as they leak toward a Linux ``-w`` flag).
_HOST_CWD_PREFIXES = ("/Users/", "/home/", "C:\\", "C:/")
_CONTAINER_BACKENDS = frozenset({"docker", "singularity", "modal", "daytona", "vercel_sandbox"})
def _plugin_env_flag(env_type: str, attr: str, default=False):
"""Classification flag of a plugin-registered backend. Fail-soft: *default*
when the registry is unavailable, the backend unknown, or the provider
raises — a misbehaving plugin must never take the terminal tool down."""
if not env_type or env_type in _CONTAINER_BACKENDS or env_type in {"local", "ssh", "managed_modal"}:
return default
try:
from agent.terminal_env_registry import provider_flag
return provider_flag(env_type, attr, default)
except Exception:
return default
def _is_container_backend(env_type: str) -> bool:
"""True for built-in container backends and plugins declaring ``is_container``."""
return env_type in _CONTAINER_BACKENDS or _plugin_env_flag(env_type, "is_container")
def _get_plugin_env_provider(env_type: str):
"""Return the registered plugin provider for *env_type*, or None."""
if not env_type or env_type in _CONTAINER_BACKENDS or env_type in {"local", "ssh", "managed_modal"}:
return None
try:
from agent.terminal_env_registry import get_provider
return get_provider(env_type)
except Exception:
return None
def _is_unusable_container_cwd(cwd: str) -> bool:
"""True if *cwd* is a host or relative path that can't be a container
workdir: ``docker run -w`` needs an absolute in-sandbox path, otherwise the
container fails to start (exit 125). Windows drive paths aren't ``isabs``
on POSIX, so they're caught by the prefix check."""
if not cwd:
return False
return cwd.startswith(_HOST_CWD_PREFIXES) or not os.path.isabs(cwd)
def _tenv(name: str, default: str = "") -> str:
"""Scope-aware read of a ``TERMINAL_*`` variable. Every terminal setting
must go through this: under gateway multiplexing the active profile's
config arrives via a per-turn scope, and a raw ``os.getenv`` would read
whatever a previous turn pinned into the process env (cross-profile leak)."""
from tools.terminal_scope import terminal_env
return terminal_env(name, default)
def _tenv_bool(name: str, default: str) -> bool:
"""Scope-aware boolean ``TERMINAL_*`` read: true/1/yes (case-insensitive)."""
return _tenv(name, default).lower() in {"true", "1", "yes"}
+329
View File
@@ -0,0 +1,329 @@
"""Sandbox lifecycle for the terminal tool: idle reaping, teardown, manual/atexit
cleanup, and the lazy ensure_task_env bring-up. The env cache dicts and locks
stay in tools.terminal_tool (tests patch them there) and are read through it
at call time.
Split out of ``tools/terminal_tool.py``; every public/patched name is re-imported there,
so ``tools.terminal_tool.<name>`` keeps resolving (and monkeypatching) as before.
"""
import logging
import inspect
import shutil
import threading
import time
from pathlib import Path
from typing import Any, Dict, Optional
from tools.environments.singularity import _get_scratch_dir
from tools.terminal_tool_backends import (
_container_config_from_config,
_ssh_config_from_config,
)
# Log-record parity with the origin module.
logger = logging.getLogger("tools.terminal_tool")
# Advisory disk-usage check; cached so the recursive scan doesn't run on
# every command (a result up to 5 minutes stale is harmless).
_disk_usage_cache: dict = {"timestamp": 0.0, "result": False}
_DISK_USAGE_CACHE_TTL = 300.0 # seconds
def _check_disk_usage_warning():
"""True when hermes scratch dirs exceed the warning threshold (cached, advisory)."""
from tools.terminal_tool import DISK_USAGE_WARNING_THRESHOLD_GB
import time as _time_mod
now = _time_mod.monotonic()
if now - _disk_usage_cache["timestamp"] < _DISK_USAGE_CACHE_TTL:
return _disk_usage_cache["result"]
try:
scratch_dir = _get_scratch_dir()
total_bytes = 0
import glob
for path in glob.glob(str(scratch_dir / "hermes-*")):
for f in Path(path).rglob('*'):
if f.is_file():
try:
total_bytes += f.stat().st_size
except OSError as e:
logger.debug("Could not stat file %s: %s", f, e)
total_gb = total_bytes / (1024 ** 3)
exceeded = total_gb > DISK_USAGE_WARNING_THRESHOLD_GB
if exceeded:
logger.warning("Disk usage (%.1fGB) exceeds threshold (%.0fGB). Consider running cleanup_all_environments().",
total_gb, DISK_USAGE_WARNING_THRESHOLD_GB)
_disk_usage_cache["timestamp"] = _time_mod.monotonic()
_disk_usage_cache["result"] = exceeded
return exceeded
except Exception as e:
logger.debug("Disk usage warning check failed: %s", e, exc_info=True)
# Don't update cache on error so the next call retries.
return False
def _create_configured_env(
config: Dict[str, Any], env_type: str, *, image: str, cwd: str, timeout: int,
task_id: str, host_cwd: Optional[str], local_config: Optional[dict] = None,
):
"""``_create_environment`` with the ssh/container kwargs shaped from *config*
(shared by the terminal tool and the lazy :func:`ensure_task_env` bring-up)."""
from tools.terminal_tool import _create_environment, _is_container_backend
return _create_environment(
env_type=env_type, image=image, cwd=cwd, timeout=timeout,
ssh_config=_ssh_config_from_config(config) if env_type == "ssh" else None,
container_config=(
_container_config_from_config(config) if _is_container_backend(env_type) else None
),
local_config=local_config, task_id=task_id, host_cwd=host_cwd,
)
def _teardown_env(env: Any, task_id: str, *, force_remove: Optional[bool] = None, done_msg: str = "Cleaned up inactive environment for task: %s") -> None:
"""Stop *env* via cleanup()/stop()/terminate(), whichever it has; log the outcome.
``force_remove`` is forwarded to ``cleanup()`` only when given and the
backend's signature accepts it (DockerEnvironment; others don't). A
404/"not found" error means the sandbox is already gone — logged at info.
"""
try:
if hasattr(env, 'cleanup'):
if force_remove is not None and "force_remove" in inspect.signature(env.cleanup).parameters:
env.cleanup(force_remove=force_remove)
else:
env.cleanup()
elif hasattr(env, 'stop'):
env.stop()
elif hasattr(env, 'terminate'):
env.terminate()
logger.info(done_msg, task_id)
except Exception as e:
error_str = str(e)
if "404" in error_str or "not found" in error_str.lower():
logger.info("Environment for task %s already cleaned up", task_id)
else:
logger.warning("Error cleaning up environment for task %s: %s", task_id, e)
def _clear_file_ops_cache(task_id: str) -> None:
"""Invalidate the file_ops cache entry so ShellFileOperations can't reference a dead sandbox."""
try:
from tools.file_tools import clear_file_ops_cache
clear_file_ops_cache(task_id)
except ImportError:
pass
def _cleanup_inactive_envs(lifetime_seconds: int = 300):
"""Clean up environments that have been inactive for longer than lifetime_seconds."""
from tools.terminal_tool import (
_active_environments, _creation_locks, _creation_locks_lock, _env_lock,
_last_activity,
)
current_time = time.time()
# Sandboxes with active background processes stay alive (refresh activity).
try:
from tools.process_registry import process_registry
for task_id in list(_last_activity.keys()):
if process_registry.has_active_processes(task_id):
_last_activity[task_id] = current_time
except ImportError:
pass
# Phase 1: unregister stale entries under the lock. Do NOT call
# env.cleanup() inside the lock — Modal/Docker teardown can block 10-15s
# and would stall every concurrent terminal/file tool call.
envs_to_stop = [] # list of (task_id, env) pairs
with _env_lock:
for task_id, last_time in list(_last_activity.items()):
if current_time - last_time > lifetime_seconds:
env = _active_environments.pop(task_id, None)
_last_activity.pop(task_id, None)
if env is not None:
envs_to_stop.append((task_id, env))
with _creation_locks_lock:
for task_id, _ in envs_to_stop:
_creation_locks.pop(task_id, None)
# Phase 2: stop the sandboxes outside the lock.
for task_id, env in envs_to_stop:
_clear_file_ops_cache(task_id)
_teardown_env(env, task_id)
def get_active_env(task_id: str):
"""Return the active BaseEnvironment for *task_id*, or None."""
from tools.terminal_tool import _active_environments, _env_lock, _resolve_container_task_id
lookup = _resolve_container_task_id(task_id)
with _env_lock:
return _active_environments.get(lookup) or _active_environments.get(task_id)
def ensure_task_env(task_id: Optional[str] = None):
"""Lazily create and cache the sandbox env for *task_id* if none is active.
Lets non-terminal callers (``tools.image_source`` reading container-only
paths) bring the sandbox up on demand with the same machinery as the
terminal tool. No-op on local. Returns the env, or ``None`` when local or
when creation fails (best-effort; the caller's fail-closed path stays intact).
"""
from tools.terminal_tool import (
_active_environments, _creation_locks, _creation_locks_lock, _env_lock,
_get_env_config, _last_activity, _resolve_container_task_id,
_resolve_task_host_cwd, _select_image, _start_cleanup_thread, get_active_env,
resolve_task_overrides,
)
config = _get_env_config()
env_type = config["env_type"]
if env_type == "local":
return None
effective_task_id = _resolve_container_task_id(task_id)
existing = get_active_env(effective_task_id)
if existing is not None:
with _env_lock:
_last_activity[effective_task_id] = time.time()
return existing
overrides = resolve_task_overrides(task_id)
image = _select_image(env_type, overrides, config)
_start_cleanup_thread()
with _creation_locks_lock:
task_lock = _creation_locks.setdefault(effective_task_id, threading.Lock())
with task_lock:
existing = get_active_env(effective_task_id)
if existing is not None:
return existing
try:
new_env = _create_configured_env(
config, env_type, image=image, cwd=config["cwd"],
timeout=config["timeout"], task_id=effective_task_id,
host_cwd=_resolve_task_host_cwd(config, task_id),
)
except Exception as exc: # noqa: BLE001 — best-effort bring-up
logger.warning(
"Lazy %s environment init failed for task %s: %s",
env_type, effective_task_id[:8], exc,
)
return None
with _env_lock:
_active_environments[effective_task_id] = new_env
_last_activity[effective_task_id] = time.time()
logger.info(
"%s environment lazily initialized for task %s",
env_type, effective_task_id[:8],
)
return new_env
def is_persistent_env(task_id: str) -> bool:
"""True if *task_id*'s active env persists across turns.
The agent loop skips per-turn teardown for these (persistent docker,
daytona, modal, …); non-persistent backends are torn down at end of turn
to prevent leakage, and the idle reaper handles the rest. Session-scoped
docker containers count as persistent HERE: their lifetime is the session
(removed by ``AIAgent.close()`` → ``cleanup_vm`` and the idle reaper).
"""
from tools.terminal_tool import get_active_env
env = get_active_env(task_id)
if env is None:
return False
if getattr(env, "_session_scoped", False):
return True
return bool(getattr(env, "_persistent", False))
def cleanup_all_environments():
"""Clean up ALL active environments. Use with caution."""
from tools.terminal_tool import _active_environments, cleanup_vm
task_ids = list(_active_environments.keys())
cleaned = 0
for task_id in task_ids:
try:
cleanup_vm(task_id)
cleaned += 1
except Exception as e:
logger.error("Error cleaning %s: %s", task_id, e, exc_info=True)
# Also clean any orphaned directories
scratch_dir = _get_scratch_dir()
import glob
for path in glob.glob(str(scratch_dir / "hermes-*")):
try:
shutil.rmtree(path, ignore_errors=True)
logger.info("Removed orphaned: %s", path)
except OSError as e:
logger.debug("Failed to remove orphaned path %s: %s", path, e)
if cleaned > 0:
logger.info("Cleaned %d environments", cleaned)
return cleaned
def cleanup_vm(task_id: str, *, force_remove: bool = False):
"""Manually clean up a specific environment by task_id.
*force_remove* is forwarded to backends that accept it (currently only
``DockerEnvironment``). Default False matches session-lifecycle semantics:
callers (``AIAgent.close()`` on TUI/gateway session teardown, the per-turn
cleanup of non-persistent envs) must honor the user's persist-mode
preference — stopping the container here would break the "ONE long-lived
container shared across sessions" contract. Pass ``force_remove=True``
only for user-initiated teardown. The idle reaper calls ``env.cleanup()``
directly, so persist-mode idle envs are likewise no-op'd; only the orphan
reaper at next startup reclaims them.
"""
from tools.terminal_tool import (
_active_environments, _creation_locks, _creation_locks_lock, _env_lock,
_last_activity,
)
# Unregister under the lock; run the (slow) cleanup outside it.
with _env_lock:
env = _active_environments.pop(task_id, None)
_last_activity.pop(task_id, None)
with _creation_locks_lock:
_creation_locks.pop(task_id, None)
_clear_file_ops_cache(task_id)
if env is None:
return
_teardown_env(
env, task_id, force_remove=force_remove,
done_msg="Manually cleaned up environment for task: %s",
)
def _evict_environment_for_task(task_id: Optional[str]) -> None:
"""Drop any cached env for *task_id* (and its collapsed key) after an
infrastructure failure, so later calls don't reuse a dead connection."""
from tools.terminal_tool import (
_active_environments, _env_lock, _last_activity, _resolve_container_task_id,
)
keys = {_resolve_container_task_id(task_id)}
if task_id:
keys.add(task_id)
evicted = []
with _env_lock:
for key in keys:
env = _active_environments.pop(key, None)
_last_activity.pop(key, None)
if env is not None:
evicted.append(env)
for env in evicted:
try:
env.cleanup()
except Exception:
logger.debug("cleanup of degraded environment failed", exc_info=True)
+638
View File
@@ -0,0 +1,638 @@
"""Sudo password plumbing and shell-command rewrites for the terminal tool: the
per-scope interactive password cache, the /dev/tty prompt, real-sudo tokenizer
(sudo -S -p '' rewrite), NOPASSWD probe, and the compound-background brace-
group rewrite.
Split out of ``tools/terminal_tool.py``; every public/patched name is re-imported there,
so ``tools.terminal_tool.<name>`` keeps resolving (and monkeypatching) as before.
"""
import logging
import os
import platform
import re
import subprocess
import sys
import threading
import time
from utils import env_var_enabled
# Log-record parity with the origin module.
logger = logging.getLogger("tools.terminal_tool")
# Interactive sudo password cache, scoped to the session key when present,
# else callback identity (ACP / CLI), else the current thread — so one
# session can never reuse another's cached password in a long-lived process.
_sudo_password_cache: dict[str, str] = {}
_sudo_password_cache_lock = threading.Lock()
def _get_sudo_password_cache_scope() -> str:
"""Return the cache scope for interactive sudo passwords."""
from tools.terminal_tool import _current_session_key, _get_sudo_password_callback
session_key = _current_session_key()
if session_key:
return f"session:{session_key}"
callback = _get_sudo_password_callback()
if callback is not None:
owner = getattr(callback, "__self__", None)
func = getattr(callback, "__func__", None)
if owner is not None and func is not None:
return f"callback-owner:{id(owner)}:{id(func)}"
return f"callback:{id(callback)}"
return f"thread:{threading.get_ident()}"
def _get_cached_sudo_password() -> str:
"""Return the cached sudo password for the current scope."""
scope = _get_sudo_password_cache_scope()
with _sudo_password_cache_lock:
return _sudo_password_cache.get(scope, "")
def _set_cached_sudo_password(password: str) -> None:
"""Persist a sudo password for the current scope."""
scope = _get_sudo_password_cache_scope()
with _sudo_password_cache_lock:
if password:
_sudo_password_cache[scope] = password
else:
_sudo_password_cache.pop(scope, None)
def _reset_cached_sudo_passwords() -> None:
"""Clear all cached sudo passwords (tests / process teardown)."""
with _sudo_password_cache_lock:
_sudo_password_cache.clear()
def _in_delegated_child_context() -> bool:
"""True while running inside a delegate_task child.
Subagents run on parent-process worker threads and inherit process-wide
``HERMES_INTERACTIVE=1``, which does NOT mean this context can reach the
user: a raw ``/dev/tty`` sudo prompt from a child races the TUI for the
tty and blocks the child for the full timeout. Children must always be
headless for sudo prompting. The ContextVar is set by
``delegated_child_context()`` and propagates via ``copy_context``.
"""
try:
from agent.delegation_context import is_delegated_child_context
return is_delegated_child_context()
except Exception:
return False
def _handle_sudo_failure(output: str, env_type: str) -> str:
"""Append a SUDO_PASSWORD tip when sudo failed in a headless context
(gateway session or delegate_task child); otherwise return *output* as is."""
is_gateway = env_var_enabled("HERMES_GATEWAY_SESSION")
is_delegated_child = _in_delegated_child_context()
if not is_gateway and not is_delegated_child:
return output
sudo_failures = [
"sudo: a password is required",
"sudo: no tty present",
"sudo: a terminal is required",
]
for failure in sudo_failures:
if failure in output:
from hermes_constants import display_hermes_home as _dhh
if is_delegated_child:
return output + (
"\n\n💡 Tip: Subagents cannot prompt for a sudo password. "
f"Add SUDO_PASSWORD to {_dhh()}/.env on the agent machine, "
"or run the command without sudo."
)
return output + f"\n\n💡 Tip: To enable sudo over messaging, add SUDO_PASSWORD to {_dhh()}/.env on the agent machine."
return output
# sudo -S rejects a bad cached/interactive password with these messages.
_SUDO_WRONG_PASSWORD_MARKERS = (
"sudo: authentication failed",
"sudo: incorrect password attempt",
"sudo: maximum 3 incorrect authentication attempts",
"sudo: 3 incorrect password attempts",
)
def _sudo_wrong_password_failure(output: str) -> bool:
"""Return True when sudo rejected a piped password."""
if not output:
return False
lowered = output.lower()
return any(marker in lowered for marker in _SUDO_WRONG_PASSWORD_MARKERS)
def _invalidate_cached_sudo_on_auth_failure(
command: str | None, output: str
) -> bool:
"""Drop a session-cached sudo password after sudo rejects it.
Env-configured ``SUDO_PASSWORD`` is left alone — that is an explicit
operator choice, not an interactive cache entry.
"""
from tools.terminal_tool import _count_real_sudo_invocations, _sudo_wrong_password_failure
if "SUDO_PASSWORD" in os.environ:
return False
if not _sudo_wrong_password_failure(output):
return False
if _count_real_sudo_invocations(command or "") == 0:
return False
if not _get_cached_sudo_password():
return False
_set_cached_sudo_password("")
return True
def _prompt_for_sudo_password(timeout_seconds: int = 45) -> str:
"""Prompt for a sudo password; "" on skip (empty Enter), timeout, or error.
Prefers the CLI-registered callback (prompt_toolkit-integrated); otherwise
reads /dev/tty (msvcrt on Windows) with echo disabled. Time spent waiting
on the human is excluded from tool deadlines via ``human_wait_window``.
"""
from tools.terminal_tool import _get_sudo_password_callback
_sudo_cb = _get_sudo_password_callback()
if _sudo_cb is not None:
try:
from tools.approval import human_wait_window
with human_wait_window():
return _sudo_cb() or ""
except Exception:
return ""
result = {"password": None, "done": False}
def read_password_thread():
"""Read password with echo disabled. Uses msvcrt on Windows, /dev/tty on Unix."""
tty_fd = None
old_attrs = None
try:
if platform.system() == "Windows":
import msvcrt
chars = []
while True:
c = msvcrt.getwch()
if c in {"\r", "\n"}:
break
if c == "\x03":
raise KeyboardInterrupt
chars.append(c)
result["password"] = "".join(chars)
else:
import termios
tty_fd = os.open("/dev/tty", os.O_RDONLY)
old_attrs = termios.tcgetattr(tty_fd)
new_attrs = termios.tcgetattr(tty_fd)
new_attrs[3] = new_attrs[3] & ~termios.ECHO
termios.tcsetattr(tty_fd, termios.TCSAFLUSH, new_attrs)
chars = []
while True:
b = os.read(tty_fd, 1)
if not b or b in {b"\n", b"\r"}:
break
chars.append(b)
result["password"] = b"".join(chars).decode("utf-8", errors="replace")
except (EOFError, KeyboardInterrupt, OSError):
result["password"] = ""
except Exception:
result["password"] = ""
finally:
if tty_fd is not None and old_attrs is not None:
try:
import termios as _termios
_termios.tcsetattr(tty_fd, _termios.TCSAFLUSH, old_attrs)
except Exception as e:
logger.debug("Failed to restore terminal attributes: %s", e)
if tty_fd is not None:
try:
os.close(tty_fd)
except Exception as e:
logger.debug("Failed to close tty fd: %s", e)
result["done"] = True
try:
os.environ["HERMES_SPINNER_PAUSE"] = "1"
time.sleep(0.2)
print()
print("┌" + "─" * 58 + "┐")
print("│ 🔐 SUDO PASSWORD REQUIRED" + " " * 30 + "│")
print("├" + "─" * 58 + "┤")
print("│ Enter password below (input is hidden), or: │")
print("│ • Press Enter to skip (command fails gracefully) │")
print(f"│ • Wait {timeout_seconds}s to auto-skip" + " " * 27 + "│")
print("└" + "─" * 58 + "┘")
print()
print(" Password (hidden): ", end="", flush=True)
password_thread = threading.Thread(target=read_password_thread, daemon=True)
password_thread.start()
from tools.approval import human_wait_window
with human_wait_window():
password_thread.join(timeout=timeout_seconds)
if result["done"]:
password = result["password"] or ""
print() # newline after hidden input
if password:
print(" ✓ Password received (cached for this session)")
else:
print(" ⏭ Skipped - continuing without sudo")
print()
sys.stdout.flush()
return password
else:
print("\n ⏱ Timeout - continuing without sudo")
print(" (Press Enter to dismiss)")
print()
sys.stdout.flush()
return ""
except (EOFError, KeyboardInterrupt):
print()
print(" ⏭ Cancelled - continuing without sudo")
print()
sys.stdout.flush()
return ""
except Exception as e:
print(f"\n [sudo prompt error: {e}] - continuing without sudo\n")
sys.stdout.flush()
return ""
finally:
if "HERMES_SPINNER_PAUSE" in os.environ:
del os.environ["HERMES_SPINNER_PAUSE"]
def _looks_like_env_assignment(token: str) -> bool:
"""Return True when *token* is a leading shell environment assignment."""
if "=" not in token or token.startswith("="):
return False
name, _value = token.split("=", 1)
return bool(re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", name))
def _read_shell_token(command: str, start: int) -> tuple[str, int]:
"""Read one shell token, preserving quotes/escapes, starting at *start*."""
i = start
n = len(command)
while i < n:
ch = command[i]
if ch.isspace() or ch in ";|&()":
break
if ch == "'":
i += 1
while i < n and command[i] != "'":
i += 1
if i < n:
i += 1
continue
if ch == '"':
i += 1
while i < n:
inner = command[i]
if inner == "\\" and i + 1 < n:
i += 2
continue
if inner == '"':
i += 1
break
i += 1
continue
if ch == "\\" and i + 1 < n:
i += 2
continue
i += 1
return command[start:i], i
def _rewrite_real_sudo_invocations(command: str) -> tuple[str, int]:
"""Rewrite only real unquoted sudo command words, not plain text mentions.
Walks the command with the shared tokenizer, tracking whether the cursor
sits at a command-start position (after newline, ``;``/``|``/``&``/``(``,
``&&``/``||``/``;;``, or a leading ``VAR=val`` assignment); comments at
command start are copied through verbatim. Returns the rewritten command
and the number of sudo invocations rewritten.
"""
out: list[str] = []
i = 0
n = len(command)
command_start = True
sudo_count = 0
while i < n:
ch = command[i]
if ch.isspace():
out.append(ch)
if ch == "\n":
command_start = True
i += 1
continue
if ch == "#" and command_start:
comment_end = command.find("\n", i)
if comment_end == -1:
out.append(command[i:])
break
out.append(command[i:comment_end])
i = comment_end
continue
if command.startswith(("&&", "||", ";;"), i):
out.append(command[i:i + 2])
i += 2
command_start = True
continue
if ch in ";|&(":
out.append(ch)
i += 1
command_start = True
continue
if ch == ")":
out.append(ch)
i += 1
command_start = False
continue
token, next_i = _read_shell_token(command, i)
if command_start and token == "sudo":
out.append("sudo -S -p ''")
sudo_count += 1
else:
out.append(token)
command_start = bool(command_start and _looks_like_env_assignment(token))
i = next_i
return "".join(out), sudo_count
def _count_real_sudo_invocations(command: str) -> int:
"""Return how many real sudo command words appear in *command*."""
return _rewrite_real_sudo_invocations(command)[1]
def _sudo_nopasswd_works() -> bool:
"""True when local sudo currently works without prompting.
Local backend only — Docker/SSH/Modal must not inherit host sudo state.
Re-probes every call (no cache) so an expired sudo timestamp can't make a
later command silently block waiting for a password.
"""
from tools.terminal_tool import _tenv
terminal_env = _tenv("TERMINAL_ENV", "local").strip().lower() or "local"
if terminal_env != "local":
return False
try:
probe = subprocess.run(
["sudo", "-n", "true"],
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=3,
check=False,
)
return probe.returncode == 0
except Exception:
return False
def _rewrite_compound_background(command: str) -> str:
"""Wrap `A && B &` (or `A || B &`) to `A && { B & }` at depth 0.
Bash binds `&&` tighter than `&`, so `A && B &` backgrounds a subshell
that runs B in the foreground and waits for it; a long-running B leaves
that subshell stuck in ``wait4`` forever, and its open stdout pipe can
keep the terminal tool from returning. The brace group keeps `&&`'s
skip-B-on-failure semantics without a fork: bash backgrounds B as a
simple command and exits immediately, orphaning B normally.
Handles redirects (``&>``, ``2>&1``) and skips quoted strings and
parenthesised subshells. Simple ``cmd &`` is left alone — it doesn't
have the subshell-wait bug.
"""
n = len(command)
i = 0
paren_depth = 0
brace_depth = 0
# Position in *command* just after the most recent `&&` / `||` at depth 0
# in the current statement; -1 when no chain operator is active.
last_chain_op_end = -1
rewrites: list[tuple[int, int]] = [] # (chain_op_end, amp_pos)
while i < n:
ch = command[i]
# Newline terminates a statement at depth 0 — reset chain state.
# Checked before the whitespace skip so we don't miss it.
if ch == "\n" and paren_depth == 0 and brace_depth == 0:
last_chain_op_end = -1
i += 1
continue
if ch.isspace():
i += 1
continue
# Comments (only at statement start — conservative: any `#` not inside
# a token ends the line). `_read_shell_token` handles quoted strings
# below so `#` inside quotes is safe.
if ch == "#":
nl = command.find("\n", i)
if nl == -1:
break
i = nl
continue
if ch == "\\" and i + 1 < n:
i += 2
continue
# Quoted tokens — consume whole string via the shared tokenizer.
if ch in {"'", '"'}:
_, next_i = _read_shell_token(command, i)
i = max(next_i, i + 1)
continue
if ch == "(":
paren_depth += 1
i += 1
continue
if ch == ")":
paren_depth = max(0, paren_depth - 1)
i += 1
continue
# Brace groups: `{ ... }` is a group (no subshell fork), and bash
# requires whitespace after `{`. We track depth so already-rewritten
# output (`A && { B & }`) is idempotent — the inner `&` is part of
# the group, not a new compound to rewrite. Also skip content inside
# the group since `A && B &` there is separately well-formed.
if ch == "{" and i + 1 < n and (command[i + 1].isspace() or command[i + 1] == "\n"):
brace_depth += 1
i += 1
continue
if ch == "}" and brace_depth > 0:
brace_depth -= 1
# Closing a group completes a compound statement; reset chain.
last_chain_op_end = -1
i += 1
continue
# Inside parens or brace groups, skip operators — they parse in their
# own scope. `(...)` subshells have the same bug class but are not the
# common agent pattern; leave for a follow-up.
if paren_depth > 0 or brace_depth > 0:
i += 1
continue
# Chain operators at depth 0
if command.startswith("&&", i) or command.startswith("||", i):
last_chain_op_end = i + 2
i += 2
continue
# Statement terminators reset the chain state
if ch == ";":
last_chain_op_end = -1
i += 1
continue
# Single `|` (pipe) starts a new pipeline stage; don't rewrite
# across it. `||` handled above.
if ch == "|":
last_chain_op_end = -1
i += 1
continue
# `&` handling: distinguish `&&`, `&>`, fd redirect (`>&`, `<&`),
# and a true backgrounding `&`.
if ch == "&":
# `&&` handled above; won't reach here
if i + 1 < n and command[i + 1] == ">":
# `&>` redirect — consume
i += 2
continue
# `>&` / `<&` fd target — look back past whitespace
j = i - 1
while j >= 0 and command[j].isspace():
j -= 1
if j >= 0 and command[j] in "<>":
i += 1
continue
# Real background operator
if last_chain_op_end >= 0:
rewrites.append((last_chain_op_end, i))
last_chain_op_end = -1
i += 1
continue
# Regular unquoted token — advance past it via the shared tokenizer
_, next_i = _read_shell_token(command, i)
i = max(next_i, i + 1)
if not rewrites:
return command
# Apply rewrites back-to-front so earlier indices remain valid.
result = command
for chain_end, amp_pos in reversed(rewrites):
# Skip whitespace right after the `&&`/`||` so the brace group
# opens flush against the inner command.
insert_pos = chain_end
while insert_pos < amp_pos and result[insert_pos].isspace():
insert_pos += 1
prefix = result[:insert_pos]
middle = result[insert_pos:amp_pos] # inner command + trailing space
suffix = result[amp_pos + 1 :]
# `{` needs a trailing space in bash; the closing `}` needs to be
# preceded by `;` or `&` — we're providing `&` from the backgrounding.
result = prefix + "{ " + middle + "& }" + suffix
return result
def _transform_sudo_command(command: str | None) -> tuple[str | None, str | None]:
"""Rewrite bare ``sudo`` to ``sudo -S -p ''`` when a password is available.
Shared by every execution environment. Returns ``(command, sudo_stdin)``:
``sudo_stdin`` is one password line per sudo invocation that the caller
must PREPEND to the process stdin (sudo -S consumes exactly one line and
passes the rest through, so it's safe alongside the caller's own
stdin_data). Backends that can't pipe stdin (modal, daytona,
vercel_sandbox) embed the password in the command string themselves.
With no password available the command is returned unchanged and
``sudo_stdin`` is None, so it fails gracefully with
"sudo: a password is required". Password sources, in order: configured
SUDO_PASSWORD, the session cache, then an interactive prompt (45s
timeout, cached on success) when a UI is reachable.
"""
from tools.terminal_tool import _get_sudo_password_callback, _prompt_for_sudo_password, _sudo_nopasswd_works
if command is None:
return None, None
transformed, sudo_count = _rewrite_real_sudo_invocations(command)
if sudo_count == 0:
return command, None
# Scope-aware read: under multiplex the process env may hold another
# profile's SUDO_PASSWORD; unscoped callers keep the os.environ read.
try:
from agent.secret_scope import UnscopedSecretError, get_secret
try:
_configured_password = get_secret("SUDO_PASSWORD")
except UnscopedSecretError:
_configured_password = os.environ.get("SUDO_PASSWORD")
except Exception:
_configured_password = os.environ.get("SUDO_PASSWORD")
has_configured_password = _configured_password is not None
sudo_password = (
_configured_password
if has_configured_password
else _get_cached_sudo_password()
)
# sudoers NOPASSWD hosts must not be forced through the prompt or the
# -S password pipe (local backend only; re-probed every call).
if not has_configured_password and not sudo_password and _sudo_nopasswd_works():
return command, None
has_sudo_prompt_callback = _get_sudo_password_callback() is not None
# delegate_task children inherit HERMES_INTERACTIVE=1 (and possibly a
# stale thread-local callback on a recycled worker) but have no user on
# the other side — they always behave as headless; configured password,
# session cache and the NOPASSWD probe still apply.
should_prompt_for_sudo = (
env_var_enabled("HERMES_INTERACTIVE") or has_sudo_prompt_callback
) and not _in_delegated_child_context()
if not has_configured_password and not sudo_password and should_prompt_for_sudo:
sudo_password = _prompt_for_sudo_password(timeout_seconds=45)
if sudo_password:
_set_cached_sudo_password(sudo_password)
if has_configured_password or sudo_password:
# Trailing newline is required: sudo -S reads one line per invocation.
# Compound commands (`sudo a && sudo b`) need one password line each.
password_line = sudo_password + "\n"
return transformed, password_line * sudo_count
return command, None