diff --git a/tools/skill_usage.py b/tools/skill_usage.py index 0c1892643b..3412d9e25e 100644 --- a/tools/skill_usage.py +++ b/tools/skill_usage.py @@ -40,10 +40,9 @@ STATE_STALE = "stale" STATE_ARCHIVED = "archived" _VALID_STATES = {STATE_ACTIVE, STATE_STALE, STATE_ARCHIVED} -# Load-bearing built-ins (by frontmatter ``name``) the curator must NEVER archive or consolidate, regardless -# of ``curator.prune_builtins``, pin state, or LLM judgment — silently archiving one turns its slash command -# into "Unknown command". Keep tiny; it is not a substitute for ``curator.prune_builtins: false``. -# (``plan`` used to live here; it is now a first-class command with no skill on disk.) +# Load-bearing built-ins (by frontmatter ``name``) the curator must NEVER archive/consolidate regardless of +# ``curator.prune_builtins``, pins or LLM judgment — archiving one turns its slash command into "Unknown +# command". Keep tiny; not a substitute for ``prune_builtins: false``. (``plan`` moved to a built-in command.) PROTECTED_BUILTIN_SKILLS: Set[str] = set() @@ -174,8 +173,7 @@ def _read_hub_installed_names() -> Set[str]: return set() names = {str(k) for k in installed} skills_dir = _skills_dir() - for entry in installed.values(): - install_path = entry.get("install_path") if isinstance(entry, dict) else None + for install_path in (e.get("install_path") for e in installed.values() if isinstance(e, dict)): if not isinstance(install_path, str) or not install_path.strip(): continue try: @@ -225,9 +223,8 @@ def _toggle_suppressed_name(skill_name: str, *, add: bool) -> None: def _iter_skill_mds(base: Path, *, local_only: bool) -> Iterator[Tuple[str, Path]]: - """``(frontmatter name, SKILL.md)`` for flat and category-nested skills under *base*, skipping metadata/VCS/ - venv/cache dirs. *local_only* also skips external skill dirs mounted below the tree — discovery may see - them, autonomous curation must not.""" + """``(frontmatter name, SKILL.md)`` for flat and nested skills under *base*, skipping metadata/VCS/venv/cache + dirs. *local_only* also skips external skill dirs mounted below the tree (discovery sees them; curation must not).""" for skill_md in base.rglob("SKILL.md"): if not (is_excluded_skill_path(skill_md) or (local_only and is_external_skill_path(skill_md))): yield _read_skill_name(skill_md, fallback=skill_md.parent.name), skill_md @@ -249,11 +246,9 @@ def list_agent_created_skill_names() -> List[str]: """Skills the curator may manage: agent-authored (``created_by: agent`` record) plus, when ``curator.prune_builtins`` is on, bundled built-ins (inactivity anchored on first sight). Never hub skills.""" prune_builtins = _prune_builtins_enabled() # read once, before the walk - - def _keep(name: str, _skill_md: Path, bundled: Set[str], usage: Dict[str, Any]) -> bool: - # Built-ins never carry a curator-managed record, so the record gate applies only to local skills. - return prune_builtins if name in bundled else _is_curator_managed_record(usage.get(name)) - return _scan_local_skills(_keep) + # Built-ins never carry a curator-managed record, so the record gate applies only to local skills. + return _scan_local_skills( + lambda name, _md, bundled, usage: prune_builtins if name in bundled else _is_curator_managed_record(usage.get(name))) def list_archived_skill_names() -> List[str]: @@ -265,20 +260,16 @@ def list_archived_skill_names() -> List[str]: def _read_skill_name(skill_md: Path, fallback: str) -> str: """The frontmatter ``name:`` field of a SKILL.md (first 4000 chars), else *fallback*.""" try: - text = skill_md.read_text(encoding="utf-8", errors="replace")[:4000] + lines = [line.strip() for line in skill_md.read_text(encoding="utf-8", errors="replace")[:4000].split("\n")] except OSError: return fallback - in_frontmatter = False - for stripped in (line.strip() for line in text.split("\n")): - if stripped == "---": - if in_frontmatter: - break - in_frontmatter = True - elif in_frontmatter and stripped.startswith("name:"): - value = stripped.split(":", 1)[1].strip().strip("\"'") - if value: - return value - return fallback + if "---" not in lines: + return fallback + block = lines[lines.index("---") + 1:] # frontmatter runs to the closing --- or (truncated) end of text + if "---" in block: + block = block[:block.index("---")] + values = (line.split(":", 1)[1].strip().strip("\"'") for line in block if line.startswith("name:")) + return next((v for v in values if v), fallback) def is_agent_created(skill_name: str) -> bool: @@ -301,9 +292,8 @@ def _external_read_only_message(skill_name: str) -> str: def is_curation_eligible(skill_name: str, skill_path: Optional[Path] = None) -> bool: - """May the curator track/archive this skill? Agent-created: yes. Bundled: only with - ``curator.prune_builtins``. Hub-installed / external-dir / protected built-ins: never (external owner). - Org-shared skills are eligible for improvement (edits stay local) but protected from ARCHIVE/DELETE elsewhere.""" + """Agent-created: yes. Bundled: only with ``curator.prune_builtins``. Hub / external-dir / protected built-ins: + never (external owner). Org-shared skills are eligible for improvement but protected from ARCHIVE/DELETE elsewhere.""" if ((skill_path is not None and is_external_skill_path(skill_path)) or is_protected_builtin(skill_name) or is_hub_installed(skill_name)): return False @@ -314,9 +304,8 @@ def is_curation_eligible(skill_name: str, skill_path: Optional[Path] = None) -> def _is_curator_managed_record(record: Any) -> bool: - """The on-disk ``created_by`` field reads like provenance but is a curator-management OPT-IN policy flag: - ``"agent"`` means "curator-managed", not proof of authorship (the user can flip it via ``hermes curator - adopt``). The name is kept because it is already in every user's ``.usage.json``.""" + """``created_by`` reads like provenance but is a curator-management OPT-IN flag: ``"agent"`` means "curator-managed", + not proof of authorship (``hermes curator adopt`` flips it). Name kept: it is in every user's ``.usage.json``.""" return isinstance(record, dict) and (record.get("created_by") == "agent" or record.get("agent_created") is True) @@ -326,30 +315,26 @@ def is_curator_managed(skill_name: str) -> bool: def list_unmanaged_skill_names() -> List[str]: - """Curation-ELIGIBLE skills with no provenance marker: records predating ``created_by``, or FOREGROUND - ``skill_manage(action="create")`` results (skills a user asks for belong to the user). Invisible to - ``curated_report()`` and every automatic transition; surfaced by ``hermes curator status`` and handed over - only by explicit ``hermes curator adopt`` — provenance is a declaration, never inferred from activity.""" - def _keep(name: str, skill_md: Path, bundled: Set[str], usage: Dict[str, Any]) -> bool: - return name not in bundled and not _is_curator_managed_record(usage.get(name)) and is_curation_eligible(name, skill_md) - return _scan_local_skills(_keep) + """Curation-ELIGIBLE skills with no provenance marker (records predating ``created_by``, or FOREGROUND + ``skill_manage`` creates — those belong to the user). Invisible to ``curated_report()`` and automatic + transitions; surfaced by ``hermes curator status``, handed over only by explicit ``hermes curator adopt`` — + provenance is a declaration, never inferred from activity.""" + return _scan_local_skills( + lambda name, md, bundled, usage: name not in bundled and not _is_curator_managed_record(usage.get(name)) + and is_curation_eligible(name, md)) def unmanaged_report() -> List[Dict[str, Any]]: - """Rows for :func:`list_unmanaged_skill_names`. ``has_provenance_key`` is False when the record has no - ``created_by`` key (pre-dates the mechanism), True when present but unset (foreground create) — explains - WHY a skill is unmanaged; not a signal to adopt on.""" + """Rows for :func:`list_unmanaged_skill_names`. ``has_provenance_key`` False = no ``created_by`` key (pre-dates + the mechanism), True = present but unset (foreground create); explains WHY, not a signal to adopt on.""" usage = load_usage() - return [ - _report_row(name, raw, has_provenance_key=isinstance(raw, dict) and "created_by" in raw, - has_record=isinstance(raw, dict)) - for name, raw in ((n, usage.get(n)) for n in list_unmanaged_skill_names())] + return [_report_row(n, usage.get(n), has_provenance_key="created_by" in usage.get(n, {}), has_record=n in usage) + for n in list_unmanaged_skill_names()] def adopt_skill(skill_name: str) -> Tuple[bool, str]: - """Hand *skill_name* to the curator by user declaration — writes the same ``created_by: agent`` marker the - background review fork writes. The inactivity clock is NOT reset. Refuses hub-installed, external, bundled - and protected built-in skills. Returns (ok, message).""" + """User-declared handover: writes the same ``created_by: agent`` marker the review fork writes; the inactivity + clock is NOT reset. Refuses hub, external, bundled and protected skills. Returns (ok, message).""" if not skill_name: return False, "no skill name given" if is_protected_builtin(skill_name): @@ -428,9 +413,8 @@ def get_record(skill_name: str) -> Dict[str, Any]: def _locked_update( skill_name: str, op: Callable[[Dict[str, Dict[str, Any]]], Tuple[Any, bool]], fail_log: str, guard: Optional[Callable[[], bool]] = None) -> Any: - """Run *op(data) -> (result, dirty)* on the usage map under the file lock; save only when dirty. *guard* - runs before the lock is taken. Returns result, or None when the guard failed, the save did not land, or - anything raised (logged at DEBUG via *fail_log*).""" + """Run *op(data) -> (result, dirty)* under the file lock, saving only when dirty; *guard* runs before locking. + None when the guard failed, the save did not land, or anything raised (DEBUG-logged via *fail_log*).""" try: if guard is not None and not guard(): return None @@ -449,8 +433,8 @@ def seed_record_if_missing(skill_name: str) -> None: if not skill_name or not is_curation_eligible(skill_name): return - def _seed(data): - if missing := not isinstance(data.get(skill_name), dict): + def _seed(data): # load_usage() already dropped non-dict values, so "missing" == key absent + if missing := skill_name not in data: data[skill_name] = _empty_record() return None, missing _locked_update(skill_name, _seed, "skill_usage.seed_record_if_missing(%s) failed: %s") @@ -462,12 +446,9 @@ def _mutate(skill_name: str, mutator, *, require_curation_eligible: bool = False ``require_curation_eligible=True`` so they never write state onto a skill the curator can't manage.""" if not skill_name: return None - - def _apply(data): - rec = data[skill_name] = data[skill_name] if isinstance(data.get(skill_name), dict) else _empty_record() - return mutator(rec), True guard = (lambda: is_curation_eligible(skill_name)) if require_curation_eligible else None - return _locked_update(skill_name, _apply, "skill_usage._mutate(%s) failed: %s", guard) + return _locked_update(skill_name, lambda data: (mutator(data.setdefault(skill_name, _empty_record())), True), + "skill_usage._mutate(%s) failed: %s", guard) def _set_field(skill_name: str, key: str, value: Any) -> bool: @@ -556,8 +537,7 @@ def bump_patch( _bump(rec, "patch_count", "last_patched_at") rec["patch_generation"] = _non_negative_int(rec.get("patch_generation")) + 1 return {"created_by": rec.get("created_by")} - lifecycle_action = "patched" if action == "patch" else "edited" - _mutate_and_emit(skill_name, lifecycle_action, _apply, task_id=task_id, session_id=session_id) + _mutate_and_emit(skill_name, "patched" if action == "patch" else "edited", _apply, task_id=task_id, session_id=session_id) def record_created( @@ -633,9 +613,8 @@ def forget(skill_name: str) -> None: # --- Archive / restore --- def _relocate(src: Path, dest: Path, skill_name: str, action: str, **capture_kwargs: Any) -> Tuple[bool, str]: - """Move *src* to *dest* for *action* ("archive" | "restore") with an audit-ledger entry around it, then - apply the suppression + state side effects. Ledger capture is best-effort and never blocks the move; the - rename falls back to shutil.move across devices. Returns (ok, message).""" + """Move *src* to *dest* for *action* ("archive" | "restore") inside an audit-ledger entry, then apply the + suppression + state side effects. Ledger capture is best-effort; rename falls back to shutil.move across devices.""" try: from tools import skill_ledger as _ledger _ledger_before = _ledger.capture_before(src, **capture_kwargs) @@ -693,10 +672,9 @@ def archive_skill(skill_name: str) -> Tuple[bool, str]: def restore_skill(skill_name: str) -> Tuple[bool, str]: - """Move an archived skill back to the flat top-level layout (category nesting is NOT reconstructed). - - Refuses names that now collide with a hub skill, or a bundled built-in unless ``curator.prune_builtins`` - is on (then restoring is the documented way to lift a prune) — either would shadow the upstream copy.""" + """Move an archived skill back to the flat top-level layout (category nesting is NOT reconstructed). Refuses + names now colliding with a hub skill, or a bundled built-in unless ``curator.prune_builtins`` is on (then + restoring is the documented way to lift a prune) — either would shadow the upstream copy.""" if is_hub_installed(skill_name): return False, f"skill '{skill_name}' is now hub-installed; restore would shadow the upstream version" if is_bundled(skill_name) and not _prune_builtins_enabled(): @@ -704,7 +682,6 @@ def restore_skill(skill_name: str) -> Tuple[bool, str]: archive_root = _archive_dir() if not archive_root.exists(): return False, "no archive directory" - # Exact name first (recursive: older archive paths left nested layouts), then the timestamped-duplicate # fallback. Only "-YYYYMMDDHHMMSS" (14 digits) counts — a bare startswith("-") would let # restoring "git" pull an archived "git-helpers" out and rename it, destroying the sibling's only copy. @@ -748,21 +725,15 @@ def _find_external_skill_dir(skill_name: str) -> Optional[Path]: # --- Reporting — for the curator CLI / slash command --- def curated_report() -> List[Dict[str, Any]]: - """One backfilled row per curator-managed skill with ``provenance`` ('agent'|'bundled'|'hub') and - ``_persisted`` (a real record exists — the curator seeds the inactivity clock for fresh backfills instead of - treating them as ancient). Bundled skills only with ``curator.prune_builtins``; hub skills never.""" + """One backfilled row per curator-managed skill with ``provenance`` ('agent'|'bundled'|'hub') and ``_persisted`` + (real record exists; fresh backfills get their inactivity clock seeded instead of counting as ancient).""" data = load_usage() names = set(list_agent_created_skill_names()) # A pinned-but-unmanaged skill must stay visible or its pin silently vanishes from `curator status`; the # local-dir guard keeps stale records for deleted dirs from rendering as ghost rows (`curator unpin` cleans up). - names.update( - name for name, rec in data.items() - if isinstance(rec, dict) and rec.get("pinned") and is_curation_eligible(name) and _find_skill_dir(name) is not None - ) - rows = [_report_row(name, data.get(name), _persisted=isinstance(data.get(name), dict)) for name in sorted(names)] - for row in rows: - row["provenance"] = provenance(row["name"]) - return rows + names.update(name for name, rec in data.items() + if rec.get("pinned") and is_curation_eligible(name) and _find_skill_dir(name) is not None) + return [_report_row(n, data.get(n), _persisted=n in data, provenance=provenance(n)) for n in sorted(names)] def provenance(skill_name: str) -> str: @@ -778,5 +749,4 @@ def usage_report() -> List[Dict[str, Any]]: return [] data = load_usage() names = sorted({name for name, _skill_md in _iter_skill_mds(base, local_only=False)}) - return [_report_row(n, data.get(n), provenance=provenance(n), _persisted=isinstance(data.get(n), dict)) - for n in names] + return [_report_row(n, data.get(n), provenance=provenance(n), _persisted=n in data) for n in names] diff --git a/tools/skillevaluator_scan.py b/tools/skillevaluator_scan.py index 21d6f82b39..53cbc412ca 100644 --- a/tools/skillevaluator_scan.py +++ b/tools/skillevaluator_scan.py @@ -77,9 +77,7 @@ def tier1_advisory_enabled() -> bool: try: from hermes_cli.config import load_config skills_cfg = load_config().get("skills") or {} - if not isinstance(skills_cfg, dict): - return True - value = skills_cfg.get("tier1_advisory", True) + value = skills_cfg.get("tier1_advisory", True) if isinstance(skills_cfg, dict) else True if isinstance(value, str): return value.strip().lower() not in ("false", "0", "no", "off") return bool(value) diff --git a/tools/skills_guard.py b/tools/skills_guard.py index 6bdc2d3cdf..4f81f8916e 100644 --- a/tools/skills_guard.py +++ b/tools/skills_guard.py @@ -12,6 +12,7 @@ import re import fnmatch import hashlib import json +from contextlib import suppress from dataclasses import asdict, dataclass, field from datetime import datetime, timezone from pathlib import Path @@ -20,21 +21,15 @@ from typing import List, Tuple SCANNER_VERSION = "skills-guard-v2" -TRUSTED_REPOS = { - "openai/skills", - "anthropics/skills", - "huggingface/skills", - # NVIDIA-verified: each entry ships a signed `skill.oms.sig` + governance `skill-card.md`. - "NVIDIA/skills", -} +# NVIDIA-verified skills each ship a signed `skill.oms.sig` + governance `skill-card.md`. +TRUSTED_REPOS = {"openai/skills", "anthropics/skills", "huggingface/skills", "NVIDIA/skills"} INSTALL_POLICY = { # safe caution dangerous "builtin": ("allow", "allow", "allow"), "trusted": ("allow", "allow", "block"), "community": ("allow", "block", "block"), - # "ask" surfaces as an error to the agent, which can retry without the flagged content. Only - # consulted when skills.guard_agent_created is on (skill_manager_tool._guard_agent_created_enabled). + # "ask" = error to the agent (retry without the flagged content); only when skills.guard_agent_created is on. "agent-created": ("allow", "allow", "ask"), } @@ -83,11 +78,10 @@ _OTHER_AGENT_CONFIG_FILES = r'\.(?:claude/settings|codex/config)[\w.]*' def _shell_write_re(file_alt: str) -> str: - """Mechanical shell write into *file_alt*: ``>``/``>>`` redirection, ``sed -i``, ``tee`` (target as - immediate argument, so ``| tee output | AGENTS.md |`` table cells miss), ``cp``/``mv`` with the file in - destination position (a source arg is required, so ``cp AGENTS.md backup/`` — a read — misses; - ``AGENTS.md.bak`` is not the file). A single ``>`` needs a preceding word/quote/paren char so - blockquotes (``> text``) and arrows (``-> file``) miss.""" + """Mechanical shell write into *file_alt*: ``>``/``>>``, ``sed -i``, ``tee`` (target as immediate argument, so + ``| tee output | AGENTS.md |`` cells miss), ``cp``/``mv`` with the file as destination (a source arg is required, + so ``cp AGENTS.md backup/`` misses; ``AGENTS.md.bak`` is not the file). A single ``>`` needs a preceding + word/quote/paren char so blockquotes (``> text``) and arrows (``-> file``) miss.""" return ( rf'(?:>>|[\w"\'`)\]]\s*>)\s*[~\w./-]*{file_alt}(?!\.?\w)' rf'|\bsed\b[^\n]*\s(?:-[A-Za-z]*i[A-Za-z]*|--in-place)\b[^\n]*{file_alt}(?!\.?\w)' @@ -97,10 +91,9 @@ def _shell_write_re(file_alt: str) -> str: def _prose_modify_re(file_alt: str) -> str: - """Prose instructing modification of *file_alt*: an imperative-position verb (line start / bullet), or - a mid-line verb strengthened by a directive marker ("you must", "please", "make sure to"). - Descriptive prose ("skills that edit AGENTS.md") matches neither; the verb→file gap forbids commas so - enumerations ("Write or refactor skills, AGENTS.md, CLAUDE.md") miss.""" + """Prose instructing modification of *file_alt*: an imperative-position verb (line start / bullet), or a mid-line + verb with a directive marker ("you must", "please", "make sure to"). Descriptive prose ("skills that edit + AGENTS.md") misses; the verb→file gap forbids commas so enumerations ("Write skills, AGENTS.md, CLAUDE.md") miss.""" return ( rf'^\s*(?:[-*+]\s+|\d+[.)]\s+)?{MODIFY_VERB_RE}[^\n,]{{0,80}}?{file_alt}\b' rf'|(?:\byou\s+(?:must|should|need\s+to)\s+|\bplease\s+' @@ -397,11 +390,9 @@ def _unicode_char_name(char: str) -> str: def _compute_docstring_lines(lines: list) -> set: - """1-indexed line numbers inside (or on the boundary of) triple-quoted strings. - - ``in_docstring`` toggles on each line with an odd count of a marker; opening, interior, closing and - self-contained single-line docstrings are all included so ``os.environ`` in prose is not scored. - Heuristic (ignores a triple quote inside a string literal) but covers the common false-positive shapes.""" + """1-indexed line numbers inside (or on the boundary of) triple-quoted strings: opening, interior, closing and + self-contained one-line docstrings all count, so ``os.environ`` in prose is not scored. Heuristic (ignores a + triple quote inside a string literal) but covers the common false-positive shapes.""" doc_lines: set = set() in_docstring = False for i, line in enumerate(lines): @@ -413,8 +404,6 @@ def _compute_docstring_lines(lines: list) -> set: return doc_lines -# --- Scanning functions ----------------------------------------------------- - def scan_file(file_path: Path, rel_path: str = "") -> List[Finding]: """Scan one file for threat patterns and invisible unicode. *rel_path* is the display path (defaults to the file name). Regex findings dedupe per pattern per line; invisible chars yield one per line.""" @@ -431,10 +420,9 @@ def scan_file(file_path: Path, rel_path: str = "") -> List[Finding]: for pattern, pid, severity, category, description in _COMPILED_THREAT_PATTERNS: for i, line in enumerate(lines, start=1): if i not in docstring_lines and pattern.search(line): - matched_text = line.strip() - if len(matched_text) > 120: - matched_text = matched_text[:117] + "..." - findings.append(Finding(pid, severity, category, rel_path, i, matched_text, description)) + text = line.strip() + findings.append(Finding(pid, severity, category, rel_path, i, + text if len(text) <= 120 else text[:117] + "...", description)) for i, line in enumerate(lines, start=1): char = next((c for c in INVISIBLE_CHARS if c in line), None) if char is not None: @@ -446,11 +434,9 @@ def scan_file(file_path: Path, rel_path: str = "") -> List[Finding]: def scan_skill(skill_path: Path, source: str = "community") -> ScanResult: - """Structural checks + pattern scan of every text file in a skill dir (or a single file). - - A `.skillignore` / `.clawhubignore` (gitignore-style) excludes dev/docs artifacts from BOTH the - structural checks and the pattern scan; the ignore file itself is always excluded and `SKILL.md` can - never be un-ignored. *source* (e.g. "openai/skills") resolves the trust level.""" + """Structural checks + pattern scan of every text file in a skill dir (or a single file). A `.skillignore` / + `.clawhubignore` (gitignore-style) excludes dev/docs artifacts from BOTH passes; the ignore file itself is + always excluded and `SKILL.md` can never be un-ignored. *source* (e.g. "openai/skills") sets the trust level.""" skill_name = skill_path.name trust_level = _resolve_trust_level(source) all_findings: List[Finding] = [] @@ -472,11 +458,9 @@ def scan_skill(skill_path: Path, source: str = "community") -> ScanResult: def _content_digest(skill_path: Path) -> str: - """Canonical SHA-256 over (POSIX relative path, file bytes), ORDERED by the rel-path string. - - Sorting Paths diverged on Windows (case-insensitive normcase) from ``tools.skills_hub.bundle_content_hash``, - which sorts plain strings — every installed skill then reported ``update_available`` forever. Sorting the - posix strings keeps the digest OS-independent and byte-symmetric with the bundle side.""" + """Canonical SHA-256 over (POSIX relative path, file bytes), ORDERED by the rel-path STRING: sorting Paths is + case-insensitive on Windows and diverged from ``tools.skills_hub.bundle_content_hash`` (plain-string sort), so + every installed skill reported ``update_available`` forever. String order keeps both sides byte-symmetric.""" h = hashlib.sha256() if not skill_path.is_dir(): h.update(skill_path.read_bytes()) @@ -511,28 +495,23 @@ def scan_skill_cached( cached = json.loads(cache_file.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): cached = None - if (isinstance(cached, dict) and cached.get("bundle_hash") == bundle_hash - and cached.get("scanner_version") == SCANNER_VERSION - and cached.get("source") == source and cached.get("source_url") == source_url): + expected = {"bundle_hash": bundle_hash, "scanner_version": SCANNER_VERSION, "source": source, "source_url": source_url} + if isinstance(cached, dict) and all(cached.get(k) == v for k, v in expected.items()): result = ScanResult( skill_name=skill_path.name, source=source, trust_level=cached["trust_level"], verdict=cached["verdict"], findings=[Finding(**item) for item in cached.get("findings", [])], scanned_at=cached["scanned_at"], summary=cached.get("summary", "")) - result.scan_provenance = provenance = {**cached, "fresh": False} - return result, provenance - - result = scan_skill(skill_path, source=source) - findings = [asdict(item) for item in result.findings] - provenance = { - "source": source, "source_url": source_url, "bundle_hash": bundle_hash, "scanner_version": SCANNER_VERSION, - "verdict": result.verdict, "trust_level": result.trust_level, "findings": findings, - "rules": sorted({item["pattern_id"] for item in findings}), - "scanned_at": result.scanned_at, "summary": result.summary, "fresh": True} - try: - cache_root.mkdir(parents=True, exist_ok=True) - cache_file.write_text(json.dumps(provenance, indent=2) + "\n", encoding="utf-8") - except OSError: - pass + provenance = {**cached, "fresh": False} + else: + result = scan_skill(skill_path, source=source) + findings = [asdict(item) for item in result.findings] + provenance = { + **expected, "verdict": result.verdict, "trust_level": result.trust_level, "findings": findings, + "rules": sorted({item["pattern_id"] for item in findings}), + "scanned_at": result.scanned_at, "summary": result.summary, "fresh": True} + with suppress(OSError): + cache_root.mkdir(parents=True, exist_ok=True) + cache_file.write_text(json.dumps(provenance, indent=2) + "\n", encoding="utf-8") result.scan_provenance = provenance return result, provenance @@ -572,8 +551,6 @@ def format_scan_report(result: ScanResult) -> str: return "\n".join(lines) -# --- Structural checks ------------------------------------------------------ - def _check_structure(skill_dir: Path, ignore=None) -> List[Finding]: """Structural anomalies: file count, total size, binary/executable files, symlinks escaping the skill dir, oversized files. *ignore(rel_path) -> bool* excludes paths from every count and finding.""" @@ -583,14 +560,10 @@ def _check_structure(skill_dir: Path, ignore=None) -> List[Finding]: def add(pid: str, severity: str, category: str, rel: str, match: str, description: str) -> None: findings.append(Finding(pid, severity, category, rel, 0, match, description)) - - file_count = 0 - total_size = 0 + file_count = total_size = 0 for f in skill_dir.rglob("*"): - if not f.is_file() and not f.is_symlink(): - continue rel = str(f.relative_to(skill_dir)) - if ignore(rel): + if not (f.is_file() or f.is_symlink()) or ignore(rel): continue file_count += 1 if f.is_symlink(): @@ -626,8 +599,6 @@ def _check_structure(skill_dir: Path, ignore=None) -> List[Finding]: return findings -# --- Internal helpers ------------------------------------------------------- - # `.skillignore` is Hermes-native; `.clawhubignore` is honored for skills published through ClawHub. _SKILL_IGNORE_FILENAMES = (".skillignore", ".clawhubignore") _ALWAYS_IGNORED_NAMES = set(_SKILL_IGNORE_FILENAMES) @@ -635,11 +606,10 @@ _NEVER_IGNORABLE = {"SKILL.md"} def _load_skill_ignore(skill_dir: Path): - """Build ``ignore(rel_posix_path) -> bool`` from a skill's `.skillignore` / `.clawhubignore`. - - gitignore basics: blank lines and ``#`` comments skipped; trailing ``/`` marks a directory (matches it - and everything under it); ``*``/``?`` globs via fnmatch on the full relative path and each segment; - leading ``/`` anchors to the skill root. Ignore files are always excluded; ``SKILL.md`` never is.""" + """Build ``ignore(rel_posix_path) -> bool`` from `.skillignore` / `.clawhubignore`. gitignore basics: blank + lines and ``#`` comments skipped; trailing ``/`` = directory (it and everything under it); ``*``/``?`` globs via + fnmatch on the full path and each segment; leading ``/`` anchors to the root. Ignore files always excluded; + ``SKILL.md`` never.""" patterns: List[str] = [] for ig in (skill_dir / name for name in _SKILL_IGNORE_FILENAMES): try: diff --git a/tools/skills_tool.py b/tools/skills_tool.py index 279454f225..e359190225 100644 --- a/tools/skills_tool.py +++ b/tools/skills_tool.py @@ -330,6 +330,7 @@ def _resolve_plugin_skill(name, file_path, task_id, preprocess): active_memory_provider = None try: from plugins.memory import _get_active_memory_provider, _prune_inactive_memory_provider_skills + active_memory_provider = _get_active_memory_provider() _prune_inactive_memory_provider_skills(active_memory_provider) except Exception as exc: @@ -356,8 +357,7 @@ def _resolve_plugin_skill(name, file_path, task_id, preprocess): return _serve_plugin_skill( plugin_skill_md, namespace, bare, file_path=file_path, preprocess=preprocess, session_id=task_id), None - available = pm.list_plugin_skills(namespace) - if available: # plugin exists but this specific skill is missing + if available := pm.list_plugin_skills(namespace): # plugin exists but this specific skill is missing return _fail( f"Skill '{bare}' not found in plugin '{namespace}'.", available_skills=[f"{namespace}:{s}" for s in available], @@ -493,8 +493,7 @@ def _skill_readiness(frontmatter: Dict[str, Any], skill_name: str) -> Tuple[dict setup_needed = bool(remaining) # Only vars actually set pass through to sandboxed execution (execute_code, terminal). - available_env_names = [e["name"] for e in required_env_vars if e["name"] not in remaining] - if available_env_names: + if available_env_names := [e["name"] for e in required_env_vars if e["name"] not in remaining]: try: from tools.env_passthrough import register_env_passthrough @@ -515,6 +514,7 @@ def _skill_readiness(frontmatter: Dict[str, Any], skill_name: str) -> Tuple[dict except Exception: logger.debug("Could not register credential files for skill %s", skill_name, exc_info=True) + status = SkillReadinessStatus.SETUP_NEEDED if setup_needed else SkillReadinessStatus.AVAILABLE fields = { "required_environment_variables": required_env_vars, "required_commands": [], @@ -523,18 +523,15 @@ def _skill_readiness(frontmatter: Dict[str, Any], skill_name: str) -> Tuple[dict "missing_required_commands": [], "setup_needed": setup_needed, "setup_skipped": capture_result["setup_skipped"], - "readiness_status": ( - SkillReadinessStatus.SETUP_NEEDED if setup_needed else SkillReadinessStatus.AVAILABLE - ).value} + "readiness_status": status.value} extras: dict = {} - setup_help = next((e["help"] for e in required_env_vars if e.get("help")), None) - if setup_help: + if setup_help := next((e["help"] for e in required_env_vars if e.get("help")), None): extras["setup_help"] = setup_help if capture_result["gateway_setup_hint"]: extras["gateway_setup_hint"] = capture_result["gateway_setup_hint"] if setup_needed: missing_items = [f"env ${n}" for n in remaining] + [f"file {p}" for p in missing_cred_files] - setup_note = _build_setup_note(SkillReadinessStatus.SETUP_NEEDED, missing_items, setup_help) + setup_note = _build_setup_note(status, missing_items, setup_help) if _is_remote_env_backend(backend) and setup_note: setup_note = f"{setup_note} {backend.upper()}-backed skills need these requirements available inside the remote environment as well." if setup_note: @@ -667,8 +664,8 @@ def skill_view( # tags/related_skills: metadata.hermes.* (agentskills.io) first, then top-level. metadata = frontmatter.get("metadata") hermes_meta = (metadata.get("hermes", {}) or {}) if isinstance(metadata, dict) else {} - tags = _parse_tags(hermes_meta.get("tags") or frontmatter.get("tags", "")) - related_skills = _parse_tags(hermes_meta.get("related_skills") or frontmatter.get("related_skills", "")) + tags, related_skills = ( + _parse_tags(hermes_meta.get(k) or frontmatter.get(k, "")) for k in ("tags", "related_skills")) linked_files = _skill_linked_files(skill_dir) try: @@ -678,10 +675,8 @@ def skill_view( skill_name = frontmatter.get("name", skill_md.stem if not skill_dir else skill_dir.name) readiness, readiness_extras = _skill_readiness(frontmatter, skill_name) - rendered_content = content - if preprocess: - rendered_content = _preprocess_skill( - content, skill_dir, task_id, "Could not preprocess skill content for %s", skill_name) + rendered_content = content if not preprocess else _preprocess_skill( + content, skill_dir, task_id, "Could not preprocess skill content for %s", skill_name) org_provenance = None if skill_dir: try: diff --git a/tools/skills_tool_plugin.py b/tools/skills_tool_plugin.py index 392997565a..ff7b22cd4f 100644 --- a/tools/skills_tool_plugin.py +++ b/tools/skills_tool_plugin.py @@ -67,8 +67,7 @@ def _available_skill_files(skill_dir: Path) -> Dict[str, List[str]]: def _serve_skill_file( skill_root: Path, file_path: str, label: str, *, hint: str | None = None, - list_available: bool = False, read_error_prefix: bool = False, mark_read: bool = False, -) -> str: + list_available: bool = False, read_error_prefix: bool = False, mark_read: bool = False) -> str: """Serve one linked file from a skill directory as a skill_view JSON result. ``hint`` decorates traversal/containment errors and ``list_available`` adds the @@ -130,8 +129,7 @@ def _preprocess_skill(content: str, skill_dir, session_id, debug_msg: str, *args def _serve_plugin_skill( skill_md: Path, namespace: str, bare: str, file_path: str | None = None, *, - preprocess: bool = True, session_id: str | None = None, -) -> str: + preprocess: bool = True, session_id: str | None = None) -> str: """Read a plugin-provided skill, apply guards, return JSON.""" from hermes_cli.plugins import _get_disabled_plugins, get_plugin_manager from tools import skills_tool as _st diff --git a/tools/skills_tool_setup.py b/tools/skills_tool_setup.py index a37c0b2193..159adb6fb9 100644 --- a/tools/skills_tool_setup.py +++ b/tools/skills_tool_setup.py @@ -82,8 +82,7 @@ def _normalize_setup_metadata(frontmatter: Dict[str, Any]) -> Dict[str, Any]: "env_var": env_var, "prompt": str(item.get("prompt") or f"Enter value for {env_var}").strip(), "secret": bool(item.get("secret", True))} - provider_url = str(item.get("provider_url") or item.get("url") or "").strip() - if provider_url: + if provider_url := str(item.get("provider_url") or item.get("url") or "").strip(): entry["provider_url"] = provider_url collect_secrets.append(entry) return {"help": _clean_str(setup.get("help")), "collect_secrets": collect_secrets} @@ -104,12 +103,10 @@ def _get_required_environment_variables( normalized: Dict[str, Any] = { "name": env_name, "prompt": str(entry.get("prompt") or f"Enter value for {env_name}").strip()} - help_text = _clean_str( - entry.get("help") or entry.get("provider_url") or entry.get("url") or setup.get("help")) - if help_text: + if help_text := _clean_str( + entry.get("help") or entry.get("provider_url") or entry.get("url") or setup.get("help")): normalized["help"] = help_text - required_for = _clean_str(entry.get("required_for")) - if required_for: + if required_for := _clean_str(entry.get("required_for")): normalized["required_for"] = required_for if entry.get("optional"): normalized["optional"] = True @@ -158,10 +155,7 @@ def _capture_required_environment_variables( setup_skipped = False remaining_names: List[str] = [] for entry in missing_entries: - metadata = {"skill_name": skill_name} - for k in ("help", "required_for"): - if entry.get(k): - metadata[k] = entry[k] + metadata = {"skill_name": skill_name, **{k: entry[k] for k in ("help", "required_for") if entry.get(k)}} try: callback_result = callback(entry["name"], entry["prompt"], metadata) except Exception: diff --git a/tools/transcription_tools.py b/tools/transcription_tools.py index a93d28bdc1..e0292f505c 100644 --- a/tools/transcription_tools.py +++ b/tools/transcription_tools.py @@ -673,9 +673,7 @@ def transcribe_audio( shutil.rmtree(cleanup_dir, ignore_errors=True) -def transcribe_audio_local_fallback( - file_path: str, model: Optional[str] = None -) -> Dict[str, Any]: +def transcribe_audio_local_fallback(file_path: str, model: Optional[str] = None) -> Dict[str, Any]: """Try an already-installed local STT backend without changing config. Passive inbound-media recovery after the configured provider failed: never diff --git a/tools/tts_streaming.py b/tools/tts_streaming.py index 823e48aec1..a84625048f 100644 --- a/tools/tts_streaming.py +++ b/tools/tts_streaming.py @@ -335,10 +335,7 @@ class XAIStreamer(StreamingTTSProvider): return asyncio.run(self._drain_async(text)) async def _drain_async(self, text: str) -> List[bytes]: - frames: List[bytes] = [] - async for frame in self._async_frames(text): - frames.append(frame) - return frames + return [frame async for frame in self._async_frames(text)] async def _async_frames(self, text: str): import json as _json diff --git a/tools/tts_tool.py b/tools/tts_tool.py index 0dd14e086a..5485725b6d 100644 --- a/tools/tts_tool.py +++ b/tools/tts_tool.py @@ -46,120 +46,62 @@ def _resolve_provider_key(env_var: str, provider_id: str) -> str: from tools.managed_tool_gateway import resolve_managed_tool_gateway # noqa: F401 — seam patched by tests from tools.tts_command_provider import ( # noqa: F401 — historical names re-exported - BUILTIN_TTS_PROVIDERS, - COMMAND_TTS_OUTPUT_FORMATS, - DEFAULT_COMMAND_TTS_MAX_TEXT_LENGTH, - DEFAULT_COMMAND_TTS_OUTPUT_FORMAT, - DEFAULT_COMMAND_TTS_TIMEOUT_SECONDS, - _configured_command_tts_output_path, - _generate_command_tts, - _get_command_tts_output_format, - _get_command_tts_timeout, - _get_named_provider_config, - _is_command_provider_config, - _is_command_tts_voice_compatible, - _iter_command_providers, - _resolve_command_provider_config, + BUILTIN_TTS_PROVIDERS, COMMAND_TTS_OUTPUT_FORMATS, DEFAULT_COMMAND_TTS_MAX_TEXT_LENGTH, + DEFAULT_COMMAND_TTS_OUTPUT_FORMAT, DEFAULT_COMMAND_TTS_TIMEOUT_SECONDS, + _configured_command_tts_output_path, _generate_command_tts, _get_command_tts_output_format, + _get_command_tts_timeout, _get_named_provider_config, _is_command_provider_config, + _is_command_tts_voice_compatible, _iter_command_providers, _resolve_command_provider_config, command_env_passthrough as _command_provider_env_passthrough, render_command_template as _render_command_tts_template, - run_command_provider as _run_command_tts, - shell_quote_context as _shell_quote_context, + run_command_provider as _run_command_tts, shell_quote_context as _shell_quote_context, ) from tools.tool_backend_helpers import ( # noqa: F401 — seams patched by tests, resolved via tts_tool_openai._origin() - NOUS_MANAGED_PROVIDER, - managed_nous_tools_enabled, - read_selection, - resolve_openai_audio_api_key, + NOUS_MANAGED_PROVIDER, managed_nous_tools_enabled, read_selection, resolve_openai_audio_api_key, ) from tools.tts_tool_delivery import ( # noqa: F401 — historical names re-exported - FALLBACK_MAX_TEXT_LENGTH, - PROVIDER_MAX_TEXT_LENGTH, - _resolve_max_text_length, - AudioDeliveryProfile, - _build_audio_delivery_files, - _concat_audio_files, - _convert_to_opus, - _pack_audio_files_for_delivery, - _repair_ogg_container, - _resolve_audio_delivery_profile, - _sniff_audio_container, - _split_oversized_sentence, - _split_text_for_tts, - _wrap_pcm_as_wav, + FALLBACK_MAX_TEXT_LENGTH, PROVIDER_MAX_TEXT_LENGTH, _resolve_max_text_length, + AudioDeliveryProfile, _build_audio_delivery_files, _concat_audio_files, _convert_to_opus, + _pack_audio_files_for_delivery, _repair_ogg_container, _resolve_audio_delivery_profile, + _sniff_audio_container, _split_oversized_sentence, _split_text_for_tts, _wrap_pcm_as_wav, ) from tools.tts_tool_providers import ( # noqa: F401 — historical names re-exported - DEFAULT_ELEVENLABS_MODEL_ID, - DEFAULT_ELEVENLABS_VOICE_ID, - DEFAULT_GEMINI_TTS_MODEL, - DEFAULT_GEMINI_TTS_VOICE, - DEFAULT_MINIMAX_BASE_URL, - DEFAULT_MINIMAX_CN_BASE_URL, - TTS_RESPONSE_BODY_LIMIT_BYTES, - _XAI_FIRST_SENTENCE_RE, - _XAI_INLINE_SPEECH_TAGS, - _XAI_WRAPPING_SPEECH_TAGS, - _apply_xai_auto_speech_tags, - _elevenlabs_environment_kwargs, - _generate_edge_tts, - _generate_elevenlabs, - _generate_gemini_tts, - _generate_minimax_tts, - _generate_mistral_tts, - _generate_xai_tts, - _resolve_minimax_tts_runtime, + DEFAULT_ELEVENLABS_MODEL_ID, DEFAULT_ELEVENLABS_VOICE_ID, DEFAULT_GEMINI_TTS_MODEL, + DEFAULT_GEMINI_TTS_VOICE, DEFAULT_MINIMAX_BASE_URL, DEFAULT_MINIMAX_CN_BASE_URL, + TTS_RESPONSE_BODY_LIMIT_BYTES, _XAI_FIRST_SENTENCE_RE, _XAI_INLINE_SPEECH_TAGS, + _XAI_WRAPPING_SPEECH_TAGS, _apply_xai_auto_speech_tags, _elevenlabs_environment_kwargs, + _generate_edge_tts, _generate_elevenlabs, _generate_gemini_tts, _generate_minimax_tts, + _generate_mistral_tts, _generate_xai_tts, _resolve_minimax_tts_runtime, ) from tools.tts_tool_local import ( # noqa: F401 — historical names re-exported - DEFAULT_PIPER_VOICE, - _LOCAL_TTS_MODEL_CACHES, - _TTS_MODEL_CACHE_MAX, - _generate_kittentts, - _generate_neutts, - _generate_piper_tts, - _kittentts_model_cache, - _piper_voice_cache, - _resolve_piper_voice_path, - _tts_cache_get_or_load, + DEFAULT_PIPER_VOICE, _LOCAL_TTS_MODEL_CACHES, _TTS_MODEL_CACHE_MAX, _generate_kittentts, + _generate_neutts, _generate_piper_tts, _kittentts_model_cache, _piper_voice_cache, + _resolve_piper_voice_path, _tts_cache_get_or_load, ) from tools.tts_tool_speaker import stream_tts_to_speaker # noqa: F401 — historical name re-exported from tools.tts_text_normalize import _strip_markdown_for_tts # noqa: F401 — historical name re-exported from tools.tts_tool_plugins import ( # noqa: F401 — historical names re-exported - _dispatch_to_plugin_provider, - _plugin_provider_is_available, + _dispatch_to_plugin_provider, _plugin_provider_is_available, _plugin_provider_is_voice_compatible, ) from tools.tts_tool_openai import ( # noqa: F401 — historical names re-exported - DEFAULT_OPENAI_BASE_URL, - DEFAULT_OPENAI_MODEL, - DEFAULT_OPENAI_VOICE, - MANAGED_OPENAI_TTS_MODELS, - _generate_deepinfra_tts, - _generate_openai_tts, - _has_openai_audio_backend, + DEFAULT_OPENAI_BASE_URL, DEFAULT_OPENAI_MODEL, DEFAULT_OPENAI_VOICE, MANAGED_OPENAI_TTS_MODELS, + _generate_deepinfra_tts, _generate_openai_tts, _has_openai_audio_backend, _resolve_openai_audio_client_config, ) from tools.tts_tool_lifecycle import ( # noqa: F401 — historical names re-exported - _local_tts_warmers, - _reset_tts_leases_for_tests, - acquire_tts_lease, - release_tts_lease, - release_tts_provider, - tts_lease_holders, - warm_tts_provider, + _local_tts_warmers, _reset_tts_leases_for_tests, acquire_tts_lease, release_tts_lease, + release_tts_provider, tts_lease_holders, warm_tts_provider, ) -# --------------------------------------------------------------------------- -# Lazy SDK importers -- providers import only when used (headless boxes lack PortAudio etc.) -# --------------------------------------------------------------------------- +# --- Lazy SDK importers -- providers import only when used (headless boxes lack PortAudio etc.) --- def _sdk_importer(module: str, attr: Optional[str] = None, feature: Optional[str] = None) -> Callable[[], Any]: """Lazy SDK importer: returns ``module`` (or ``module.attr``), raising ImportError when absent. ``feature`` names a ``tools.lazy_deps`` feature to best-effort install first (users who - enabled a provider by editing config.yaml never ran the post-setup hook); any failure - there falls through so the raw import still raises a clean ImportError. sounddevice - additionally raises OSError when PortAudio is unavailable. - """ + enabled a provider in config.yaml never ran the post-setup hook); any failure there falls + through so the raw import still raises cleanly. sounddevice also raises OSError without PortAudio.""" def _import(): if feature: try: @@ -209,9 +151,7 @@ def _check_piper_available() -> bool: return _package_installed("piper") -# --------------------------------------------------------------------------- -# Defaults / config -# --------------------------------------------------------------------------- +# --- Defaults / config --- DEFAULT_PROVIDER = "edge" @@ -225,21 +165,13 @@ _DEFAULT_OUTPUT_DIR_AT_IMPORT = DEFAULT_OUTPUT_DIR def _default_output_dir() -> str: - """The active profile's audio output dir at call time. - - Long-lived multi-profile runtimes switch profiles after import, so a frozen constant - would keep writing into the launch profile's cache. ``DEFAULT_OUTPUT_DIR`` stays a - module attribute for tests/patchers and wins whenever it has been patched. - """ + """The active profile's audio output dir at call time (long-lived runtimes switch profiles + after import); a monkeypatched ``DEFAULT_OUTPUT_DIR`` wins.""" if DEFAULT_OUTPUT_DIR != _DEFAULT_OUTPUT_DIR_AT_IMPORT: return DEFAULT_OUTPUT_DIR return _get_default_output_dir() -# Back-compat alias. Prefer ``_resolve_max_text_length()`` for new code. -MAX_TEXT_LENGTH = FALLBACK_MAX_TEXT_LENGTH - - def _load_tts_config() -> Dict[str, Any]: """Return the ``tts`` config section ({} when unavailable).""" try: @@ -254,12 +186,8 @@ def _load_tts_config() -> Dict[str, Any]: def _get_provider(tts_config: Dict[str, Any]) -> str: - """The explicitly configured TTS provider, or the free default. - - Inference credentials do not imply consent to paid speech generation: cloud TTS is - opt-in via ``tts.provider``. The managed selection (``nous``) is serviced by the - OpenAI implementation routed through the managed openai-audio gateway. - """ + """The configured TTS provider, or the free default — inference credentials never imply consent + to paid speech. ``nous`` is serviced by the OpenAI path via the managed openai-audio gateway.""" provider = (tts_config.get("provider") or DEFAULT_PROVIDER).lower().strip() return "openai" if provider == NOUS_MANAGED_PROVIDER else provider @@ -278,64 +206,34 @@ def _has_any_command_tts_provider(tts_config: Optional[Dict[str, Any]] = None) - return any(True for _ in _iter_command_providers(tts_config)) -# --------------------------------------------------------------------------- -# Built-in provider dispatch -# --------------------------------------------------------------------------- -# provider -> (availability predicate or None, "package missing" error, log line, generator -# name). Predicates and generator names resolve module globals at call time so tests that -# monkeypatch ``tools.tts_tool._import_x`` / ``_check_x`` / ``_generate_x`` apply. +# --- Built-in provider dispatch --- +# provider -> (availability predicate or None, log label, generator name, "package missing" error). +# Predicates and generator names resolve module globals at call time so tests that monkeypatch +# ``tools.tts_tool._import_x`` / ``_check_x`` / ``_generate_x`` apply. _BUILTIN_DISPATCH: Dict[str, tuple] = { - "elevenlabs": ( - lambda: _importable(_import_elevenlabs), - "ElevenLabs provider selected but 'elevenlabs' package not installed. Run: pip install elevenlabs", - "Generating speech with ElevenLabs...", - "_generate_elevenlabs", - ), - "openai": ( - lambda: _importable(_import_openai_client), - "OpenAI provider selected but 'openai' package not installed.", - "Generating speech with OpenAI TTS...", - "_generate_openai_tts", - ), - "deepinfra": ( - lambda: _importable(_import_openai_client), - "DeepInfra TTS uses the 'openai' SDK but it isn't installed.", - "Generating speech with DeepInfra TTS...", - "_generate_deepinfra_tts", - ), - "minimax": (None, None, "Generating speech with MiniMax TTS...", "_generate_minimax_tts"), - "xai": (None, None, "Generating speech with xAI TTS...", "_generate_xai_tts"), - "mistral": ( - lambda: _importable(_import_mistral_client), - "Mistral provider selected but 'mistralai' package not installed. " - "Run `hermes setup` to install Mistral support.", - "Generating speech with Mistral Voxtral TTS...", - "_generate_mistral_tts", - ), - "gemini": (None, None, "Generating speech with Google Gemini TTS...", "_generate_gemini_tts"), - "neutts": ( - lambda: _check_neutts_available(), - "NeuTTS provider selected but neutts is not installed. " - "Run hermes setup and choose NeuTTS, or install espeak-ng and run python -m pip install -U neutts[all].", - "Generating speech with NeuTTS (local)...", - "_generate_neutts", - ), - "kittentts": ( - lambda: _importable(_import_kittentts), - "KittenTTS provider selected but 'kittentts' package not installed. " - "Run 'hermes setup tts' and choose KittenTTS, or install manually: " - "pip install https://github.com/KittenML/KittenTTS/releases/download/0.8.1/kittentts-0.8.1-py3-none-any.whl", - "Generating speech with KittenTTS (local, ~25MB)...", - "_generate_kittentts", - ), - "piper": ( - lambda: _importable(_import_piper), - "Piper provider selected but 'piper-tts' package not installed. " - "Run 'hermes tools' and select Piper under TTS, or install manually: " - "pip install piper-tts", - "Generating speech with Piper (local)...", - "_generate_piper_tts", - ), + "elevenlabs": (lambda: _importable(_import_elevenlabs), "ElevenLabs", "_generate_elevenlabs", + "ElevenLabs provider selected but 'elevenlabs' package not installed. Run: pip install elevenlabs"), + "openai": (lambda: _importable(_import_openai_client), "OpenAI TTS", "_generate_openai_tts", + "OpenAI provider selected but 'openai' package not installed."), + "deepinfra": (lambda: _importable(_import_openai_client), "DeepInfra TTS", "_generate_deepinfra_tts", + "DeepInfra TTS uses the 'openai' SDK but it isn't installed."), + "minimax": (None, "MiniMax TTS", "_generate_minimax_tts", None), + "xai": (None, "xAI TTS", "_generate_xai_tts", None), + "mistral": (lambda: _importable(_import_mistral_client), "Mistral Voxtral TTS", "_generate_mistral_tts", + "Mistral provider selected but 'mistralai' package not installed. " + "Run `hermes setup` to install Mistral support."), + "gemini": (None, "Google Gemini TTS", "_generate_gemini_tts", None), + "neutts": (lambda: _check_neutts_available(), "NeuTTS (local)", "_generate_neutts", + "NeuTTS provider selected but neutts is not installed. " + "Run hermes setup and choose NeuTTS, or install espeak-ng and run python -m pip install -U neutts[all]."), + "kittentts": (lambda: _importable(_import_kittentts), "KittenTTS (local, ~25MB)", "_generate_kittentts", + "KittenTTS provider selected but 'kittentts' package not installed. " + "Run 'hermes setup tts' and choose KittenTTS, or install manually: " + "pip install https://github.com/KittenML/KittenTTS/releases/download/0.8.1/kittentts-0.8.1-py3-none-any.whl"), + "piper": (lambda: _importable(_import_piper), "Piper (local)", "_generate_piper_tts", + "Piper provider selected but 'piper-tts' package not installed. " + "Run 'hermes tools' and select Piper under TTS, or install manually: " + "pip install piper-tts"), } @@ -354,14 +252,11 @@ def _run_edge_tts(text: str, file_str: str, tts_config: Dict[str, Any]) -> None: def _select_builtin_engine(provider: str) -> tuple: - """Check a built-in provider's SDK. Returns ``(engine, None)`` or ``(provider, error_json)``. - - Unknown names take the Edge default; when edge-tts is missing, NeuTTS is the local - fallback (``engine`` then differs from ``provider``). - """ + """Check a built-in provider's SDK -> ``(engine, None)`` or ``(provider, error_json)``. Unknown + names take the Edge default; without edge-tts NeuTTS is the fallback (engine != provider).""" entry = _BUILTIN_DISPATCH.get(provider) if entry is not None: - available, missing_error = entry[0], entry[1] + available, missing_error = entry[0], entry[3] if available is not None and not available(): return provider, _error_json(missing_error) return provider, None @@ -379,26 +274,23 @@ def _select_builtin_engine(provider: str) -> tuple: def _synthesize_builtin(engine: str, text: str, file_str: str, tts_config: Dict[str, Any], instructions: Optional[str]) -> None: """Run the already-selected built-in *engine*.""" entry = _BUILTIN_DISPATCH.get(engine) + logger.info("Generating speech with %s...", entry[1] if entry else "Edge TTS") if entry is None: - logger.info("Generating speech with Edge TTS...") _run_edge_tts(text, file_str, tts_config) - return - logger.info(entry[2]) - if engine == "openai": + elif engine == "openai": _generate_openai_tts(text, file_str, tts_config, instructions=instructions) else: - globals()[entry[3]](text, file_str, tts_config) + globals()[entry[2]](text, file_str, tts_config) def _finalize_voice_delivery( file_str: str, provider: str, command_provider_config: Optional[Dict[str, Any]], want_opus: bool, ) -> tuple: - """Decide voice-bubble eligibility and Opus-convert when needed; returns ``(path, voice_compatible)``. + """Decide voice-bubble eligibility, Opus-converting when needed -> ``(path, voice_compatible)``. - Command and plugin providers are documents by default and opt in via ``voice_compatible``; - native-Opus built-ins are voice-compatible when the platform wants Opus and they wrote - .ogg; MP3/WAV built-ins are converted with ffmpeg only when the platform needs Opus. - """ + Command/plugin providers are documents unless they opt in via ``voice_compatible``; native-Opus + built-ins qualify when the platform wants Opus and they wrote .ogg; MP3/WAV built-ins are + ffmpeg-converted only when the platform needs Opus.""" if command_provider_config is not None: opted_in = _is_command_tts_voice_compatible(command_provider_config) elif provider not in BUILTIN_TTS_PROVIDERS: @@ -418,9 +310,7 @@ def _finalize_voice_delivery( return file_str, file_str.endswith(".ogg") -# --------------------------------------------------------------------------- -# Main tool function -# --------------------------------------------------------------------------- +# --- Main tool function --- def _apply_call_overrides(tts_config: Dict[str, Any], speed: Optional[float], provider: Optional[str]): """Apply per-call ``speed`` (clamped, on a shallow copy) and resolve the provider name.""" @@ -441,13 +331,11 @@ def _session_platform() -> tuple: def _resolve_output_base( output_path: Optional[str], provider: str, command_provider_config: Optional[Dict[str, Any]], want_opus: bool, ) -> tuple: - """Pick the output file. Returns ``(Path, None)`` or ``(None, error_json)``. + """Pick the output file -> ``(Path, None)`` or ``(None, error_json)``. - A caller-supplied path is rejected on ``..`` traversal (bug or prompt-injection; an - absolute path is fine) and on protected credential/system locations. Command providers - get their configured extension. Default: ``