Merge branch 'simp/r3-34' into simp/integration3

This commit is contained in:
Teknium
2026-09-03 00:08:19 -07:00
20 changed files with 833 additions and 1717 deletions
+52 -82
View File
@@ -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 "<skill>-YYYYMMDDHHMMSS" (14 digits) counts — a bare startswith("<skill>-") 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]
+1 -3
View File
@@ -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)
+42 -72
View File
@@ -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:
+11 -16
View File
@@ -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:
+2 -4
View File
@@ -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
+5 -11
View File
@@ -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:
+1 -3
View File
@@ -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
+1 -4
View File
@@ -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
+94 -230
View File
@@ -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: ``<audio cache>/tts_<timestamp>.<ext>`` where
ext is the command format, ``.ogg`` for native-Opus providers on Opus platforms, else ``.mp3``.
"""
A caller path is rejected on ``..`` traversal (bug or prompt-injection; absolute is fine) and
on protected credential/system locations. Default ``<audio cache>/tts_<timestamp>.<ext>``: the
command format, ``.ogg`` for native-Opus providers on Opus platforms, else ``.mp3``."""
if output_path:
from tools.path_security import has_traversal_component
if has_traversal_component(output_path):
@@ -486,23 +374,14 @@ def _tool_failure(prefix: str, provider: str, exc: BaseException) -> str:
def _text_to_speech_single(
text: str,
file_str: str,
*,
provider: str,
tts_config: Dict[str, Any],
command_provider_config: Optional[Dict[str, Any]],
want_opus: bool,
instructions: Optional[str],
text: str, file_str: str, *, provider: str, tts_config: Dict[str, Any],
command_provider_config: Optional[Dict[str, Any]], want_opus: bool, instructions: Optional[str],
) -> str:
"""Synthesize one provider-safe text chunk into *file_str* and return one final-encoded file.
"""Synthesize one normalized, provider-safe chunk into *file_str*; returns the result envelope.
Text arrives already normalized and the output path already validated. Command providers
resolve BEFORE built-in dispatch; built-in names short-circuit so
``tts.providers.openai.command`` can't shadow OpenAI. Plugin providers fire only for names
that are neither built-in nor command; a None return falls through to built-in dispatch
(unknown -> Edge default).
"""
Command providers resolve BEFORE built-in dispatch, but built-in names short-circuit so
``tts.providers.openai.command`` can't shadow OpenAI. Plugins fire only for names that are
neither; a None return falls through to built-in dispatch (unknown -> Edge default)."""
try:
if command_provider_config is not None:
logger.info("Generating speech with command TTS provider '%s'...", provider)
@@ -548,12 +427,10 @@ class _ChunkFailed(Exception):
def _synthesize_chunks(chunks: List[str], base_path: Path, generated_artifacts: set, **single_kwargs) -> tuple:
"""Synthesize every chunk into ``<base>.chunkNNN<ext>`` (or ``base`` alone) sequentially.
"""Synthesize chunks into ``<base>.chunkNNN<ext>`` (or ``base`` alone) -> ``(encoded_paths, results)``.
Every path touched is added to *generated_artifacts* so the caller can sweep non-final
files. Returns ``(encoded_paths, chunk_results)``; raises :class:`_ChunkFailed` when a
chunk reports failure and ``RuntimeError`` when it returns garbage or no audio.
"""
Every touched path lands in *generated_artifacts* for the caller's sweep. Raises
:class:`_ChunkFailed` on a reported failure, ``RuntimeError`` on garbage or missing audio."""
provider = single_kwargs["provider"]
encoded_paths: List[str] = []
chunk_results: List[Dict[str, Any]] = []
@@ -580,20 +457,14 @@ def _synthesize_chunks(chunks: List[str], base_path: Path, generated_artifacts:
def text_to_speech_tool(
text: str,
output_path: Optional[str] = None,
speed: Optional[float] = None,
instructions: Optional[str] = None,
provider: Optional[str] = None,
text: str, output_path: Optional[str] = None, speed: Optional[float] = None,
instructions: Optional[str] = None, provider: Optional[str] = None,
) -> str:
"""Convert text to speech audio with long-form chunking; returns the JSON result envelope.
"""Convert text to speech with long-form chunking; returns the JSON result envelope.
Text is normalized, split into provider-safe chunks (never silently truncated),
synthesized sequentially (each chunk final-encoded), then packed against the destination
platform's upload limit. Multi-chunk voice output is re-encoded when combined; a failed
combine keeps separate valid files; no over-limit artifact is returned. ``speed`` is a
0.25-4.0 multiplier; ``instructions`` is voice-design guidance for backends that take it.
"""
Text is normalized, split into provider-safe chunks (never silently truncated), synthesized
sequentially, then packed against the platform's upload limit: a failed combine keeps the
separate valid files and no over-limit artifact is ever returned."""
if not text or not text.strip():
return tool_error("Text is required", success=False)
@@ -628,11 +499,8 @@ def text_to_speech_tool(
final_paths: List[str] = []
try:
encoded_paths, chunk_results = _synthesize_chunks(
chunks, base_path, generated_artifacts,
provider=provider,
tts_config=tts_config,
command_provider_config=command_provider_config,
want_opus=want_opus,
chunks, base_path, generated_artifacts, provider=provider, tts_config=tts_config,
command_provider_config=command_provider_config, want_opus=want_opus,
instructions=instructions,
)
voice_compatible = bool(chunk_results) and all(bool(r.get("voice_compatible")) for r in chunk_results)
@@ -678,9 +546,7 @@ def text_to_speech_tool(
pass
# ---------------------------------------------------------------------------
# check_fn
# ---------------------------------------------------------------------------
# --- check_fn ---
def _minimax_requirements() -> bool:
try:
@@ -728,9 +594,7 @@ def check_tts_requirements() -> bool:
return _plugin_provider_is_available(provider)
# ---------------------------------------------------------------------------
# Registry
# ---------------------------------------------------------------------------
# --- Registry ---
from tools.registry import registry, tool_error
TTS_SCHEMA = {
+38 -82
View File
@@ -71,14 +71,10 @@ def _positive_int(value: Any) -> Optional[int]:
def _resolve_max_text_length(provider: Optional[str], tts_config: Optional[Dict[str, Any]] = None) -> int:
"""Return the input-character cap for *provider*.
Order: ``tts.<provider>.max_text_length`` > ElevenLabs model table >
``PROVIDER_MAX_TEXT_LENGTH`` > command provider's own ``max_text_length``
(else ``DEFAULT_COMMAND_TTS_MAX_TEXT_LENGTH``) > ``FALLBACK_MAX_TEXT_LENGTH``.
Non-positive / non-int overrides fall through so a broken config can't
disable truncation.
"""
"""Input-character cap for *provider*: ``tts.<provider>.max_text_length`` > ElevenLabs model
table > ``PROVIDER_MAX_TEXT_LENGTH`` > command provider's own ``max_text_length`` (else
``DEFAULT_COMMAND_TTS_MAX_TEXT_LENGTH``) > ``FALLBACK_MAX_TEXT_LENGTH``. Non-positive /
non-int overrides fall through so a broken config can't disable truncation."""
if not provider:
return FALLBACK_MAX_TEXT_LENGTH
key = provider.lower().strip()
@@ -118,9 +114,7 @@ _OPUS_VOICE_ARGS = [
]
# ---------------------------------------------------------------------------
# Text chunking and delivery profiles
# ---------------------------------------------------------------------------
# --- Text chunking and delivery profiles ---
@dataclass(frozen=True)
class AudioDeliveryProfile:
@@ -161,11 +155,21 @@ def _resolve_audio_delivery_profile(
return AudioDeliveryProfile(platform=key, max_file_bytes=max_file_bytes, safety_ratio=float(safety_ratio))
def _pack_under_cap(pieces: List[str], max_chars: int) -> List[str]:
"""Greedily join *pieces* with single spaces, starting a new chunk past *max_chars*."""
def _pack_under_cap(pieces: List[str], max_chars: int, *, slice_oversized: bool = False) -> List[str]:
"""Greedily join *pieces* with single spaces, starting a new chunk past *max_chars*.
With ``slice_oversized`` an over-long piece flushes the running chunk and emits its hard
slices as their own chunks (the tail slice is not merged with following pieces).
"""
chunks: List[str] = []
current = ""
for piece in pieces:
if slice_oversized and len(piece) > max_chars:
if current:
chunks.append(current)
current = ""
chunks.extend(piece[i:i + max_chars] for i in range(0, len(piece), max_chars))
continue
candidate = f"{current} {piece}".strip()
if current and len(candidate) > max_chars:
chunks.append(current)
@@ -178,29 +182,8 @@ def _pack_under_cap(pieces: List[str], max_chars: int) -> List[str]:
def _split_oversized_sentence(sentence: str, max_chars: int) -> List[str]:
"""Split one over-limit sentence on word boundaries, then hard boundaries.
An over-long word flushes the running chunk and emits its slices as their
own chunks (the tail slice is not merged with following words).
"""
chunks: List[str] = []
current = ""
for word in sentence.split():
if len(word) > max_chars:
if current:
chunks.append(current)
current = ""
chunks.extend(word[i:i + max_chars] for i in range(0, len(word), max_chars))
continue
candidate = f"{current} {word}".strip()
if current and len(candidate) > max_chars:
chunks.append(current)
current = word
else:
current = candidate
if current:
chunks.append(current)
return chunks
"""Split one over-limit sentence on word boundaries, then hard boundaries."""
return _pack_under_cap(sentence.split(), max_chars, slice_oversized=True)
def _split_text_for_tts(text: str, max_chars: int) -> List[str]:
@@ -226,10 +209,7 @@ def _split_text_for_tts(text: str, max_chars: int) -> List[str]:
def _pack_audio_files_for_delivery(audio_paths: List[str], profile: AudioDeliveryProfile) -> List[List[str]]:
"""Group already-final-encoded chunks under the conservative size target.
A group never mixes container suffixes (they can't be concat-copied).
"""
"""Group final-encoded chunks under the size target; never mixes suffixes (can't concat-copy)."""
groups: List[List[str]] = []
current: List[str] = []
current_size = 0
@@ -248,9 +228,7 @@ def _pack_audio_files_for_delivery(audio_paths: List[str], profile: AudioDeliver
return groups
# ---------------------------------------------------------------------------
# ffmpeg encoding helpers
# ---------------------------------------------------------------------------
# --- ffmpeg encoding helpers ---
def _ffmpeg_run(
ffmpeg: str, args: List[str], *, timeout: int = 30, check: bool = False, capture: bool = True,
@@ -277,11 +255,8 @@ def _wav_sidecar_path(output_path: str) -> str:
def _finalize_wav_output(wav_path: str, output_path: str) -> str:
"""Move a WAV-native engine's output (NeuTTS / Piper / KittenTTS) into the requested container.
ffmpeg-convert when available, otherwise rename the WAV to the expected path so the
tool stays usable (the extension is then misleading but the audio plays).
"""
"""Move a WAV-native engine's output into the requested container: ffmpeg-convert when
available, else rename so the tool stays usable (misleading extension, audio plays)."""
if wav_path == output_path:
return output_path
ffmpeg = shutil.which("ffmpeg")
@@ -315,11 +290,9 @@ def _wrap_pcm_as_wav(
def _write_wav_bytes_as(wav_bytes: bytes, output_path: str) -> str:
"""Write in-memory WAV to *output_path*, ffmpeg-converting to its container.
``.wav`` is written directly; ``.ogg`` is forced to Opus (ffmpeg's .ogg default is
Vorbis, which voice bubbles reject); anything else is a plain ffmpeg conversion. A
failed conversion raises RuntimeError. Without ffmpeg the raw WAV is written under
the requested name (misleading extension, but the audio still plays).
"""
``.ogg`` is forced to Opus (ffmpeg's .ogg default is Vorbis, which voice bubbles reject).
A failed conversion raises RuntimeError; without ffmpeg the raw WAV is written under
the requested name (misleading extension, but the audio still plays)."""
if output_path.lower().endswith(".wav"):
with open(output_path, "wb") as f:
f.write(wav_bytes)
@@ -350,11 +323,7 @@ def _convert_to_opus(mp3_path: str) -> Optional[str]:
def _ffmpeg_transcode_to_opus(input_path: str, ogg_path: str) -> Optional[str]:
"""Transcode *input_path* to real Ogg/Opus at *ogg_path* via ffmpeg.
Safe when ``input_path == ogg_path`` (writes to a temp file, then replaces).
Returns the output path on success, None on failure.
"""
"""Transcode *input_path* to real Ogg/Opus at *ogg_path* (in-place safe via temp file); None on failure."""
if shutil.which("ffmpeg") is None:
return None
@@ -382,9 +351,7 @@ def _ffmpeg_transcode_to_opus(input_path: str, ogg_path: str) -> Optional[str]:
return None
# ---------------------------------------------------------------------------
# Container sniffing / repair
# ---------------------------------------------------------------------------
# --- Container sniffing / repair ---
# Several backends silently ignore the requested opus format (Edge only emits MP3, Piper
# writes WAV, xAI writes MP3, some OpenAI-compatible servers ignore response_format="opus"),
# which breaks native voice bubbles. Sniff the magic bytes once after synthesis and repair
@@ -403,12 +370,8 @@ def _sniff_audio_container(path: str) -> str:
def _repair_ogg_container(file_str: str) -> str:
"""Ensure a path claiming ``.ogg`` actually contains an Ogg container.
MP3/WAV/FLAC bytes are transcoded in place to real Ogg/Opus. On failure the file is
renamed to its sniffed real extension so platforms get an honest file instead of a
0-second voice bubble.
"""
"""Ensure a ``.ogg`` path really holds Ogg: transcode in place, else rename to the sniffed
real extension so platforms get an honest file instead of a 0-second voice bubble."""
if not file_str.endswith(".ogg"):
return file_str
container = _sniff_audio_container(file_str)
@@ -432,18 +395,13 @@ def _repair_ogg_container(file_str: str) -> str:
return file_str
# ---------------------------------------------------------------------------
# Long-form audio combination and delivery packing
# ---------------------------------------------------------------------------
# --- Long-form audio combination and delivery packing ---
def _concat_audio_files(audio_paths: List[str], output_path: str, *, voice_compatible: bool = False) -> Optional[str]:
"""Combine independently encoded chunks with ffmpeg.
"""Combine independently encoded chunks with ffmpeg (never byte-joined).
OGG/Opus is always decoded and re-encoded (even without voice opt-in); matching MP3
chunks keep their encoded frames (``-c:a copy``). Structured containers are never
byte-joined. Returns ``None`` when ffmpeg is missing or fails so callers keep the
individually valid files.
"""
OGG/Opus is always re-encoded (even without voice opt-in); matching MP3 chunks keep their
frames (``-c:a copy``). None when ffmpeg is missing/fails so callers keep the valid parts."""
if not audio_paths:
raise ValueError("No audio chunks to combine")
if len(audio_paths) == 1:
@@ -489,13 +447,11 @@ def _concat_audio_files(audio_paths: List[str], output_path: str, *, voice_compa
def _build_audio_delivery_files(
audio_paths: List[str], output_path: str, profile: AudioDeliveryProfile, *, voice_compatible: bool = False,
) -> Tuple[List[str], bool]:
"""Pack final-encoded chunks and enforce the hard upload limit.
"""Pack final-encoded chunks and enforce the hard upload limit; returns ``(final_paths, combined_any)``.
Groups are packed against the conservative target, then every combined artifact is
checked at its real post-encoding size; an over-limit group is split in half and
retried. A failed combine returns the constituent files separately. A single chunk
above the hard limit fails closed. Returns ``(final_paths, combined_any)``.
"""
Groups are packed against the conservative target, then each combined artifact is checked
at its real size; an over-limit group is split in half and retried. A failed combine
returns the constituent files separately. A single chunk above the hard limit fails closed."""
if not audio_paths:
raise ValueError("No final-encoded TTS audio chunks")
for path in audio_paths:
+14 -30
View File
@@ -55,14 +55,11 @@ _LAZY_SDK_FEATURES = {"edge": "tts.edge", "elevenlabs": "tts.elevenlabs", "mistr
def _signal_user_tts_provider(name: str, tts_config: Dict[str, Any], hook: str) -> Optional[str]:
"""Forward a lease ``hook`` (``"warm"`` / ``"release"``) to a user-declared provider.
"""Forward a lease ``hook`` (``"warm"``/``"release"``) to a user-declared provider; returns the action.
Command providers run their optional ``warm_command`` / ``release_command`` (same
template/env/timeout rules as ``command``; output discarded) on a background thread so
a toggle never waits on a model server. Plugin providers get :meth:`TTSProvider.warm`
/ :meth:`TTSProvider.release`. Best-effort: failures are logged at debug. Returns the
action taken.
"""
Command providers run their optional ``<hook>_command`` (same template/env/timeout rules as
``command``) on a background thread so a toggle never waits on a model server; plugins get
:meth:`TTSProvider.warm`/``release``. Best-effort: failures are logged at debug."""
if not name or name in BUILTIN_TTS_PROVIDERS:
return None
cfg = _get_named_provider_config(tts_config, name)
@@ -97,14 +94,11 @@ def _signal_user_tts_provider(name: str, tts_config: Dict[str, Any], hook: str)
def warm_tts_provider(tts_config: Optional[Dict[str, Any]] = None, provider: Optional[str] = None) -> Dict[str, Any]:
"""Pre-load the configured TTS provider so the next synthesis starts hot.
"""Pre-load the configured TTS provider so the next synthesis starts hot (blocking; never raises).
Local engines load their voice/model into the same LRU slot synthesis reads (including
first-use download); lazily-installed cloud SDKs are made importable; user-declared
providers get ``warm_command`` / :meth:`TTSProvider.warm`; everything else is
``action: "noop"``. Never raises — the result dict carries ``warmed`` / ``action`` /
``error``. Blocking; UI threads should run it in the background.
"""
Local engines fill the same LRU slot synthesis reads (including first-use download); lazily
installed cloud SDKs are made importable; user-declared providers get their warm hook;
everything else is ``action: "noop"``. The result carries ``warmed`` / ``action`` / ``error``."""
if tts_config is None:
tts_config = _origin()._load_tts_config()
name = (provider or _origin()._get_provider(tts_config) or "").lower().strip()
@@ -153,12 +147,8 @@ def warm_tts_provider(tts_config: Optional[Dict[str, Any]] = None, provider: Opt
def release_tts_provider(provider: Optional[str] = None) -> Dict[str, Any]:
"""Drop resident local TTS models so their memory is returned.
With ``provider`` given only that engine's cache is cleared; otherwise every local
cache is, and the configured user-declared provider is signalled (plugin ``release()``
/ command ``release_command``). Returns ``{"released": <model instances dropped>}``.
"""
"""Drop resident local models -> ``{"released": <count>}``. With ``provider`` only that engine's
cache is cleared; otherwise every cache is, and the configured user provider is signalled."""
name = (provider or "").lower().strip()
if not name:
tts_config = _origin()._load_tts_config()
@@ -175,11 +165,8 @@ def release_tts_provider(provider: Optional[str] = None) -> Dict[str, Any]:
def acquire_tts_lease(lease: str, tts_config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""Register ``lease`` (e.g. ``"desktop:read-aloud"``) as a live consumer and warm the provider.
Re-acquiring is idempotent but still re-warms (cheap on a cache hit, and heals a cache
cleared elsewhere).
"""
"""Register ``lease`` (e.g. ``"desktop:read-aloud"``) and warm the provider. Re-acquiring is
idempotent but still re-warms (cheap on a cache hit; heals a cache cleared elsewhere)."""
with _tts_lease_lock:
_tts_leases.add(lease)
holders = len(_tts_leases)
@@ -189,11 +176,8 @@ def acquire_tts_lease(lease: str, tts_config: Optional[Dict[str, Any]] = None) -
def release_tts_lease(lease: str) -> Dict[str, Any]:
"""Drop ``lease``; when it was the last one, unload resident local models.
Releasing a never-acquired lease is a no-op (still reports the holder count) so
surfaces can call it unconditionally on their "off" path.
"""
"""Drop ``lease``; the last one out unloads resident local models. A never-acquired lease is a
no-op (still reports the holder count) so surfaces can call this unconditionally."""
with _tts_lease_lock:
_tts_leases.discard(lease)
holders = len(_tts_leases)
+10 -29
View File
@@ -31,9 +31,7 @@ def _origin():
return tts_tool
# ---------------------------------------------------------------------------
# Bounded model caches
# ---------------------------------------------------------------------------
# --- Bounded model caches ---
# Each cached entry is a whole loaded model (tens of MB); an unbounded dict would pin one
# per distinct voice for the process lifetime. Most sessions use one or two voices and a
# cold reload is cheap.
@@ -48,12 +46,8 @@ _LOCAL_TTS_MODEL_CACHES: Dict[str, Dict[str, Any]] = {"piper": _piper_voice_cach
def _tts_cache_get_or_load(cache: Dict[str, Any], key: str, load: Callable[[], Any]) -> Any:
"""Get ``key`` from ``cache`` or load it, keeping the cache LRU-bounded.
A hit refreshes recency (pop + reinsert on the insertion-ordered dict); a miss loads
then evicts LRU entries beyond ``_TTS_MODEL_CACHE_MAX``. Callers holding an evicted
reference keep it alive; only the slot is released.
"""
"""Get ``key`` from ``cache`` or load it, LRU-bounded at ``_TTS_MODEL_CACHE_MAX`` (a hit refreshes
recency via pop + reinsert; eviction only releases the slot, not live references)."""
if key in cache:
cache[key] = cache.pop(key)
return cache[key]
@@ -74,9 +68,7 @@ def _run_helper(cmd: list, timeout: int) -> subprocess.CompletedProcess:
)
# ---------------------------------------------------------------------------
# NeuTTS (subprocess via tools/neutts_synth.py so the ~500MB model exits after use)
# ---------------------------------------------------------------------------
# --- NeuTTS (subprocess via tools/neutts_synth.py so the ~500MB model exits after use) ---
def _generate_neutts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str:
neutts_config = tts_config.get("neutts") or {}
@@ -98,9 +90,7 @@ def _generate_neutts(text: str, output_path: str, tts_config: Dict[str, Any]) ->
return _finalize_wav_output(wav_path, output_path)
# ---------------------------------------------------------------------------
# Piper (local neural VITS, 44 languages)
# ---------------------------------------------------------------------------
# --- Piper (local neural VITS, 44 languages) ---
def _get_piper_voices_dir() -> Path:
"""``<HERMES_HOME>/cache/piper-voices/`` so voice downloads follow profile boundaries."""
@@ -111,12 +101,8 @@ def _get_piper_voices_dir() -> Path:
def _resolve_piper_voice_path(voice: str, download_dir: Path) -> str:
"""Resolve *voice* (an .onnx path or a voice name) to a concrete .onnx file.
Names like ``en_US-lessac-medium`` are downloaded into *download_dir* on first use via
``python -m piper.download_voices``. Raises RuntimeError when the model can't be
located or downloaded.
"""
"""Resolve *voice* (an .onnx path or a name like ``en_US-lessac-medium``, downloaded into
*download_dir* on first use) to a concrete .onnx file; RuntimeError when it can't be."""
voice = voice or DEFAULT_PIPER_VOICE
candidate = Path(voice).expanduser()
if candidate.suffix.lower() == ".onnx" and candidate.exists():
@@ -146,11 +132,8 @@ def _resolve_piper_voice_path(voice: str, download_dir: Path) -> str:
def _load_piper_voice_for_config(tts_config: Dict[str, Any]) -> Tuple[Any, Dict[str, Any]]:
"""Resolve + load (or fetch from cache) the Piper voice ``tts_config`` selects.
Shared by synthesis and ``warm_tts_provider`` so a warm-up fills exactly the cache
slot the next synthesis hits. Returns ``(voice, piper_config)``.
"""
"""Resolve + load (or fetch from cache) the selected Piper voice -> ``(voice, piper_config)``.
Shared by synthesis and ``warm_tts_provider`` so a warm-up fills exactly the slot synthesis hits."""
PiperVoice = _origin()._import_piper()
piper_config = _section(tts_config, "piper")
voice_name = piper_config.get("voice") or DEFAULT_PIPER_VOICE
@@ -211,9 +194,7 @@ def _generate_piper_tts(text: str, output_path: str, tts_config: Dict[str, Any])
return _finalize_wav_output(wav_path, output_path)
# ---------------------------------------------------------------------------
# KittenTTS (local ONNX, 25-80MB models, CPU only)
# ---------------------------------------------------------------------------
# --- KittenTTS (local ONNX, 25-80MB models, CPU only) ---
def _load_kittentts_model_for_config(tts_config: Dict[str, Any]) -> Tuple[Any, Dict[str, Any]]:
"""Load (or fetch from cache) the KittenTTS model; returns ``(model, kittentts_config)``."""
+10 -23
View File
@@ -52,15 +52,10 @@ def _openai_section(tts_config: Any, key: str) -> Dict[str, Any]:
def _resolve_openai_audio_client_config() -> tuple[str, str, bool]:
"""Return ``(api_key, base_url, is_managed)`` for the OpenAI audio client.
``is_managed`` marks the Nous managed audio gateway (a restricted proxy) so callers can
coerce the request to what it supports. Strict selection semantics on the stored
``tts`` provider: ``"nous"`` → managed gateway ONLY (unentitled/unreachable is an
error); any other stored provider → direct credentials ONLY (``tts.openai.api_key``
then ``VOICE_TOOLS_OPENAI_KEY``/``OPENAI_API_KEY``), no silent managed fallback;
never-configured tts section → legacy ladder: config key → env key → managed.
"""
"""``(api_key, base_url, is_managed)`` for the OpenAI audio client (``is_managed`` = the restricted
Nous proxy, so callers coerce the request). Strict on the stored ``tts`` selection: ``"nous"``
→ managed ONLY (error if unavailable); any other → direct credentials ONLY (``tts.openai.api_key``
then ``VOICE_TOOLS_OPENAI_KEY``/``OPENAI_API_KEY``); unset → config key → env key → managed."""
origin = _origin()
openai_cfg = _openai_section(origin._load_tts_config(), "openai")
direct_base = openai_cfg.get("base_url") or DEFAULT_OPENAI_BASE_URL
@@ -115,14 +110,10 @@ def _generate_openai_tts(
instructions: Optional[str] = None) -> str:
"""Generate audio via the OpenAI ``audio.speech.create`` SDK shape.
Explicit kwargs let OpenAI-compatible backends (DeepInfra) pass their own
credentials/model/voice and skip ``_resolve_openai_audio_client_config`` (the
managed-gateway path). When None: ``api_key`` comes from the OpenAI auth chain,
``base_url`` from ``tts.openai.base_url`` then the auth-chain fallback then the OpenAI
default, model/voice/speed from ``tts.openai`` (speed falling back to global
``tts.speed``). ``instructions`` is forwarded only when truthy so ``tts-1`` and strict
OpenAI-compatible servers that reject unknown kwargs are unaffected.
"""
Explicit kwargs let OpenAI-compatible backends (DeepInfra) supply credentials/model/voice
and skip the managed-gateway resolution; otherwise the OpenAI auth chain and ``tts.openai``
(speed falling back to ``tts.speed``) apply. ``instructions`` is forwarded only when truthy
so ``tts-1`` and strict OpenAI-compatible servers that reject unknown kwargs are unaffected."""
fallback_base: Optional[str] = None
is_managed = False
explicit_base_url = base_url is not None
@@ -181,12 +172,8 @@ def _generate_openai_tts(
def _generate_deepinfra_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str:
"""Resolve DeepInfra credentials/model, then delegate to the OpenAI handler.
DeepInfra's audio endpoint is OpenAI-compatible. Model ids come live from the shared
``hermes_cli.models`` catalog helpers (no hardcoded ids, so retired models disappear
without a patch).
"""
"""Resolve DeepInfra credentials/model (live ``hermes_cli.models`` catalog, no hardcoded ids), then
delegate to the OpenAI-compatible handler."""
api_key = _origin()._resolve_provider_key("DEEPINFRA_API_KEY", "deepinfra")
if not api_key:
raise ValueError("DEEPINFRA_API_KEY not set. Run `hermes setup` to configure, or set the env var directly.")
+6 -12
View File
@@ -22,12 +22,9 @@ logger = logging.getLogger("tools.tts_tool")
def _lookup_plugin_provider(key: str, *, discover: bool = True, retry: bool = False):
"""The registered ``TTSProvider`` named *key*, or None.
``discover`` runs plugin discovery first; ``retry`` re-discovers with ``force=True`` on
a miss (long-lived sessions may have discovered plugins before this one was
installed/enabled). Raises on registry/discovery failure — callers decide if fatal.
"""
"""The registered ``TTSProvider`` named *key*, or None. ``discover`` runs plugin discovery first;
``retry`` re-discovers with ``force=True`` on a miss (a long-lived session may predate the
plugin's install). Raises on registry/discovery failure — callers decide if fatal."""
from agent.tts_registry import get_provider
if discover:
@@ -44,12 +41,9 @@ def _lookup_plugin_provider(key: str, *, discover: bool = True, retry: bool = Fa
def _dispatch_to_plugin_provider(text: str, output_path: str, provider: str, tts_config: Dict[str, Any]) -> Optional[str]:
"""Route to a plugin-registered TTS provider; None means "fall through".
Invariants enforced here even though the caller checks them too, so a caller refactor
can't silently break them: built-in names never reach the plugin registry; a same-named
``type: command`` provider wins over a plugin; dispatch fires only for a registered
:class:`TTSProvider` whose name equals the configured value (unknown names -> None).
Plugin exceptions propagate — ``text_to_speech_tool`` converts them to the error envelope.
"""
Invariants re-checked here so a caller refactor can't break them: built-in names never reach
the registry; a same-named ``type: command`` provider wins; only an exact registered name
dispatches. Plugin exceptions propagate to ``text_to_speech_tool``'s error envelope."""
if not provider:
return None
key = provider.lower().strip()
+35 -76
View File
@@ -100,9 +100,15 @@ def _section(tts_config: Dict[str, Any], key: str) -> Dict[str, Any]:
return section if isinstance(section, dict) else {}
# ---------------------------------------------------------------------------
# Bounded upstream response reading
# ---------------------------------------------------------------------------
def _require_key(env_var: str, provider_id: str, hint: str) -> str:
"""Resolve *env_var* via the origin key resolver; ValueError ``"<ENV> not set. <hint>"`` when absent."""
api_key = _origin()._resolve_provider_key(env_var, provider_id) or ""
if not api_key:
raise ValueError(f"{env_var} not set. {hint}")
return api_key
# --- Bounded upstream response reading ---
def _response_has_explicit_stream(response: Any) -> bool:
"""True for real ``requests`` responses (or doubles defining ``iter_content`` themselves)."""
@@ -182,9 +188,7 @@ def _post_json(url: str, payload: Dict[str, Any], headers: Dict[str, str], **ext
return requests.post(url, headers=headers, json=payload, timeout=60, stream=True, **extra)
# ---------------------------------------------------------------------------
# Auxiliary-model speech-tag rewrites
# ---------------------------------------------------------------------------
# --- Auxiliary-model speech-tag rewrites ---
def _extract_auxiliary_message_content(response: Any) -> str:
try:
@@ -232,9 +236,7 @@ def _rewrite_with_auxiliary_model(
return fallback
# ---------------------------------------------------------------------------
# Edge TTS (free default)
# ---------------------------------------------------------------------------
# --- Edge TTS (free default) ---
async def _generate_edge_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str:
_edge_tts = _origin()._import_edge_tts()
@@ -247,16 +249,11 @@ async def _generate_edge_tts(text: str, output_path: str, tts_config: Dict[str,
return output_path
# ---------------------------------------------------------------------------
# ElevenLabs
# ---------------------------------------------------------------------------
# --- ElevenLabs ---
def _elevenlabs_environment_kwargs(el_config: Dict[str, Any]) -> Dict[str, Any]:
"""Client kwargs redirecting the SDK to ``tts.elevenlabs.base_url``/``wss_url``.
Empty when no base_url is set (SDK default environment); ``wss_url`` defaults
to the base_url host with a ``ws(s)://`` scheme.
"""
"""SDK client kwargs for ``tts.elevenlabs.base_url``/``wss_url``; empty (SDK default environment)
without a base_url. ``wss_url`` defaults to the base_url host with a ``ws(s)://`` scheme."""
base_url = (el_config.get("base_url") or "").rstrip("/")
if not base_url:
return {}
@@ -266,13 +263,9 @@ def _elevenlabs_environment_kwargs(el_config: Dict[str, Any]) -> Dict[str, Any]:
def _generate_elevenlabs(text: str, output_path: str, tts_config: Dict[str, Any]) -> str:
origin = _origin()
api_key = origin._resolve_provider_key("ELEVENLABS_API_KEY", "elevenlabs") or ""
if not api_key:
raise ValueError("ELEVENLABS_API_KEY not set. Get one at https://elevenlabs.io/")
api_key = _require_key("ELEVENLABS_API_KEY", "elevenlabs", "Get one at https://elevenlabs.io/")
el_config = tts_config.get("elevenlabs") or {}
client = origin._import_elevenlabs()(api_key=api_key, **_elevenlabs_environment_kwargs(el_config))
client = _origin()._import_elevenlabs()(api_key=api_key, **_elevenlabs_environment_kwargs(el_config))
audio_generator = client.text_to_speech.convert(
text=text,
voice_id=el_config.get("voice_id", DEFAULT_ELEVENLABS_VOICE_ID),
@@ -285,9 +278,7 @@ def _generate_elevenlabs(text: str, output_path: str, tts_config: Dict[str, Any]
return output_path
# ---------------------------------------------------------------------------
# xAI TTS (dedicated /v1/tts endpoint, not the OpenAI audio shape)
# ---------------------------------------------------------------------------
# --- xAI TTS (dedicated /v1/tts endpoint, not the OpenAI audio shape) ---
_XAI_INLINE_SPEECH_TAGS = (
"pause", "long-pause", "hum-tune", "laugh", "chuckle", "giggle", "cry", "tsk",
"tongue-click", "lip-smack", "breath", "inhale", "exhale", "sigh",
@@ -304,13 +295,9 @@ _XAI_FIRST_SENTENCE_RE = re.compile(r"^(.{12,120}?[.!?…])\s+(?=\S)", flags=re.
def _apply_xai_auto_speech_tags(text: str) -> str:
"""Add xAI speech tags for more natural voice-mode replies.
Local conservative pass first ([pause] between paragraphs and after the first
sentence). If the text carried no explicit speech tags already, the auxiliary
model then rewrites it with the richer xAI tag set; any failure falls back to
the locally tagged text.
"""
"""Add xAI speech tags: a conservative local pass ([pause] between paragraphs / after the first
sentence), then — only when the text carried no explicit tags — an auxiliary-model rewrite
with the richer xAI tag set, falling back to the locally tagged text on any failure."""
clean = text.strip()
if not clean:
return text
@@ -343,11 +330,8 @@ def _apply_xai_auto_speech_tags(text: str) -> str:
def _clamped_number(raw: Any, cast, lo, hi):
"""Parse an optional numeric knob and clamp into [lo, hi]; ``None``/unparseable -> None.
An empty string is deliberately passed to the clamp unconverted (the resulting
TypeError is reported by the caller's generic handler as a TTS failure).
"""
"""Parse an optional numeric knob and clamp into [lo, hi]; ``None``/unparseable -> None. An empty
string is deliberately clamped unconverted (its TypeError surfaces as a generic TTS failure)."""
if raw is None:
return None
if raw != "":
@@ -425,9 +409,7 @@ def _generate_xai_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -
return output_path
# ---------------------------------------------------------------------------
# MiniMax TTS
# ---------------------------------------------------------------------------
# --- MiniMax TTS ---
@dataclass(frozen=True)
class _MiniMaxTTSRuntime:
@@ -447,12 +429,8 @@ _MINIMAX_OFFICIAL_HOSTS = {
def _resolve_minimax_tts_runtime(tts_config: Dict[str, Any]) -> _MiniMaxTTSRuntime:
"""Select MiniMax TTS region, endpoint, and credential atomically.
An explicit ``tts.minimax.region`` wins. Without one, the legacy global
credential wins when present; a China credential is selected only when it
is the sole configured MiniMax credential.
"""
"""Select MiniMax region, endpoint and credential atomically: explicit ``tts.minimax.region`` wins,
else the legacy global credential; ``cn`` only when it is the sole configured credential."""
mm_config = _section(tts_config, "minimax")
resolve_key = _origin()._resolve_provider_key
credentials = {
@@ -489,12 +467,8 @@ def _raise_minimax_api_error(result: Dict[str, Any]) -> None:
def _generate_minimax_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str:
"""Generate audio via MiniMax.
Two endpoints, detected from the URL: ``t2a_v2`` (nested payload, JSON reply
with hex-encoded audio) and legacy ``text_to_speech`` (flat payload, raw
``audio/*`` body).
"""
"""Generate audio via MiniMax: ``t2a_v2`` (nested payload, JSON reply with hex audio) or the legacy
``text_to_speech`` endpoint (flat payload, raw ``audio/*`` body), detected from the URL."""
runtime = _resolve_minimax_tts_runtime(tts_config)
mm_config = _section(tts_config, "minimax")
model = mm_config.get("model", DEFAULT_MINIMAX_MODEL)
@@ -564,21 +538,15 @@ def _generate_minimax_tts(text: str, output_path: str, tts_config: Dict[str, Any
raise RuntimeError("MiniMax TTS returned no audio data")
# ---------------------------------------------------------------------------
# Mistral (Voxtral TTS) — base64 audio, native Opus for voice bubbles
# ---------------------------------------------------------------------------
# --- Mistral (Voxtral TTS) — base64 audio, native Opus for voice bubbles ---
def _generate_mistral_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str:
origin = _origin()
api_key = origin._resolve_provider_key("MISTRAL_API_KEY", "mistral") or ""
if not api_key:
raise ValueError("MISTRAL_API_KEY not set. Get one at https://console.mistral.ai/")
api_key = _require_key("MISTRAL_API_KEY", "mistral", "Get one at https://console.mistral.ai/")
mi_config = tts_config.get("mistral") or {}
client_kwargs: Dict[str, Any] = {"api_key": api_key}
if mi_config.get("base_url"):
client_kwargs["server_url"] = mi_config["base_url"] # the Mistral SDK calls it server_url
Mistral = origin._import_mistral_client()
Mistral = _origin()._import_mistral_client()
try:
with Mistral(**client_kwargs) as client:
response = client.audio.speech.complete(
@@ -596,9 +564,7 @@ def _generate_mistral_tts(text: str, output_path: str, tts_config: Dict[str, Any
return _write_bytes(output_path, audio_bytes)
# ---------------------------------------------------------------------------
# Google Gemini TTS
# ---------------------------------------------------------------------------
# --- Google Gemini TTS ---
def _read_gemini_persona_prompt(gemini_config: Dict[str, Any]) -> str:
"""Read ``tts.gemini.persona_prompt_file`` (relative -> under HERMES_HOME), failing soft."""
@@ -664,11 +630,8 @@ def _rewrite_gemini_tts_audio_tags(text: str, persona_prompt: str = "") -> str:
def _compose_gemini_tts_prompt(text: str, gemini_config: Dict[str, Any], persona_prompt: Optional[str] = None) -> str:
"""Build the Gemini prompt from persona direction plus the live transcript.
A ``{transcript}`` / ``{{transcript}}`` placeholder in the persona prompt is
substituted in place; otherwise the transcript is appended under a heading.
"""
"""Gemini prompt = persona direction + transcript; a ``{transcript}`` / ``{{transcript}}``
placeholder is substituted in place, otherwise the transcript is appended under a heading."""
transcript = text.strip()
if persona_prompt is None:
persona_prompt = _read_gemini_persona_prompt(gemini_config)
@@ -703,12 +666,8 @@ def _gemini_error_detail(response: Any) -> str:
def _generate_gemini_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str:
"""Generate audio via Gemini ``generateContent`` with ``responseModalities=["AUDIO"]``.
The API returns raw 24kHz mono 16-bit PCM as base64; it is wrapped as WAV and
ffmpeg-converted to MP3/Opus when the caller asked for those (no ffmpeg -> the
WAV is written under the requested name, same as NeuTTS).
"""
"""Generate audio via Gemini ``generateContent`` (``responseModalities=["AUDIO"]``). The reply is
base64 24kHz mono 16-bit PCM, wrapped as WAV and ffmpeg-converted to the requested container."""
origin = _origin()
api_key = (
origin._resolve_provider_key("GEMINI_API_KEY", "gemini")
+29 -51
View File
@@ -37,8 +37,8 @@ def _unlink_quietly(path: Optional[str]) -> None:
pass
def _align_int16_chunks(chunks: Iterable[bytes], stop_evt: threading.Event) -> Iterator[bytes]:
"""Yield int16-aligned byte chunks; a dangling odd byte is padded at the end."""
def _align_int16_chunks(chunks: Iterable[bytes], stop_evt: threading.Event, *, pad_tail: bool = True) -> Iterator[bytes]:
"""Yield int16-aligned byte chunks; a dangling odd byte is padded at the end (or dropped)."""
leftover = b""
for chunk in chunks:
if stop_evt.is_set():
@@ -48,7 +48,7 @@ def _align_int16_chunks(chunks: Iterable[bytes], stop_evt: threading.Event) -> I
if aligned_len >= 2:
yield buf[:aligned_len]
leftover = buf[aligned_len:] if aligned_len < len(buf) else b""
if leftover:
if leftover and pad_tail:
yield b"\x00"
@@ -95,13 +95,10 @@ def _drain_chunks(chunk_queue: "queue.Queue[Optional[bytes]]") -> List[bytes]:
class _SyncSentencePipeline:
"""Overlap per-sentence synthesis with playback for non-streaming providers.
Serial synthesize-then-play added a full synthesis-time of dead air per sentence. One
single-thread synthesis executor (sentences FIFO; providers never see concurrent calls)
feeds one playback worker through a small bounded queue: while sentence n plays, n+1 is
already synthesizing. The bound keeps lookahead/temp files small and gives the caller
backpressure. ``text_to_speech_tool`` / ``play_audio_file`` are resolved late so tests
that monkeypatch them keep working.
"""
One single-thread synthesis executor (FIFO; providers never see concurrent calls) feeds one
playback worker through a small bounded queue, so sentence n+1 synthesizes while n plays;
the bound keeps lookahead/temp files small and gives the caller backpressure.
``text_to_speech_tool`` / ``play_audio_file`` are resolved late so test patches apply."""
def __init__(self, stop_event: threading.Event, *, lookahead: int = 2):
self._stop = stop_event
@@ -157,13 +154,11 @@ class _SyncSentencePipeline:
class _StreamerPlayback:
"""Prefetch + FIFO playback for a chunked :class:`StreamingTTSProvider`.
``speak(text)`` calls ``streamer.stream()`` right away and hands the iterator to a
prefetch thread (at most 3 in flight) that buffers chunks into a bounded per-sentence
queue; the single playback worker plays those queues in order, so sentence N+1 is
already arriving while N plays. Output goes to a PortAudio stream when one could be
opened, otherwise via temp WAV files. A failing PortAudio write is retried on a
reinitialized stream up to ``_MAX_REINIT`` times before falling back to temp files.
"""
``speak(text)`` starts ``streamer.stream()`` immediately on a prefetch thread (at most 3 in
flight) buffering into a bounded per-sentence queue; one playback worker drains those in
order, so sentence N+1 arrives while N plays. Output is a PortAudio stream when one opened,
else temp WAV files; a failing write is retried on a reinitialized stream up to
``_MAX_REINIT`` times before falling back to temp files."""
_MAX_REINIT = 3
_CHUNK_QUEUE_MAX = 64
@@ -284,25 +279,17 @@ class _StreamerPlayback:
if self._current_stream is None:
self._play_sentence_via_tempfile(chunk_queue)
return
pcm_leftover = b""
while True:
chunk = chunk_queue.get()
if chunk is None or self.stop_event.is_set():
return
buf = pcm_leftover + chunk
aligned_len = len(buf) - (len(buf) % 2)
if aligned_len >= 2:
for aligned in _align_int16_chunks(iter(chunk_queue.get, None), self.stop_event, pad_tail=False):
try:
self._write_pcm(aligned)
except Exception as write_exc:
logger.warning("PortAudio write failed, attempting stream reinit: %s", write_exc)
if not self._recover_stream():
return
try:
self._write_pcm(buf[:aligned_len])
except Exception as write_exc:
logger.warning("PortAudio write failed, attempting stream reinit: %s", write_exc)
if not self._recover_stream():
return
try:
self._write_pcm(buf[:aligned_len])
except Exception:
pass
pcm_leftover = buf[aligned_len:] if aligned_len < len(buf) else b""
self._write_pcm(aligned)
except Exception:
pass
def _playback_worker(self) -> None:
"""Single consumer: play audio segments from the queue in order."""
@@ -337,24 +324,15 @@ class _StreamerPlayback:
def stream_tts_to_speaker(
text_queue: queue.Queue,
stop_event: threading.Event,
tts_done_event: threading.Event,
display_callback: Optional[Callable[[str], None]] = None,
provider: Optional[str] = None,
text_queue: queue.Queue, stop_event: threading.Event, tts_done_event: threading.Event,
display_callback: Optional[Callable[[str], None]] = None, provider: Optional[str] = None,
):
"""Consume text deltas from *text_queue*, cut them into sentences, and speak each one
the moment it's ready — the conversational path.
"""Consume text deltas from *text_queue*, cut into sentences, speak each the moment it's ready.
A registered streaming provider plays chunked PCM for the lowest latency; every other
provider (edge, the default) is spoken per-sentence via the sync ``text_to_speech_tool``
path, so audio still starts on sentence one.
Protocol: the producer puts ``str`` deltas onto *text_queue*; a ``None`` sentinel
signals end-of-text (flush remaining buffer); *stop_event* aborts early (barge-in);
*tts_done_event* is **set** in the ``finally`` block so callers waiting on it
(continuous voice mode) know playback is finished.
"""
A registered streaming provider plays chunked PCM; every other provider is spoken
per-sentence via ``text_to_speech_tool``, so audio still starts on sentence one. Protocol:
``str`` deltas, a ``None`` sentinel = end-of-text (flush), *stop_event* aborts (barge-in),
*tts_done_event* is **set** in ``finally`` so continuous voice mode knows playback finished."""
tts_done_event.clear()
origin = _origin()
sync_pipeline: Optional[_SyncSentencePipeline] = None
+72 -175
View File
@@ -1,12 +1,10 @@
"""URL safety checks — blocks requests to private/internal network addresses (SSRF).
``security.allow_private_urls: true`` disables private-IP blocking for environments
whose DNS resolves public names to private/benchmark ranges; cloud metadata
hostnames/IPs are **always** blocked. DNS rebinding (TOCTOU) is closed for Hermes-owned
httpx paths by ``create_ssrf_safe_client()`` / ``create_ssrf_safe_async_client()``, which
re-apply the policy at TCP connect and dial the validated IP while preserving Host/SNI.
Redirect bypass is mitigated by response hooks re-validating each target
(``redirect_target_from_response``); third-party SDK fetches redirect server-side.
``security.allow_private_urls: true`` disables private-IP blocking (DNS that resolves public
names to private ranges); cloud metadata hostnames/IPs are **always** blocked. DNS rebinding
(TOCTOU) is closed for Hermes-owned httpx paths by ``create_ssrf_safe_[async_]client()``, which
re-apply the policy at TCP connect and dial the validated IP while preserving Host/SNI. Redirect
bypass is mitigated by response hooks re-validating each target (``redirect_target_from_response``).
"""
import ipaddress
@@ -26,9 +24,7 @@ logger = logging.getLogger(__name__)
# Proxy env vars: when set, the runtime should delegate DNS to the proxy.
_PROXY_ENV_VARS = ("HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy")
_HTTP_SCHEMES = frozenset({"http", "https"})
_IPAddress = ipaddress.IPv4Address | ipaddress.IPv6Address
@@ -37,15 +33,11 @@ def _proxy_is_configured() -> bool:
def normalize_url_for_request(url: str) -> str:
"""Return an ASCII-safe HTTP URL for Hermes-owned URL tools (IRI -> URI).
Users/models often supply IRIs (``https://wttr.in/Köln``). Preserves URL syntax
and existing percent escapes while IDNA-encoding the host and percent-encoding
non-ASCII path/query/fragment text. URL tool inputs only — never shell commands.
"""
"""ASCII-safe HTTP URL for Hermes-owned URL tools (IRI -> URI, e.g. ``https://wttr.in/Köln``).
Preserves URL syntax and existing percent escapes while IDNA-encoding the host and
percent-encoding non-ASCII path/query/fragment text. URL tool inputs only — never shell commands."""
if not isinstance(url, str):
return url
raw = url.strip()
if not raw:
return raw
@@ -53,17 +45,13 @@ def normalize_url_for_request(url: str) -> str:
# Repair model-emitted whitespace between scheme separator and authority
# (``https:// docs.example``); that position is never meaningful in HTTP URLs.
raw = re.sub(r"^([A-Za-z][A-Za-z0-9+.-]*://)\s+", r"\1", raw)
try:
parsed = urlsplit(raw)
except ValueError:
return raw
if parsed.scheme.lower() not in _HTTP_SCHEMES:
return raw
netloc = parsed.netloc
hostname = parsed.hostname
netloc, hostname = parsed.netloc, parsed.hostname
if hostname:
try:
ascii_host = hostname.encode("idna").decode("ascii")
@@ -71,12 +59,9 @@ def normalize_url_for_request(url: str) -> str:
ascii_host = hostname
if ascii_host != hostname:
netloc = netloc.replace(hostname, ascii_host, 1)
path = quote(parsed.path, safe="/%:@!$&'()*+,;=")
query = quote(parsed.query, safe="/%:@!$&'()*+,;=?")
fragment = quote(parsed.fragment, safe="/%:@!$&'()*+,;=?")
return urlunsplit((parsed.scheme, netloc, path, query, fragment))
safe = "/%:@!$&'()*+,;="
return urlunsplit((parsed.scheme, netloc, quote(parsed.path, safe=safe),
quote(parsed.query, safe=safe + "?"), quote(parsed.fragment, safe=safe + "?")))
# Unambiguously credential-bearing query param names. Deliberately narrow: bare
@@ -86,17 +71,13 @@ _SENSITIVE_QUERY_PARAM_NAMES = frozenset({
"access_token", "api_key", "apikey", "auth_token", "authorization", "awsaccesskeyid",
"client_secret", "credential", "credentials", "jwt", "password", "passwd", "secret",
"session_id", "signature", "token", "x_amz_security_token", "x_amz_signature",
"x-amz-security-token", "x-amz-signature",
})
"x-amz-security-token", "x-amz-signature"})
def sensitive_query_param_name(url: str) -> Optional[str]:
"""Return the first credential-named query parameter in ``url`` (with a value), if any.
Checked before handing URLs to third-party fetch/browser backends: catches opaque
magic links, OAuth codes, signed-URL signatures and custom ``?token=...`` values
that prefix-based token redaction misses.
"""
"""First credential-named query parameter in ``url`` (with a value), if any. Checked before
handing URLs to third-party fetch/browser backends: catches opaque magic links, OAuth codes,
signed-URL signatures and custom ``?token=...`` values that prefix-based redaction misses."""
if not isinstance(url, str) or "?" not in url:
return None
try:
@@ -105,18 +86,15 @@ def sensitive_query_param_name(url: str) -> Optional[str]:
return None
if parsed.scheme.lower() not in _HTTP_SCHEMES or not parsed.query:
return None
for key, value in parse_qsl(parsed.query, keep_blank_values=True):
if value and unquote(key).lower() in _SENSITIVE_QUERY_PARAM_NAMES:
return key
return None
return next((key for key, value in parse_qsl(parsed.query, keep_blank_values=True)
if value and unquote(key).lower() in _SENSITIVE_QUERY_PARAM_NAMES), None)
# Cloud metadata hostnames — always blocked regardless of DNS or config toggle.
_BLOCKED_HOSTNAMES = frozenset({"metadata.google.internal", "metadata.goog"})
# Cloud metadata / credential endpoints (the #1 SSRF target) — always blocked.
# IPv4-mapped IPv6 forms are listed because resolvers may return ``::ffff:x.x.x.x``
# and ipaddress treats those as distinct.
# Cloud metadata / credential endpoints (the #1 SSRF target) — always blocked, also in
# IPv4-mapped IPv6 form (resolvers may return ``::ffff:x.x.x.x``; ipaddress treats those as distinct).
_METADATA_V4 = (
"169.254.169.254", # AWS/GCP/Azure/DO/Oracle metadata
"169.254.170.2", # AWS ECS task metadata (task IAM creds)
@@ -128,15 +106,12 @@ _ALWAYS_BLOCKED_IPS = frozenset(
| {ipaddress.ip_address("::ffff:" + ip) for ip in _METADATA_V4}
| {ipaddress.ip_address("fd00:ec2::254")} # AWS metadata (IPv6)
)
_ALWAYS_BLOCKED_NETWORKS = (
ipaddress.ip_network("169.254.0.0/16"), # entire link-local range (no legit agent target)
ipaddress.ip_network("::ffff:169.254.0.0/112"), # IPv4-mapped link-local range
)
# Entire link-local range (no legit agent target), plus its IPv4-mapped form.
_ALWAYS_BLOCKED_NETWORKS = tuple(ipaddress.ip_network(n) for n in ("169.254.0.0/16", "::ffff:169.254.0.0/112"))
# Exact HTTPS hostnames allowed to resolve to private/benchmark-space IPs
# (QQ media legitimately resolves to 198.18.0.0/15 behind local proxy infra).
_TRUSTED_PRIVATE_IP_HOSTS = frozenset({"multimedia.nt.qq.com.cn"})
_MAX_SSRF_CONNECT_IPS = 8
# 100.64.0.0/10 (CGNAT, RFC 6598) is neither is_private nor is_global in
@@ -144,27 +119,19 @@ _MAX_SSRF_CONNECT_IPS = 8
_CGNAT_NETWORK = ipaddress.ip_network("100.64.0.0/10")
# Global toggle cache (process lifetime; see _global_allow_private_urls).
_allow_private_resolved = False
_cached_allow_private: bool = False
_allow_private_resolved, _cached_allow_private = False, False
def _global_allow_private_urls() -> bool:
"""Return True when the user has opted out of private-IP blocking.
Priority: ``HERMES_ALLOW_PRIVATE_URLS`` env, ``security.allow_private_urls``,
legacy ``browser.allow_private_urls``. A multiplex gateway serves several
independently configured profiles in one process, so profile-scoped turns
(``get_hermes_home_override()`` set) bypass the process-global cache —
otherwise the first profile's opt-out would disable blocking for every later one.
"""
"""True when the user has opted out of private-IP blocking. Priority: ``HERMES_ALLOW_PRIVATE_URLS``
env, ``security.allow_private_urls``, legacy ``browser.allow_private_urls``. Profile-scoped turns
(``get_hermes_home_override()`` set) bypass the process-global cache — a multiplex gateway serves
several profiles in one process; the first profile's opt-out must not disable blocking for later ones."""
global _allow_private_resolved, _cached_allow_private
if get_hermes_home_override() is not None:
return _resolve_allow_private_urls()
if not _allow_private_resolved:
_allow_private_resolved = True
_cached_allow_private = _resolve_allow_private_urls()
_allow_private_resolved, _cached_allow_private = True, _resolve_allow_private_urls()
return _cached_allow_private
@@ -175,7 +142,6 @@ def _resolve_allow_private_urls() -> bool:
return True
if env_val in {"false", "0", "no"}:
return False # explicit false does not fall through to config
try:
from hermes_cli.config import read_raw_config
cfg = read_raw_config()
@@ -185,15 +151,13 @@ def _resolve_allow_private_urls() -> bool:
return True
except Exception:
pass # config unavailable (tests, early import) — keep default
return False
def _reset_allow_private_cache() -> None:
"""Reset the cached toggle — only for tests."""
global _allow_private_resolved, _cached_allow_private
_allow_private_resolved = False
_cached_allow_private = False
_allow_private_resolved = _cached_allow_private = False
def _normalize_hostname(host: Optional[str]) -> str:
@@ -201,7 +165,7 @@ def _normalize_hostname(host: Optional[str]) -> str:
def _parse_ip(hostname: str) -> Optional[_IPAddress]:
"""Return the IP object for a literal-IP hostname, else None."""
"""IP object for a literal-IP hostname, else None."""
try:
return ipaddress.ip_address(hostname)
except ValueError:
@@ -209,14 +173,11 @@ def _parse_ip(hostname: str) -> Optional[_IPAddress]:
def _iter_resolved_ips(addr_info: Any):
"""Yield ``(raw, ip_str, ip)`` per getaddrinfo answer.
``ip_str`` has any IPv6 scope ID (``%eth0``) stripped; ``ip`` is None when the
answer is still unparseable — each caller decides skip / fail-closed / raise.
"""
"""Yield ``(raw, ip_str, ip)`` per getaddrinfo answer. ``ip_str`` has any IPv6 scope ID
(``%eth0``) stripped; ``ip`` is None when still unparseable — each caller decides skip/fail/raise."""
for _family, _, _, _, sockaddr in addr_info:
raw = sockaddr[0]
ip_str = raw.split("%")[0] if "%" in raw else raw
ip_str = raw.split("%")[0]
yield raw, ip_str, _parse_ip(ip_str)
@@ -238,36 +199,28 @@ def _is_blocked_ip(ip: _IPAddress) -> bool:
def is_always_blocked_url(url: str) -> bool:
"""Return True when the URL targets the always-blocked floor (cloud metadata).
Narrower than ``is_safe_url``: only the sentinel hostnames/IPs, regardless of
backend, routing, or ``allow_private_urls`` — for callers that deliberately bypass
the full check (e.g. hybrid cloud browser routing private URLs to a local sidecar)
but must still enforce the non-negotiable floor. Returns False for ordinary
private/loopback URLs, DNS failures on non-sentinel hosts, and parse errors
(the caller's ordinary fail-closed path handles those).
"""
"""True when the URL targets the always-blocked floor (cloud metadata) — only the sentinel
hostnames/IPs, regardless of backend, routing, or ``allow_private_urls``. For callers that
deliberately bypass the full check (e.g. hybrid cloud browser routing private URLs to a local
sidecar) but must still enforce the floor. False for ordinary private/loopback URLs, DNS
failures and parse errors (the caller's ordinary fail-closed path handles those)."""
try:
hostname = _normalize_hostname(urlparse(url).hostname)
if not hostname:
return False
if hostname in _BLOCKED_HOSTNAMES:
logger.warning("Blocked request to internal hostname (always-blocked floor): %s", hostname)
return True
ip = _parse_ip(hostname)
if ip is not None:
if _is_always_blocked_ip(ip):
logger.warning("Blocked request to cloud metadata address (always-blocked floor): %s", hostname)
return True
return False
try:
addr_info = _getaddrinfo(hostname)
except socket.gaierror:
return False # DNS failure is not part of the floor; caller's path handles it
for raw, ip_str, resolved in _iter_resolved_ips(addr_info):
if resolved is None:
logger.warning("Unparseable IP address %r for hostname %s — skipping address", raw, hostname)
@@ -277,9 +230,7 @@ def is_always_blocked_url(url: str) -> bool:
"Blocked request to cloud metadata address (always-blocked floor): %s -> %s", hostname, ip_str
)
return True
return False
except Exception as exc:
# Parse/unexpected errors are not "always blocked"; caller decides fail-open/closed.
logger.debug("is_always_blocked_url error for %s: %s", url, exc)
@@ -292,11 +243,8 @@ def _allows_private_ip_resolution(hostname: str, scheme: str) -> bool:
def _resolved_ip_block_reason(ip: _IPAddress, allow_private: bool) -> Optional[str]:
"""Why a resolved answer must be rejected, or None if it may be dialed.
The metadata floor is checked first and ignores ``allow_private``; ordinary
private/internal classes are only blocked when ``allow_private`` is False.
"""
"""Why a resolved answer must be rejected, or None if it may be dialed. The metadata floor
ignores ``allow_private``; ordinary private/internal classes are blocked only when it is False."""
if _is_always_blocked_ip(ip):
return "cloud metadata address"
if not allow_private and _is_blocked_ip(ip):
@@ -305,12 +253,9 @@ def _resolved_ip_block_reason(ip: _IPAddress, allow_private: bool) -> Optional[s
def is_safe_url(url: str) -> bool:
"""Return True if the URL target is not a private/internal address.
Resolves the hostname and checks every answer. Fails closed on DNS errors and
unexpected exceptions. ``allow_private_urls`` skips private-IP blocking, but
cloud metadata endpoints remain blocked regardless.
"""
"""True if the URL target is not a private/internal address. Resolves the hostname and checks
every answer; fails closed on DNS errors and unexpected exceptions. ``allow_private_urls``
skips private-IP blocking, but cloud metadata endpoints remain blocked regardless."""
try:
parsed = urlparse(url)
hostname = _normalize_hostname(parsed.hostname)
@@ -325,11 +270,9 @@ def is_safe_url(url: str) -> bool:
if hostname in _BLOCKED_HOSTNAMES:
logger.warning("Blocked request to internal hostname: %s", hostname)
return False
allow_all_private = _global_allow_private_urls()
allow_private_ip = _allows_private_ip_resolution(hostname, scheme)
allow_private = allow_all_private or allow_private_ip
try:
addr_info = _getaddrinfo(hostname)
except socket.gaierror:
@@ -340,29 +283,23 @@ def is_safe_url(url: str) -> bool:
if _parse_ip(hostname) is None and _proxy_is_configured():
logger.debug(
"DNS resolution failed for %s — proxy configured, allowing through for proxy-side resolution",
hostname,
)
hostname)
return True
logger.warning("Blocked request — DNS resolution failed for: %s", hostname)
return False
for raw, ip_str, ip in _iter_resolved_ips(addr_info):
if ip is None:
logger.warning("Blocked request — unparseable IP address %r for hostname %s", raw, hostname)
return False
reason = _resolved_ip_block_reason(ip, allow_private)
if reason is not None:
logger.warning("Blocked request to %s: %s -> %s", reason, hostname, ip_str)
return False
if allow_all_private:
logger.debug("Allowing private/internal resolution (security.allow_private_urls=true): %s", hostname)
elif allow_private_ip:
logger.debug("Allowing trusted hostname despite private/internal resolution: %s", hostname)
return True
except Exception as exc:
# Fail closed: parsing edge cases must not become SSRF bypass vectors.
logger.warning("Blocked request — URL safety check error for %s: %s", url, exc)
@@ -370,7 +307,7 @@ def is_safe_url(url: str) -> bool:
async def async_is_safe_url(url: str) -> bool:
"""Same rules as :func:`is_safe_url`, with the blocking DNS work off the event loop."""
""":func:`is_safe_url` with the blocking DNS work off the event loop."""
return await asyncio.to_thread(is_safe_url, url)
@@ -379,40 +316,30 @@ class SSRFConnectionBlocked(ValueError):
def _resolved_http_connect_ips(host: str, port: int, scheme: str) -> list[str]:
"""Resolve and validate *host* at TCP-connect time; return dialable IP strings.
Closes the DNS-rebinding gap between pre-flight validation and connection
setup for direct httpx clients. The result is capped at ``_MAX_SSRF_CONNECT_IPS``,
but EVERY answer is validated.
"""
"""Resolve and validate *host* at TCP-connect time; return dialable IP strings. Closes the
DNS-rebinding gap between pre-flight validation and connect for direct httpx clients. The
result is capped at ``_MAX_SSRF_CONNECT_IPS``, but EVERY answer is validated."""
hostname = _normalize_hostname(host)
if not hostname:
raise SSRFConnectionBlocked("Blocked request with empty hostname")
if hostname in _BLOCKED_HOSTNAMES:
raise SSRFConnectionBlocked(f"Blocked request to internal hostname: {hostname}")
allow_private = _global_allow_private_urls() or _allows_private_ip_resolution(hostname, scheme)
try:
addr_info = _getaddrinfo(hostname, port)
except socket.gaierror as exc:
raise SSRFConnectionBlocked(f"Blocked request - DNS resolution failed for: {hostname}") from exc
safe_ips: list[str] = []
for raw, ip_str, ip in _iter_resolved_ips(addr_info):
if ip is None:
raise SSRFConnectionBlocked(
f"Blocked request - unparseable IP address {raw!r} for hostname {hostname}"
) from ValueError(f"{ip_str!r} does not appear to be an IPv4 or IPv6 address")
reason = _resolved_ip_block_reason(ip, allow_private)
if reason is not None:
raise SSRFConnectionBlocked(f"Blocked request to {reason} during connect: {hostname} -> {ip_str}")
if ip_str not in safe_ips and len(safe_ips) < _MAX_SSRF_CONNECT_IPS:
safe_ips.append(ip_str)
if not safe_ips:
raise SSRFConnectionBlocked(f"Blocked request - DNS returned no results for: {hostname}")
return safe_ips
@@ -420,11 +347,8 @@ def _resolved_http_connect_ips(host: str, port: int, scheme: str) -> list[str]:
class _SSRFGuardedBackendBase:
"""httpcore backend that re-resolves + validates at connect time and dials a vetted IP.
Host/SNI stay on the original hostname (the transport still sees ``host``);
Unix sockets are refused outright. Candidate IPs are tried in order and the
last connect error is re-raised so callers see the real network failure.
"""
Host/SNI stay on the original hostname; Unix sockets are refused outright. Candidate IPs are
tried in order and the last connect error is re-raised so callers see the real failure."""
def __init__(self, backend: Any, schemes_by_origin_var: Any):
self._backend = backend
@@ -434,6 +358,11 @@ class _SSRFGuardedBackendBase:
scheme = self._schemes_by_origin_var.get({}).get((host, port)) or ("https" if port == 443 else "http")
return _resolved_http_connect_ips(host, port, scheme)
@staticmethod
def _connect_errors() -> tuple:
import httpcore
return (httpcore.ConnectError, httpcore.ConnectTimeout)
@staticmethod
def _no_usable_ips(host: str, last_exc: Exception | None) -> Exception:
if last_exc is not None:
@@ -451,16 +380,12 @@ class _SSRFGuardedAsyncNetworkBackend(_SSRFGuardedBackendBase):
async def connect_tcp(self, host: str, port: int, timeout: float | None = None,
local_address: str | None = None, socket_options: Any = None) -> Any:
import httpcore
ips = await asyncio.to_thread(self._connect_ips, host, port)
last_exc: Exception | None = None
for ip in ips:
for ip in await asyncio.to_thread(self._connect_ips, host, port):
try:
return await self._backend.connect_tcp(
ip, port, timeout=timeout, local_address=local_address, socket_options=socket_options,
)
except (httpcore.ConnectError, httpcore.ConnectTimeout) as exc:
ip, port, timeout=timeout, local_address=local_address, socket_options=socket_options)
except self._connect_errors() as exc:
last_exc = exc
raise self._no_usable_ips(host, last_exc)
@@ -478,15 +403,12 @@ class _SSRFGuardedNetworkBackend(_SSRFGuardedBackendBase):
def connect_tcp(self, host: str, port: int, timeout: float | None = None,
local_address: str | None = None, socket_options: Any = None) -> Any:
import httpcore
last_exc: Exception | None = None
for ip in self._connect_ips(host, port):
try:
return self._backend.connect_tcp(
ip, port, timeout=timeout, local_address=local_address, socket_options=socket_options,
)
except (httpcore.ConnectError, httpcore.ConnectTimeout) as exc:
ip, port, timeout=timeout, local_address=local_address, socket_options=socket_options)
except self._connect_errors() as exc:
last_exc = exc
raise self._no_usable_ips(host, last_exc)
@@ -496,9 +418,7 @@ class _SSRFGuardedNetworkBackend(_SSRFGuardedBackendBase):
def _origin_scheme_context(request: Any) -> dict[tuple[str, int], str]:
host, port, scheme = request.url.host, request.url.port, request.url.scheme
if not host or port is None or scheme not in _HTTP_SCHEMES:
return {}
return {(host, port): scheme}
return {(host, port): scheme} if host and port is not None and scheme in _HTTP_SCHEMES else {}
@contextmanager
@@ -512,22 +432,17 @@ def _origin_scope(schemes_by_origin_var: Any, request: Any):
def _install_ssrf_guard_on_transport(transport: Any, schemes_by_origin_var: Any, *, is_async: bool = False) -> None:
"""Swap the transport's pool network backend for the SSRF-guarded one (idempotent).
Only the client's direct transport is guarded; proxy mounts are left alone so
final-target resolution is delegated to the (trusted) proxy egress.
"""
"""Swap the transport's pool network backend for the SSRF-guarded one (idempotent). Only the
direct transport is guarded; proxy mounts delegate final-target resolution to the trusted proxy."""
state = getattr(transport, "__dict__", {}) if transport is not None else {}
if transport is None or state.get("_hermes_ssrf_guarded", False):
return
label = "async httpx transport" if is_async else "httpx transport"
pool = state.get("_pool")
if pool is None or not hasattr(pool, "_network_backend"):
raise SSRFConnectionBlocked(f"Unsupported {label} cannot be made SSRF-safe")
backend_cls = _SSRFGuardedAsyncNetworkBackend if is_async else _SSRFGuardedNetworkBackend
pool._network_backend = backend_cls(schemes_by_origin_var)
method_name = "handle_async_request" if is_async else "handle_request"
handle = getattr(transport, method_name, None)
if handle is None:
@@ -540,7 +455,6 @@ def _install_ssrf_guard_on_transport(transport: Any, schemes_by_origin_var: Any,
def guarded_sync(request: Any) -> Any:
with _origin_scope(schemes_by_origin_var, request):
return handle(request)
setattr(transport, method_name, guarded_async if is_async else guarded_sync)
transport._hermes_ssrf_guarded = True
@@ -548,22 +462,16 @@ def _install_ssrf_guard_on_transport(transport: Any, schemes_by_origin_var: Any,
def _install_ssrf_guard_on_client(client: Any, *, is_async: bool = False) -> None:
"""Guard ``client._transport`` only; ``_mounts`` (env/explicit proxies) stay untouched."""
import contextvars
var_name = "hermes_ssrf_async_origin_schemes" if is_async else "hermes_ssrf_origin_schemes"
_install_ssrf_guard_on_transport(
getattr(client, "__dict__", {}).get("_transport"), contextvars.ContextVar(var_name), is_async=is_async,
)
getattr(client, "__dict__", {}).get("_transport"), contextvars.ContextVar(var_name), is_async=is_async)
def create_ssrf_safe_async_client(**kwargs: Any) -> Any:
"""Create an ``httpx.AsyncClient`` with connect-time SSRF validation.
Direct HTTP(S) connections are resolved, validated, and dialed by IP at
TCP-connect time while the request hostname is preserved for Host, SNI, and
certificate verification. Proxied requests delegate resolution to the proxy.
"""
"""``httpx.AsyncClient`` with connect-time SSRF validation: direct HTTP(S) connections are
resolved, validated, and dialed by IP while the hostname is preserved for Host, SNI, and
certificate verification. Proxied requests delegate resolution to the proxy."""
import httpx
client = httpx.AsyncClient(**kwargs)
_install_ssrf_guard_on_client(client, is_async=True)
return client
@@ -572,30 +480,19 @@ def create_ssrf_safe_async_client(**kwargs: Any) -> Any:
def create_ssrf_safe_client(**kwargs: Any) -> Any:
"""Create an ``httpx.Client`` with connect-time SSRF validation."""
import httpx
client = httpx.Client(**kwargs)
_install_ssrf_guard_on_client(client)
return client
def redirect_target_from_response(response: Any) -> Optional[str]:
"""Return the redirect target visible from inside an httpx response hook.
``response.next_request`` is frequently ``None`` inside hooks (populated later
by the redirect follower), which would make an SSRF redirect guard silently
never fire. Resolve from the ``Location`` header first (relative via
``urljoin``), falling back to ``next_request``.
"""
"""Redirect target visible from inside an httpx response hook. ``response.next_request`` is
frequently ``None`` inside hooks (populated later by the follower), which would make an SSRF
redirect guard silently never fire — so resolve from ``Location`` first, then ``next_request``."""
if not getattr(response, "is_redirect", False):
return None
headers = getattr(response, "headers", {}) or {}
location = headers.get("location")
location = (getattr(response, "headers", {}) or {}).get("location")
if location:
return urljoin(str(getattr(response, "url", "")), str(location))
next_request = getattr(response, "next_request", None)
if next_request:
return str(next_request.url)
return None
return str(next_request.url) if next_request else None
+66 -147
View File
@@ -3,9 +3,8 @@
(``agent/video_gen_provider.py`` ABC, ``agent/video_gen_registry.py``, ``plugins/video_gen/<name>/``).
Ships **no in-tree provider**: enable a plugin and select it in ``hermes tools`` → Video
Generation. Covers text-, image- and reference-to-video; the tool layer only does lightweight
validation and each provider clamps/ignores unsupported params inside ``generate``, so the
surface stays stable as providers ship. Video edit/extend are deliberately not exposed here.
Generation. The tool layer only does lightweight validation; each provider clamps/ignores
unsupported params inside ``generate``. Video edit/extend are deliberately not exposed here.
"""
from __future__ import annotations
@@ -19,8 +18,7 @@ from agent.video_gen_provider import (
COMMON_RESOLUTIONS,
DEFAULT_ASPECT_RATIO,
DEFAULT_RESOLUTION,
error_response,
)
error_response)
from tools.registry import registry, tool_error
logger = logging.getLogger(__name__)
@@ -75,23 +73,15 @@ VIDEO_GENERATE_SCHEMA: Dict[str, Any] = {
}
# ---------------------------------------------------------------------------
# Config readers (mirror image_generation_tool.py)
# ---------------------------------------------------------------------------
def _read_video_gen_key(key: str) -> Optional[str]:
"""Return the stripped ``video_gen.<key>`` string from config.yaml, or None."""
try:
from hermes_cli.config import load_config
cfg = load_config()
section = cfg.get("video_gen") if isinstance(cfg, dict) else None
value = section.get(key) if isinstance(section, dict) else None
from hermes_cli.config import cfg_get, load_config
value = cfg_get(load_config(), "video_gen", key)
except Exception as exc:
logger.debug("Could not read video_gen config: %s", exc)
return None
if isinstance(value, str) and value.strip():
return value.strip()
return None
return value.strip() if isinstance(value, str) and value.strip() else None
def _read_configured_video_provider() -> Optional[str]:
@@ -106,32 +96,21 @@ def _discovered_registry():
"""Import the provider registry after (idempotent) plugin discovery so user-installed plugins are visible."""
from agent import video_gen_registry
from hermes_cli.plugins import _ensure_plugins_discovered
_ensure_plugins_discovered()
return video_gen_registry, _ensure_plugins_discovered
# ---------------------------------------------------------------------------
# Availability check + provider resolution
# ---------------------------------------------------------------------------
def check_video_generation_requirements() -> bool:
"""True when at least one registered provider reports available."""
try:
registry_mod, _ = _discovered_registry()
for provider in registry_mod.list_providers():
try:
if provider.is_available():
return True
except Exception:
continue
return any(_provider_call(p, "is_available", False) for p in registry_mod.list_providers())
except Exception:
pass
return False
return False
def _resolve_active_provider():
"""Active provider or None; forces a discovery refresh on a miss (long-lived sessions
that started before a plugin was installed)."""
"""Active provider or None; a miss forces a discovery refresh (sessions older than the plugin install)."""
try:
registry_mod, ensure_discovered = _discovered_registry()
provider = registry_mod.get_active_provider()
@@ -147,32 +126,23 @@ def _resolve_active_provider():
def _missing_provider_error(configured: Optional[str]) -> str:
if configured:
return json.dumps(error_response(
error=(
f"video_gen.provider='{configured}' is set but no plugin "
f"registered that name. Run `hermes plugins list` to see "
f"installed video gen backends, or `hermes tools` → Video "
f"Generation to pick one."
),
error_type="provider_not_registered",
provider=configured,
))
error=(f"video_gen.provider='{configured}' is set but no plugin registered that name. "
f"Run `hermes plugins list` to see installed video gen backends, or "
f"`hermes tools` → Video Generation to pick one."),
error_type="provider_not_registered", provider=configured))
return json.dumps(error_response(
error=(
"No video generation backend is configured. Run `hermes tools` → "
"Video Generation to enable one (xAI, FAL, or Google Veo)."
),
error_type="no_provider_configured",
))
error=("No video generation backend is configured. Run `hermes tools` → "
"Video Generation to enable one (xAI, FAL, or Google Veo)."),
error_type="no_provider_configured"))
_BOOL_WORDS = {"true": True, "1": True, "yes": True, "on": True,
"false": False, "0": False, "no": False, "off": False}
# ---------------------------------------------------------------------------
# Handler
# ---------------------------------------------------------------------------
def _coerce_int(value: Any) -> Optional[int]:
if value is None or value == "":
return None
try:
return int(value)
return None if value is None or value == "" else int(value)
except (TypeError, ValueError):
return None
@@ -180,21 +150,15 @@ def _coerce_int(value: Any) -> Optional[int]:
def _coerce_bool(value: Any) -> Optional[bool]:
if isinstance(value, bool):
return value
if isinstance(value, str):
return {"true": True, "1": True, "yes": True, "on": True,
"false": False, "0": False, "no": False, "off": False}.get(value.strip().lower())
return None
return _BOOL_WORDS.get(value.strip().lower()) if isinstance(value, str) else None
def _normalize_reference_images(value: Any) -> Optional[List[str]]:
if value is None:
return None
if isinstance(value, str):
value = [value]
if not isinstance(value, (list, tuple)):
return None
out = [item.strip() for item in value if isinstance(item, str) and item.strip()]
return out or None
return [item.strip() for item in value if isinstance(item, str) and item.strip()] or None
def _handle_video_generate(args: Dict[str, Any], **_kw: Any) -> str:
@@ -205,29 +169,28 @@ def _handle_video_generate(args: Dict[str, Any], **_kw: Any) -> str:
# Confinement chokepoint (mirrors image_generate): non-local backends hand providers data: URLs.
from tools.image_generation_tool import _confine_source_images
image_url, reference_image_urls, confine_error = _confine_source_images(
image_url, reference_image_urls, task_id)
if confine_error is not None:
return confine_error
duration = _coerce_int(args.get("duration"))
aspect_ratio = (args.get("aspect_ratio") or DEFAULT_ASPECT_RATIO).strip() or DEFAULT_ASPECT_RATIO
resolution = (args.get("resolution") or DEFAULT_RESOLUTION).strip() or DEFAULT_RESOLUTION
negative_prompt = (args.get("negative_prompt") or "").strip() or None
audio = _coerce_bool(args.get("audio"))
seed = _coerce_int(args.get("seed"))
upscale = _coerce_bool(args.get("upscale"))
# Coerced BEFORE validation (ordering parity: a bad value raises before a missing prompt).
optional = {
"duration": _coerce_int(args.get("duration")),
"aspect_ratio": (args.get("aspect_ratio") or DEFAULT_ASPECT_RATIO).strip() or DEFAULT_ASPECT_RATIO,
"resolution": (args.get("resolution") or DEFAULT_RESOLUTION).strip() or DEFAULT_RESOLUTION,
"negative_prompt": (args.get("negative_prompt") or "").strip() or None,
"audio": _coerce_bool(args.get("audio")),
"seed": _coerce_int(args.get("seed")),
"upscale": _coerce_bool(args.get("upscale"))}
model_override = (args.get("model") or "").strip() or None
# Soft validation — providers do their own; a backend may accept image-only, our surface never does.
# Soft validation — providers do their own; our surface never accepts image-only.
if not prompt:
return tool_error("prompt is required for video generation")
if "operation" in args or "video_url" in args:
return tool_error(
"video_generate only supports text-to-video, image-to-video, and "
"reference-to-video; use a provider-specific tool for video edit/extend"
)
"reference-to-video; use a provider-specific tool for video edit/extend")
configured = _read_configured_video_provider()
provider = _resolve_active_provider()
if provider is None:
@@ -235,20 +198,9 @@ def _handle_video_generate(args: Dict[str, Any], **_kw: Any) -> str:
# Explicit arg wins, then config, then provider default.
model = model_override or _read_configured_video_model() or provider.default_model()
kwargs: Dict[str, Any] = {
"model": model,
"_model_override_explicit": bool(model_override),
"image_url": image_url,
"reference_image_urls": reference_image_urls,
"duration": duration,
"aspect_ratio": aspect_ratio,
"resolution": resolution,
"negative_prompt": negative_prompt,
"audio": audio,
"seed": seed,
"upscale": upscale,
}
"model": model, "_model_override_explicit": bool(model_override),
"image_url": image_url, "reference_image_urls": reference_image_urls, **optional}
# Drop None entries so providers see clean defaults.
kwargs = {k: v for k, v in kwargs.items() if v is not None}
pname = getattr(provider, "name", "?")
@@ -256,42 +208,28 @@ def _handle_video_generate(args: Dict[str, Any], **_kw: Any) -> str:
def _err(error: str, error_type: str) -> str:
return json.dumps(error_response(
error=error, error_type=error_type,
provider=getattr(provider, "name", ""), model=model or "", prompt=prompt,
))
provider=getattr(provider, "name", ""), model=model or "", prompt=prompt))
try:
result = provider.generate(prompt=prompt, **kwargs)
except TypeError as exc:
# An un-widened provider signature is a plugin bug, not a caller error.
logger.warning(
"video_gen provider '%s' rejected kwargs (signature too narrow): %s",
pname, exc,
)
logger.warning("video_gen provider '%s' rejected kwargs (signature too narrow): %s", pname, exc)
return _err(
f"Provider '{pname}' signature is "
f"out of date with the video_generate schema. Report this "
f"to the plugin author.",
"provider_contract",
)
f"Provider '{pname}' signature is out of date with the video_generate schema. "
f"Report this to the plugin author.",
"provider_contract")
except Exception as exc:
logger.warning("video_gen provider '%s' raised: %s", pname, exc)
return _err(f"Provider '{pname}' error: {exc}", "provider_exception")
if not isinstance(result, dict):
return _err("Provider returned a non-dict result", "provider_contract")
return json.dumps(result)
# ---------------------------------------------------------------------------
# Dynamic schema — reflect the active backend's actual capabilities
# ---------------------------------------------------------------------------
# Surfacing the per-model surface (modalities, enums, durations, audio/negative-prompt)
# means the model usually gets the call right first try. model_tools.get_tool_definitions()
# keys its cache on config.yaml mtime, so the schema rebuilds on provider/model change.
# Optional params advertised only when the provider's capabilities() sets the flag
# (order = schema property order).
# Dynamic schema — reflects the active backend's actual capabilities so the model usually gets
# the call right first try. model_tools.get_tool_definitions() keys its cache on config.yaml
# mtime, so the schema rebuilds on provider/model change. Optional params below are advertised
# only when the provider's capabilities() sets the flag (order = schema property order).
_CAPABILITY_PARAMS = (
("supports_negative_prompt", "negative_prompt", {
"type": "string",
@@ -334,34 +272,31 @@ _GENERIC_DESCRIPTION = (
def _schema(description: str, properties: Dict[str, Any]) -> Dict[str, Any]:
return {
"description": description,
"parameters": {"type": "object", "properties": properties, "required": ["prompt"]},
}
"parameters": {"type": "object", "properties": properties, "required": ["prompt"]}}
def _provider_call(provider: Any, method: str, default: Any) -> Any:
"""``provider.<method>()`` or ``default`` when it raises or returns a falsy value."""
try:
return getattr(provider, method)() or default
except Exception:
return default
def _build_dynamic_video_schema() -> Dict[str, Any]:
"""Render description AND params from capabilities() + the model's catalog entry; enums and
duration bounds tighten to the active model. Unadvertised args are still accepted (replay compat)."""
"""Description AND params from capabilities() + the model's catalog entry; enums and duration
bounds tighten to the active model. Unadvertised args are still accepted (replay compat)."""
static_props = VIDEO_GENERATE_SCHEMA["parameters"]["properties"]
parts: List[str] = [_GENERIC_DESCRIPTION]
configured_model = _read_configured_video_model()
provider = _resolve_active_provider()
if provider is None:
parts.append(
"\nNo video backend is available. Calls will return an error "
"until the user picks one via `hermes tools` → Video Generation."
)
"until the user picks one via `hermes tools` → Video Generation.")
return _schema("\n".join(parts), {"prompt": static_props["prompt"]})
try:
caps = provider.capabilities() or {}
except Exception:
caps = {}
try:
models = provider.list_models() or []
except Exception:
models = []
caps = _provider_call(provider, "capabilities", {})
models = _provider_call(provider, "list_models", [])
active_model = configured_model or provider.default_model()
model_meta = next((m for m in models if isinstance(m, dict) and m.get("id") == active_model), {})
@@ -374,11 +309,9 @@ def _build_dynamic_video_schema() -> Dict[str, Any]:
if "image" in model_modalities and "text" not in model_modalities:
parts.append(
"- this model is image-to-video only — image_url is REQUIRED; "
"text-only calls will be rejected"
)
"text-only calls will be rejected")
elif "text" in model_modalities and "image" not in model_modalities:
parts.append("- this model is text-to-video only — image_url is not supported")
effective_modalities = model_modalities or set(caps.get("modalities") or [])
can_i2v = "image" in effective_modalities
t2v = "text" in effective_modalities
@@ -386,33 +319,26 @@ def _build_dynamic_video_schema() -> Dict[str, Any]:
parts.append("- image-to-video only: image_url is REQUIRED")
elif not can_i2v:
parts.append("- text-to-video only (no image input)")
if provider.name == "xai":
parts.append(
"- chaining: for edit/extend pass the public HTTPS MP4 in `video` "
"or `public_url` from the prior Imagine result (files-cdn). For "
"image-to-video / reference-to-video pass public image URLs the "
"same way"
)
"same way")
try:
from tools.xai_http import xai_storage_notice_text
notice = xai_storage_notice_text("video_gen")
except Exception:
notice = ""
if notice:
parts.append(f"- storage: {notice}")
properties: Dict[str, Any] = {"prompt": static_props["prompt"]}
if can_i2v:
properties["image_url"] = {
"type": "string",
"description": (
"Public HTTPS URL of a still image to animate "
"(image-to-video). Omit for text-to-video."
),
}
"(image-to-video). Omit for text-to-video.")}
max_refs = int(caps.get("max_reference_images") or 0)
if max_refs > 0:
properties["reference_image_urls"] = {
@@ -421,10 +347,7 @@ def _build_dynamic_video_schema() -> Dict[str, Any]:
"maxItems": max_refs,
"description": (
f"Up to {max_refs} public HTTPS reference image URLs "
"(style or character refs)."
),
}
"(style or character refs).")}
min_duration = model_meta.get("min_duration", caps.get("min_duration"))
max_duration = model_meta.get("max_duration", caps.get("max_duration"))
duration_param = dict(static_props["duration"])
@@ -433,8 +356,7 @@ def _build_dynamic_video_schema() -> Dict[str, Any]:
duration_param["maximum"] = int(max_duration)
duration_param["description"] = (
f"Video duration in seconds ({min_duration}-{max_duration}). "
"Omit for the provider default."
)
"Omit for the provider default.")
properties["duration"] = duration_param
# Tighten enums to the active backend's actual sets when declared.
@@ -443,7 +365,6 @@ def _build_dynamic_video_schema() -> Dict[str, Any]:
if caps.get(caps_key):
param["enum"] = list(caps[caps_key])
properties[key] = param
for flag, key, param in _CAPABILITY_PARAMS:
if caps.get(flag):
properties[key] = param
@@ -451,8 +372,7 @@ def _build_dynamic_video_schema() -> Dict[str, Any]:
parts.append(
"- audio: native stereo audio is generated with every video "
"(always on; no toggle) — describe the desired sound in the "
"prompt"
)
"prompt")
properties["model"] = static_props["model"]
return _schema("\n".join(parts), properties)
@@ -466,5 +386,4 @@ registry.register(
requires_env=[],
is_async=False,
emoji="🎬",
dynamic_schema_overrides=_build_dynamic_video_schema,
)
dynamic_schema_overrides=_build_dynamic_video_schema)
+275 -534
View File
File diff suppressed because it is too large Load Diff
+69 -133
View File
@@ -1,9 +1,8 @@
"""Image format detection, normalization and region cropping for vision tools.
Everything here runs BEFORE an image is base64-embedded. A vision tool result
is baked into immutable conversation history and re-sent every turn, so an
unsupported media type or corrupt bytes would wedge the session with a
non-retryable 400 on every resume — normalization must happen up front.
Everything here runs BEFORE an image is base64-embedded: a vision tool result is
baked into immutable history and re-sent every turn, so an unsupported media type
or corrupt bytes would wedge the session with a non-retryable 400 on every resume.
"""
from __future__ import annotations
@@ -30,8 +29,11 @@ _EXTENSION_MIME_TYPES = {
# Media types the major vision providers (Anthropic in particular) accept
# inline. SVG/BMP/TIFF are rejected with a non-retryable 400.
_ANTHROPIC_SUPPORTED_MEDIA_TYPES = frozenset(
{"image/jpeg", "image/png", "image/gif", "image/webp"}
_ANTHROPIC_SUPPORTED_MEDIA_TYPES = frozenset({"image/jpeg", "image/png", "image/gif", "image/webp"})
_MAGIC_MIME_TYPES = (
(b"\xff\xd8\xff", "image/jpeg"), ((b"GIF87a", b"GIF89a"), "image/gif"), (b"BM", "image/bmp"),
)
@@ -41,17 +43,12 @@ def _determine_mime_type(image_path: Path) -> str:
def _detect_image_mime_type_from_bytes(data: bytes) -> Optional[str]:
"""Magic-byte MIME sniff (authoritative; no extension trust).
Returns ``None`` for anything without a recognized header — including SVG,
which has no magic bytes (the resolver sniffs ``<svg`` and passes it
through for rasterization).
"""
"""Magic-byte MIME sniff (authoritative; no extension trust). ``None`` for anything without a
recognized header — including SVG, which has none (the resolver sniffs ``<svg`` itself)."""
header = data[:64]
if header.startswith(b"\x89PNG\r\n\x1a\n"):
# Magic bytes alone are insufficient: reject corrupt PNGs before they
# can be embedded. Pillow is optional — without it fall back to
# header-only sniffing; only an actual failed verify() rejects.
# Reject corrupt PNGs before they can be embedded. Pillow is optional —
# without it fall back to header-only sniffing; only a failed verify() rejects.
try:
from PIL import Image
except ImportError:
@@ -59,52 +56,41 @@ def _detect_image_mime_type_from_bytes(data: bytes) -> Optional[str]:
try:
with Image.open(BytesIO(data)) as image:
image.verify()
return "image/png"
except Exception:
return None
return "image/png"
if header.startswith(b"\xff\xd8\xff"):
return "image/jpeg"
if header.startswith((b"GIF87a", b"GIF89a")):
return "image/gif"
if header.startswith(b"BM"):
return "image/bmp"
for magic, mime in _MAGIC_MIME_TYPES:
if header.startswith(magic):
return mime
if len(header) >= 12 and header[:4] == b"RIFF" and header[8:12] == b"WEBP":
return "image/webp"
return None
def _supported_media_types() -> frozenset:
"""Formats the ACTIVE main model's server can decode.
The managed llama-server decodes with stb_image — no WebP — and an
undecodable image part fails SILENTLY (the model confabulates), so the set
is narrowed there and normalization converts those formats to PNG.
"""
"""Formats the ACTIVE main model's server can decode. The managed llama-server decodes with
stb_image — no WebP — and an undecodable image part fails SILENTLY (the model confabulates),
so the set is narrowed there and normalization converts those formats to PNG."""
try:
from agent.auxiliary_client import _runtime_main_value
from hermes_cli.local_runtime.capabilities import (
ACCEPTED_IMAGE_MIMES,
is_managed_provider,
)
if is_managed_provider(
str(_runtime_main_value("provider") or ""),
str(_runtime_main_value("base_url") or "")):
from agent.auxiliary_client import _runtime_main_value as _v
from hermes_cli.local_runtime.capabilities import ACCEPTED_IMAGE_MIMES, is_managed_provider
if is_managed_provider(str(_v("provider") or ""), str(_v("base_url") or "")):
return ACCEPTED_IMAGE_MIMES
except Exception: # noqa: BLE001 — best-effort narrowing only
except Exception: # best-effort narrowing only
pass
return _ANTHROPIC_SUPPORTED_MEDIA_TYPES
def _nonempty_file(path: Path) -> bool:
return path.exists() and path.stat().st_size > 0
def _rasterize_svg_to_png(svg_path: Path, out_path: Path) -> bool:
"""Best-effort SVG → PNG via cairosvg, svglib+reportlab, rsvg-convert, inkscape (all soft deps)."""
def _ok() -> bool:
return out_path.exists() and out_path.stat().st_size > 0
try:
import cairosvg # type: ignore
cairosvg.svg2png(url=str(svg_path), write_to=str(out_path))
return _ok()
return _nonempty_file(out_path)
except Exception:
pass
try:
@@ -113,23 +99,18 @@ def _rasterize_svg_to_png(svg_path: Path, out_path: Path) -> bool:
drawing = svg2rlg(str(svg_path))
if drawing is not None:
renderPM.drawToFile(drawing, str(out_path), fmt="PNG")
return _ok()
return _nonempty_file(out_path)
except Exception:
pass
import shutil
import subprocess
for cmd in (
["rsvg-convert", "-o", str(out_path), str(svg_path)],
["inkscape", str(svg_path), "--export-type=png",
f"--export-filename={out_path}"],
):
["inkscape", str(svg_path), "--export-type=png", f"--export-filename={out_path}"]):
if shutil.which(cmd[0]):
try:
subprocess.run(
cmd, check=True, capture_output=True, timeout=30,
stdin=subprocess.DEVNULL,
)
if _ok():
subprocess.run(cmd, check=True, capture_output=True, timeout=30, stdin=subprocess.DEVNULL)
if _nonempty_file(out_path):
return True
except Exception:
continue
@@ -137,58 +118,43 @@ def _rasterize_svg_to_png(svg_path: Path, out_path: Path) -> bool:
def _normalize_to_supported_image(
image_path: Path, detected_mime: str
) -> tuple[Optional[Path], Optional[str], Optional[str]]:
"""Ensure an image is in a provider-supported format.
Returns ``(path, mime, error)``: the input unchanged when already
supported; ``(new_png_path, "image/png", None)`` after conversion — a temp
file the CALLER must clean up; ``(None, None, message)`` when impossible.
SVG is rasterized; other Pillow-readable rasters (BMP, TIFF) re-encode to PNG.
"""
image_path: Path, detected_mime: str) -> tuple[Optional[Path], Optional[str], Optional[str]]:
"""Ensure an image is in a provider-supported format. Returns ``(path, mime, error)``: the input
unchanged when supported; ``(new_png_path, "image/png", None)`` after conversion — a temp file
the CALLER must clean up; ``(None, None, message)`` when impossible. SVG is rasterized; other
Pillow-readable rasters (BMP, TIFF) re-encode to PNG."""
if detected_mime in _supported_media_types():
return image_path, detected_mime, None
out_dir = get_hermes_dir("cache/vision", "temp_vision_images")
out_dir.mkdir(parents=True, exist_ok=True)
out_path = out_dir / f"converted_{uuid.uuid4()}.png"
if detected_mime == "image/svg+xml":
if _rasterize_svg_to_png(image_path, out_path):
return out_path, "image/png", None
return (
None,
None,
return None, None, (
"This is an SVG, which vision models cannot read directly, and no "
"SVG rasterizer is installed (tried cairosvg, svglib, rsvg-convert, "
"inkscape). Convert the SVG to PNG first — e.g. open it in a browser "
"and screenshot it, or install a rasterizer "
"(`pip install cairosvg`) — then re-run vision_analyze on the PNG.",
)
"(`pip install cairosvg`) — then re-run vision_analyze on the PNG.")
try:
from PIL import Image as _PILImage
with _PILImage.open(image_path) as _img:
if _img.mode not in ("RGB", "RGBA", "L"):
_img = _img.convert("RGBA")
_img.save(out_path, format="PNG")
if out_path.exists() and out_path.stat().st_size > 0:
if _nonempty_file(out_path):
return out_path, "image/png", None
except Exception as _exc:
logger.warning("Failed to normalize %s image to PNG: %s",
detected_mime, _exc)
return (
None,
None,
logger.warning("Failed to normalize %s image to PNG: %s", detected_mime, _exc)
return None, None, (
f"Image format {detected_mime!r} is not supported by the vision API "
f"and could not be converted to PNG (install Pillow for raster "
f"conversion). Convert it to PNG or JPEG and try again.",
)
f"conversion). Convert it to PNG or JPEG and try again.")
# Full raster validation runs on untrusted images in a shared CPU executor:
# bound animated-image work by frame count AND total decoded area so a compact
# file cannot monopolize a worker with unbounded frames.
# Full raster validation runs on untrusted images in a shared CPU executor: bound animated
# work by frame count AND total decoded area so a compact file cannot monopolize a worker.
_VISION_MAX_VALIDATED_FRAME_COUNT = 100
_VISION_MAX_VALIDATED_AGGREGATE_PIXELS = 100_000_000
@@ -196,17 +162,12 @@ _VISION_MAX_VALIDATED_AGGREGATE_PIXELS = 100_000_000
def _validate_raster_image_decodable(
image_path: Path,
max_frames: int = _VISION_MAX_VALIDATED_FRAME_COUNT,
max_pixels: int = _VISION_MAX_VALIDATED_AGGREGATE_PIXELS,
) -> Optional[str]:
"""Return an error unless Pillow can fully decode every frame.
Header sniffing and ``Image.open`` only inspect containers: a timed-out
download can look like a valid PNG with a truncated pixel stream. Without
Pillow the image passes unvalidated rather than rejecting everything.
"""
max_pixels: int = _VISION_MAX_VALIDATED_AGGREGATE_PIXELS) -> Optional[str]:
"""Return an error unless Pillow can fully decode every frame. Header sniffing and ``Image.open``
only inspect containers: a timed-out download can look like a valid PNG with a truncated pixel
stream. Without Pillow the image passes unvalidated rather than rejecting everything."""
try:
from PIL import Image as _PILImage
from PIL import ImageSequence as _PILImageSequence
from PIL import Image as _PILImage, ImageSequence as _PILImageSequence
except ImportError:
return None
try:
@@ -214,23 +175,19 @@ def _validate_raster_image_decodable(
image.verify()
with _PILImage.open(image_path) as image:
validated_pixels = 0
for frame_number, frame in enumerate(
_PILImageSequence.Iterator(image), start=1
):
for frame_number, frame in enumerate(_PILImageSequence.Iterator(image), start=1):
if frame_number > max_frames:
return (
"Image validation rejected animation: "
f"frame {frame_number} exceeds the maximum "
f"{max_frames} validated frames."
)
f"{max_frames} validated frames.")
next_validated_pixels = validated_pixels + frame.width * frame.height
if next_validated_pixels > max_pixels:
return (
"Image validation rejected animation: aggregate decoded "
f"pixel count would reach {next_validated_pixels} at frame "
f"{frame_number}, exceeding the maximum "
f"{max_pixels}."
)
f"{max_pixels}.")
frame.load()
validated_pixels = next_validated_pixels
except Exception as exc:
@@ -239,12 +196,9 @@ def _validate_raster_image_decodable(
def _image_exceeds_dimension(image_path: Path, max_dimension: int) -> bool:
"""True if the longest side exceeds ``max_dimension`` px.
Anthropic enforces an 8000px per-side cap independently of the byte cap.
Returns False (no forced resize) without Pillow or on unreadable files —
a missing soft dependency must never break the embed path.
"""
"""True if the longest side exceeds ``max_dimension`` px (Anthropic's 8000px per-side cap is
independent of bytes). False without Pillow or on unreadable files — a missing soft
dependency must never break the embed path."""
try:
from PIL import Image as _PILImage
with _PILImage.open(image_path) as _img:
@@ -254,57 +208,39 @@ def _image_exceeds_dimension(image_path: Path, max_dimension: int) -> bool:
def _crop_image_region(
image_path: Path,
region: Any,
offset_out: Optional[dict] = None,
image_path: Path, region: Any, offset_out: Optional[dict] = None
) -> tuple[Optional[Path], Optional[str], Optional[str]]:
"""Crop to ``region`` = [x1, y1, x2, y2] (original-image pixels).
Applied BEFORE downscaling so the crop gets the full resolution budget.
Coordinates clamp to the image bounds; a zero-area/inverted region is
rejected with an error naming the real dimensions. Returns
``(cropped_temp_path, mime, None)`` — caller owns cleanup — or
``(None, None, error)``. Ported from QwenLM/qwen-code zoom-image.ts (Apache-2.0).
"""
"""Crop to ``region`` = [x1, y1, x2, y2] (original-image pixels), BEFORE downscaling so the crop
gets the full resolution budget. Coordinates clamp to the image bounds; a zero-area/inverted
region is rejected with an error naming the real dimensions. Returns ``(cropped_temp_path,
mime, None)`` — caller owns cleanup — or ``(None, None, error)``.
Ported from QwenLM/qwen-code zoom-image.ts (Apache-2.0)."""
try:
from PIL import Image
except ImportError:
return None, None, (
"region cropping requires Pillow (`pip install Pillow`); "
"retry without the region parameter."
)
if (
not isinstance(region, (list, tuple))
or len(region) != 4
or not all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in region)
):
"retry without the region parameter.")
if not (isinstance(region, (list, tuple)) and len(region) == 4
and all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in region)):
return None, None, (
"Invalid region: expected [x1, y1, x2, y2] as four numbers "
"(pixel coordinates in the original image)."
)
"(pixel coordinates in the original image).")
try:
with Image.open(image_path) as img:
width, height = img.size
x1, y1, x2, y2 = (int(v) for v in region)
cx1 = max(0, min(x1, width))
cy1 = max(0, min(y1, height))
cx2 = max(0, min(x2, width))
cy2 = max(0, min(y2, height))
cx1, cy1, cx2, cy2 = (max(0, min(v, b)) for v, b in zip((x1, y1, x2, y2), (width, height) * 2))
if cx2 <= cx1 or cy2 <= cy1:
return None, None, (
f"Invalid region [{x1}, {y1}, {x2}, {y2}]: crops to zero "
f"area after clamping to the image bounds. The image is "
f"{width}x{height} px — pick x1<x2 and y1<y2 inside "
f"[0, 0, {width}, {height}]."
)
f"[0, 0, {width}, {height}].")
cropped = img.crop((cx1, cy1, cx2, cy2))
if offset_out is not None:
offset_out.update(x=cx1, y=cy1, width=cx2 - cx1, height=cy2 - cy1)
out_path = image_path.with_name(
f"{image_path.stem}_region_{uuid.uuid4().hex[:8]}.png"
)
out_path = image_path.with_name(f"{image_path.stem}_region_{uuid.uuid4().hex[:8]}.png")
if cropped.mode not in ("RGB", "RGBA", "L", "LA", "P"):
cropped = cropped.convert("RGB")
cropped.save(out_path, format="PNG")