diff --git a/tools/AGENTS.md b/tools/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..41c7775f6d366e77aad56673d9071c50d0aca0f6 --- /dev/null +++ b/tools/AGENTS.md @@ -0,0 +1,108 @@ +# tools/ + toolsets.py + model_tools.py — model tools + +Applies on top of the root `AGENTS.md`: settle the **Footprint Ladder** before adding anything here. +Most capabilities should NOT be core tools. Long-form: `website/docs/developer-guide/adding-tools.md`, +`tools-runtime.md`. + +## Registry and discovery + +`tools/registry.py` has no deps and is imported by every tool file; each `tools/*.py` calls +`registry.register()` at import time; `model_tools.py` imports the registry and triggers discovery +(`discover_builtin_tools()`), then `run_agent.py`, `cli.py`, `batch_runner.py`, `environments/` +consume it. Any `tools/*.py` with a top-level `registry.register()` is imported automatically — no +manual import list. A tool that is a whole package (`tools/connectors/`) registers from +`tools//tool.py`, the only file discovery scans inside a package; every sibling in the package +is a library by construction, and the package needs an `__init__.py` or discovery skips it with a +warning (setuptools would drop it from the wheel). The registry handles schema collection, dispatch (`handle_function_call()`), +availability (`check_fn`, TTL-cached process-wide), and error wrapping. **All handlers return a JSON +string.** + +## Adding a core tool (2 files) — only when the user is explicitly contributing a core tool + +For custom/local-only tools do NOT edit core: create `~/.hermes/plugins//plugin.yaml` + +`__init__.py` and call `ctx.register_tool(...)`; plugin toolsets are discovered automatically and +toggled without touching `tools/` or `toolsets.py` (`plugins/AGENTS.md`). + +1. `tools/your_tool.py`: + ```python + from tools.registry import registry + def check_requirements() -> bool: return bool(os.getenv("EXAMPLE_API_KEY")) + def example_tool(param: str, task_id: str = None) -> str: return json.dumps({"success": True, ...}) + registry.register(name="example_tool", toolset="example", + schema={"name": "example_tool", "description": "...", "parameters": {...}}, + handler=lambda args, **kw: example_tool(param=args.get("param", ""), task_id=kw.get("task_id")), + check_fn=check_requirements, requires_env=["EXAMPLE_API_KEY"]) + ``` +2. `toolsets.py`: add the name to `_HERMES_CORE_TOOLS` (all platforms) or a new toolset. **Required** + — discovery registers the schema, but a tool is only exposed if a toolset names it. + `_HERMES_CORE_TOOLS` is the default bundle every platform's base toolset inherits, not dead code. + +Rules for tool code: +- **Schema descriptions must not name tools from other toolsets** (`browser_navigate` saying "prefer + web_search"). Those tools may be unavailable (missing key, disabled toolset) and the model + hallucinates calls to them. Cross-references are added dynamically in `get_tool_definitions()` in + `model_tools.py` — see the `browser_navigate` / `execute_code` post-processing blocks. +- **Paths in schema descriptions use `display_hermes_home()`** (schema is built at import, after + `_apply_profile_override()` set `HERMES_HOME`). **State files use `get_hermes_home()`**, never + `Path.home()/.hermes`, so each profile gets its own state. +- **No `offset`/`limit` on instructional tools** (skills, prompts, playbooks) — models read page 1 + and skip the rest (root rubric). +- **`check_fn` answers reachability/opt-in, never surface.** It is TTL-cached process-wide, and one + process serves many sessions; GUI-only tools go in a named toolset (`desktop_ui`, `project`) + folded in by `_load_enabled_toolsets(platform)` (root: capability is a property of the SESSION). +- **Agent-level tools** (`todo`, `memory`) are intercepted before `handle_function_call()` via the + `INLINE_TOOL_EXECUTORS` table (`agent/inline_tool_executors.py`; `agent/AGENTS.md`). +- **`_last_resolved_tool_names`** is a process-global in `model_tools.py`; `_run_single_child()` in + `delegate_tool.py` saves/restores it around child runs — readers may see it stale mid-delegation. +- New tools integrate with existing setup UX (`hermes tools`, `hermes setup`, auto-install) rather + than a raw env var; secrets go in `OPTIONAL_ENV_VARS` (`hermes_cli/AGENTS.md`). + +## Toolsets (`toolsets.py`) + +Single `TOOLSETS` dict. Keys today: `browser, clarify, code_execution, cronjob, debugging, +delegation, discord, discord_admin, feishu_doc, feishu_drive, file, homeassistant, image_gen, +kanban, memory, messaging, moa, rl, safe, search, session_search, skills, spotify, terminal, todo, +tts, video, vision, web, yuanbao` (don't assert the list in tests). Per-platform enable/disable via +`hermes tools` (curses) or `tools..enabled/disabled` in config.yaml. `browser_exec` +replaces the other browser tools when `browser.backend` is `browser-use`. + +## Backends and providers inside tools/ + +Several tools front pluggable backends: terminal environments in `tools/environments/` (local, +docker, ssh, modal, daytona, singularity; `terminal_tool_backends.py`, `tool_backend_helpers.py`), +browser (`browser_tool_*.py`: cdp, cloud, install, lifecycle, session, real_profile, vision), MCP +client (`mcp_tool_*.py`: config, discovery, transport, registration, content, errors), TTS +(`tts_tool_providers.py`, `tts_command_provider.py`), skills hub sources (`skills_hub_official.py` +`OptionalSkillSource`). Adding a backend = a new sibling or provider entry in the existing table, +never an `elif` on a backend name (root shape rules). Remote-backend file visibility problems are +fixed at the mount, not by adding a tool. + +## Delegation (`tools/delegate_tool.py`) + +Spawns a subagent with isolated context + terminal session; the parent waits for the summary unless +`background=true`, which returns a delegation id and re-enters the result via the async-delegation +completion queue. Shapes: single (`goal` + optional `context`, `toolsets`) or batch (`tasks: [...]`, +concurrency capped by `delegation.max_concurrent_children`, default 3). A background batch returns as ONE +completion by default; with `delegation.independent_completions` it is split into completion **units** +(`delegate_tool_dispatch._units_of`): tasks sharing a `group` join and report together; each ungrouped +task reports alone as it finishes. Units of one call share ONE pool slot (`slot_key` in +`async_delegation._dispatch`) — never count units against capacity; the executor is sized by live UNITS +and the stall clock arms when the runner starts, so a queued unit is never judged stalled. Roles: `leaf` (default; +no `delegate_task`, `clarify`, `memory`, `send_message`, `cronjob`; keeps `execute_code`) and +`orchestrator` (keeps `delegate_task`; gated by `delegation.orchestrator_enabled`, bounded by +`delegation.max_spawn_depth`, default 2). Config knobs under `delegation:`: +`max_concurrent_children, independent_completions, max_spawn_depth, child_timeout_seconds, orchestrator_enabled, +subagent_auto_approve, inherit_mcp_toolsets, max_iterations`. **Child processes:** a child's background +processes are killed at its teardown and their notices are suppressed in the parent; `process_manage(action="handoff")` +(children only) flips `ProcessSession.owner_task_id` to the parent under the registry lock +(`process_registry.transfer_ownership`) so the completion routes and reaps by the new owner; un-handed leftovers land on +the result as `orphaned_processes`, exited-but-never-read notify processes as `unread_completions` (`_ChildRun.account_background_processes`, before `cleanup` kills them). **Durability:** background +delegation is process-local; work that must survive restart uses `cronjob` or +`terminal(background=True, notify_on_complete=True)`. API: `website/docs/developer-guide/subagent-lifecycle-api.md`. + +## Tests + +`tests/tools/`. Test the handler through the registry (real dispatch), not the bare function only; +assert contracts ("every registered tool has a toolset", "no schema description names a tool from +another toolset") rather than tool counts. Approval/security-boundary tools are E2E'd with real +imports against a temp `HERMES_HOME` (see `tests/tools/test_approval_config_readonly.py`). diff --git a/tools/apply_layout_tool.py b/tools/apply_layout_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..8395a2d4809b50241959718749ae65f05f2747fd --- /dev/null +++ b/tools/apply_layout_tool.py @@ -0,0 +1,60 @@ +"""Apply a layout preset in the Hermes desktop GUI (``layout.apply`` via ``desktop_ui``). + +The renderer resolves the id against its layouts registry (core, plugin and user +presets are one list); only the active window's session acts, so a background turn +never rearranges the desktop. Preset ids are free-form on purpose. The renderer +answers with the applied id/title, or the available ids when unknown, so the model +can self-correct without a registry-listing tool. +""" + +from tools import desktop_ui +from tools.registry import registry, tool_error + + +def apply_layout_tool(preset: str) -> str: + """Ask the desktop GUI to apply layout preset ``preset``.""" + name = (preset or "").strip() + if not name: + return tool_error("preset is required — a layout preset id, e.g. 'default' or 'focus'.") + return desktop_ui.emit_or_error( + "layout.apply", {"preset": name}, f"Failed to apply layout '{name}': ", + "Layout apply is only available in the Hermes desktop app.", {"success": True, "preset": name}, + ) + + +APPLY_LAYOUT_SCHEMA = { + "name": "apply_layout", + "description": ( + "Apply a saved layout preset to the Hermes desktop app when the user " + "asks to rearrange the workspace. Built-ins: default (chat + " + "sidebars), focus (chat only), terminal-deck, quad; plugin/user " + "presets by id. To reveal ONE pane, use focus_pane instead." + ), + "parameters": { + "type": "object", + "properties": { + "preset": { + "type": "string", + "description": "Layout preset id to apply (e.g. 'default', 'focus', 'terminal-deck', 'quad', or a user/plugin preset id).", + }, + }, + "required": ["preset"], + }, +} + + +registry.register( + name="apply_layout", + toolset="desktop_ui", + schema=APPLY_LAYOUT_SCHEMA, + handler=lambda args, **kw: apply_layout_tool(preset=args.get("preset", "")), + emoji="🧱", +) + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. +import json # noqa: F401,E402 +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/approval_detection.py b/tools/approval_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..0d7732f24ac75719050ab243cb2c907bfc1e76af --- /dev/null +++ b/tools/approval_detection.py @@ -0,0 +1,1456 @@ +"""Dangerous-command detection: normalization, tokenizing, and pattern tables. + +Pure command classification for :mod:`tools.approval` — no approval state, config reads, or +prompting live here. +""" + +import functools +import logging +import os +import re +import shlex +import tempfile +import unicodedata + +logger = logging.getLogger("tools.approval") + +# Sensitive write targets, matched via ~ / $HOME / $HERMES_HOME spellings. The resolved absolute +# home is folded into these forms at detection time by _normalize_command_for_detection(), so no +# import-time path snapshot (stale once HERMES_HOME is set after import) lives in the patterns. +_SSH_SENSITIVE_PATH = r'(?:~|\$home|\$\{home\})/\.ssh(?:/|$)' +_HERMES_ENV_PATH = ( + r'(?:~\/\.hermes/|(?:\$home|\$\{home\})/\.hermes/|(?:\$hermes_home|\$\{hermes_home\})/)' r'\.env\b' +) +# ~/.hermes/config.yaml IS the security policy (approvals.mode, yolo, allowlist) and the config cache is mtime-keyed, +# so a write takes effect mid-session. Terminal-side coverage (sed -i, tee, >, cp) pairs the file_tools deny. +_HERMES_CONFIG_PATH = ( + r'(?:~\/\.hermes/|(?:\$home|\$\{home\})/\.hermes/|(?:\$hermes_home|\$\{hermes_home\})/)' r'config\.yaml\b' +) +_PROJECT_ENV_PATH = r'(?:(?:/|\.{1,2}/)?(?:[^\s/"\'`]+/)*\.env(?:\.[^/\s"\'`]+)*)' +_PROJECT_CONFIG_PATH = r'(?:(?:/|\.{1,2}/)?(?:[^\s/"\'`]+/)*config\.yaml)' +_SHELL_RC_FILES = r'(?:~|\$home|\$\{home\})/\.' r'(?:bashrc|zshrc|profile|bash_profile|zprofile)\b' +_CREDENTIAL_FILES = r'(?:~|\$home|\$\{home\})/\.' r'(?:netrc|pgpass|npmrc|pypirc)\b' +# macOS: /etc, /var, /tmp, /home are symlinks to /private/*, so /private/etc/sudoers would bypass a plain +# "/etc/" check. Match both forms. +_MACOS_PRIVATE_SYSTEM_PATH = r'/private/(?:etc|var|tmp|home)/' +_SYSTEM_CONFIG_PATH = rf'(?:/etc/|{_MACOS_PRIVATE_SYSTEM_PATH})' +_SENSITIVE_WRITE_TARGET = ( + rf'(?:{_SYSTEM_CONFIG_PATH}|/dev/sd|{_SSH_SENSITIVE_PATH}|{_HERMES_ENV_PATH}|{_HERMES_CONFIG_PATH}|' + rf'{_SHELL_RC_FILES}|{_CREDENTIAL_FILES})' +) +_USER_SENSITIVE_WRITE_TARGET = rf'(?:{_SSH_SENSITIVE_PATH}|{_SHELL_RC_FILES}|{_CREDENTIAL_FILES})' +_PROJECT_SENSITIVE_WRITE_TARGET = rf'(?:{_PROJECT_ENV_PATH}|{_PROJECT_CONFIG_PATH})' +# cp/mv/install: the sensitive path is a write target only as the LAST argument (destination), so +# `cp config.yaml backup.yaml` (config.yaml as SOURCE) stays out. +_COMMAND_TAIL = r'(?:\s*(?:&&|\|\||;).*)?$' +# `>`/`>>`/tee: the path is ALWAYS a write target regardless of what follows, so only require a +# shell word boundary (_COMMAND_TAIL let `echo x > .env extra` / `echo x > .env # note` slip past). +# `#` is deliberately NOT a boundary: a glued `#` is part of the filename (`.env#backup`). +_WRITE_TARGET_BOUNDARY = r'(?=[\s;&|<>"\']|$)' + +# ---- Hardline (unconditional) blocklist --------------------------------------------------- +# Commands that NEVER run via the agent, regardless of --yolo, approvals.mode=off, or cron approve +# mode — a floor below yolo. Applies only to environments that can damage the host (local, ssh, +# container-host cron); containerized backends already bypass the dangerous-command layer. +# Deliberately tiny: only things with no recovery path (root wipe, raw block device writes, +# shutdown, DoS). Recoverable operations (git reset --hard, chmod -R 777, curl|sh) stay in +# DANGEROUS_PATTERNS. + +# Start-of-command position: start of string, newline, subshell opener ($( or backtick), optionally consuming +# sudo/env/exec/nohup/setsid/time wrappers. Keeps shutdown/reboot rules from firing on "echo reboot" / "grep +# 'shutdown' log". Real ;/&/| separators are converted to newlines by the quote-aware _mark_command_starts pass; +# keeping them here mistakes quoted data (grep '(safe|rm -rf /)') for commands. +_CMDPOS = ( + r'(?:^|[\n`]|\$\()' r'\s*' # start position, optional whitespace + r'(?:sudo\s+(?:-[^\s]+\s+)*)?' r'(?:env\s+(?:\w+=\S*\s+)*)?' # optional sudo with flags, env VAR=VAL pairs + r'(?:(?:exec|nohup|setsid|time)\s+)*' r'\s*' # optional wrapper commands +) + + +# Destructive-path matcher for the rm hardline rules: accept the path fully wrapped in a matching +# quote pair (`rm -rf "/"`, `rm -rf "$HOME"`) OR bare with a terminator (whitespace, end, or +# `) ` ; | &` so `$(rm -rf /)` is caught). A bare-token-only anchor lets quoted spellings slip past the floor. +def _hardline_rm_path(path_alt: str, tail: str = r'(?:\s|$|[)`;|&])') -> str: + return rf'(?:["\'](?:{path_alt})["\']|(?:{path_alt}){tail})' + + +# Protected system roots whose recursive deletion has no recovery path. +_HARDLINE_SYSTEM_DIRS = (r'/home|/home/\*|/root|/root/\*|/etc|/etc/\*|/usr|/usr/\*|' + r'/var|/var/\*|/bin|/bin/\*|/sbin|/sbin/\*|/boot|/boot/\*|/lib|/lib/\*') + +# `rm` plus flag group, shared by the rm hardline rules (plain concatenation, not f-string: +# backslashes in replacement fields are unsupported on the 3.11 floor). _CMDPOS-anchored so `rm` +# must be an actual command word — "rm -rf /" as DATA in `git commit -m "…rm -rf /…"` must not trip the floor. +_RM_FLAG_PREFIX = _CMDPOS + r'rm\s+(-[^\s]*\s+)*' +# Package-manager global options, each optionally taking ONE non-dash operand. +_PKG_OPTS = r'(?:-[^\s]+(?:\s+[^-\s][^\s]*)?\s+)*' + +HARDLINE_PATTERNS = [ + # Root path: any root-anchored path whose components collapse to "/" in the shell ("/", "//", + # "/.", "/./", "/../..", optional trailing glob). Each inter-slash segment must be exactly "." + # or "..", so "/tmp", "/.ssh", even "/..." are literal dirs that fall through to the softer + # DANGEROUS rules. The "/ \*" alt covers `rm -rf / *` (two args: "/" plus the glob). + (_RM_FLAG_PREFIX + _hardline_rm_path(r'/(?:(?:\.\.?)?/)*(?:\.\.?)?\**|/ \*'), "recursive delete of root filesystem"), + (_RM_FLAG_PREFIX + _hardline_rm_path(_HARDLINE_SYSTEM_DIRS), "recursive delete of system directory"), + (_RM_FLAG_PREFIX + _hardline_rm_path(r'(?:~|\$\{?HOME\}?)(?:/?|/\*)?'), "recursive delete of home directory"), + # Command-name rules (mkfs, dd, kill, shutdown...) are _CMDPOS-anchored so quoted prose + # (`echo "does this use mkfs?"`) cannot trip the floor. + # See #93392. + (_CMDPOS + r'mkfs(\.[a-z0-9]+)?\b', "format filesystem (mkfs)"), + # `dd` is a command-name token, so anchor it to command position like mkfs/rm/shutdown (#93392): quoted + # prose such as `git commit -m "never dd of=/dev/sda"` is an argument, not a command. The argument tail + # ([^\n]*of=/dev/...) is kept so flag order doesn't matter. + (_CMDPOS + r'dd\b[^\n]*\bof=/dev/(sd|nvme|hd|mmcblk|vd|xvd)[a-z0-9]*', "dd to raw block device"), + # Positionless rules (no command-name token: `>` sits mid-command, the fork bomb is a function + # definition) are matched against a QUOTE-MASKED variant (_QUOTE_MASKED_HARDLINE_DESCRIPTIONS / + # _mask_quoted_prose) so quoted prose cannot trip them; sh -c / bash -c / eval payloads still scan raw. + # The redirect rule has no command-name token to anchor (`>` appears mid-command: `cat f > /dev/sda`), + # so command-position anchoring is the wrong tool. It is instead matched against a QUOTE-MASKED variant + # of the command (see _QUOTE_MASKED_HARDLINE / _mask_quoted_strings) so quoted prose (`echo "cat f > + # /dev/sda"`) cannot trip it, while shell-carrying wrappers (sh -c / bash -c / eval) still surface their + # payload as a raw detection variant — quoting is not a bypass (#93392). + (r'>\s*/dev/(sd|nvme|hd|mmcblk|vd|xvd)[a-z0-9]*\b', "redirect to raw block device"), + (r':\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:', "fork bomb"), + # Kill every process on the system — anchor the command-name token so `echo "kill -1 sends SIGHUP to + # everything"` doesn't trip (#93392). + (_CMDPOS + r'kill\s+(-[^\s]+\s+)*-1\b', "kill all processes"), + (_CMDPOS + r'(shutdown|reboot|halt|poweroff)\b', "system shutdown/reboot"), + (_CMDPOS + r'init\s+[06]\b', "init 0/6 (shutdown/reboot)"), + (_CMDPOS + r'systemctl\s+(poweroff|reboot|halt|kexec)\b', "systemctl poweroff/reboot"), + (_CMDPOS + r'telinit\s+[06]\b', "telinit 0/6 (shutdown/reboot)"), +] + +# Pre-compiled at module load so the hot-path matcher never pays the cold re.compile fan-out +# (re._cache can be evicted by unrelated regex work). +_RE_FLAGS = re.IGNORECASE | re.DOTALL +# Positionless hardline rules matched against quote-masked variants (see above). +_QUOTE_MASKED_HARDLINE_DESCRIPTIONS = frozenset({"redirect to raw block device", "fork bomb"}) +HARDLINE_PATTERNS_COMPILED = [ + (re.compile(p, _RE_FLAGS), d, d in _QUOTE_MASKED_HARDLINE_DESCRIPTIONS) for p, d in HARDLINE_PATTERNS +] +# Commands that hand a quoted argument to another shell to EXECUTE: quoted text is code, not +# prose, so quote-masked hardline rules scan the raw string. +_SHELL_CARRIER_NAMES = frozenset({"eval", "sh", "bash", "zsh", "ksh", "dash", "source", "."}) + + +def _contains_shell_carrier(command: str) -> bool: + """Return whether any command-position word is a shell-carrying command.""" + return any( + os.path.basename(_deobfuscate_shell_word_for_detection(word)).lower() in _SHELL_CARRIER_NAMES + for _, _, word in _iter_shell_command_word_spans(command) + ) + + +def _mask_quoted_prose(command: str) -> str: + """Blank out quoted string CONTENT for positionless hardline matching (detection-only). + Quote characters stay; inside double quotes `$(...)` and backtick spans are kept RAW because + the shell really executes them. An unclosed quote masks to end-of-string, which cannot hide a + runnable command (the shell would not run it either). + + Detection-only rewrite used by the quote-masked hardline rules (redirect-to-block-device, fork bomb): + text inside single or double quotes is data the shell passes as an argument, so `echo "cat f > + /dev/sda"` must not trip the unconditional floor (#93392). Unquoted text is untouched. + """ + return "".join( + command[i:j] if quote is None or kind in ("quote", "subst") else " " * (j - i) + for kind, i, j, quote in _scan_shell(command, subst="q", naive_backtick=True) + ) + + +# ---- Sudo stdin guard: without SUDO_PASSWORD configured, an explicit "sudo -S" is the LLM piping +# a guessed password via stdin (brute-force vector). Unconditional block. +_SUDO_STDIN_RE = re.compile(r'(?:^|[;&|`\n]|&&|\|\||\$\()\s*sudo\s+-S\b', re.IGNORECASE) + + +def _check_sudo_stdin_guard(command: str) -> tuple: + """Detect ``sudo -S`` without configured SUDO_PASSWORD -> (is_blocked, description). When + SUDO_PASSWORD is set, ``_transform_sudo_command`` injects ``-S`` itself, so this guard only + fires when the LLM wrote it explicitly.""" + if "SUDO_PASSWORD" not in os.environ and _SUDO_STDIN_RE.search(_normalize_command_for_detection(command).lower()): + return (True, "sudo password guessing via stdin (sudo -S)") + return (False, None) + + +def detect_hardline_command(command: str) -> tuple: + """Check hardline patterns (NEVER bypassable, even in YOLO) -> (is_hardline, description).""" + if _command_parser_limit_exceeded(command): + return (True, _PARSER_LIMIT_DESCRIPTION) + # The malformed-quoting verdict needs the author's quote state. Normalization strips escapes + # (`\"` -> `"`), so a shell-valid pattern like `grep -o "[^\"]*"` lexed as unterminated and was + # reported as a hardline block (118 of 125 hardline blocks in one week of real use, every one a + # benign grep). Only quoted newlines are masked: they are data, and masking keeps quoting intact. + _, malformed_grep = _grep_safe_detection_variant(_mask_quoted_newlines(command)) + if malformed_grep: + return (True, _MALFORMED_EXEC_DESCRIPTION) + for command_variant in _command_detection_variants(command): + variant_lower = command_variant.lower() + masked_lower: str | None = None + for pattern_re, description, quote_masked in HARDLINE_PATTERNS_COMPILED: + if quote_masked and masked_lower is None: + # Positionless rules see quoted prose as DATA, except under shell carriers + # (sh -c, eval, source) whose quoted argument is code — those scan raw. bash -c + # payloads also surface as their own raw variants via _execution_flag_findings. + masked_lower = ( + variant_lower if _contains_shell_carrier(command_variant) + else _mask_quoted_prose(command_variant).lower() + ) + if pattern_re.search(masked_lower if quote_masked else variant_lower): + return (True, description) + return (False, None) + + +# ---- Dangerous command patterns ----------------------------------------------------------- +DANGEROUS_PATTERNS = [ + (r'\brm\s+(-[^\s]*\s+)*/', "delete in root path"), + (r'\brm\s+-[^\s]*r', "recursive delete"), + (r'\brm\s+--recursive\b', "recursive delete (long flag)"), + # GNU rm permutes options, so flags may FOLLOW operands (`rm build/ -rf`). The operand run + # cannot cross a command separator (so `rm foo | grep -r` is not attributed to rm), a quote, + # or a bare ` -- ` end-of-options (after which `-rf` is a literal filename). The flag token + # must follow whitespace so the `r` in long options like `--registry` does not count. + (r'\brm\s+(?!--(?:\s|$))(?:(?!\s--(?:\s|$))[^\n"\';|&])*\s' r'(?:-[a-z]*r[a-z]*\b|--recursive\b)', + # GNU rm permutes options, so a recursive flag group may legally FOLLOW the operands: `rm build/ -rf`, + # `rm build/ -r -f`, and `rm build/ --recursive --force` are all equivalent to the flags-first + # spellings the two patterns above catch — without this rule they run with no approval prompt at all. + # Port of openai/codex#33464 ("recognize force options when they follow operands"). + "recursive delete (flags after operands)"), + # Windows cmd/powershell destructive built-ins: gate only when executed through the shell so + # prose/filenames containing "del"/"rd" do not trip. + (r'\bcmd(?:\.exe)?\s+/(?:c|k)\s+.*\b(?:del|erase|rd|rmdir)\b', "Windows cmd destructive delete"), + # PowerShell runs the verb as default positional arg (no -Command needed); anchor the verb to command + # position (after leading -Flag switches and optional -Command/-c) so `-File c:\del-logs\run.ps1` is not caught. + (r'\b(?:powershell|pwsh)(?:\.exe)?\b(?:\s+-\S+)*\s+(?:-(?:command|c)\s+)?["\']?(?:remove-item|rmdir|erase|del|rd|ri|rm)\b', "Windows PowerShell destructive delete"), + (r'\b(?:powershell|pwsh)(?:\.exe)?\b.*\s-(?:encodedcommand|enc|e)\b', "PowerShell encoded command execution"), + # ── Windows destructive tier: native Windows EXEs/cmdlets reachable from ANY backend on a + # Windows host (incl. git-bash). Input is lowercased by the variant loop, so patterns are + # lowercase. Each requires the destructive flag/verb so benign usage (`taskkill /IM app.exe`, + # `reg query`, `icacls file`) does NOT prompt. Bare Remove-Item form (ACP clients, pwsh-default + # SSH hosts, or compound commands where `powershell` appeared earlier). + # See #69472. + (r'\bremove-item\b[^\n;|&]*\s-(?:recurse|force)\b', "PowerShell destructive delete (Remove-Item)"), + # Bare cmd builtins with /s (recurse) or /q (quiet); plain `del file.txt` is covered only by the prefixed rule. + (r'\b(?:del|erase|rd|rmdir)\s+(?:/[a-z]\s+)*/[sq]\b', "Windows destructive delete (recursive/quiet switch)"), + # Remote content piped to Invoke-Expression — PowerShell's `curl | sh`. + (r'\b(?:iwr|invoke-webrequest|invoke-restmethod|irm|curl|wget)\b[^\n]*\|\s*(?:iex|invoke-expression)\b', "pipe remote content to PowerShell (iwr | iex)"), + (r'\b(?:iex|invoke-expression)\s*\(\s*(?:iwr|invoke-webrequest|invoke-restmethod|irm)\b', "execute remote content via Invoke-Expression"), + # Force process kills — Windows analogue of pkill -9. + (r'\btaskkill\b[^\n]*\s/f\b', "force kill processes (taskkill /F)"), + (r'\bstop-process\b[^\n]*\s-force\b', "force kill processes (Stop-Process -Force)"), + # Volume/disk destruction — Windows analogue of mkfs / dd. + (r'\bformat-volume\b', "format filesystem (Format-Volume)"), + (r'\bclear-disk\b', "wipe disk (Clear-Disk)"), + (r'\bdiskpart\b', "disk partitioning (diskpart)"), + (r'\bformat(?:\.com)?\s+[a-z]:', "format drive (format.com)"), + (r'\bcipher\s+/w\b', "wipe free space (cipher /w)"), + # ACL destruction — Windows analogue of chmod 777. + (r'\bicacls\b[^\n]*\s/grant\b[^\n]*\b(?:everyone|todos|jeder|tout\s+le\s+monde|\*s-1-1-0)\b', "grant Everyone access (icacls)"), + (r'\bicacls\b[^\n]*\s/reset\b', "reset ACLs recursively (icacls /reset)"), + # Backup/recovery destruction — classic ransomware prep. + (r'\bvssadmin\b[^\n]*\bdelete\s+shadows\b', "delete volume shadow copies (vssadmin)"), + (r'\bwbadmin\b[^\n]*\bdelete\b', "delete backups (wbadmin)"), + (r'\bbcdedit\b[^\n]*\s/set\b', "modify boot configuration (bcdedit /set)"), + # Registry deletion with force flag. + (r'\breg(?:\.exe)?\s+delete\b', "registry delete (reg delete)"), + (r'\bremove-itemproperty\b[^\n]*\s-force\b', "registry value delete (Remove-ItemProperty -Force)"), + # Windows service/system stop — analogue of systemctl stop. + (r'\bstop-service\b[^\n]*\s-force\b', "force stop service (Stop-Service -Force)"), + (r'\bsc(?:\.exe)?\s+(?:stop|delete)\b', "stop/delete service (sc)"), + # Windows-form credential paths; the POSIX ~/.ssh patterns never match drive-letter or backslash spellings. + (r'\busers[\\/][^\\/\s]+[\\/]\.ssh\b', "access to SSH keys (Windows path)"), + (r'\bappdata[\\/](?:local|roaming)[\\/]hermes[^\n]*\.env\b', "access to Hermes secrets (Windows path)"), + # ── end of Windows tier + (r'\bchmod\s+(-[^\s]*\s+)*(777|666|o\+[rwx]*w|a\+[rwx]*w)\b', "world/other-writable permissions"), + (r'\bchmod\s+--recursive\b.*(777|666|o\+[rwx]*w|a\+[rwx]*w)', "recursive world/other-writable (long flag)"), + (r'\bchown\s+(-[^\s]*)?R\s+root', "recursive chown to root"), + (r'\bchown\s+--recur[a-z]*\b.*root', "recursive chown to root (long flag)"), + # _CMDPOS-anchored like the hardline twins: quoted prose mentioning mkfs/dd must not require approval to echo. + # See #93392. + (_CMDPOS + r'mkfs\b', "format filesystem"), + (_CMDPOS + r'dd\s+.*if=', "disk copy"), + (r'>\s*/dev/sd', "write to block device"), + (r'\bDROP\s+(TABLE|DATABASE)\b', "SQL DROP"), + # [^\n]* not .*: under DOTALL a WHERE on the *next* line would satisfy the lookahead and + # silently allow DELETE without WHERE. + (r'\bDELETE\s+FROM\b(?![^\n]*\bWHERE\b)', "SQL DELETE without WHERE"), + (r'\bTRUNCATE\s+(TABLE)?\s*\w', "SQL TRUNCATE"), + (rf'>\s*{_SYSTEM_CONFIG_PATH}', "overwrite system config"), + (r'\bsystemctl\s+(-[^\s]+\s+)*(stop|restart|disable|mask)\b', "stop/restart system service"), + (r'\bkill\s+-9\s+-1\b', "kill all processes"), + (r'\bpkill\s+-9\b', "force kill processes"), + # killall with SIGKILL (-9 / -KILL / -s KILL / -SIGKILL) and `killall -r ` broad sweeps + # that can wipe unrelated processes. + (r'\bkillall\s+(-[^\s]*\s+)*-(9|KILL|SIGKILL)\b', "force kill processes (killall -KILL)"), + (r'\bkillall\s+(-[^\s]*\s+)*-s\s+(KILL|SIGKILL|9)\b', "force kill processes (killall -s KILL)"), + (r'\bkillall\s+(-[^\s]*\s+)*-r\b', "kill processes by regex (killall -r)"), + (r':\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:', "fork bomb"), + # Shell -c is parsed structurally by _execution_flag_findings(); a regex searching a dash-token + # for "c" also matched --norc/--rcfile/--restricted. + (r'\b(curl|wget)\b.*\|\s*(?:[/\w]*/)?(?:ba)?sh(?:\s|$|-c)', "pipe remote content to shell"), + (r'\b(bash|sh|zsh|ksh)\s+<\s* | base64 -d | bash` carries no dangerous keywords in the + # raw text yet runs arbitrary commands. + (r'\b(base64|base32|base16)\s+(?:-[dD]|--decode)\b.*\|\s*\b(bash|sh|zsh|ksh|dash)\b', "pipe decoded content to shell (possible command obfuscation)"), + # xxd uses -r for decode, not -d. + (r'\bxxd\s+-r\b.*\|\s*\b(bash|sh|zsh|ksh|dash)\b', "pipe xxd-decoded content to shell (possible command obfuscation)"), + # `echo 'eq -pe v/' | tr 'eqv' 'rmf' | bash` decodes to `rm -rf /`. + (r'\becho\b[^|]*\|\s*\btr\b[^|]*\|\s*\b(bash|sh|zsh|ksh|dash)\b', "pipe tr-transformed output to shell (possible command obfuscation)"), + (r'\bopenssl\b.*\b(?:base64|enc)\b[^|]*\s+-[dD]\b[^|]*\|\s*\b(bash|sh|zsh|ksh|dash)\b', + "pipe openssl-decoded content to shell (possible command obfuscation)"), + (rf'\btee\b.*["\']?{_SENSITIVE_WRITE_TARGET}', "overwrite system file via tee"), + (rf'>>?\s*["\']?{_SENSITIVE_WRITE_TARGET}', "overwrite system file via redirection"), + (rf'\btee\b.*["\']?{_PROJECT_SENSITIVE_WRITE_TARGET}["\']?{_WRITE_TARGET_BOUNDARY}', "overwrite project env/config via tee"), + (rf'>>?\s*["\']?{_PROJECT_SENSITIVE_WRITE_TARGET}["\']?{_WRITE_TARGET_BOUNDARY}', "overwrite project env/config via redirection"), + (r'\bxargs\s+.*\brm\b', "xargs with rm"), + # -execdir has the same semantics as -exec (runs in each match's directory). + (r'\bfind\b.*-exec(?:dir)?\s+(/\S*/)?rm\b', "find -exec/-execdir rm"), + (r'\bfind\b.*-delete\b', "find -delete"), + # Gateway lifecycle: stopping/restarting the gateway kills all running agents. Global flags + # between `hermes` and `gateway` (`hermes -p ade gateway restart`) are allowed so a profile flag can't slip past. + (r'\bhermes\s+(?:-{1,2}\S+(?:\s+\S+)?\s+)*gateway\s+(stop|restart)\b', "stop/restart hermes gateway (kills running agents)"), + (r'\bhermes\s+update\b', "hermes update (restarts gateway, kills running agents)"), + # Docker/Podman daemon redirect — global flags or env that point the CLI at a DIFFERENT (often remote) daemon: + # `docker -H ssh://prod stop app` looks local but operates on remote infra, so any redirect requires approval + # regardless of subcommand. The flag must be in global position (before the subcommand) and -H/--host/--context + # must carry a value, keeping `docker -h` and `docker run -h ` out. Listed BEFORE the lifecycle rules so + # a redirected lifecycle command surfaces the more specific reason. + (r'\bdocker\s+(?:-{1,2}\S+(?:[=\s]\S+)?\s+)*(?:-h|--host)[=\s]+\S+', "docker with remote daemon redirect (-H/--host)"), + (r'\bdocker\s+(?:-{1,2}\S+(?:[=\s]\S+)?\s+)*(?:-c|--context)[=\s]+\S+', "docker with daemon redirect (--context: alternate daemon)"), + (r'\bdocker\s+context\s+use\b', "docker context use (switches default daemon for future commands)"), + (r'\bpodman\s+(?:-{1,2}\S+(?:[=\s]\S+)?\s+)*(?:--url|--connection|--identity)[=\s]+\S+', "podman with remote daemon redirect (--url/--connection/--identity)"), + (r'\bpodman\s+(?:-{1,2}\S+(?:[=\s]\S+)?\s+)*(?:-r\b|--remote\b)', "podman remote mode (-r/--remote: remote daemon)"), + (r'\b(?:docker_host|docker_context|container_host|container_connection)=\S+', "docker/podman daemon redirect via environment (DOCKER_HOST/CONTAINER_HOST)"), + # Container lifecycle (docker.sock mounts let the agent stop/kill containers) always needs + # consent. Global flags between docker/compose and the verb and the legacy `docker-compose` + # binary are allowed so a flag can't slip past. + (r'\bdocker(?:-compose|\s+compose)\s+(?:-{1,2}\S+(?:[=\s]\S+)?\s+)*(restart|stop|kill|down)\b', "docker compose restart/stop/kill/down (container lifecycle)"), + (r'\bdocker\s+(?:-{1,2}\S+(?:[=\s]\S+)?\s+)*(restart|stop|kill)\b', "docker restart/stop/kill (container lifecycle)"), + # Gateway protection: never start gateway outside systemd management + (r'gateway\s+run\b.*(&\s*$|&\s*;|\bdisown\b|\bsetsid\b)', "start gateway outside systemd (use 'systemctl --user restart hermes-gateway')"), + (r'\bnohup\b.*gateway\s+run\b', "start gateway outside systemd (use 'systemctl --user restart hermes-gateway')"), + # Self-termination protection: prevent agent from killing its own process + (r'\b(pkill|killall)\b.*\b(hermes|gateway|cli\.py)\b', "kill hermes/gateway process (self-termination)"), + # Self-termination via kill + $(pgrep/pidof): the substitution is opaque to the name-based + # pattern above, so catch the structural form. + (r'\bkill\b.*\$\(\s*(pgrep|pidof)\b', "kill process via pgrep/pidof expansion (self-termination)"), + (r'\bkill\b.*`\s*(pgrep|pidof)\b', "kill process via backtick pgrep/pidof expansion (self-termination)"), + # launchctl-driven gateway stop/restart on macOS (label `ai.hermes.gateway`). Two independent lookaheads, NOT a + # sequential match: a for-loop building the label from a list defined EARLIER (`for item in 'ai.hermes...'; do + # launchctl bootout "$label"`) never has "hermes" after the verb, and that slipped past and restarted 4 gateways + # with zero approval. Erring broad is correct for an approval gate: an extra prompt is cheap. + (r'(?=[\s\S]*\blaunchctl\s+(?:stop|kickstart|bootout|unload|kill|disable|remove)\b)(?=[\s\S]*\b(?:hermes|ai\.hermes)\b)', "stop/restart hermes launchd service (kills running agents)"), + (rf'\b(cp|mv|install)\b.*\s{_SYSTEM_CONFIG_PATH}', "copy/move file into system config path"), + (rf'\b(cp|mv|install)\b.*\s["\']?{_PROJECT_SENSITIVE_WRITE_TARGET}["\']?{_COMMAND_TAIL}', "overwrite project env/config file"), + # cp/mv/install OVERWRITING a credential/SSH/shell-rc/Hermes file (key implant, login-time + # injection) — pairs the tee/redirection coverage. Anchored to the command tail so only the + # DESTINATION fires; reading OUT of a sensitive path (`cp ~/.ssh/config /tmp/x`) stays safe. + # The trailing `[^\s"\']*` consumes the rest of the destination filename. + # The tee/redirection patterns above already gate _SENSITIVE_WRITE_TARGET (~/.ssh/*, + # ~/.netrc/.pgpass/.npmrc/.pypirc, shell rc files, ~/.hermes/config.yaml/.env), but cp/mv/install was + # only paired for /etc and project-relative env/config — so `cp evil ~/.ssh/authorized_keys` (key + # implant), `cp creds ~/.netrc`, and `cp evil ~/.bashrc` (login-time command injection) slipped through + # with auto-approve. Same unpaired-door rationale as #14639 / the sed-tee-redirect pairing on these + # targets. `authorized_keys` after the `~/.ssh/` fragment). + (rf'\b(cp|mv|install)\b.*\s["\']?{_SENSITIVE_WRITE_TARGET}[^\s"\']*["\']?{_COMMAND_TAIL}', "copy/move file into sensitive credential/SSH/shell-rc path"), + # In-place edits mutate the file directly, bypassing redirection/tee/cp coverage; gate the same + # startup/credential files. + (rf'\bsed\s+-[^\s]*i.*(?:{_USER_SENSITIVE_WRITE_TARGET})[^\s"\']*', "in-place edit of sensitive credential/SSH/shell-rc path"), + (rf'\bsed\s+--in-place\b.*(?:{_USER_SENSITIVE_WRITE_TARGET})[^\s"\']*', "in-place edit of sensitive credential/SSH/shell-rc path (long flag)"), + (rf'\b(?:perl|ruby)\b.*(?:^|\s)-[^\s]*i\b.*(?:{_USER_SENSITIVE_WRITE_TARGET})[^\s"\']*', "in-place edit of sensitive credential/SSH/shell-rc path (perl/ruby)"), + (rf'\bsed\s+-[^\s]*i.*\s{_SYSTEM_CONFIG_PATH}', "in-place edit of system config"), + (rf'\bsed\s+--in-place\b.*\s{_SYSTEM_CONFIG_PATH}', "in-place edit of system config (long flag)"), + # sed -i on Hermes config/.env bypasses the redirection/tee rules; pairs the file_tools + # write_file/patch deny so the terminal side is not an open door. + # In-place edit of a Hermes-managed security file (~/.hermes/config.yaml or .env). sed -i bypasses the + # redirection/tee patterns above because it mutates the file directly. See #14639. + (rf'\bsed\s+-[^\s]*i.*(?:{_HERMES_CONFIG_PATH}|{_HERMES_ENV_PATH})', "in-place edit of Hermes config/env"), + (rf'\bsed\s+--in-place\b.*(?:{_HERMES_CONFIG_PATH}|{_HERMES_ENV_PATH})', "in-place edit of Hermes config/env (long flag)"), + # perl/ruby -i: the flag may be its own token after other flags (`-p -i -e`), combined (`-pi`), or carry a backup + # suffix (`-i.bak`), so match any flag token containing `i` anywhere; `perl -e '...'` (no -i) does not trip. + # perl -i and ruby -i perform the same in-place mutation as sed -i but are not caught by the -e/-c + # script-execution pattern above (which targets code evaluation, not file mutation). Pairs the sed -i + # coverage from #14639. + (rf'\b(?:perl|ruby)\b.*(?:^|\s)-[^\s]*i\b.*(?:{_HERMES_CONFIG_PATH}|{_HERMES_ENV_PATH})', "in-place edit of Hermes config/env (perl/ruby)"), + # Interpreter heredocs are handled by _execution_flag_findings(); only shell heredocs stay + # regex-based. `bash <<'EOF'` runs arbitrary commands without triggering the `bash -c` path. + (r'\b(bash|sh|zsh|ksh)\s+<<', "shell execution via heredoc"), + # Git destructive operations. `git reset --hard` accepts any unambiguous long-flag prefix (--h, + # --ha, --har): --hard is the only reset mode starting with "h", and `--help` is special-cased + # by git before mode resolution. + (r'\bgit\s+reset\s+--h(?:a(?:r(?:d)?)?)?\b', "git reset --hard (destroys uncommitted changes)"), + (r'\bgit\s+push\b.*--forc[a-z]*\b', "git force push (rewrites remote history)"), + (r'\bgit\s+push\b.*-f\b', "git force push short flag (rewrites remote history)"), + (r'\bgit\s+clean\s+-[^\s]*f', "git clean with force (deletes untracked files)"), + (r'\bgit\s+branch\s+-D\b', "git branch force delete"), + # `-D` = `-d --force`; the long spellings are different tokens, so match delete+force in either order, bounded to + # one command segment (no `;`/`|`/`&`/newline) so an unrelated later command isn't contaminated. + (r'\bgit\s+branch\b[^;|&\n]*?(?:-d\b|--delete\b)[^;|&\n]*?(?:-f\b|--force\b)', "git branch force delete (long flags)"), + (r'\bgit\s+branch\b[^;|&\n]*?(?:-f\b|--force\b)[^;|&\n]*?(?:-d\b|--delete\b)', "git branch force delete (long flags, force-first)"), + # chmod +x then immediate run: the script content may hold dangerous commands individual patterns miss. + (r'\bchmod\s+\+x\b.*[;&|]+\s*\./', "chmod +x followed by immediate execution"), + # Sudo stdin/askpass/shell/list-privs flags. The agent has no TTY, so sudo invocations that succeed + # non-interactively read the password from stdin (-S) or askpass (-A); -s (shell) and -a (list) are gated as + # privilege chains (read SUDO_PASSWORD from .env -> sudo -S -s). Plain `sudo cmd` is TTY-bound and excluded. Input + # is lowercased, so S/s and A/a collapse. Lazy `[^;|&\n]*?` allows flag args without spanning separators. sudo + # resolves unambiguous long-flag prefixes: `--stdin` is the only long option starting with "st", `--askpass` the + # only one starting with "a". + (r'\bsudo\b[^;|&\n]*?\s+(?:-s\b|--st[a-z]*\b|-a\b|--a[a-z]*\b)', "sudo with privilege flag (stdin/askpass/shell/list)"), + # Combined short-flag form (-nS, -sa, -las). + (r'\bsudo\b[^;|&\n]*?\s+-[a-z]*[sa][a-z]*\b', "sudo with combined-flag privilege escalation"), + # Package-manager uninstall commands can remove installed software outside + # the current project (notably `npm uninstall -g`). Treat their destructive + # subcommands like other state-removing operations while leaving installs + # and updates alone. + # _CMDPOS-anchored (quoted prose like `git commit -m "npm uninstall docs"` is data); the + # option group also swallows one operand (`--prefix DIR`, `--proxy URL`, `--cwd DIR`). + (_CMDPOS + r'npm\s+' + _PKG_OPTS + r'(?:uninstall|unlink|remove|rm|r|un)\b', "package manager uninstall"), + (_CMDPOS + r'pnpm\s+' + _PKG_OPTS + r'(?:uninstall|remove|rm|un)\b', "package manager uninstall"), + (_CMDPOS + r'yarn\s+' + _PKG_OPTS + r'(?:global\s+)?(?:uninstall|remove)\b', "package manager uninstall"), + (_CMDPOS + r'pip(?:3)?\s+' + _PKG_OPTS + r'uninstall\b', "package manager uninstall"), + (_CMDPOS + r'brew\s+' + _PKG_OPTS + r'(?:uninstall|remove|rm)\b', "package manager uninstall"), +] + + +DANGEROUS_PATTERNS_COMPILED = [(re.compile(p, _RE_FLAGS), d) for p, d in DANGEROUS_PATTERNS] + +# Preserve approvals stored under the removed interpreter regex rules. +_REMOVED_PATTERN_KEY_ALIASES = { + "script execution via -e/-c flag": "(python[23]?|perl|ruby|node)\\s+-[ec]\\s+", + "script execution via heredoc": "(python[23]?|perl|ruby|node)\\s+<<", +} +# description <-> legacy regex-derived key (the old approval key, kept for backwards compatibility +# with stored allowlist/session entries), both ways. +_PATTERN_KEY_ALIASES: dict[str, set[str]] = {} +for _canonical_key, _legacy_key in [ + (d, p.split(r'\b')[1] if r'\b' in p else p[:20]) for p, d in DANGEROUS_PATTERNS +] + list(_REMOVED_PATTERN_KEY_ALIASES.items()): + _PATTERN_KEY_ALIASES.setdefault(_canonical_key, set()).update({_canonical_key, _legacy_key}) + _PATTERN_KEY_ALIASES.setdefault(_legacy_key, set()).update({_legacy_key, _canonical_key}) + + +def _approval_key_aliases(pattern_key: str) -> set[str]: + """All approval keys for this pattern: the description plus the historical regex-derived key + older allowlist/session entries may still use.""" + return _PATTERN_KEY_ALIASES.get(pattern_key, {pattern_key}) + + +# ---- Detection ---------------------------------------------------------------------------- +def _normalize_command_for_detection(command: str) -> str: + """Normalize a command before pattern matching so ANSI escapes, null bytes, Unicode fullwidth + forms, and shell splicing tricks cannot bypass detection.""" + from tools.ansi_strip import strip_ansi + command = unicodedata.normalize('NFKC', strip_ansi(command).replace('\x00', '')) + # Collapse backslash-newline continuations (`rm -rf \/` runs as `rm -rf /`). MUST + # precede the generic escape strip below, whose [^\n] class skips newlines and would leave the + # backslash wedged between tokens, defeating the structured rm/mkfs/dd patterns incl. the HARDLINE floor. + command = re.sub(r'\\\r?\n', '', command) + # Fold absolute user/Hermes home prefixes to ~/ and ~/.hermes/ so the static patterns catch /home/alice/.bashrc + # and C:\Users\alice\.bashrc. Resolved at detection time (not import time) so it tracks HOME/HERMES_HOME set + # later. MUST run before the backslash strip (which would dissolve C:\Users\alice to C:Usersalice). Hermes home + # first: on Windows it nests under the user home, and folding the user home first would eat the prefix it needs. + command = _rewrite_resolved_hermes_home(command) + command = _rewrite_resolved_user_home(command) + # Strip backslash-escapes (r\m -> rm) and empty-string literals (r''m -> rm). + command = re.sub(r'\\([^\n])', r'\1', command) + command = re.sub(r"''|\"\"", '', command) + # Collapse $IFS / ${IFS...} (incl. `${IFS:0:1}`) to a space: IFS defaults to whitespace, so `rm${IFS}-rf${IFS}/` + # runs as `rm -rf /`, and every pattern — incl. the hardline floor — anchors on literal \s between tokens. + return re.sub(r'\$\{IFS\b[^}]*\}|\$IFS\b', ' ', command) + + +# Shell metacharacters, quotes, and whitespace that terminate a path token. +_PATH_TOKEN_STOP = r"""\s'"`;|&<>()""" +_PATH_TAIL = r"(?P(?:[/\\][^/\\" + _PATH_TOKEN_STOP + r"]*)+)" + + +@functools.lru_cache(maxsize=64) +def _home_prefix_fold_regex(path: str): + """Compile a regex matching *path* as an absolute directory prefix. + Components match with either separator so native Windows, forward-slash, and mixed forms all + fold; the caller normalizes the tail's backslashes to ``/``. A non-empty tail is required, so a + bare home is never folded. Returns ``None`` for an unset/degenerate path (fewer than two + components: ``/``, ``C:\\``, ``""``) so a stray HOME cannot rewrite unrelated prefixes.""" + components = [c for c in re.split(r"[/\\]+", path) if c] if path else [] + if len(components) < 2: + return None + # Optional leading root separator; a Windows drive letter is a component. + return re.compile(r"[/\\]*" + r"[/\\]+".join(re.escape(c) for c in components) + _PATH_TAIL) + + +def _fold_home_prefixes(command: str, paths, replacement: str) -> str: + """Fold each resolved home prefix in *command* to *replacement* (no trailing separator; the tail + supplies it). Longest first so a deeper home folds before a shorter overlapping one that would clobber it.""" + for path in dict.fromkeys(sorted((p for p in paths if p), key=len, reverse=True)): + pattern = _home_prefix_fold_regex(path) + if pattern is not None: + command = pattern.sub(lambda m: replacement + m.group("tail").replace("\\", "/"), command) + return command + + +def _rewrite_resolved_user_home(command: str) -> str: + """User home (expanduser / realpath / $HOME) -> ``~/``; no-op when unset, degenerate, or unresolvable.""" + try: + # expanduser, realpath, and an explicit HOME — Windows expanduser uses USERPROFILE, not HOME. + home = os.path.expanduser("~") + paths = [home, os.path.realpath(home), os.environ.get("HOME", "")] + except Exception: + return command + return _fold_home_prefixes(command, paths, "~") + + +def _rewrite_resolved_hermes_home(command: str) -> str: + """Resolved HERMES_HOME (and its realpath) -> ``~/.hermes/`` so the _HERMES_CONFIG_PATH / + _HERMES_ENV_PATH rules match Docker/gateway deployments that spell the absolute path.""" + try: + from hermes_constants import get_hermes_home + home = get_hermes_home().expanduser() + paths = [str(home), str(home.resolve(strict=False))] + except Exception: + return command + return _fold_home_prefixes(command, paths, "~/.hermes") + + +_PARAM_REPLACEMENT_RE = re.compile(r"\$\{[^}/\s]+/[^}/]*/(?P[^}]*)\}") +_PARAM_DEFAULT_RE = re.compile(r"\$\{[^}:}\s]+:-(?P[^}]*)\}") +_SIMPLE_SHELL_LITERAL_RE = re.compile(r"^[A-Za-z0-9_./:@%+=,-]+$") +_ENV_ASSIGNMENT_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=.*") +_COMMAND_WRAPPER_WORDS = {"sudo", "env", "exec", "nohup", "setsid", "time", "command", "builtin", + "nice", "timeout", "stdbuf", "ionice", "chrt", "taskset", "chroot"} +_SUDO_OPTIONS_WITH_ARG = {"-c", "--close-from", "-g", "--group", "-h", "--host", "-p", "--prompt", "-u", "--user"} +# Adapted from embwl0x's command-position work in #76063. Option operands are +# data, not executable positions; option spelling remains case-sensitive. +_COMMAND_WRAPPER_OPTIONS_WITH_ARG = { + "chroot": {"--groups", "--userspec"}, + "sudo": _SUDO_OPTIONS_WITH_ARG, + "env": {"-a", "--argv0", "-C", "--chdir", "-S", "--split-string", "-u", "--unset"}, + "exec": {"-a"}, "nice": {"-n", "--adjustment"}, + "time": {"-f", "--format", "-o", "--output"}, + "timeout": {"-k", "--kill-after", "-s", "--signal"}, + "stdbuf": {"-e", "--error", "-i", "--input", "-o", "--output"}, + "ionice": {"-c", "--class", "-n", "--classdata"}, +} +_COMMAND_WRAPPER_NON_EXECUTING_OPTIONS = { + "command": {"-v", "-V"}, "chrt": {"-p", "--pid"}, + "ionice": {"-p", "--pid", "--pgid", "--uid"}, "taskset": {"-p", "--pid"}, +} +_COMMAND_WRAPPER_POSITIONAL_ARGS = {"chroot": 1, "chrt": 1, "taskset": 1, "timeout": 1} +_SHELL_COMMAND_TRANSITIONS = {"if", "then", "else", "elif", "do", "while", "until", "!"} +_SHELL_REDIRECTION_RE = re.compile(r"(?:[0-9]+)?(?:>>|<<|<>|>&|<&|>\||[<>])") + +_INTERPRETER_NAME_RES = tuple((family, re.compile(pattern)) for family, pattern in ( + ("python", r"py(?:\.exe)?|python[23]?(?:\.\d+)*(?:\.exe)?"), ("node", r"node(?:js)?(?:\.exe)?"), + ("perl", r"perl[0-9]*(?:\.\d+)*(?:\.exe)?"), ("ruby", r"ruby[0-9.]*(?:\.exe)?"), ("php", r"php(?:\.exe)?"), + ("powershell", r"powershell(?:\.exe)?|pwsh(?:\.exe)?"), +)) +_INTERPRETER_EXEC_FLAGS = { + "python": {"-c"}, "node": {"-e", "--eval", "-p", "--print"}, "perl": {"-e", "--eval"}, "ruby": {"-e"}, + "php": {"-r"}, "powershell": {"-command", "-c", "-file", "-f"}, +} +_INTERPRETER_WITH_ARG = { + "python": {"-W", "-X", "--check-hash-based-pycs"}, + "node": {"-C", "--conditions", "--cpu-prof-dir", "--diagnostic-dir", "--icu-data-dir", "--import", "--loader", + "--openssl-config", "--require", "--title"}, + "perl": {"-0", "-F", "-I", "-M", "-m", "-x"}, "ruby": {"-C", "-E", "-F", "-I", "-K", "-r"}, + "php": {"-c", "-d", "-z"}, + "powershell": {"-configurationname", "-custompipename", "-executionpolicy", "-inputformat", "-outputformat", + "-settingsfile", "-version", "-windowstyle", "-workingdirectory"}, +} +_READ_TOOL_EXEC_FLAGS = { + "sort": {"--compress-program"}, "rg": {"--pre", "--hostname-bin"}, "ag": {"--pager"}, + "man": {"--pager", "--html", "-P", "-H"}, +} +# Required-argument options are ownership boundaries: an option-looking next token is data, not another option. These +# sets mirror the invocation grammar of the supported binaries (ripgrep 14, GNU sort, man-db, and ag 2.2). +_READ_TOOL_LONG_OPTIONS_WITH_ARG = { + "rg": { + "--after-context", "--before-context", "--color", "--colors", "--context", "--context-separator", + "--dfa-size-limit", "--encoding", "--engine", "--field-context-separator", "--field-match-separator", + "--file", "--generate", "--glob", "--hostname-bin", "--hyperlink-format", "--iglob", "--ignore-file", + "--max-columns", "--max-count", "--max-depth", "--max-filesize", "--path-separator", "--pre", "--pre-glob", + "--regex-size-limit", "--regexp", "--replace", "--sort", "--sortr", "--threads", "--type", "--type-add", + "--type-clear", "--type-not", + }, + "sort": { + "--batch-size", "--buffer-size", "--compress-program", "--field-separator", "--files0-from", "--key", + "--output", "--parallel", "--random-source", "--sort", "--temporary-directory", + }, + "man": { + "--config-file", "--encoding", "--extension", "--locale", "--manpath", "--pager", "--preprocessor", + "--prompt", "--recode", "--sections", "--systems", + }, + "ag": { + "--ackmate-dir-filter", "--color-line-number", "--color-match", "--color-path", "--depth", + "--filename-pattern", "--file-search-regex", "--ignore", "--ignore-dir", "--max-count", "--pager", + "--path-to-ignore", "--width", "--workers", + }, +} +_READ_TOOL_SHORT_OPTIONS_WITH_ARG = { + "rg": frozenset("efEmjgdtTABCMr"), "sort": frozenset("koStT"), "man": frozenset("CRLmMSserEPp"), + "ag": frozenset("gGmpW"), +} +_GREP_OPTIONS_WITH_ARG = { + "--after-context", "--before-context", "--binary-files", "--context", "--directories", "--devices", "--exclude", + "--exclude-dir", "--exclude-from", "--include", "--label", "--max-count", "--regexp", "--file", +} +_GREP_SHORT_OPTIONS_WITH_ARG = {"A", "B", "C", "D", "d", "e", "f", "m"} +_BASH_OPTIONS_WITH_ARG = {"-O", "+O", "-o", "+o", "--init-file", "--rcfile"} +_BASH_SHORT_OPTION_LETTERS = frozenset("ilrsDcabefhkmnptuvxBCEHPTOo") +_MAX_DETECTION_COMMAND_CHARS, _MAX_SEPARATOR_FREE_COMMAND_CHARS, _MAX_DETECTION_SEGMENTS = 128_000, 4_096, 25_000 +_PARSER_LIMIT_DESCRIPTION = "command parser limit exceeded" +_MALFORMED_EXEC_DESCRIPTION = "command parser limit or malformed executable payload" +_GATEWAY_LIFECYCLE_SPLICE_DESCRIPTION = "stop/restart hermes gateway via shell-spliced verb (kills running agents)" + + +def _command_parser_limit_exceeded(command: str) -> bool: + """Bound all parser work before normalization/tokenization. Separator counting is deliberately + conservative: quoted separators over-count, but crossing the ceiling fails closed rather than + letting an uninspected suffix execute.""" + if len(command) > _MAX_DETECTION_COMMAND_CHARS: + return True + # Long separator-free input has no compound-command utility and makes every regex inspect one giant token. + if len(command) > _MAX_SEPARATOR_FREE_COMMAND_CHARS and not any(char in command for char in ";&|\n"): + return True + return sum(command.count(char) for char in ";&|\n") >= _MAX_DETECTION_SEGMENTS + + +def _backtick_end_from(segment: str, i: int) -> int | None: + """Index of the backtick closing the one opened at ``i``, or None when none follows.""" + j = segment.find("`", i + 1) + while j != -1 and segment[j - 1] == "\\": + j = segment.find("`", j + 1) + return None if j == -1 else j + + +def _shell_tokens_with_spans(segment: str, start: int): + """Return shell words as ``(value, start, end, quoted)`` or ``None`` on malformed quoting. + Deliberately small lexer that never expands shell syntax; it exists to keep source spans (which + ``shlex`` does not expose) for deciding which quoted grep operand is data, not another command. + + Lexing stops at the end of the simple command that begins at *start*: an unquoted ``;``, ``|``, + ``&`` or newline, or the ``)`` / backtick that closes the substitution the command sits inside. + Without that, a grep nested as ``"$(grep … | cut …)"`` was lexed together with the enclosing + command's closing quote, read as unbalanced quoting, and reported as a hardline block (546 + blocked turns in one run, every one a false positive; ``sed -n "$(grep -n X f | cut -d: -f1),+3p" f`` + is the canonical shape).""" + tokens, value, token_start, quote = [], [], None, None + depth = 0 # $(...) nesting opened AFTER start; a closer at depth 0 ends the enclosing substitution + # A backtick opened AFTER start is an operand substitution (``grep -e `cmd` f``); the matching + # closer belongs to it, not to an enclosing backtick the command might sit inside. + in_backtick = False + + def flush(end: int) -> None: + raw = segment[token_start:end] + # Only a wholly single-quoted operand is inert shell data. Double quotes still execute $() + # and backticks; unquoted substitutions do too. + inert = (raw.startswith("'") and raw.endswith("'")) or ("='" in raw and raw.endswith("'")) + tokens.append(("".join(value), token_start, end, inert)) + + end_at = len(segment) + for kind, i, _, _ in _scan_shell(segment, start): + ch = segment[i] + if kind == "char" and not quote: + if ch.isspace() and ch != "\n": + if token_start is not None: + flush(i) + value, token_start = [], None + continue + if segment.startswith("$(", i): + depth += 1 + elif ch == "`": + if in_backtick: + in_backtick = False + elif depth == 0 and _backtick_end_from(segment, i) is None: + end_at = i # unmatched: it closes the substitution this command sits inside + break + else: + in_backtick = True + elif ch == ")": + if depth == 0: + end_at = i + break + depth -= 1 + elif ch in ";|&\n": + end_at = i + break + if token_start is None: + token_start = i + if kind == "quote": + quote = None if quote else ch + elif kind == "esc": + value.append(segment[i + 1]) + elif ch == "\\" and not quote: + return None # dangling backslash + else: + value.append(ch) + if quote: + return None + if token_start is not None: + flush(end_at) + return tokens + + +def _quoted_grep_pattern_spans(command: str) -> tuple[list[tuple[int, int]], bool]: + """Structurally locate quoted grep PCRE operands -> (spans, malformed). On an ambiguous or + malformed grep parse callers fail closed and use the original command: no text is hidden on + an uncertain parse.""" + spans: list[tuple[int, int]] = [] + offset = 0 + for segment in _iter_top_level_shell_segments(command): + segment_at = command.find(segment, offset) + offset = segment_at + len(segment) + for start, _, word in _iter_shell_command_word_spans(segment): + if os.path.basename(_deobfuscate_shell_word_for_detection(word)).lower() not in {"grep", "egrep"}: + continue + tokens = _shell_tokens_with_spans(segment, start) + if tokens is None: + return [], True + args, pattern_indexes = tokens[1:], [] + pcre = explicit_patterns = False + operand_index, i, options = None, 0, True + while i < len(args): + token = args[i][0] + if options and token == "--": + options = False + elif options and token.startswith("--"): + option, equals, _ = token.partition("=") + pcre = pcre or option == "--perl-regexp" + explicit_patterns = explicit_patterns or option in {"--regexp", "--file"} + takes_next = option in _GREP_OPTIONS_WITH_ARG and not equals + if takes_next and i + 1 >= len(args): + return [], True + if option == "--regexp": + pattern_indexes.append(i + 1 if takes_next else i) + i += 1 if takes_next else 0 + elif options and token.startswith("-") and token != "-": + chars = token[1:] + for j, char in enumerate(chars): + pcre = pcre or char == "P" + explicit_patterns = explicit_patterns or char in {"e", "f"} + if char in _GREP_SHORT_OPTIONS_WITH_ARG: + # The first argument-taking short option owns the rest of the bundle, + # or the next token when it comes last. + attached = j + 1 < len(chars) + if not attached and i + 1 >= len(args): + return [], True + if char == "e": + pattern_indexes.append(i if attached else i + 1) + i += 0 if attached else 1 + break + elif operand_index is None: + operand_index = i + i += 1 + if not explicit_patterns: + if operand_index is None: + return [], pcre + pattern_indexes.append(operand_index) + if pcre: + spans.extend( + (segment_at + token_start, segment_at + token_end) + for _, token_start, token_end, quoted in map(args.__getitem__, pattern_indexes) if quoted + ) + return spans, False + + +def _splice(command: str, edits) -> str: + """Apply sorted, non-overlapping ``(start, end, text)`` edits to *command* in one pass + (re-slicing per edit is quadratic on 10k+ segments).""" + parts, previous = [], 0 + for start, end, text in edits: + parts.extend((command[previous:start], text)) + previous = end + return "".join(parts) + command[previous:] + + +def _grep_safe_detection_variant(command: str) -> tuple[str, bool]: + spans, malformed = _quoted_grep_pattern_spans(command) + if malformed or not spans: + return command, malformed + return _splice(command, [(start, end, " " * (end - start)) for start, end in spans]), False + + +def _interpreter_family(executable: str) -> str | None: + name = os.path.basename(executable).lower() + return next((family for family, name_re in _INTERPRETER_NAME_RES if name_re.fullmatch(name)), None) + + +def _shell_segment_tokens(segment: str, start: int) -> list[str] | None: + """Tokenize an already-bounded command segment. ``None`` distinguishes malformed quoting from + an empty segment so callers can fail closed for a program-bearing option rather than silently + skip it.""" + try: + lexer = shlex.shlex(segment[start:], posix=True, punctuation_chars="<>") + lexer.whitespace_split, lexer.commenters = True, "" + return list(lexer) + except ValueError: + return None + + +def _iter_top_level_shell_segments(command: str): + """Yield top-level command segments in one left-to-right pass.""" + start = 0 + for kind, i, j, quote in _scan_shell(command, comments=True): + if kind == "comment" or (kind == "char" and quote is None and command[i] in ";&|\n"): + if start < i: + yield command[start:i] + start = j + if start < len(command): + yield command[start:] + + +def _interpreter_exec_flag(family: str, args: list[str]) -> str | None: + """Return an execution-bearing interpreter option, if present.""" + flags, with_arg = _INTERPRETER_EXEC_FLAGS[family], _INTERPRETER_WITH_ARG[family] + powershell = family == "powershell" + skip_value = False + for token in args: + if skip_value: + skip_value = False + continue + if token == "--" or (not powershell and not token.startswith("-")): + break + option, equals, _ = token.partition("=") + comparable = option.lower() if powershell else option + if comparable in flags: + return comparable + # `-Wonce` and `ruby -rjson` attach an option value; they are not short-option bundles containing an execution + # flag. PowerShell's normal long options also use one dash, so bundle parsing never applies to that family. + has_attached_option_value = any( + option.startswith(short) and len(option) > len(short) + for short in with_arg if short.startswith("-") and not short.startswith("--") + ) + if not powershell and not option.startswith("--") and len(option) > 2 and not has_attached_option_value: + bundled = next((f"-{char}" for char in option[1:] if f"-{char}" in flags), None) + if bundled: + return bundled + skip_value = comparable in with_arg and not equals + return None + + +def _bash_exec_payload(args: list[str]) -> tuple[bool, str | None]: + """Return whether Bash ``-c`` occurs and the command string it owns. + Bash's O/o options consume the following argument even when they precede a later ``-c`` or + share its short-option bundle; the two startup-file long options own their next token. + Parsing those first prevents both missed payloads and false ``-c`` hits.""" + index = 0 + while index < len(args): + token = args[index] + if token == "--" or not token.startswith(("-", "+")): + break + if token in _BASH_OPTIONS_WITH_ARG: + index += 2 + continue + chars = token[1:] + # Bash option letters are case-sensitive; restricting to the documented alphabet + # preserves invalid controls such as `-Wc`. + if token.startswith("--") or not set(chars) <= _BASH_SHORT_OPTION_LETTERS: + index += 1 + continue + consumed_option_arg = int("O" in chars or "o" in chars) + if "c" in chars: + payload_index = index + 1 + consumed_option_arg + return True, (args[payload_index] if payload_index < len(args) else None) + index += 1 + consumed_option_arg + return False, None + + +def _read_tool_exec_flag(tool: str, args: list[str]) -> tuple[str, str] | None: + """Return (option, program) for a read-only tool's program-running flag.""" + flags = _READ_TOOL_EXEC_FLAGS[tool] + index = 0 + while index < len(args): + token = args[index] + if token == "--": + break + option, equals, payload = token.partition("=") + payload = payload if equals else None + matched = option if option in flags else None + if tool == "man" and token.startswith(("-P", "-H")) and len(token) > 2: + matched, payload = token[:2], token[2:] + if matched: + if payload is None and index + 1 < len(args): + payload = args[index + 1] + # The option owns its program argument regardless of spelling; the real binaries + # execute a '-'-prefixed payload rather than reparsing it. + if payload: + return matched, payload + index += 2 if payload is not None and "=" not in token else 1 + elif option in _READ_TOOL_LONG_OPTIONS_WITH_ARG[tool] and payload is None: + index += 2 + elif token.startswith("-") and not token.startswith("--") and len(token) > 1: + # In a short bundle, the first argument-taking option owns the rest of the token, or + # the following token when it occurs last. + shorts = _READ_TOOL_SHORT_OPTIONS_WITH_ARG[tool] + owner = next((k for k, char in enumerate(token[1:], start=1) if char in shorts), None) + index += 2 if owner == len(token) - 1 else 1 + else: + index += 1 + return None + + +def _execution_flag_findings(command: str): + """Yield scoped execution mechanisms and any executable payloads.""" + for segment in _iter_top_level_shell_segments(command): + for start, _, word in _iter_shell_command_word_spans(segment): + executable = _deobfuscate_shell_word_for_detection(word) + tokens = _shell_segment_tokens(segment, start) + executable_name = os.path.basename(executable).lower() + family = _interpreter_family(executable) + if tokens is None: + if family is not None or executable_name in _READ_TOOL_EXEC_FLAGS: + yield (_MALFORMED_EXEC_DESCRIPTION, None) + continue + if not tokens: + continue + args = tokens[1:] + if family and _interpreter_exec_flag(family, args): + yield ("script execution via -e/-c flag", None) + elif family and any(token.startswith("<<") for token in args): + yield ("script execution via heredoc", None) + else: + if executable_name in {"bash", "sh", "zsh", "ksh"}: + found, payload = _bash_exec_payload(args) + if found: + yield ("shell command via -c/-lc flag", payload) + if executable_name in _READ_TOOL_EXEC_FLAGS: + finding = _read_tool_exec_flag(executable_name, args) + if finding: + yield (f"arbitrary program execution via {executable_name} {finding[0]}", finding[1]) + + +def _skip_shell_whitespace(command: str, pos: int) -> int: + while pos < len(command) and command[pos].isspace(): + pos += 1 + return pos + + +def _scan_shell(text: str, start: int = 0, end: int | None = None, *, subst: str = "", + brace: bool = False, stop_unterminated: bool = False, naive_backtick: bool = False, + comments: bool = False): + """Yield ``(kind, i, j, quote)`` lexical steps over ``text[start:end]`` without expanding. + + The single quote/escape state machine behind every detection scanner. ``kind`` is ``"char"`` + (one char), ``"esc"`` (backslash + the char it escapes; never inside single quotes), ``"quote"`` + (an opening/closing quote char) or ``"subst"`` (a ``$(...)`` / backtick / ``${...}`` span); + With *comments*, ``"comment"`` spans are skipped without interpreting their quote syntax. + ``quote`` is the state the step was read in (``None``, ``'`` or ``"``). Substitutions are + recognized unquoted when ``"u"`` is in *subst*, inside double quotes when ``"q"`` is; *brace* + adds unquoted ``${...}``. An unterminated substitution falls through as plain chars unless + *stop_unterminated*, which yields ``("subst", i, None, quote)`` and ends the scan (the caller + descends to *end* itself). *naive_backtick* closes a backtick at the next backtick even if + escaped (the quoted-prose masker's historical behavior).""" + n = len(text) if end is None else end + quote: str | None = None + i = start + while i < n: + ch = text[i] + kind, j = "char", i + 1 + if comments and quote is None and _is_shell_comment_start(text, i): + kind, j = "comment", text.find("\n", i, n) + if j < 0: + j = n + elif quote != "'" and ch == "\\" and i + 1 < n: + kind, j = "esc", i + 2 + elif ch == quote or (quote is None and ch in "'\""): + kind = "quote" + elif quote != "'" and ("q" if quote else "u") in subst and ( + ch == "`" or text.startswith("$(", i) or (brace and not quote and text.startswith("${", i)) + ): + if ch == "`": + close = text.find("`", i + 1) + 1 or None if naive_backtick else _scan_backtick_end(text, i) + elif text[i + 1] == "(": + close = _scan_dollar_paren_end(text, i) + else: + close = text.find("}", i + 2) + 1 or None + if close is not None: + kind, j = "subst", close + elif stop_unterminated: + yield ("subst", i, None, quote) + return + yield (kind, i, j, quote) + if kind == "quote": + quote = None if quote else ch + i = j + + +def _scan_dollar_paren_end(command: str, start: int) -> int | None: + """Return the offset after a balanced ``$(...)`` command substitution.""" + depth = 1 + for kind, i, _, quote in _scan_shell(command, start + 2): + if kind == "char" and not quote: + depth += command.startswith("$(", i) - (command[i] == ")") + if depth == 0: + return i + 1 + return None + + +def _scan_backtick_end(command: str, start: int) -> int | None: + # Backticks have no quote awareness: only a backslash escapes the next char. + match = re.compile(r"(?:\\.|[^`\\])*`", re.DOTALL).match(command, start + 1) + return match.end() if match else None + + +def _read_shell_word(command: str, pos: int) -> tuple[int, int, str]: + """Read one shell word without executing expansions.""" + start = end = _skip_shell_whitespace(command, pos) + for kind, i, j, quote in _scan_shell(command, start, subst="u", brace=True): + if kind == "char" and quote is None and (command[i].isspace() or command[i] in ";&|<>()"): + break + end = j + return (start, end, command[start:end]) + + +def _literal_command_substitution_output(script: str) -> str | None: + """Resolve tiny literal command substitutions without executing a shell.""" + try: + tokens = shlex.split(script, posix=True) + except ValueError: + tokens = [] + if not tokens: + return None + command, args = tokens[0].lower(), tokens[1:] + if command == "echo": + while args and re.fullmatch(r"-[nEe]+", args[0]): + args = args[1:] + elif command != "printf": + return None + if len(args) == 1 and _SIMPLE_SHELL_LITERAL_RE.fullmatch(args[0]): + return args[0] + if command == "printf" and len(args) == 2 and args[0] == "%s" and _SIMPLE_SHELL_LITERAL_RE.fullmatch(args[1]): + return args[1] + return None + + +def _replace_simple_command_substitutions(word: str) -> str: + chars: list[str] = [] + i = 0 + while i < len(word): + opener = 2 if word.startswith("$(", i) else 1 if word[i] == "`" else 0 + end = (_scan_dollar_paren_end if opener == 2 else _scan_backtick_end)(word, i) if opener else None + replacement = _literal_command_substitution_output(word[i + opener:end - 1]) if end is not None else None + if replacement is None: + replacement, end = word[i], i + 1 + chars.append(replacement) + i = end + return "".join(chars) + + +def _replace_simple_shell_expansions(word: str) -> str: + word = _replace_simple_command_substitutions(word) + word = _PARAM_REPLACEMENT_RE.sub(lambda match: match.group("replacement"), word) + return _PARAM_DEFAULT_RE.sub(lambda match: match.group("default"), word) + + +def _strip_shell_word_syntax(word: str) -> str: + return "".join( + word[i + 1] if kind == "esc" else word[i] + for kind, i, _, _ in _scan_shell(word) if kind != "quote" + ) + + +def _deobfuscate_shell_word_for_detection(word: str) -> str: + """Approximate how shell syntax can spell a command word: collapses quoting/escaping plus + simple literal command substitutions in the word itself. Intentionally narrow and non-executing.""" + for _ in range(2): + previous = word + word = _strip_shell_word_syntax(_replace_simple_shell_expansions(word)) + if word == previous: + break + return word + + +def _is_shell_comment_start(command: str, index: int) -> bool: + return command[index] == "#" and (index == 0 or command[index - 1].isspace() + or command[index - 1] in ";&|()<>") + + +def _iter_shell_command_starts(command: str): + starts = [0] + + def scan(start: int, end: int) -> None: + skip = -1 + for kind, i, j, quote in _scan_shell(command, start, end, subst="uq", stop_unterminated=True, + comments=True): + if kind == "subst": + # Record a nested $(...)/backtick command start and scan its body. + inner = i + (1 if command[i] == "`" else 2) + starts.append(inner) + scan(inner, end if j is None else j - 1) + elif kind == "char" and quote is None and i != skip: + # `${` opens a parameter expansion, not a brace group: a start marked inside it would + # split `${IFS}` and defeat the IFS collapse in normalization. + if command[i] in "({;\n" and not (command[i] == "{" and i > 0 and command[i - 1] == "$"): + starts.append(i + 1) + elif command[i] in "&|": + repeated = i + 1 < end and command[i + 1] == command[i] + skip = i + 1 if repeated else skip + starts.append(i + 1 + repeated) + + scan(0, len(command)) + seen = set() + for start in starts: + start = _skip_shell_whitespace(command, start) + if start >= len(command) or start in seen or _is_shell_comment_start(command, start): + continue + seen.add(start) + yield start + _, end, word = _read_shell_word(command, start) + if word in _SHELL_COMMAND_TRANSITIONS: + starts.append(end) + + +def _mark_command_starts(command: str, marker: str = "\n") -> str: + """Insert *marker* (a newline) before each real (quote-aware) command start. + ``\\n`` is already a ``_CMDPOS`` separator, so this exposes subshell ``(cmd)`` and brace-group + ``{ cmd; }`` openers — which the flat pattern class omits — to the anchored patterns WITHOUT the + quoted-prose false positives that adding ``(`` / ``{`` to ``_CMDPOS`` would cause: starts inside + quotes are never produced, so ``--title "block (reboot)"`` is left as-is.""" + offsets = sorted(o for o in _iter_shell_command_starts(command) if o > 0) + return _splice(command, [(o, o, marker) for o in offsets]) if offsets else command + + +def _mask_quoted_newlines(command: str) -> str: + """Replace raw newlines inside single/double quotes with a space (detection-only). + A quoted newline is DATA to the shell, yet the flat ``_CMDPOS`` class treats every raw ``\\n`` + as a command start, so multi-line quoted arguments (commit messages, heredoc text) tripped the + hardline blocklist when a data line began with e.g. ``sudo reboot``. Quote tracking mirrors + ``_iter_shell_command_starts``. Unquoted newlines pass through and ``_mark_command_starts`` + still re-inserts newlines at genuine starts; an unclosed quote absorbs following newlines + exactly as the shell would, so masking them cannot hide a runnable command.""" + if "\n" not in command: + return command + return _mask_quoted_newlines_span(command, 0, len(command)) + + +def _mask_quoted_newlines_span(command: str, start: int, end: int) -> str: + """``_mask_quoted_newlines`` over ``command[start:end]``. A ``$(...)`` / backtick substitution + inside double quotes is EXECUTABLE, not data: its body is re-scanned with a fresh quote state so a + newline that separates commands inside it survives as a command boundary. Masking it as quoted + data turned ``"$(grep x f\nreboot)"`` into ``... f reboot)``, which no later stage can tell from an + operand; the pre-fix scanner only caught it by refusing the whole command as malformed.""" + out: list[str] = [] + for kind, i, j, quote in _scan_shell(command, start, end, subst="q"): + if kind == "subst": + # j is the index just past the closer; keep the opener and closer, recurse into the body. + body_start = i + (2 if command.startswith("$(", i) else 1) + body_end = j - 1 + out.append(command[i:body_start]) + out.append(_mask_quoted_newlines_span(command, body_start, body_end)) + out.append(command[body_end:j]) + elif quote and kind == "char" and command[i] == "\n": + out.append(" ") + else: + out.append(command[i:j]) + return "".join(out) + + +def _iter_shell_command_word_spans(command: str): + """Yield command-position words that may be executable names.""" + for pos in _iter_shell_command_starts(command): + wrapper, positionals = None, 0 + options, skip_arg = True, False + while pos < len(command): + redirect = _SHELL_REDIRECTION_RE.match(command, _skip_shell_whitespace(command, pos)) + if redirect: + _, pos, _ = _read_shell_word(command, redirect.end()) + continue + word_start, word_end, word = _read_shell_word(command, pos) + if word_start == word_end: + break + pos = word_end + deobfuscated = _deobfuscate_shell_word_for_detection(word) + name = os.path.basename(deobfuscated).lower() + if skip_arg: + skip_arg = False + continue + if wrapper and options and deobfuscated == "--": + options = False + continue + if wrapper and options and deobfuscated.startswith("-"): + option = deobfuscated.split("=", 1)[0] + if wrapper == "env" and (option == "--split-string" or deobfuscated.startswith("-S")): + # The split string and remaining argv form ONE command, handled + # by _env_split_payload; the suffix is not a new executable. + break + queries = _COMMAND_WRAPPER_NON_EXECUTING_OPTIONS.get(wrapper, set()) + if option in queries or (wrapper == "command" and not option.startswith("--") + and set(option[1:]) & {"v", "V"}): + break + skip_arg = "=" not in deobfuscated and option in _COMMAND_WRAPPER_OPTIONS_WITH_ARG.get(wrapper, set()) + continue + if positionals: + positionals -= 1 + continue + if _ENV_ASSIGNMENT_RE.fullmatch(word): + continue + yield (word_start, word_end, word) + if name not in _COMMAND_WRAPPER_WORDS: + break + wrapper, options = name, True + positionals = _COMMAND_WRAPPER_POSITIONAL_ARGS.get(name, 0) + + +def _shell_command_segment(command: str, start: int) -> str: + """Bound a candidate to its command, preserving quoted argument bytes.""" + end = len(command) + for kind, i, _, quote in _scan_shell(command, start, subst="uq", brace=True, comments=True): + if kind == "comment" or (kind == "char" and quote is None and command[i] in ";&|\n)`"): + end = i + break + return command[start:end].strip() + + +def _split_env_string(payload: str) -> list[str] | None: + r"""Project GNU env -S literal argv, not POSIX shell words. + + Dynamic ${NAME} expansion is deliberately not evaluated: the execution + backend's environment need not be this process's environment. + """ + escapes = {"f": "\f", "n": "\n", "r": "\r", "t": "\t", "v": "\v", + "#": "#", "$": "$", "\"": "\"", "'": "'", "\\": "\\"} + args, word = [], [] + quote, started, index = None, False, 0 + while index < len(payload): + char = payload[index] + index += 1 + if char == "\\": + if index == len(payload): + return None + escaped = payload[index] + if quote == "'" and escaped not in ("'", "\\"): + word.append(char) + started = True + continue + index += 1 + if escaped == "c": + if quote: + return None + break + if escaped == "_" and quote is None: + if started: + args.append("".join(word)) + word, started = [], False + continue + if escaped not in escapes and escaped != "_": + return None + word.append(" " if escaped == "_" else escapes[escaped]) + started = True + continue + if char in ("'", '"') and (quote is None or char == quote): + quote = char if quote is None else None + started = True + continue + if quote is None and char in " \t\n\r\v\f": + if started: + args.append("".join(word)) + word, started = [], False + continue + if quote is None and char == "#" and not started: + break + if char == "$" and quote != "'": + return None + word.append(char) + started = True + if quote: + return None + if started: + args.append("".join(word)) + return args + + +def _env_split_payload(tokens: list[str]) -> str | None: + index = 1 + while index < len(tokens): + token = tokens[index] + if token == "--" or not token.startswith("-"): + return None + option, equals, value = token.partition("=") + if option == "--split-string" or token.startswith("-S"): + attached = equals if option == "--split-string" else len(token) > 2 + if not attached: + index += 1 + payload = (value if option == "--split-string" else token[2:]) if attached else ( + tokens[index] if index < len(tokens) else "") + args = _split_env_string(payload) + # Protect literal separators when reusing command-position detection; + # only a real shell -c carrier may turn these argv bytes into code. + return shlex.join(args + tokens[index + 1:]) if args is not None else None + index += 2 if not equals and option in _COMMAND_WRAPPER_OPTIONS_WITH_ARG["env"] else 1 + return None + + +def _deny_command_variants(command: str): + """Add executable projections without reparsing normalized argument data. + + Whole-input matching is retained for existing globs. New projections parse + the original quote state, preserve path-specific rules, and fold only the + executable basename (never arbitrary argument paths). + """ + yield from _command_detection_variants(command) + pending, seen = [command], set() + while pending: + source = pending.pop() + if source in seen: + continue + seen.add(source) + for start, end, word in _iter_shell_command_word_spans(source): + segment = _shell_command_segment(source, start) + executable = _deobfuscate_shell_word_for_detection(word) + tail = segment[end - start:] + # Collapse only unquoted inter-word whitespace; quoted prose is data. + parts = [] + for kind, i, j, quote in _scan_shell(tail): + if kind == "char" and quote is None and tail[i].isspace(): + if not parts or parts[-1] != " ": + parts.append(" ") + else: + parts.append(tail[i:j]) + tail = "".join(parts) + for name in dict.fromkeys((executable, os.path.basename(executable))): + candidate = name + tail + yield candidate + # Apply the existing text matching semantics only AFTER locating + # executable positions; never parse its rewritten quotes again. + yield _normalize_command_for_detection(candidate) + if os.path.basename(executable) == "env": + tokens = _shell_segment_tokens(segment, 0) + if tokens: + payload = _env_split_payload(tokens) + if payload: + pending.append(payload) + for _, payload in _execution_flag_findings(source): + if payload: + pending.append(payload) + + +def _command_detection_variants(command: str): + # Mask quoted newlines BEFORE normalization: normalization strips escapes (\" -> ") and "" + # pairs, corrupting quote tracking (`echo "a\""` becomes an unterminated quote) so masking + # afterwards could swallow a REAL unquoted newline separator. The raw command carries faithful quote state. + normalized = _normalize_command_for_detection(_mask_quoted_newlines(command)) + # Quote-aware grep parsing hides only structurally identified pattern operands; malformed or + # ambiguous input stays byte-for-byte intact. + grep_safe, _ = _grep_safe_detection_variant(normalized) + seen = {grep_safe} + yield grep_safe + + def fresh(variant: str) -> bool: + if not variant or variant in seen: + return False + seen.add(variant) + return True + + # Windows-path variant: normalization strips backslashes as shell escapes, so `del C:\Users\me\.ssh\id_rsa` + # reaches the patterns as `del C:Usersme.sshid_rsa`. When the RAW command has a drive-letter or UNC backslash + # path, also yield a variant with backslashes flattened to `/` BEFORE normalization. Gated on a real path shape so + # POSIX escape semantics (`echo a\"b`) are untouched elsewhere. + # See #69472. + if re.search(r"(?:[A-Za-z]:|\\\\)[\\\\]", command) or re.search(r"[A-Za-z]:\\", command): + win_variant = _normalize_command_for_detection(_mask_quoted_newlines(command.replace("\\", "/"))) + if fresh(win_variant): + yield win_variant + # Program-bearing options are parsed in their owning command's context; surfacing only the payload lets the + # hardline floor inspect what will actually run without promoting similar flags or quoted prose. + pending = [normalized] + while pending: + for _, payload in _execution_flag_findings(pending.pop()): + if fresh(payload): + yield payload + # A payload may start with an option-looking program and then invoke a hardline command + # after a separator; mark its starts. + marked_payload = _mark_command_starts(payload) + if marked_payload != payload and fresh(marked_payload): + yield marked_payload + pending.append(payload) + # Subshell `(cmd)` / brace-group `{ cmd; }` openers put `cmd` at a real command position the flat `_CMDPOS` + # patterns can't see (adding `(`/`{` there would match quoted prose like `--title "(reboot)"`). Insert a newline + # at each start the QUOTE-AWARE tokenizer found instead; this covers every `_CMDPOS` rule in one place. + marked = _mark_command_starts(grep_safe) + if marked != grep_safe and fresh(marked): + yield marked + # Every variant above tracks quotes on NORMALIZED text, where `\"` has already become `"`. That + # flips quote parity, so in `cat "f\"n.txt"; rm -rf /` the `; rm` start sat "inside" a phantom + # quote, no start was marked, and the hardline floor let it through. Mark starts on the RAW + # command (only quoted newlines masked), then normalize; the leading space keeps the marker + # from being eaten as a `\` continuation when the preceding text ends in a backslash. + faithful = _normalize_command_for_detection(_mark_command_starts(_mask_quoted_newlines(command), marker=" \n")) + if fresh(faithful): + yield faithful + # Quoting/escaping can spell an executable in pieces (r\m, r''m). Keep that deobfuscation scoped + # to command words so arguments don't false-positive. + for word_start, word_end, word in _iter_shell_command_word_spans(normalized): + deobfuscated = _deobfuscate_shell_word_for_detection(word) + if deobfuscated and deobfuscated != word: + variant = normalized[:word_start] + deobfuscated + normalized[word_end:] + if fresh(variant): + yield variant + + +def _is_verification_artifact_cleanup(command: str) -> bool: + """Return whether *command* only removes one Hermes ad-hoc temp script.""" + try: + argv = shlex.split(command, posix=True) + except ValueError: + return False + if len(argv) != 3 or argv[0] != "rm" or argv[1] != "-f": + return False + operand = argv[2] + temp_dir = os.path.realpath(tempfile.gettempdir()) + basename = os.path.basename(operand) + return ( + operand == os.path.join(temp_dir, basename) + and os.path.dirname(os.path.realpath(operand)) == temp_dir + and re.fullmatch(r"hermes-(?:verify|ad-hoc)-[A-Za-z0-9_.-]+", basename) is not None + ) + + +def _is_shell_token_spliced_gateway_lifecycle(command: str) -> bool: + """Catch gateway-lifecycle verbs spelled with quote splicing. + Backslash splicing (``kick\\start``) is undone by normalization, but quote splicing is not: + ``_deobfuscate_shell_word_for_detection`` is deliberately scoped to command-position words + (widening it would let quoted prose like ``git commit -m "rm -rf /"`` match), and the spliced + verb is an ARGUMENT, so ``launchctl kick"start" -k gui/501/ai.hermes.gateway`` auto-approved. + Delegates to ``cron.lifecycle_guard`` (shlex-tokenized, anchored on a hermes-gateway + identifier). Runs last so an ordinary pattern match keeps its more specific reason; this layer + only prompts — the non-bypassable block still lives in ``cron.lifecycle_guard``. + + ``_normalize_command_for_detection`` strips backslash escapes, so ``kick\\start`` already reaches the + launchctl pattern above. See #80269. + """ + try: + from cron.lifecycle_guard import contains_gateway_lifecycle_command + except Exception: + return False + return contains_gateway_lifecycle_command(command) + + +def detect_dangerous_command(command: str) -> tuple: + """Check dangerous patterns -> (is_dangerous, pattern_key, description).""" + if _command_parser_limit_exceeded(command): + return (True, _PARSER_LIMIT_DESCRIPTION, _PARSER_LIMIT_DESCRIPTION) + if _is_verification_artifact_cleanup(command): + return (False, None, None) + for command_variant in _command_detection_variants(command): + command_lower = command_variant.lower() + for pattern_re, description in DANGEROUS_PATTERNS_COMPILED: + if pattern_re.search(command_lower): + return (True, description, description) + normalized = _normalize_command_for_detection(command) + for description, _ in _execution_flag_findings(normalized): + return (True, description, description) + if _is_shell_token_spliced_gateway_lifecycle(command): + return (True, _GATEWAY_LIFECYCLE_SPLICE_DESCRIPTION, _GATEWAY_LIFECYCLE_SPLICE_DESCRIPTION) + return (False, None, None) diff --git a/tools/approval_human_wait.py b/tools/approval_human_wait.py new file mode 100644 index 0000000000000000000000000000000000000000..37ad9942e45c49dfd66c59bc04b0a93900cf8da8 --- /dev/null +++ b/tools/approval_human_wait.py @@ -0,0 +1,169 @@ +"""Human-wait accounting for :mod:`tools.approval` (per session). + +Tracks wall-clock time the agent spends verifiably blocked on a HUMAN prompt +(CLI approval prompt, gateway approval round-trip). The concurrent tool batch +deadline in agent/tool_executor.py excludes this time so a slow human answer +never times a batch out — but ONLY this time. Measuring at the source (rather +than residency in the authorization gate, which is arbitrary code) is what keeps +a wedged pre_tool_call plugin or a dead approval client from growing the +exclusion 1:1 with wall clock and defeating the deadline entirely. Keyed by +session so one gateway session's pending approval cannot extend a different +session's batch deadline; state is process-global like the rest of the approval +state, bounded by _HUMAN_WAIT_MAX_SESSIONS. +""" + +import contextlib +import threading +import time + + +# ========================================================================= Human-wait accounting (per +# session) ========================================================================= Tracks the wall-clock +# time the agent spends verifiably blocked on a HUMAN prompt (CLI approval prompt, gateway approval +# round-trip). The concurrent tool batch deadline in agent/tool_executor.py excludes this time so a slow +# human answer never times a batch out — but ONLY this time. Measuring human waits at the source (rather +# than residency in the authorization gate, which is arbitrary code) is what keeps a wedged pre_tool_call +# plugin or a dead approval client from growing the exclusion 1:1 with wall clock and defeating the deadline +# entirely (#79719). Keyed by session so one gateway session's pending approval cannot extend a different +# session's batch deadline. State is process-global like the rest of this module's approval state; entries +# are bounded by _HUMAN_WAIT_MAX_SESSIONS. +class _HumanWaitState: + __slots__ = ("pending", "window_started", "completed_seconds") + + def __init__(self) -> None: + self.pending = 0 + self.window_started: float | None = None + self.completed_seconds = 0.0 + + +_human_wait_lock = threading.Lock() +_human_wait_states: dict[str, _HumanWaitState] = {} +_HUMAN_WAIT_MAX_SESSIONS = 256 +# Margin added on top of approvals.timeout when clamping a window's contribution (read-side AND close-side) and when +# bounding the authorization gate's serialization-lock acquire in agent/tool_executor.py. One constant so the clamps +# can't drift apart. +HUMAN_WAIT_MARGIN_S = 60.0 + + +def human_wait_ceiling() -> float: + """Max seconds a single window may contribute: approvals.timeout + margin. + Every legitimate human wait self-terminates at ``approvals.timeout`` (the CLI + prompt join and the gateway poll loop both enforce it), so a window that + overstays this ceiling is itself wedged and must not keep extending a batch + deadline. Also the bound on the authorization gate's serialization-lock + acquire in agent/tool_executor.py, so the two cannot drift. Never call while + holding ``_human_wait_lock`` — it reads the config cache. + ``_get_approval_timeout`` caps at ``agent.deadline.MAX_SAFE_TIMEOUT_S`` so the + value is always safe for ``Lock.acquire(timeout=...)`` / ``Thread.join(timeout=...)``.""" + from tools import approval_context + return float(approval_context._get_approval_timeout()) + HUMAN_WAIT_MARGIN_S + + +def _clamped_window_seconds(started: float, now: float, ceiling: float) -> float: + """Seconds an open window contributes: elapsed, floored at 0, capped. Shared + by the close-time accrual and the open-window read so the two clamps stay + identical by construction.""" + return min(max(0.0, now - started), ceiling) + + +def _human_wait_state(session_key: str) -> _HumanWaitState: + """Return (creating if needed) the wait state for *session_key*. Caller must + hold ``_human_wait_lock``. Evicts idle entries (no pending waiter) + insertion-order-first until the table is under the cap so an army of + short-lived session keys cannot grow it without bound. Entries with an open + window are never evicted (that would corrupt live accounting), so the cap is + best-effort under 256+ concurrently-pending sessions.""" + state = _human_wait_states.get(session_key) + if state is None: + for key in list(_human_wait_states): + if len(_human_wait_states) < _HUMAN_WAIT_MAX_SESSIONS: + break + if _human_wait_states[key].pending == 0: + del _human_wait_states[key] + state = _human_wait_states[session_key] = _HumanWaitState() + return state + + +def _resolve_key(session_key: str | None) -> str: + if session_key is not None: + return session_key + from tools import approval_context + return approval_context.get_current_session_key() + + +def activity_heartbeat(label: str): + """Callable that pings the agent's inactivity tracker (at most every ~10s) + while a human wait is parked, so the gateway watchdog does not kill the agent + while the user is still answering. No-op in minimal tool-only environments.""" + try: + from tools.environments.base import touch_activity_if_due + except Exception: # pragma: no cover - minimal tool-only environments + return lambda: None + now = time.monotonic() + state = {"last_touch": now, "start": now} + return lambda: touch_activity_if_due(state, label) + + +@contextlib.contextmanager +def human_wait_window(session_key: str | None = None): + """Mark the enclosed block as time spent blocked on a human prompt. Wrap ONLY + code that is genuinely parked waiting for a user's answer (the CLI approval + prompt, the gateway approval poll loop). The concurrent tool batch deadline + excludes this time; wrapping anything else re-creates the hang where + arbitrary wedged code pushes the deadline out forever. Overlapping windows + for the same session coalesce (pending counter), so two serialized approval + prompts don't double-count the same wall clock. + + See #79719. + """ + key = _resolve_key(session_key) + now = time.monotonic() + with _human_wait_lock: + state = _human_wait_state(key) + if state.pending == 0: + state.window_started = now + state.pending += 1 + try: + yield + finally: + now = time.monotonic() + # Clamp the accrual too: a window that overstayed the ceiling was wedged — + # record at most the ceiling, not the whole overstay. + ceiling = human_wait_ceiling() + with _human_wait_lock: + state = _human_wait_states.get(key) + if state is not None: + state.pending -= 1 + if state.pending == 0: + if state.window_started is not None: + state.completed_seconds += _clamped_window_seconds(state.window_started, now, ceiling) + state.window_started = None + + +def human_wait_seconds(session_key: str | None = None) -> float: + """Return total human-wait seconds recorded for the session: completed windows + plus the currently open one (if any). Monotonically non-decreasing for the + life of the process — except when an idle session's entry is evicted under + cap pressure, which can only shrink a consumer's baseline delta to zero (the + safe direction: the deadline fires sooner). Deadline consumers snapshot a + baseline at batch start and use the delta. Each window's contribution is + clamped to :func:`human_wait_ceiling` (belt-and-braces against the + wedged-window hang). + + Each window's contribution is clamped to :func:`human_wait_ceiling`: every legitimate human wait + self-terminates at ``approvals.timeout`` (both the CLI prompt join and the gateway poll loop enforce + it), so a window that overstays that bound is itself wedged and must not keep extending a batch deadline + (belt-and-braces for #79719). + """ + key = _resolve_key(session_key) + now = time.monotonic() + # Resolve the clamp outside the lock: it reads the config cache, which must never nest under _human_wait_lock. + ceiling = human_wait_ceiling() + with _human_wait_lock: + state = _human_wait_states.get(key) + if state is None: + return 0.0 + total = state.completed_seconds + if state.window_started is not None: + total += _clamped_window_seconds(state.window_started, now, ceiling) + return total diff --git a/tools/async_delegation.py b/tools/async_delegation.py new file mode 100644 index 0000000000000000000000000000000000000000..0069015e7e3404d8b078c7fa5f31aee9f3c7d3e1 --- /dev/null +++ b/tools/async_delegation.py @@ -0,0 +1,1003 @@ +#!/usr/bin/env python3 +"""Async (background) delegation registry behind ``delegate_task(background=true)``. + +The parent dispatches a subagent on a module-level daemon executor and returns a handle +immediately. On completion a ``type="async_delegation"`` event (self-contained task-source +block) is pushed onto the SHARED ``process_registry.completion_queue`` the CLI/gateway drain +while idle, so results surface as a NEW turn (never mid-turn) and inherit its de-dup and +crash-recovery wiring. Only the async lifecycle lives here; the child run is an injected ``runner``.""" + +from __future__ import annotations + +import json +import logging +import os +import sqlite3 +import threading +import time +import uuid +from concurrent.futures import ThreadPoolExecutor +from typing import Any, Callable, Dict, List, Optional + +from hermes_constants import get_hermes_home +from tools.daemon_pool import DaemonThreadPoolExecutor +from tools.thread_context import propagate_context_to_thread + +logger = logging.getLogger(__name__) + +# ── Module-level state ────────────────────────────────────────────────────── +# Persistent daemon executor (never a `with ThreadPoolExecutor()` block, which +# would join on exit and defeat async); daemon workers can't hang a hard exit. +_executor: Optional[ThreadPoolExecutor] = None +_executor_lock = threading.Lock() +_executor_max_workers: int = 0 + +_records_lock = threading.Lock() +# delegation_id -> record dict; kept for the run plus a short completed tail. +_records: Dict[str, Dict[str, Any]] = {} + +_DEFAULT_MAX_ASYNC_CHILDREN = 3 +# Completed records retained (in memory and in the ledger) for status queries. +_MAX_RETAINED_COMPLETED = 50 +_DURABLE_RETENTION_SECONDS = 7 * 24 * 60 * 60 +_MAX_DURABLE_PENDING = 1000 +# Cap retried deliveries so an unroutable row converges to terminal 'dropped'. +_MAX_DELIVERY_ATTEMPTS = 8 +# Pending completions older than this are dropped on restart replay instead of +# re-run as a full-context turn; 48h keeps weekend results deliverable. +_MAX_COMPLETION_REPLAY_AGE_S = 48 * 3600.0 +_DB_LOCK = threading.Lock() + +# ── Stale-delegation detection (progress-based, on by default) ────────────── +# A runner wedged before returning never reaches its finalizer, so it would show +# "dispatched" forever. No wall-clock timeout (heavy work must never be killed for +# taking long): one monitor thread samples per-dispatch PROGRESS via an injected +# ``progress_fn``; a frozen child is interrupted, given a grace window to unwind via +# the normal finalize path, and only force-finalized (terminal ``stalled`` event) if +# it never returns. Thresholds mirror delegate_tool's sync heartbeat monitor. +_STALE_CHECK_INTERVAL = 30.0 +_STALE_IDLE_SECONDS = 450.0 +_STALE_IN_TOOL_SECONDS = 1200.0 +_STALL_GRACE_SECONDS = 120.0 + +_monitor_lock = threading.Lock() +_monitor_thread: Optional[threading.Thread] = None +_monitor_stop = threading.Event() + +_LIVE_STATES = {"running", "stalling", "finalizing"} +_ACTIVE_STATES = ("running", "stalling") +# Routing origin persisted at dispatch so a restart-recovered completion can +# reconstruct a full SessionSource (scope_id drives relay tenant egress). +_ROUTING_KEYS = ("scope_id", "user_id", "user_name") +# Structured stall metadata — additive, present only on stall finalizations. +_STALL_META_KEYS = ("stalled_after_quiet_seconds", "stall_threshold_seconds", "stall_phase", "stall_grace_seconds") +# Private stall bookkeeping on the record -> public field in list_async_delegations(). +_STALL_FIELD_MAP = (("_stall_quiet_seconds", "stalled_after_quiet_seconds"), + ("_stall_threshold_seconds", "stall_threshold_seconds"), ("_stall_in_tool", "stall_in_tool")) + + +# ── Durable ledger (state.db / async_delegations) ─────────────────────────── +def _db_path(): + return get_hermes_home() / "state.db" + + +def _connect() -> sqlite3.Connection: + from hermes_cli.sqlite_util import open_db + # Same state.db as hermes_state.SessionDB -- reuse its owner-only (0600) + # hardening so this writer doesn't create/leave the file (and its WAL + # sidecars) at the process umask. See hermes_state._secure_state_db_files. + from hermes_state import _secure_state_db_files + + path = _db_path() + path.parent.mkdir(parents=True, exist_ok=True) + _secure_state_db_files(path, create_main=True) + # wal=False: SessionDB owns state.db's journal mode (_initialize_schema applies the barriers). + conn = open_db(path, db_label="state.db (async_delegation)", busy_timeout_ms=10_000, + wal=False, row_factory=None, initialize=_initialize_schema) + _secure_state_db_files(path) + return conn + + +def _initialize_schema(conn: sqlite3.Connection) -> None: + from hermes_state_repair import apply_durability_barriers + from hermes_state_schema import reconcile_state_schema + # Preserve the journal mode SessionDB configured on state.db: forcing WAL from + # every short-lived connection collides with live transcript/FTS writers. + apply_durability_barriers(conn) + # Single durable-shape authority: the canonical SCHEMA_SQL drives both + # table creation and column backfill (reconcile_state_schema replays the + # canonical DDL and reuses SessionDB's declarative reconciliation). This + # module previously carried its own CREATE TABLE + ALTER column list, + # which drifted from SCHEMA_SQL — same-name columns with different + # nullability/defaults depending on which authority touched the database + # first (#94691). + reconcile_state_schema(conn) + + +def _transaction(): + from hermes_cli.sqlite_util import transaction + + return transaction(_connect()) + + +def _capture_routing_origin() -> Dict[str, Any]: + """Snapshot scope_id/user_id/user_name on the PARENT thread (the daemon worker + has no contextvars) so a restart-replayed completion can rebuild a SessionSource. + Best-effort: empty values are omitted.""" + try: + from gateway.session_context import get_session_env + return {k: v for k in _ROUTING_KEYS if (v := get_session_env(f"HERMES_SESSION_{k.upper()}", ""))} + except Exception: # noqa: BLE001 - routing origin is additive, never fatal + return {} + + +def _persist_dispatch(record: Dict[str, Any]) -> None: + now = time.time() + try: + from gateway.status import get_process_start_time + owner_started_at = get_process_start_time(os.getpid()) + except Exception: + owner_started_at = None + task_payload = { + key: record.get(key) + for key in ("goal", "goals", "context", "toolsets", "role", "model", "is_batch", "task_indexes", *_ROUTING_KEYS) + if key in record} + with _DB_LOCK, _transaction() as conn: + conn.execute("""INSERT OR REPLACE INTO async_delegations + (delegation_id, origin_session, origin_ui_session_id, + parent_session_id, state, dispatched_at, updated_at, + delivery_state, delivery_attempts, owner_pid, + owner_started_at, task_json, origin_session_id) + VALUES (?, ?, ?, ?, 'running', ?, ?, 'pending', 0, ?, ?, ?, ?)""", + (record["delegation_id"], record.get("session_key", ""), record.get("origin_ui_session_id", ""), + record.get("parent_session_id"), record["dispatched_at"], now, os.getpid(), owner_started_at, + json.dumps(task_payload), record.get("origin_session_id", ""))) + _prune_durable_records() + + +def _prune_durable_records() -> None: + """Bound terminal history, preferring delivered records for deletion.""" + cutoff = time.time() - _DURABLE_RETENTION_SECONDS + with _DB_LOCK, _transaction() as conn: + conn.execute( + "DELETE FROM async_delegations WHERE delivery_state='delivered' AND updated_at < ?", (cutoff,)) + terminal_count = conn.execute( + "SELECT COUNT(*) FROM async_delegations WHERE state NOT IN ('running','finalizing')").fetchone()[0] + if terminal_count > _MAX_RETAINED_COMPLETED: + conn.execute("""DELETE FROM async_delegations WHERE delegation_id IN ( + SELECT delegation_id FROM async_delegations + WHERE state NOT IN ('running','finalizing') + ORDER BY CASE delivery_state WHEN 'delivered' THEN 0 ELSE 1 END, + updated_at ASC LIMIT ? + )""", (terminal_count - _MAX_RETAINED_COMPLETED,)) + pending_count = conn.execute("""SELECT COUNT(*) FROM async_delegations + WHERE state NOT IN ('running','finalizing') AND delivery_state='pending'""").fetchone()[0] + if pending_count > _MAX_DURABLE_PENDING: + conn.execute("""DELETE FROM async_delegations WHERE delegation_id IN ( + SELECT delegation_id FROM async_delegations + WHERE state NOT IN ('running','finalizing') AND delivery_state='pending' + ORDER BY updated_at ASC LIMIT ? + )""", (pending_count - _MAX_DURABLE_PENDING,)) + + +def _persist_completion(event: Dict[str, Any], result: Dict[str, Any]) -> None: + now = time.time() + with _DB_LOCK, _transaction() as conn: + conn.execute("""UPDATE async_delegations SET state=?, completed_at=?, updated_at=?, + event_json=?, result_json=?, delivery_state='pending' + WHERE delegation_id=?""", + (event.get("status", "completed"), event.get("completed_at", now), now, + json.dumps(event), json.dumps(result), event["delegation_id"])) + + +def record_unit_child(delegation_id: str, entry: Dict[str, Any]) -> None: + """Durably record ONE finished child of a still-running multi-child unit on the unit's own row, so a crash before + the unit joins loses only the children that had not finished. Stored in ``result_json`` (overwritten by the real + result at finalize); ``recover_abandoned_delegations`` replays it. Best-effort: a failed write costs recovery + fidelity, never the live result.""" + try: + with _DB_LOCK, _transaction() as conn: + row = conn.execute("SELECT result_json FROM async_delegations WHERE delegation_id=? AND state='running'", + (delegation_id,)).fetchone() + if row is None: + return + partial = json.loads(row[0] or "{}") or {} + results = [r for r in partial.get("results") or [] if r.get("task_index") != entry.get("task_index")] + results.append(entry) + conn.execute("UPDATE async_delegations SET result_json=?, updated_at=? WHERE delegation_id=? AND state='running'", + (json.dumps({"results": results, "partial": True}), time.time(), delegation_id)) + except Exception: # noqa: BLE001 — recovery bookkeeping must never fail a live child + logger.warning("Async delegation %s: could not record finished child %s", delegation_id, entry.get("task_index"), exc_info=True) + + +def _recovered_results(task: Dict[str, Any], result_json: Optional[str], error: str) -> Optional[List[Dict[str, Any]]]: + """Per-task results for an abandoned unit: recorded children as they finished, the rest ``unknown``.""" + partial = json.loads(result_json or "{}") or {} + if not (task.get("is_batch") and partial.get("partial") and partial.get("results")): + return None + recorded = {r["task_index"]: r for r in partial["results"] if isinstance(r.get("task_index"), int)} + indexes = task.get("task_indexes") or list(range(len(task.get("goals") or []))) + return [recorded.get(i) or {"task_index": i, "status": "unknown", "summary": None, "error": error} for i in indexes] + + +def recover_abandoned_delegations() -> int: + """Classify records whose owning process disappeared as outcome unknown; children a multi-child unit had already + recorded (``record_unit_child``) are replayed with their real results.""" + try: + from gateway.status import _pid_exists, get_process_start_time + except Exception: + return 0 + now, recovered = time.time(), 0 + with _DB_LOCK, _transaction() as conn: + rows = conn.execute("""SELECT delegation_id, origin_session, origin_ui_session_id, + parent_session_id, dispatched_at, owner_pid, + owner_started_at, task_json, origin_session_id, result_json + FROM async_delegations WHERE state IN ('running','finalizing')""").fetchall() + for row in rows: + delegation_id, session_key, origin_ui, parent_id, dispatched_at, pid, started, task_json, origin_sid, result_json = row + if pid and _pid_exists(int(pid)) and (started is None or get_process_start_time(int(pid)) == int(started)): + continue + task = json.loads(task_json or "{}") + error = "Delegation owner exited before recording a terminal result; outcome unknown." + recovered_results = _recovered_results(task, result_json, error) + if recovered_results: + done = sum(1 for r in recovered_results if r.get("status") != "unknown") + error = (f"Delegation owner exited before the unit finished; {done}/{len(recovered_results)} child " + "results were recorded and are included below, the rest are unknown.") + event = { + "type": "async_delegation", "delegation_id": delegation_id, "session_key": session_key, + "origin_ui_session_id": origin_ui, "origin_session_id": origin_sid or "", + "parent_session_id": parent_id, "goal": task.get("goal", ""), "goals": task.get("goals"), + "context": task.get("context"), "toolsets": task.get("toolsets"), "role": task.get("role"), + "model": task.get("model"), "is_batch": bool(task.get("is_batch")), + "status": "unknown", "summary": None, "error": error, + **({"results": recovered_results} if recovered_results else {}), + "dispatched_at": dispatched_at, "completed_at": now, + **{k: task[k] for k in _ROUTING_KEYS if task.get(k)}} + result = {"status": "unknown", "summary": None, "error": event["error"], + **({"results": recovered_results} if recovered_results else {})} + conn.execute("""UPDATE async_delegations SET state='unknown', completed_at=?, + updated_at=?, event_json=?, result_json=?, delivery_state='pending' + WHERE delegation_id=?""", (now, now, json.dumps(event), json.dumps(result), delegation_id)) + recovered += 1 + return recovered + + +def restore_undelivered_completions(target_queue) -> int: + """Enqueue durable pending completions as fresh turns after process start. + Restored events are stamped ``restored=True`` in memory only: they came from a PREVIOUS + process, so drains without an ownership filter must leave them for a consumer that can + prove ownership. Rows older than ``_MAX_COMPLETION_REPLAY_AGE_S`` are terminally dropped + instead of replaying a turn nobody is waiting on. + + Every restored event is stamped ``restored=True`` (in-memory only — the stamp is added after the durable + payload is deserialized and is never persisted). Restored events originate from a *previous* process, so + no consumer in THIS process implicitly owns them: drain paths that run without an ownership filter (the + legacy single-session behavior) must leave them queued for a consumer that can positively prove + ownership, otherwise a brand-new session adopts a dead session's delegation results seconds after boot + (#64484). + """ + recover_abandoned_delegations() + now, restored = time.time(), 0 + with _DB_LOCK, _transaction() as conn: + rows = conn.execute("""SELECT delegation_id, event_json, completed_at, dispatched_at + FROM async_delegations + WHERE state != 'running' AND delivery_state='pending' AND event_json IS NOT NULL + ORDER BY completed_at, delegation_id""").fetchall() + for delegation_id, payload, completed_at, dispatched_at in rows: + age_basis = completed_at or dispatched_at + if age_basis and (now - age_basis) > _MAX_COMPLETION_REPLAY_AGE_S: + conn.execute("""UPDATE async_delegations SET delivery_state='dropped', + delivery_claim=NULL, delivery_claimed_at=NULL, + updated_at=? + WHERE delegation_id=? AND delivery_state='pending'""", (now, delegation_id)) + logger.warning("Async delegation %s: pending completion is %.1fh old " + "(cap %.1fh); terminally dropping the replay (result remains queryable).", + delegation_id, (now - age_basis) / 3600.0, _MAX_COMPLETION_REPLAY_AGE_S / 3600.0) + continue + evt = json.loads(payload) + if isinstance(evt, dict): + evt["restored"] = True + target_queue.put(evt) + restored += 1 + return restored + + +def _update_delivery(sql: str, params: tuple) -> bool: + """Run one UPDATE on the ledger; True iff exactly one row changed.""" + with _DB_LOCK, _transaction() as conn: + return conn.execute(sql, params).rowcount == 1 + + +def mark_completion_delivered(delegation_id: str) -> bool: + """Atomically acknowledge successful injection of a durable completion.""" + now = time.time() + return _update_delivery( + """UPDATE async_delegations SET delivery_state='delivered', delivered_at=?, updated_at=? + WHERE delegation_id=? AND delivery_state!='delivered'""", (now, now, delegation_id)) + + +def claim_completion_delivery(delegation_id: str, claim_id: str) -> bool: + """Claim one pending completion across competing consumers/processes.""" + now = time.time() + with _DB_LOCK, _transaction() as conn: + row = conn.execute( + "SELECT delivery_state FROM async_delegations WHERE delegation_id=?", (delegation_id,)).fetchone() + if row is None: + return True # legacy event created before durable dispatch + cur = conn.execute("""UPDATE async_delegations SET delivery_claim=?, delivery_claimed_at=?, + delivery_attempts=delivery_attempts+1, updated_at=? + WHERE delegation_id=? AND delivery_state='pending' + AND (delivery_claim IS NULL OR delivery_claimed_at < ?)""", + (claim_id, now, now, delegation_id, now - 300)) + return cur.rowcount == 1 + + +def is_interim_delegation_event(evt: Dict[str, Any]) -> bool: + """An early per-task notice for a batch that is still running. It shares the batch's + ``delegation_id`` but is NOT the durable completion: it must never claim, acknowledge or + dedup against the final result's row (independent review reproduced exactly that loss).""" + return evt.get("type") == "async_delegation" and bool(evt.get("task_failure_notice")) + + +def claim_event_delivery(evt: Dict[str, Any], consumer: str) -> Optional[str]: + """Claim a durable delegation event; non-durable events (and interim notices) need no token.""" + if is_interim_delegation_event(evt): + return "" + delegation_id = str(evt.get("delegation_id") or "") if evt.get("type") == "async_delegation" else "" + if not delegation_id: + return "" + claim_id = f"{consumer}:{os.getpid()}:{uuid.uuid4().hex}" + return claim_id if claim_completion_delivery(delegation_id, claim_id) else None + + +def release_completion_delivery(delegation_id: str, claim_id: str) -> bool: + """Release a failed delivery claim so another consumer may retry. Attempts are + counted at claim time; once the budget is exhausted the row converges to + terminal ``dropped`` (only pending rows replay on restart).""" + now = time.time() + with _DB_LOCK, _transaction() as conn: + capped = conn.execute("""UPDATE async_delegations SET delivery_state='dropped', + delivery_claim=NULL, delivery_claimed_at=NULL, updated_at=? + WHERE delegation_id=? AND delivery_state='pending' + AND delivery_claim=? AND delivery_attempts>=?""", + (now, delegation_id, claim_id, _MAX_DELIVERY_ATTEMPTS)) + if capped.rowcount == 1: + logger.warning("Async delegation %s exhausted its %d delivery attempts; " + "marking terminally dropped (result remains queryable).", + delegation_id, _MAX_DELIVERY_ATTEMPTS) + return True + cur = conn.execute("""UPDATE async_delegations SET delivery_claim=NULL, + delivery_claimed_at=NULL, updated_at=? + WHERE delegation_id=? AND delivery_state='pending' + AND delivery_claim=?""", (now, delegation_id, claim_id)) + return cur.rowcount == 1 + + +def defer_completion_delivery(delegation_id: str, claim_id: str) -> bool: + """Return an unadmitted completion to pending without spending a delivery attempt.""" + return _update_delivery("""UPDATE async_delegations SET delivery_claim=NULL, + delivery_claimed_at=NULL, delivery_attempts=MAX(0, delivery_attempts-1), + updated_at=? + WHERE delegation_id=? AND delivery_state='pending' AND delivery_claim=?""", + (time.time(), delegation_id, claim_id)) + + +def drop_completion_delivery(delegation_id: str, claim_id: str) -> bool: + """Terminally drop a claimed completion whose target is permanently gone (the + spawning session ended at an explicit user boundary such as /new or reset). + ``dropped`` — not ``delivered`` — keeps the ack honest; not ``pending`` keeps + restart recovery from replaying it into a fail-closed drop forever.""" + return _update_delivery("""UPDATE async_delegations SET delivery_state='dropped', + updated_at=?, delivery_claim=NULL, + delivery_claimed_at=NULL + WHERE delegation_id=? AND delivery_state='pending' + AND delivery_claim=?""", (time.time(), delegation_id, claim_id)) + + +def complete_completion_delivery(delegation_id: str, claim_id: str) -> bool: + """Acknowledge acceptance for the consumer holding this claim.""" + now = time.time() + return _update_delivery("""UPDATE async_delegations SET delivery_state='delivered', + delivered_at=?, updated_at=?, delivery_claim=NULL, + delivery_claimed_at=NULL + WHERE delegation_id=? AND delivery_state='pending' + AND delivery_claim=?""", (now, now, delegation_id, claim_id)) + + +def complete_event_delivery(evt: Dict[str, Any], claim_id: str) -> None: + _event_delivery(complete_completion_delivery, evt, claim_id) + + +def release_event_delivery(evt: Dict[str, Any], claim_id: str) -> None: + _event_delivery(release_completion_delivery, evt, claim_id) + + +def _event_delivery(fn, evt: Dict[str, Any], claim_id: str) -> None: + if claim_id and evt.get("type") == "async_delegation": + fn(str(evt.get("delegation_id") or ""), claim_id) + + +def get_durable_delegation(delegation_id: str) -> Optional[Dict[str, Any]]: + with _DB_LOCK, _transaction() as conn: + row = conn.execute("""SELECT origin_session, state, dispatched_at, completed_at, + result_json, delivery_state, delivery_attempts, + origin_session_id + FROM async_delegations WHERE delegation_id=?""", (delegation_id,)).fetchone() + return None if row is None else { + "delegation_id": delegation_id, "origin_session": row[0], "state": row[1], "dispatched_at": row[2], + "completed_at": row[3], "result": json.loads(row[4]) if row[4] else None, "delivery_state": row[5], + "delivery_attempts": row[6], "origin_session_id": row[7] or ""} + + +# ── In-memory registry queries ────────────────────────────────────────────── +def _get_executor(max_workers: int) -> ThreadPoolExecutor: + """Lazily create (or grow in place, never shrink) the shared daemon executor. Raising + ``_max_workers`` is enough: the next ``submit`` spawns threads up to the new cap.""" + global _executor, _executor_max_workers + with _executor_lock: + if _executor is None: + _executor = DaemonThreadPoolExecutor(max_workers=max_workers, thread_name_prefix="async-delegate") + _executor_max_workers = max_workers + elif max_workers > _executor_max_workers: + _executor._max_workers = max_workers + _executor_max_workers = max_workers + return _executor + + +def active_count() -> int: + """Number of live async delegation UNITS (one per completion message: a task group or an ungrouped task).""" + with _records_lock: + return sum(1 for r in _records.values() if r.get("status") in _LIVE_STATES) + + +def active_task_count() -> int: + """Number of running child subagents (a batch of N contributes N; a batch with + no goal list counts 1) — the truthful observability figure, unlike slots.""" + with _records_lock: + return sum( + len(r.get("task_indexes") or r["goals"]) + if r.get("is_batch") and isinstance(r.get("goals"), (list, tuple)) and r["goals"] else 1 + for r in _records.values() if r.get("status") in {"running", "finalizing"}) + + +def _session_records(statuses, session_key: str, origin_ui_session_id: str, parent_session_id: str) -> list: + """Records in ``statuses`` owned by a session: any non-empty selector claims the + record — ``origin_ui_session_id`` (TUI tab), ``session_key`` (routing key at + dispatch), or ``parent_session_id`` (spawner's durable id — the right one for + gateway chats, whose session_key survives ``/new`` while the session id rotates).""" + selectors = [(field, wanted) for field, wanted in ( + ("origin_ui_session_id", origin_ui_session_id), ("session_key", session_key), + ("parent_session_id", parent_session_id)) if wanted] + if not selectors: + return [] + with _records_lock: + return [r for r in _records.values() if r.get("status") in statuses + and any(str(r.get(field) or "") == wanted for field, wanted in selectors)] + + +def has_live_for_session(session_key: str = "", origin_ui_session_id: str = "", parent_session_id: str = "") -> bool: + """Whether a session still owns any live (running/stalling/finalizing) delegation.""" + return bool(_session_records(_LIVE_STATES, session_key, origin_ui_session_id, parent_session_id)) + + +def _new_delegation_id() -> str: + return f"deleg_{uuid.uuid4().hex[:8]}" + + +def _prune_completed_locked() -> None: + """Drop the oldest completed records beyond the cap. Caller holds ``_records_lock``.""" + completed = [(rid, r) for rid, r in _records.items() if r.get("status") != "running"] + completed.sort(key=lambda kv: kv[1].get("completed_at") or kv[1].get("dispatched_at") or 0) + for rid, _ in completed[: max(0, len(completed) - _MAX_RETAINED_COMPLETED)]: + _records.pop(rid, None) + + +def _current_origin_session_id() -> str: + """Raw session id of the ORIGINATING api_server request, or ``""``. ``HERMES_SESSION_ID`` + is unsafe here: building the child agent calls ``set_current_session_id(child.session_id)`` + just before dispatch, so the wake would self-post into the subagent's own session. The + request-scoped ``HERMES_SESSION_CHAT_ID`` (raw X-Hermes-Session-Id on api_server) survives + child construction; on push platforms chat_id is a chat, not a session => ``""``.""" + try: + from gateway.session_context import get_session_env + is_api = get_session_env("HERMES_SESSION_PLATFORM", "") == "api_server" + return (get_session_env("HERMES_SESSION_CHAT_ID", "") or "") if is_api else "" + except Exception: + return "" + + +# ── Dispatch ──────────────────────────────────────────────────────────────── +def _single_crash(error: str, duration: float) -> Dict[str, Any]: + return {"status": "error", "summary": None, "error": error, "api_calls": 0, "duration_seconds": duration} + + +def _batch_crash(error: str, duration: float) -> Dict[str, Any]: + return {"results": [], "error": error, "total_duration_seconds": duration} + + +def _batch_status(combined: Dict[str, Any]) -> str: + """Batch status: completed unless every child errored/was interrupted.""" + child_results = combined.get("results") or [] + ok = ("completed", "success") + return "error" if child_results and all(r.get("status") not in ok for r in child_results) else "completed" + + +def _dispatch( + *, delegation_id: str, goal: str, goals: Optional[List[str]], context: Optional[str], + toolsets: Optional[List[str]], role: str, model: Optional[str], session_key: str, + parent_session_id: Optional[str], runner: Callable[[], Dict[str, Any]], origin_ui_session_id: str, + origin_session_id: str, interrupt_fn: Optional[Callable[[], None]], max_async_children: int, + progress_fn: Optional[Callable[[], tuple]], capacity_error: str, slot_key: Optional[str] = None, + task_indexes: Optional[List[int]] = None, +) -> Dict[str, Any]: + """Shared dispatch core for single (``goals is None``) and batch units. Capacity check + + record insert happen under ONE lock hold so concurrent dispatches can't both pass the check + and exceed the cap. At capacity the dispatch is REJECTED (never queued) so a runaway model + can't pile up unbounded background work. ``slot_key`` names the pool slot the unit occupies + (default: its own id); the units of one delegate_task call share the first unit's id so + splitting a call into per-group completions never consumes more capacity than the call did.""" + is_batch = goals is not None + label = " batch" if is_batch else "" + classify = _batch_status if is_batch else (lambda r: r.get("status") or "completed") + crash_result = _batch_crash if is_batch else _single_crash + dispatched_at = time.time() + record: Dict[str, Any] = { + "delegation_id": delegation_id, "goal": goal, **({"goals": list(goals)} if is_batch else {}), + "context": context, "toolsets": list(toolsets) if toolsets else None, "role": role, "model": model, + "session_key": session_key, "origin_ui_session_id": origin_ui_session_id, + "origin_session_id": origin_session_id, "parent_session_id": parent_session_id, + **_capture_routing_origin(), + "status": "running", "dispatched_at": dispatched_at, "completed_at": None, + "interrupt_fn": interrupt_fn, **({"is_batch": True} if is_batch else {}), "progress_fn": progress_fn, + "slot_key": slot_key or delegation_id, + # Which of the call's ``goals`` this unit runs (None = all of them). + **({"task_indexes": list(task_indexes)} if task_indexes is not None else {}), + # Stale-monitor bookkeeping (see _stale_monitor_loop). + "_progress_token": None, "_progress_ts": dispatched_at, "_interrupted_at": None} + with _records_lock: + active_slots = {r.get("slot_key") or r["delegation_id"] for r in _records.values() if r.get("status") in _ACTIVE_STATES} + if record["slot_key"] not in active_slots and len(active_slots) >= max_async_children: + return {"status": "rejected", "error": capacity_error} + _records[delegation_id] = record + live_units = sum(1 for r in _records.values() if r.get("status") in _LIVE_STATES) + _persist_dispatch(record) + # Units of one call share a slot, so live units can exceed slots: size the pool by units or a + # unit queues behind a full pool and the stale monitor kills it before its child ever starts. + executor = _get_executor(max(max_async_children, live_units)) + + def _worker() -> None: + result: Dict[str, Any] = {} + status = "error" + with _records_lock: + rec = _records.get(delegation_id) + if rec is not None: + # The stall clock starts when the runner starts; a unit queued behind a full pool is not stalled. + rec.update(_started=True, _progress_ts=time.time()) + try: + result = runner() or {} + status = classify(result) + except Exception as exc: # noqa: BLE001 — must never crash the worker + logger.exception(f"Async delegation{label} %s crashed", delegation_id) + result = crash_result(f"{type(exc).__name__}: {exc}", round(time.time() - dispatched_at, 2)) + finally: + _finalize(delegation_id, result, status) + + try: + # Propagate the dispatching profile so the detached child resolves get_hermes_home() correctly. + executor.submit(propagate_context_to_thread(_worker)) + except Exception as exc: # pragma: no cover — pool submit failure is rare + with _records_lock: + _records.pop(delegation_id, None) + with _DB_LOCK, _transaction() as conn: + conn.execute("DELETE FROM async_delegations WHERE delegation_id=?", (delegation_id,)) + return {"status": "rejected", "error": f"Failed to schedule async delegation{label}: {exc}"} + if progress_fn is not None: + _ensure_stale_monitor() + return {"status": "dispatched", "delegation_id": delegation_id} + + +def dispatch_async_delegation( + *, goal: str, context: Optional[str], toolsets: Optional[List[str]], role: str, model: Optional[str], + session_key: str, parent_session_id: Optional[str] = None, runner: Callable[[], Dict[str, Any]], + origin_ui_session_id: str = "", origin_session_id: str = "", interrupt_fn: Optional[Callable[[], None]] = None, + max_async_children: int = _DEFAULT_MAX_ASYNC_CHILDREN, progress_fn: Optional[Callable[[], tuple]] = None, +) -> Dict[str, Any]: + """Spawn ``runner`` on the daemon executor and return a handle immediately. + ``session_key``/``parent_session_id`` are captured on the parent thread (the worker carries + no contextvars) and route the completion back to the spawning session. + ``progress_fn() -> (token, in_tool)`` enables stale monitoring; omitted = unmonitored. + Returns ``{"status": "dispatched", "delegation_id"}`` or ``{"status": "rejected", "error"}``.""" + delegation_id = _new_delegation_id() + handle = _dispatch( + delegation_id=delegation_id, goal=goal, goals=None, context=context, + toolsets=toolsets, role=role, model=model, session_key=session_key, + parent_session_id=parent_session_id, runner=runner, + origin_ui_session_id=origin_ui_session_id, origin_session_id=origin_session_id, + interrupt_fn=interrupt_fn, max_async_children=max_async_children, progress_fn=progress_fn, + capacity_error=( + f"Async delegation capacity reached ({max_async_children} running). Wait for one to finish " + "(its result will re-enter the chat), or run this task synchronously (background=false). " + "Raise delegation.max_concurrent_children in config.yaml to allow more concurrent background subagents.")) + if handle["status"] == "dispatched": + logger.info("Dispatched async delegation %s (session_key=%s): %s", + delegation_id, session_key or "", (goal or "")[:80]) + return handle + + +def dispatch_async_delegation_batch( + *, goals: List[str], context: Optional[str], toolsets: Optional[List[str]], role: str, model: Optional[str], + session_key: str, parent_session_id: Optional[str] = None, runner: Callable[[], Dict[str, Any]], + origin_ui_session_id: str = "", origin_session_id: str = "", interrupt_fn: Optional[Callable[[], None]] = None, + max_async_children: int = _DEFAULT_MAX_ASYNC_CHILDREN, delegation_id: Optional[str] = None, + progress_fn: Optional[Callable[[], tuple]] = None, slot_key: Optional[str] = None, + task_indexes: Optional[List[int]] = None, +) -> Dict[str, Any]: + """Dispatch a fan-out unit (a whole batch, or one ``group`` of a delegate_task call) as ONE + background unit: ``runner`` runs its tasks and returns the combined ``{"results": [...], + "total_duration_seconds": N}`` dict. The unit occupies ONE async slot — or joins the slot named + by ``slot_key`` (in-unit parallelism is bounded separately) — and produces a SINGLE completion + event carrying per-task ``results``.""" + delegation_id = delegation_id or _new_delegation_id() + # ``goals`` is the whole call (result task_index indexes it); the unit's own goals label the record. + unit_goals = [goals[i] for i in task_indexes] if task_indexes is not None else list(goals) + n = len(unit_goals) + combined_goal = unit_goals[0] if n == 1 else f"{n} parallel subagents: " + "; ".join(g[:40] for g in unit_goals) + handle = _dispatch( + delegation_id=delegation_id, goal=combined_goal, goals=goals, context=context, + toolsets=toolsets, role=role, model=model, session_key=session_key, + parent_session_id=parent_session_id, runner=runner, + origin_ui_session_id=origin_ui_session_id, origin_session_id=origin_session_id, + interrupt_fn=interrupt_fn, max_async_children=max_async_children, progress_fn=progress_fn, slot_key=slot_key, + task_indexes=task_indexes, + capacity_error=( + f"Async delegation capacity reached ({max_async_children} running). Wait for one to finish " + "(its result will re-enter the chat), or raise delegation.max_concurrent_children in " + "config.yaml to allow more concurrent background units.")) + if handle["status"] == "dispatched": + logger.info("Dispatched async delegation batch %s (%d task(s), session_key=%s)", + delegation_id, n, session_key or "") + return handle + + +# ── Finalization + completion events ──────────────────────────────────────── +def _finalize(delegation_id: str, result: Any, status: str) -> None: + """Atomically claim terminal delivery, push the completion event, then mark ``status``. + ``result`` is a dict or a callable receiving the record snapshot (stall path). The record + stays active ("finalizing") until durable persistence and queue publication finish; otherwise + process shutdown can kill this daemon worker after status flips but before SQLite commits. + A second call for the same id (late runner return after a forced stall) is a no-op.""" + with _records_lock: + record = _records.get(delegation_id) + if record is None or record.get("status") not in _ACTIVE_STATES: + return + record["status"] = "finalizing" + record["completed_at"] = time.time() + record["interrupt_fn"] = None # drop the closure; child is done + record["progress_fn"] = None # stop stale-monitor sampling + snapshot = dict(record) + _push_completion_event(snapshot, result(snapshot) if callable(result) else result, status) + with _records_lock: + if delegation_id in _records: + _records[delegation_id]["status"] = status + _prune_completed_locked() + + +def _push_completion_event(record: Dict[str, Any], result: Dict[str, Any], status: str) -> None: + """Push a type='async_delegation' event onto the shared completion queue. Batch records + (``is_batch``) carry the per-task ``results`` list (plus live transcript paths, the + full-fidelity record of each child's run) instead of a single summary. Best-effort: failure + must not crash the worker, but it WOULD mean a silently-lost result, so we log loudly.""" + is_batch = bool(record.get("is_batch")) + label = " batch" if is_batch else "" + try: + from tools.process_registry import process_registry + except Exception as exc: # pragma: no cover + logger.error(f"Async delegation{label} %s finished but process_registry import failed; " + "result lost: %s", record.get("delegation_id"), exc) + return + dispatched_at = record.get("dispatched_at") or time.time() + completed_at = record.get("completed_at") or time.time() + if is_batch: + payload = { + "is_batch": True, "results": result.get("results") or [], + "live_transcripts": result.get("live_transcripts"), "error": result.get("error"), + "total_duration_seconds": result.get("total_duration_seconds"), + **({"group": result["group"]} if result.get("group") is not None else {})} + else: + payload = { + "summary": result.get("summary"), "error": result.get("error"), "api_calls": result.get("api_calls", 0), + "duration_seconds": result.get("duration_seconds", round(completed_at - dispatched_at, 2))} + evt = { + "type": "async_delegation", "delegation_id": record.get("delegation_id"), + # session_key routes back to the originating gateway session; "" => CLI. + "session_key": record.get("session_key", ""), + "origin_ui_session_id": record.get("origin_ui_session_id", ""), + "origin_session_id": record.get("origin_session_id", ""), + "parent_session_id": record.get("parent_session_id"), + "goal": record.get("goal", ""), **({"goals": record.get("goals")} if is_batch else {}), + "context": record.get("context"), "toolsets": record.get("toolsets"), "role": record.get("role"), + "model": record.get("model") if is_batch else (result.get("model") or record.get("model")), + "status": status, **payload, "dispatched_at": dispatched_at, "completed_at": completed_at, + **({} if is_batch else {"exit_reason": result.get("exit_reason")}), + **{k: record[k] for k in _ROUTING_KEYS if record.get(k)}, + **{k: result[k] for k in _STALL_META_KEYS if k in result}} + _persist_completion(evt, result) + try: + process_registry.completion_queue.put(evt) + except Exception as exc: # pragma: no cover + logger.error(f"Async delegation{label} %s: failed to enqueue completion event; " + "result lost: %s", record.get("delegation_id"), exc) + + +def push_task_failure_notice(delegation_id: str, entry: Dict[str, Any], *, n_tasks: int) -> None: + """Surface ONE failed child of a still-running detached batch to the parent now, instead of + when the slowest sibling finishes. In a 1,393-agent run every wave-1 child died in a 401 storm + at 08:29 and the parent learned of it at 09:36, when the batch's "unknown outcome" block finally + arrived: 66 minutes of a dead wave with nothing running. The notice rides the same + ``type="async_delegation"`` event shape as the batch result (so every drain/route/format path + treats it identically) with ``task_failure_notice=True`` and a single-entry ``results`` list; the + batch record is NOT finalized and its consolidated result still arrives as before.""" + with _records_lock: + record = _records.get(delegation_id) + if record is None or record.get("status") not in _ACTIVE_STATES: + return + snapshot = dict(record) + try: + from tools.process_registry import process_registry + except Exception as exc: # pragma: no cover + logger.error("Async delegation batch %s: task failure notice dropped (process_registry import): %s", delegation_id, exc) + return + evt = { + "type": "async_delegation", "task_failure_notice": True, "is_batch": True, "n_tasks": n_tasks, + "delegation_id": delegation_id, "results": [entry], + "session_key": snapshot.get("session_key", ""), + "origin_ui_session_id": snapshot.get("origin_ui_session_id", ""), + "origin_session_id": snapshot.get("origin_session_id", ""), + "parent_session_id": snapshot.get("parent_session_id"), + "goal": snapshot.get("goal", ""), "goals": snapshot.get("goals"), "context": snapshot.get("context"), + "toolsets": snapshot.get("toolsets"), "role": snapshot.get("role"), "model": snapshot.get("model"), + "status": "running", "dispatched_at": snapshot.get("dispatched_at") or time.time(), "completed_at": time.time(), + **{k: snapshot[k] for k in _ROUTING_KEYS if snapshot.get(k)}} + try: + process_registry.completion_queue.put(evt) + except Exception as exc: # pragma: no cover + logger.error("Async delegation batch %s: failed to enqueue task failure notice: %s", delegation_id, exc) + + +# ── Stale monitor ─────────────────────────────────────────────────────────── +def _ensure_stale_monitor() -> None: + """Start (once) the stale-delegation monitor thread. One daemon thread serves + every dispatch; it exits when no monitorable records remain and is restarted + by the next dispatch with a ``progress_fn``.""" + global _monitor_thread + with _monitor_lock: + if _monitor_thread is not None and _monitor_thread.is_alive(): + return + _monitor_stop.clear() + _monitor_thread = threading.Thread( + target=_stale_monitor_loop, name="async-delegate-stale-monitor", daemon=True) + _monitor_thread.start() + + +def _sweep_stale_locked(now: float): + """One monitor pass over ``_records``; caller holds ``_records_lock``. Returns + ``(stalled, expired, any_monitorable)``: newly-stalling ``(delegation_id, quiet_for, in_tool)`` + tuples, stalling ids past the grace window, and whether anything is left to monitor.""" + stalled, expired, any_monitorable = [], [], False # (delegation_id, quiet_for, in_tool) / ids past grace + for record in _records.values(): + status = record.get("status") + if status == "stalling": + any_monitorable = True + if now - (record.get("_interrupted_at") or now) >= _STALL_GRACE_SECONDS: + expired.append(record["delegation_id"]) + continue + progress_fn = record.get("progress_fn") + if status != "running" or progress_fn is None: + continue + any_monitorable = True + if not record.get("_started"): + continue # queued behind a full pool: not stalled, but keep the monitor alive for when it starts + try: + token, in_tool = progress_fn() + except Exception: + # An unreadable child must not look permanently healthy — + # keep the last timestamp running instead of refreshing it. + token, in_tool = record.get("_progress_token"), False + if token != record.get("_progress_token"): + record.update(_progress_token=token, _progress_ts=now) + continue + quiet_for = now - (record.get("_progress_ts") or now) + limit = _STALE_IN_TOOL_SECONDS if in_tool else _STALE_IDLE_SECONDS + if quiet_for >= limit: + # Stall context feeds the terminal event and status listings. + record.update( + status="stalling", _interrupted_at=now, _stall_quiet_seconds=round(quiet_for, 2), + _stall_threshold_seconds=limit, _stall_in_tool=bool(in_tool)) + stalled.append((record["delegation_id"], quiet_for, in_tool)) + return stalled, expired, any_monitorable + + +def _call_interrupt(fn, msg: str, *args) -> bool: + """Invoke an ``interrupt_fn``; True on success, else debug-log ``msg`` (+ exc).""" + if not callable(fn): + return False + try: + fn() + return True + except Exception as exc: + logger.debug(msg, *args, exc) + return False + + +def _stale_monitor_loop() -> None: + """Sweep running delegations for stalled progress. A changed progress token refreshes the + record's timestamp; a frozen token past the idle/in-tool threshold marks the record + ``stalling`` and calls ``interrupt_fn``; a ``stalling`` record still unreturned after the + grace window is force-finalized with a terminal ``stalled`` event.""" + while not _monitor_stop.wait(_STALE_CHECK_INTERVAL): + now = time.time() + with _records_lock: + stalled, expired, any_monitorable = _sweep_stale_locked(now) + for delegation_id, quiet_for, in_tool in stalled: + logger.warning("Async delegation %s made no progress for %.0fs " + "(in_tool=%s) — interrupting; grace window %.0fs", + delegation_id, quiet_for, in_tool, _STALL_GRACE_SECONDS) + with _records_lock: + fn = (_records.get(delegation_id) or {}).get("interrupt_fn") + _call_interrupt(fn, "Async delegation %s stall interrupt failed: %s", delegation_id) + for delegation_id in expired: + _finalize(delegation_id, lambda rec, d=delegation_id: _stalled_result(d, rec), "stalled") + if not any_monitorable: + return + + +def _stalled_result(delegation_id: str, event_record: Dict[str, Any]) -> Dict[str, Any]: + """Synthetic terminal result for a stalling delegation whose runner never returned.""" + completed_at = event_record.get("completed_at") or time.time() + duration = round(completed_at - (event_record.get("dispatched_at") or completed_at), 2) + error = ( + f"Async delegation {delegation_id} stalled: the detached subagent stopped making progress " + "(no new API calls, tool activity, or streamed tokens), did not respond to interruption, and never " + "produced a completion event. The worker may be wedged inside a model API call — this is a known " + "failure mode of long-lived gateway processes (#60203). Re-dispatch the task if it is still needed.") + logger.error("Async delegation %s force-finalized as stalled after %.0fs", delegation_id, duration) + # Structured stall metadata lets parents/UIs distinguish a stall-monitor + # kill from other failures without parsing the error string. + stall_in_tool = event_record.get("_stall_in_tool") + stall_meta = { + "stalled_after_quiet_seconds": event_record.get("_stall_quiet_seconds"), + "stall_threshold_seconds": event_record.get("_stall_threshold_seconds"), + "stall_phase": "in_tool" if stall_in_tool else "idle" if stall_in_tool is not None else None, + "stall_grace_seconds": _STALL_GRACE_SECONDS} + if event_record.get("is_batch"): + return {**_batch_crash(error, duration), **stall_meta} + return {**_single_crash(error, duration), "status": "stalled", "exit_reason": "stalled", **stall_meta} + + +# ── Observability + control ───────────────────────────────────────────────── +def _children_activity_from_token(token: Any, now: float) -> Optional[List]: + """Parse a progress token into per-child activity dicts (best-effort): delegate_tool + emits one ``(api_call_count, current_tool, last_activity_ts)`` tuple per child; + foreign token shapes degrade to ``None`` entries.""" + try: + parts = list(token) + except TypeError: + return None + out: List[Optional[Dict[str, Any]]] = [] + for part in parts: + if not (isinstance(part, (list, tuple)) and len(part) >= 2): + out.append(None) + continue + entry: Dict[str, Any] = {"api_calls": part[0], "current_tool": part[1]} + if len(part) >= 3 and isinstance(part[2], (int, float)): + entry["seconds_since_activity"] = round(max(0.0, now - float(part[2])), 1) + out.append(entry) + return out + + +def list_async_delegations() -> List[Dict[str, Any]]: + """Snapshot of async delegations (running + recently completed) without callables or private + monitor bookkeeping; adds computed live fields for UIs (``seconds_since_progress``, + ``children_activity``/``in_tool`` sampled from ``progress_fn``) and stall context once tripped. + + Safe to call from any thread. See #51690. + """ + now = time.time() + samplers: Dict[str, Callable] = {} + with _records_lock: + items = [] + for r in _records.values(): + item = {k: v for k, v in r.items() if k not in {"interrupt_fn", "progress_fn"} and not k.startswith("_")} + status = r.get("status") + if status in _ACTIVE_STATES: + if r.get("_progress_ts"): + item["seconds_since_progress"] = round(now - r["_progress_ts"], 1) + if callable(r.get("progress_fn")): + samplers[r["delegation_id"]] = r["progress_fn"] + if status in ("stalling", "stalled"): + for src, dst in _STALL_FIELD_MAP: + if r.get(src) is not None: + item[dst] = r.get(src) + items.append(item) + # Sample OUTSIDE the lock — progress_fn reads child-agent attributes and a + # slow/broken sampler must not block every dispatch/finalize. + for item in items: + fn = samplers.get(item.get("delegation_id")) + if fn is None: + continue + try: + token, in_tool = fn() + except Exception: + continue + activity = _children_activity_from_token(token, now) + if activity is not None: + item["children_activity"] = activity + item["in_tool"] = bool(in_tool) + return items + + +def _interrupt_records(targets: List[Dict[str, Any]], caller: str, reason: str, msg: str) -> int: + """Call ``interrupt_fn`` on each record; log ``msg`` once; returns how many succeeded.""" + count = sum( + _call_interrupt(r.get("interrupt_fn"), "%s: %s interrupt failed: %s", caller, r.get("delegation_id")) + for r in targets) + if count: + logger.info(msg, count, reason) + return count + + +def interrupt_all(reason: str = "shutdown") -> int: + """Signal every running async delegation to stop (``/stop``, shutdown). Returns how + many. The child still emits a completion event (status='interrupted') via the + normal finalize path.""" + with _records_lock: + targets = [r for r in _records.values() if r.get("status") in _ACTIVE_STATES] + return _interrupt_records(targets, "interrupt_all", reason, "Interrupted %d async delegation(s) (%s)") + + +def interrupt_for_session( + session_key: str = "", origin_ui_session_id: str = "", parent_session_id: str = "", reason: str = "session_end", +) -> int: + """Signal running async delegations owned by ONE ending session to stop (any + selector matches, see ``_session_records``). Returns how many.""" + targets = _session_records(_ACTIVE_STATES, session_key, origin_ui_session_id, parent_session_id) + return _interrupt_records( + targets, "interrupt_for_session", reason, "Interrupted %d async delegation(s) for ending session (%s)") + + +def _reset_for_tests() -> None: + """Test-only: clear all state and tear down the executor + monitor.""" + global _executor, _executor_max_workers, _monitor_thread + with _executor_lock: + if _executor is not None: + _executor.shutdown(wait=False) + _executor = None + _executor_max_workers = 0 + _monitor_stop.set() + with _monitor_lock: + thread, _monitor_thread = _monitor_thread, None + if thread is not None and thread.is_alive(): + thread.join(timeout=2) + with _records_lock: + _records.clear() + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. + +def active_for_session(origin_ui_session_id: str) -> int: + """Number of live async delegations owned by one UI session.""" + if not origin_ui_session_id: + return 0 + with _records_lock: + return sum( + 1 + for r in _records.values() + if r.get("status") in {"running", "stalling", "finalizing"} + and str(r.get("origin_ui_session_id") or "") + == origin_ui_session_id + ) +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.py new file mode 100644 index 0000000000000000000000000000000000000000..7261c61d752fc4b5c457fbd4eb68527aafa111b8 --- /dev/null +++ b/tools/bot_mode_dm.py @@ -0,0 +1,663 @@ +"""Bot Mode agent-to-agent DM tool — ``message_agent``. + +Lets a Bot Mode agent message a teammate (a profile on this install, an agent on +a registered peer gateway, or one on another Desktop-connected machine): the +target is validated against the live roster, the attribution prefix is applied +server-side, and the reply arrives later via the background-process completion +notification (fire-and-forget). Containment: the schema is injected ONLY into a +bot's canonical "Bot Chat" session on a Bot-Mode-managed install (same gate as +``tools/bot_mode_probe.py``; never in the registry or any toolset), and dispatch +re-checks that gate so a forged call returns a structured error. Transports: +local → ``hermes -p chat --in ~ -c "Bot Chat" --create-if-missing -Q +--query-file ``; peer → ``hermes peer dm [/] < ``; both via +``terminal_tool(background=True, notify_on_complete=True)``. +""" + +from __future__ import annotations + +import contextlib +import hashlib +import json +import logging +import os +import re +import shlex +import stat +import subprocess +import sys +import tempfile +import time +from pathlib import Path +from typing import Any, Optional + +# Top-level imports stay stdlib-only: this module also runs directly as the background +# delivery runner (``python bot_mode_dm.py --run-delivery …``); Hermes helpers import lazily. + +logger = logging.getLogger(__name__) + +MESSAGE_AGENT_TOOL_NAME = "message_agent" + +# Message body cap — generous for real work, small enough that a runaway paste can't +# turn one DM into a context bomb on the recipient. +MESSAGE_MAX_CHARS = 16000 +# A runner owns and removes each DM file; this bounds residual plaintext lifetime if +# the machine dies between spawn ack and the runner's finally. +_DM_DIR_NAME = "hermes-dm" +_DM_STALE_SECONDS = 24 * 60 * 60 +_LIVE_WAIT_SECONDS = 300 + +# '/' — peer names are lowercase (``hermes peer`` normalizes them). +_PEER_TARGET_RE = re.compile(r"^([a-z0-9][a-z0-9_-]{0,63})/([a-zA-Z0-9][a-zA-Z0-9_-]{0,63})$") +# Same shape as ``tools.bot_relay._HANDLE_RE`` (kept local: see import note above). +_LOCAL_TARGET_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$") + + +def _default_home() -> str: + from hermes_constants import get_process_hermes_home + return str(get_process_hermes_home()) + + +def message_agent_tool_schema() -> dict: + """OpenAI-format schema for ``message_agent`` (injected, not registered).""" + return { + "type": "function", + "function": { + "name": MESSAGE_AGENT_TOOL_NAME, + "description": ( + "Send a message to ANOTHER agent (teammate) on this install, or to an " + "agent on a registered peer gateway. This is FIRE-AND-FORGET and " + "asynchronous, like texting: it validates the target against the live " + "roster, delivers your message into that agent's own Bot Chat with your " + "attribution automatically prefixed, and returns immediately with a " + "delivery acknowledgement. It does NOT return their reply and you must " + "not wait or poll for one — send it, finish your turn, and the reply " + "arrives later as a background-process completion notification that " + "wakes you. COMPOSE the message yourself: write what YOU want to say to " + "that agent (lead with the point; include the concrete ask or result). " + "Never paste the user's words verbatim — paraphrase the actionable " + "substance, and keep private 1:1 chat content private. Message one " + "clearly relevant teammate when it genuinely helps the user's goal; " + "don't fan out to several agents unless the user explicitly asked. " + "Use the teammate roster in your system prompt (names + roles) to pick " + "the right recipient; targets: a teammate name (e.g. 'researcher'), " + "'/' for an agent on a registered peer gateway " + "(e.g. 'spark/researcher', or just '' for the peer's main agent), " + "or an agent on another connected machine from your roster (use " + "'@' if the same handle exists on several)." + ), + "parameters": { + "type": "object", + "properties": { + "target": { + "type": "string", + "description": ( + "Who to message: a teammate profile name from your roster " + "('researcher', 'hermes' for the default agent), or " + "'' / '/' for a registered peer gateway." + ), + }, + "message": { + "type": "string", + "description": ( + "The message YOU composed for that agent (max " + f"{MESSAGE_MAX_CHARS} chars). Do not include the " + "'Message from …' prefix — it is added automatically." + ), + }, + }, + "required": ["target", "message"], + }, + }, + } + + +def message_agent_authorized(agent: Any) -> bool: + """The ``message_agent`` gate: a protocol-enabled agent whose session is a managed + Bot-Mode canonical Bot Chat. Session-stable, so it is prompt-cache safe to re-evaluate + on every tool-snapshot rebuild. Never raises.""" + try: + if not getattr(agent, "_bot_mode_protocol", True): + return False + from tools.bot_mode_probe import BOT_CHAT_TITLE, is_bot_mode_managed + + # Managed-install check, NOT section non-emptiness: a SOUL.md carrying the + # legacy protocol text gets an empty section but must still get the tool. + return _session_title(agent) == BOT_CHAT_TITLE and is_bot_mode_managed(_agent_home(agent)) + except Exception: # pragma: no cover — must never break a turn + logger.debug("message_agent_authorized failed", exc_info=True) + return False + + +def ensure_message_agent_tool(agent: Any) -> bool: + """Inject the ``message_agent`` schema into a Bot Chat agent's tool list (once per turn). + Idempotent and deterministic for the session's life (the gate is stable from the + first turn), so the tool list is byte-identical across turns — prompt-cache safe. Never raises.""" + try: + if not getattr(agent, "_bot_mode_protocol", True): + return False + tools = getattr(agent, "tools", None) + if tools and any( + isinstance(t, dict) and t.get("function", {}).get("name") == MESSAGE_AGENT_TOOL_NAME + for t in tools + ): + return True + if not message_agent_authorized(agent): + return False + if agent.tools is None: + agent.tools = [] + agent.tools.append(message_agent_tool_schema()) + valid = getattr(agent, "valid_tool_names", None) + if isinstance(valid, set): + valid.add(MESSAGE_AGENT_TOOL_NAME) + return True + except Exception: # pragma: no cover — must never break a turn + logger.debug("ensure_message_agent_tool failed", exc_info=True) + return False + + +def _resolve_local_name(target: str, roster: list[str]) -> Optional[str]: + """Map a target handle to a profile name ('hermes' → 'default').""" + want = target.strip().lower() + if want == "hermes": + return "default" if "default" in roster else None + return next((name for name in roster if name.lower() == want), None) if want else None + + +def _err(message: str, *, roster: list[str] | None = None, peers: list[str] | None = None) -> str: + from tools.bot_failure_reasons import classify_agent_error + + payload: dict[str, Any] = {"error": message, "reason": classify_agent_error(message)} + if roster is not None: + payload["teammates"] = roster + if peers is not None: + payload["peers"] = peers + return json.dumps(payload) + + +def message_agent_tool(target: str = "", message: str = "", task_id: Optional[str] = None, agent: Any = None) -> str: + """Deliver ``message`` to ``target``'s Bot Chat. Returns a JSON ack/error. + ``agent`` is the calling AIAgent — used for the Bot Chat gate and sender identity.""" + home = _agent_home(agent) + try: + from tools.bot_mode_probe import ( + BOT_CHAT_TITLE, _handle, _hermes_root, _peers, _profile_name as _self_profile_name, _roster, + is_bot_mode_managed, + ) + from tools.bot_relay import BOT_CHAT_TURN_ARGS, _hermes_cli + + if _session_title(agent) != BOT_CHAT_TITLE: + return _err("message_agent is only available in a Bot Mode 'Bot Chat' session. " + "This session is not one; do not retry.") + if not is_bot_mode_managed(home): + return _err("This install is not Bot-Mode-managed (no bot roster); " + "message_agent is unavailable. Do not retry.") + except Exception as exc: # pragma: no cover — defensive + return _err(f"Bot Mode gate check failed: {exc}") + + root, me = _hermes_root(Path(home)), _self_profile_name(Path(home)) + roster_homes = dict(_roster(root)) + roster = list(roster_homes) + peers = _peers(root) + teammates = [_handle(n) for n in roster if n != me] + + def _roster_err(msg: str) -> str: + return _err(msg, roster=teammates, peers=peers) + + body = str(message or "").strip() + if not body: + return _err("message is required — compose what you want to say to that agent.") + if len(body) > MESSAGE_MAX_CHARS: + return _err(f"message too long ({len(body)} chars > {MESSAGE_MAX_CHARS}). " + "Send the essentials; share large content as a file path instead.") + + raw_target = str(target or "").strip().lstrip("@") + if not raw_target: + return _roster_err("target is required.") + content = f"Message from 🤖 {_handle(me)} (@{_handle(me)}): " + body + delivery = dict(task_id=task_id, agent=agent) + # Attribution for the recipient's memory hooks; the text prefix above stays the human-facing signature. + author = {"id": f"bot:{me}", "name": _handle(me), "is_bot": True} + + # Peer target: '/' or a bare registered peer name. + peer_match = _PEER_TARGET_RE.match(raw_target) + if peer_match or raw_target.lower() in peers: + peer_name, peer_profile = peer_match.groups() if peer_match else (raw_target.lower(), None) + if peer_name not in peers: + return _roster_err(f"No registered peer named '{peer_name}'.") + dm_target = f"{peer_name}/{peer_profile}" if peer_profile else peer_name + # A peer dm crosses installs: qualify the id with this host so the peer's own '' stays distinct. + from agent.turn_author import bot_author_id, local_origin + peer_author = {**author, "id": bot_author_id(me, local_origin())} + # Pin the registry-owning profile: `hermes peer` resolves bot_peers via the profile-scoped + # load_config(), while the roster above reads the machine-root config — the CLI must run + # in that same profile or a secondary-profile bot sees an empty registry. + # The delivery runs in a background service context whose PATH lacks the gateway's + # venv bin dir, so a bare "hermes" resolves to a system install and dies on import + # under the wrong interpreter (#108628). _hermes_cli pins the entrypoint beside + # this interpreter; _delivery_lock/_local_delivery_home match argv[0] by basename, + # so the absolute path stays compatible. + return _start_delivery([_hermes_cli(), "-p", _self_profile_name(root), "peer", "dm", dm_target], content, + f"@{peer_profile or peer_name} on peer '{peer_name}'", stdin_file=True, + author=peer_author, **delivery) + + # Local teammate. + is_local_shape = bool(_LOCAL_TARGET_RE.match(raw_target)) + if not is_local_shape and "@" not in raw_target: + return _roster_err(f"Invalid target: {raw_target!r}.") + resolved = _resolve_local_name(raw_target, roster) if is_local_shape else None + if resolved is None or resolved == me: + # Unknown locally, or same-name target on ANOTHER connection (this gateway's 'default' + # messaging the cloud 'default'): every Desktop-connected gateway is reachable via the + # relay roster, so try that before reporting a resolution failure / self-message. + relayed = _try_relay_delivery(root, raw_target, content, me, **delivery) + if relayed is not None: + return relayed + if resolved == me: + return _err("You can't message yourself. Pick a teammate from the roster.") + return _roster_err(f"No teammate named '{raw_target}' on this install, on a connected " + "machine, or on a registered peer. Pick a name from the roster " + "(roles are listed in your system prompt).") + return _start_delivery([_hermes_cli(), "-p", resolved, *BOT_CHAT_TURN_ARGS], content, f"@{_handle(resolved)}", + stdin_file=False, profile_home=roster_homes[resolved], author=author, **delivery) + + +def _try_relay_delivery(root: Path, raw_target: str, content: str, me: str, *, + task_id: Optional[str], agent: Any) -> Optional[str]: + """Cross-connection delivery via the Desktop relay; None when the target doesn't + resolve against the relay roster. The envelope is queued on disk for the Desktop + to drain; a background waiter is spawned immediately so the relayed reply wakes + the sender through the standard completion-notification path.""" + try: + from tools.bot_mode_probe import _handle + from tools.bot_relay import ( + EnvelopeRefusedError, enqueue_envelope, read_remote_roster, resolve_remote_target, waiter_command, + ) + + roster = read_remote_roster(root) + match = resolve_remote_target(raw_target, roster) if roster else None + if match is None: + return None + if match == "ambiguous": + want = raw_target.strip().lstrip("@").lower() + forms = ", ".join(f"{r['handle']}@{r['connection_id']}" for r in roster if r["handle"].lower() == want) + return _err(f"'{raw_target}' exists on several connected machines — disambiguate with one of: {forms}.") + try: + envelope = enqueue_envelope(root, target=match, message=content, sender_profile=me, sender_handle=_handle(me)) + except EnvelopeRefusedError as exc: + # Fail fast: target definitively offline — nothing was queued. + # Structured refusal so the agent can distinguish it from a resolution error ('runtime_offline' + # per the #93091 reason enum). + return json.dumps({"error": str(exc), "reason": exc.reason}) + label = f"@{match['handle']} on {match['connection_label'] or match['connection_id']}" + return _spawn_delivery(waiter_command(root, envelope), label, task_id=task_id, agent=agent) + except Exception: + logger.debug("relay delivery attempt failed", exc_info=True) + return None + + +def _dm_dir() -> Path: + uid_getter = getattr(os, "getuid", None) + uid = uid_getter() if callable(uid_getter) else None + path = Path(tempfile.gettempdir()) / (f"{_DM_DIR_NAME}-{uid}" if uid is not None else _DM_DIR_NAME) + path.mkdir(mode=0o700, exist_ok=True) + # Shared POSIX temp roots need a per-user directory. Fail closed if an + # attacker pre-created the expected path or replaced it with a symlink. + info = path.lstat() + if not stat.S_ISDIR(info.st_mode): + raise PermissionError(f"DM temp path is not a directory: {path}") + if uid is not None and info.st_uid != uid: + raise PermissionError(f"DM temp directory is owned by another user: {path}") + if stat.S_IMODE(info.st_mode) != 0o700: + path.chmod(0o700) + return path + + +def cleanup_bot_dm_cache(max_age_hours: float = _DM_STALE_SECONDS / 3600, *, now: float | None = None) -> int: + """Delete orphaned DM payload files older than *max_age_hours*; returns count. + Same contract as the other ``cleanup_*_cache`` helpers (hourly gateway housekeeping); + legacy temp-root locations from versions predating the dedicated directory are swept too.""" + cutoff = (time.time() if now is None else now) - max_age_hours * 3600 + temp_root = Path(tempfile.gettempdir()) + locations = [(temp_root, "hermes-dm-*.txt"), (temp_root, "hermes-relay-dm-*.txt")] + with contextlib.suppress(OSError): + locations.append((_dm_dir(), "*.txt")) + from tools.bot_relay import unlink_files_older_than + + return sum(unlink_files_older_than(d, pattern, cutoff) for d, pattern in locations) + + +def _unlink_dm_file(path: str) -> None: + with contextlib.suppress(OSError): + os.unlink(path) + + +def _write_dm_file(content: str) -> str: + """The message rides a temp file — never inline shell text.""" + cleanup_bot_dm_cache() + fd, path = tempfile.mkstemp(prefix="dm-", suffix=".txt", dir=_dm_dir(), text=True) + try: + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write(content) + except BaseException: + # If fdopen itself failed the raw descriptor is still ours; closing twice is harmless. + with contextlib.suppress(OSError): + os.close(fd) + _unlink_dm_file(path) + raise + return path + + +def _delivery_lock(argv: list[str], *, stdin_file: bool): + """Per-profile turn lock for a LOCAL teammate delivery: local and relay deliveries + into one profile both run a Bot Chat turn here, so the turn window is serialized on + ``tools.bot_relay``'s cross-process lock. Peer transports (stdin mode) are locked + on the remote gateway by its own deliver path. + + See #93091. + """ + # Match the CLI element by basename: argv[0] may be an absolute venv path + # (service contexts lack PATH) and carries .exe on Windows; split on both separators. + # Split on both separators so the shape matches regardless of which platform built the argv. See #93590. + cli = (argv[0] if argv else "").rsplit("\\", 1)[-1].rsplit("/", 1)[-1] + if stdin_file or len(argv) < 3 or cli not in ("hermes", "hermes.exe") or argv[1] != "-p": + return contextlib.nullcontext() + from tools.bot_mode_probe import _hermes_root + from tools.bot_relay import acquire_turn_lock + + return acquire_turn_lock(_hermes_root(Path(_default_home())), argv[2]) + + +def _run_local_turn(argv: list[str], dm_file: str, *, env: Optional[dict[str, str]] = None) -> int: + """One Bot Chat turn via ``--query-file`` (plus one policy-gated retry); re-emits + the transport's streams and returns its exit code. Transient failures re-run the + same session; a context_overflow re-run lets the retried turn's pre-API compaction + compact the transcript first (no fresh session is ever minted). Auth/quota/config never retry.""" + + def _turn(): + return subprocess.run([*argv, "--query-file", dm_file], check=False, stdin=subprocess.DEVNULL, + capture_output=True, text=True, env=env) + + proc = _turn() + if proc.returncode != 0: + from tools.bot_failure_reasons import RETRY_NONE, classify_agent_error, retry_action + + if retry_action(classify_agent_error((proc.stderr or proc.stdout or "").strip()[-500:])) != RETRY_NONE: + proc = _turn() + stderr_text = proc.stderr or "" + reason = next((line.removeprefix("hermes-refusal-reason: ").strip() + for line in stderr_text.splitlines() + if line.startswith("hermes-refusal-reason: ")), None) + # A code wins over prose, including unknown codes from newer CLIs. + # Only older CLIs without a marker need the historical wording fallback. + refused_not_owned = (reason == "SESSION_NOT_OWNED" if reason is not None + else "already has a live owner" in stderr_text) + if proc.returncode != 0 and refused_not_owned: + # The target's Bot Chat is held live by another surface (Desktop); the turn + # never ran — tell the sender plainly instead of leaking a raw lease error. + # See #100523. + who = argv[argv.index("-p") + 1] if "-p" in argv[:-1] else "the teammate" + print(json.dumps({ + "error": f"Delivery failed: @{who}'s Bot Chat is open on another " + "surface right now, so your message was NOT delivered. Try again later.", + "reason": "target_busy", + })) + return 1 + # Re-emit the transport's streams: stdout is the reply text the + # completion notification carries back to the sending agent. + for stream, text in ((sys.stdout, proc.stdout), (sys.stderr, proc.stderr)): + if text: + stream.write(text) + stream.flush() + return proc.returncode + + +def _admit_live_dm(profile_home: Path | None, dm_file: str, author: Optional[dict] = None) -> dict | None: + """Pin intent before admission; retries may inspect, never change transport.""" + from tools.bot_live_delivery import deliver_to_live_owner, find_canonical_live_owner, read_delivery_result + from utils import fsync_directory + + intent: dict[str, Any] + intent_path = Path(dm_file + ".live.json") + if intent_path.exists(): + intent = json.loads(intent_path.read_text(encoding="utf-8")) + else: + assert profile_home is not None + owner = find_canonical_live_owner(profile_home) + if owner is None: + return None + intent = dict(owner=owner, message=Path(dm_file).read_text(encoding="utf-8"), + delivery_id=hashlib.sha256(str(Path(dm_file).resolve()).encode()).hexdigest(), + **({"author": author} if author else {})) + try: + fd = os.open(intent_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + except FileExistsError: + intent = json.loads(intent_path.read_text(encoding="utf-8")) + else: + with os.fdopen(fd, "w", encoding="utf-8") as stream: + json.dump(intent, stream) + stream.flush() + os.fsync(stream.fileno()) + fsync_directory(intent_path.parent) + home = intent["owner"]["profile_home"] + record = read_delivery_result(home, intent["delivery_id"]) + if record is None: + record = deliver_to_live_owner(home, intent["owner"], intent["message"], + delivery_id=intent["delivery_id"], author=intent.get("author")) + return record + + +def _wait_live_dm(home: str, delivery_id: str) -> int: + from tools.bot_live_delivery import read_delivery_result + + deadline = time.monotonic() + _LIVE_WAIT_SECONDS + while True: + record = read_delivery_result(home, delivery_id) + status = record["status"] if record else "ambiguous" + if status not in ("queued", "claimed") or time.monotonic() >= deadline: + break + time.sleep(min(0.5, max(0, deadline - time.monotonic()))) + payload = {key: record[key] for key in ("reply", "error", "reason") if record and record.get(key)} + payload.update(status=status, delivery_id=delivery_id) + if status in ("queued", "claimed", "ambiguous"): + payload["detail"] = "Delivery remains pending or its outcome is unknown. Do not resend; receipt is retained." + print(json.dumps(payload)) + return 0 if status in ("settled", "queued", "claimed") else 1 + + +def _local_delivery_home(argv: list[str]) -> Path | None: + cli = (argv[0] if argv else "").rsplit("\\", 1)[-1].rsplit("/", 1)[-1] + if len(argv) < 3 or cli not in ("hermes", "hermes.exe") or argv[1] != "-p": + return None + from tools.bot_mode_probe import _hermes_root, _roster + + return dict(_roster(_hermes_root(Path(_default_home())))).get(argv[2]) + + +def _run_delivery(argv: list[str], dm_file: str, *, stdin_file: bool, + profile_home: Path | None = None, author: Optional[dict] = None) -> int: + """Route to the live owner before attempting a CLI transport. Live deliveries + retain their intent/payload and immutable receipt; only CLI/peer payloads are + removed after consumption. The CLI turn window holds the profile lock, so two + deliveries into one profile queue; a bounded wait ends in a 'target_busy' refusal. + ``author`` rides to the child as HERMES_TURN_AUTHOR; ``hermes peer dm`` forwards it in the request body. + + Local (query-file) turns get one policy-gated retry (#93091 item 5): transient failures re-run the same + session; a context_overflow re-run lets the retried turn's pre-API compaction pass compact the Bot Chat + transcript first (agent/conversation_loop.py) — the sanctioned compression lever; no fresh session is + ever minted. Auth/quota/config failures never retry. Peer transports (stdin mode) retry on their own + gateway's deliver path, not here. + """ + # The live consumer owns turn admission; never compete for its CLI lease. + if not stdin_file: + home = profile_home or _local_delivery_home(argv) + if home is not None or Path(dm_file + ".live.json").exists(): + try: + record = _admit_live_dm(home, dm_file, author) + except Exception as exc: + print(json.dumps({"status": "ambiguous", "delivery_id": hashlib.sha256( + str(Path(dm_file).resolve()).encode()).hexdigest(), + "error": f"Live admission outcome unknown: {exc}. Do not resend.", + "evidence_file": dm_file})) + return 1 + if record is not None: + return _wait_live_dm(record["profile_home"], record["delivery_id"]) + try: + from tools.bot_relay import delivery_env + + env = delivery_env(author) + with _delivery_lock(argv, stdin_file=stdin_file): + if not stdin_file: + return _run_local_turn(argv, dm_file, env=env) + # Keep the file open until the transport exits; cleanup occurs + # after subprocess.run returns, not merely after stdin reaches EOF. + with open(dm_file, "r", encoding="utf-8") as stream: + return subprocess.run(argv, stdin=stream, check=False, env=env).returncode + finally: + _unlink_dm_file(dm_file) + + +def _delivery_command(argv: list[str], dm_file: str, *, stdin_file: bool, + profile_home: Path | None = None, author: Optional[dict] = None) -> str: + """Build an argv-safe command for the cleanup-owning background runner: + ``--run-delivery [--author ] [--profile-home ] ``.""" + runner_argv = [sys.executable, str(Path(__file__).resolve()), "--run-delivery", + "stdin" if stdin_file else "query-file", dm_file] + if profile_home is not None: + runner_argv.extend(["--profile-home", str(Path(profile_home).resolve())]) + runner_argv.extend(argv) + if sys.platform == "win32": + # The tracked local backend uses Git Bash on native Windows: forward slashes keep drive + # paths executable there; backslash paths are parsed as command names (exit 127). + runner_argv = [part.replace("\\", "/") for part in runner_argv] + if author: + # Inserted after the slash rewrite: JSON escapes are backslashes too. + runner_argv[3:3] = ["--author", json.dumps(author, separators=(",", ":"))] + return shlex.join(runner_argv) + + +def _start_delivery(argv: list[str], content: str, label: str, *, stdin_file: bool, + task_id: Optional[str], agent: Any, profile_home: Path | None = None, + author: Optional[dict] = None) -> str: + """Create a DM file and transfer its cleanup ownership to the runner.""" + dm_file = _write_dm_file(content) + if profile_home is not None: + try: + record = _admit_live_dm(profile_home, dm_file, author) + except Exception as exc: + return json.dumps({"status": "ambiguous", "delivery_id": hashlib.sha256( + str(Path(dm_file).resolve()).encode()).hexdigest(), + "error": f"Live delivery admission could not be confirmed: {exc}. Do not resend.", + "evidence_file": dm_file}) + if record is not None: + command = _delivery_command(argv, dm_file, stdin_file=False, profile_home=profile_home, author=author) + notification = json.loads(_spawn_delivery(command, label, task_id=task_id, agent=agent)) + result = dict(status=record["status"], delivery_id=record["delivery_id"], to=label, + detail="Durably queued for the live Bot Chat owner. Do NOT wait or resend; finish your turn.") + if notification.get("error"): + result["notification_error"] = notification["error"] + elif notification.get("process_id"): + result["process_id"] = notification["process_id"] + return json.dumps(result) + try: + command = _delivery_command(argv, dm_file, stdin_file=stdin_file, profile_home=profile_home, author=author) + except BaseException: + _unlink_dm_file(dm_file) + raise + return _spawn_delivery(command, label, dm_file=dm_file, task_id=task_id, agent=agent) + + +def _spawn_delivery(command: str, label: str, *, dm_file: Optional[str] = None, + task_id: Optional[str], agent: Any) -> str: + """Launch the cleanup-owning runner and transfer file ownership on ack. ``dm_file`` + is None for relay deliveries (the waiter watches a reply file; envelope artifacts + are owned/swept by ``tools/bot_relay.py``).""" + transferred = False + try: + from tools.terminal_tool import terminal_tool + + raw = terminal_tool(command, background=True, notify_on_complete=True, task_id=task_id, + workdir=str(Path(__file__).resolve().parent.parent), _host_local=True) + try: + parsed = json.loads(raw) + except (ValueError, TypeError): + parsed = {} + proc_id = parsed.get("session_id") or "" + if parsed.get("error"): + return _err(f"Delivery to {label} failed to start: {parsed['error']}") + if not proc_id: + return _err(f"Delivery to {label} failed to start: no process id returned") + # From here the background runner owns the file (removed after the consumer finishes). + transferred = True + return json.dumps({ + "status": "sent", + "to": label, + "detail": (f"Message dispatched to {label}. This is asynchronous — do NOT wait " + "or poll. Finish your turn now; when the delivery completes, its " + "notification carries the reply — relay it then, attributed to that agent."), + "process_id": proc_id, + "sent_at": int(time.time()), + }) + except Exception as exc: + logger.error("message_agent delivery spawn failed: %s", exc, exc_info=True) + return _err(f"Delivery to {label} could not be started: {exc}") + finally: + if dm_file and not transferred: + _unlink_dm_file(dm_file) + + +def _delivery_main(args: list[str]) -> int: + """Runner entry for the argv ``_delivery_command`` builds. Malformed argv exits 2 without touching the DM file.""" + if not args or args[0] != "--run-delivery": + return 2 + rest, author = args[1:], None + if rest[:1] == ["--author"]: + from agent.turn_author import parse_turn_author + + author = parse_turn_author(rest[1]) if len(rest) > 1 else None + if author is None: + return 2 + rest = rest[2:] + if len(rest) < 2 or rest[0] not in ("stdin", "query-file"): + return 2 + try: + argv, profile_home = rest[2:], None + if len(argv) >= 2 and argv[0] == "--profile-home": + profile_home, argv = Path(argv[1]), argv[2:] + return _run_delivery(argv, rest[1], stdin_file=rest[0] == "stdin", profile_home=profile_home, author=author) + except Exception as exc: + # 'target_busy': the queued delivery gave up after its bounded wait — surface the + # structured payload on stdout so the completion notification carries it back. + if getattr(exc, "reason", "") == "target_busy": + # See #93091. + print(json.dumps({"error": str(exc), "reason": "target_busy"})) + else: + print(f"message_agent delivery failed: {type(exc).__name__}: {exc}", file=sys.stderr) + return 1 + + +# agent-context helpers (mirror system_prompt.py's resolution) + + +def _agent_home(agent: Any) -> str: + """The calling agent's OWN home (session-db derived), not ambient env.""" + with contextlib.suppress(Exception): + db_path = getattr(getattr(agent, "_session_db", None), "db_path", None) + if db_path: + return str(Path(db_path).parent) + return _default_home() + + +def _session_title(agent: Any) -> str: + title = str(getattr(agent, "_session_title_hint", "") or "").strip() + if title: + return title + with contextlib.suppress(Exception): + sdb, sid = getattr(agent, "_session_db", None), getattr(agent, "session_id", None) + if sdb and sid: + return str(sdb.get_session_title(sid) or "").strip() + return "" + + +if __name__ == "__main__": # pragma: no cover - exercised as a background process + sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + raise SystemExit(_delivery_main(sys.argv[1:])) diff --git a/tools/browser_camofox.py b/tools/browser_camofox.py new file mode 100644 index 0000000000000000000000000000000000000000..8618a595c69f5051aa7abe4333b59e9d9fc2fb79 --- /dev/null +++ b/tools/browser_camofox.py @@ -0,0 +1,601 @@ +"""Camofox browser backend — local anti-detection browser via REST API. + +Camofox-browser (https://github.com/jo-inc/camofox-browser) is a self-hosted Node.js +server wrapping Camoufox (Firefox fork with C++ fingerprint spoofing); its REST API maps +1:1 to our browser tool interface (accessibility snapshots with element refs, click/type/ +scroll by ref, screenshots). Setup: ``npm start`` in a checkout or ``docker run -p 9377:9377 +-e CAMOFOX_PORT=9377 jo-inc/camofox-browser``, then ``CAMOFOX_URL=http://localhost:9377`` in +``~/.hermes/.env`` (Docker: see ``CAMOFOX_REWRITE_LOOPBACK_URLS`` below). +""" + +from __future__ import annotations + +import base64 +import ipaddress +import json +import logging +import os +import re +import threading +import uuid +from typing import Any, Callable, Dict, Optional +from urllib.parse import SplitResult, urlsplit, urlunsplit + +import requests + +from agent.secret_scope import get_secret +from hermes_cli.config import cfg_get, load_config, read_raw_config +from hermes_constants import get_hermes_home_override, hermes_home_key +from tools.browser_camofox_state import get_camofox_identity +from tools.registry import tool_error + +logger = logging.getLogger(__name__) + +# ---- Configuration ---- + +_DEFAULT_TIMEOUT = 30 # fallback when config is unreadable +_NO_SESSION_ERROR = "No browser session. Call browser_navigate first." +_vnc_url: Optional[str] = None # cached from /health response +_vnc_url_checked = False # only probe once per process +# Routed profiles (multiplexed gateway) each point CAMOFOX_URL at their own server, so the one-shot +# slot above would hand the launch profile's VNC address to every other profile: memo per server URL. +_vnc_url_by_camofox_url: Dict[str, Optional[str]] = {} +# browser.command_timeout, resolved lazily like browser_tool; keyed by profile home because the +# multiplexed gateway serves every profile from one process. +_cached_cmd_timeout: Optional[Dict[str, int]] = None +_cmd_timeout_resolved = False + + +def _get_command_timeout() -> int: + """``browser.command_timeout`` (floor 5s, default 30s), cached per profile home after first read.""" + global _cached_cmd_timeout, _cmd_timeout_resolved + home = hermes_home_key() + if _cached_cmd_timeout is None: + _cached_cmd_timeout = {} + if _cmd_timeout_resolved and home in _cached_cmd_timeout: + return _cached_cmd_timeout[home] + timeout = _DEFAULT_TIMEOUT + try: + val = cfg_get(read_raw_config(), "browser", "command_timeout") + if val is not None: + timeout = max(int(val), 5) + except Exception as exc: + logger.debug("Could not read browser.command_timeout: %s", exc) + _cached_cmd_timeout[home] = timeout + _cmd_timeout_resolved = True + return timeout + + +def _auth_headers() -> Dict[str, str]: + """Return Authorization header when CAMOFOX_API_KEY is set.""" + key = (get_secret("CAMOFOX_API_KEY", "") or "").strip() + return {"Authorization": f"Bearer {key}"} if key else {} + + +def get_camofox_url() -> str: + """Return the configured Camofox server URL, or empty string.""" + return (get_secret("CAMOFOX_URL", "") or "").rstrip("/") + + +def _config_cdp_url() -> str: + """Persistent ``browser.cdp_url`` from config.yaml, or "" (read here, not via + ``browser_tool_cdp._get_cdp_override`` — circular import).""" + try: + from hermes_cli.config import read_raw_config # late-bound: tests patch the source module + browser_cfg = read_raw_config().get("browser", {}) + if isinstance(browser_cfg, dict): + return str(browser_cfg.get("cdp_url", "") or "").strip() + except Exception: + pass + return "" + + +def is_camofox_mode() -> bool: + """True when the Camofox backend is selected and no CDP override is active. + + Selection is ``browser.cloud_provider: camofox``; ``CAMOFOX_URL`` is only the address + and never overrides a different stored selection (legacy: with no selection ever + written, a set ``CAMOFOX_URL`` still activates Camofox). A CDP override (``BROWSER_CDP_URL`` + env or ``browser.cdp_url``, same precedence as ``browser_tool_cdp._get_cdp_override()``) wins. + """ + if os.getenv("BROWSER_CDP_URL", "").strip() or _config_cdp_url(): + return False + try: + from tools.tool_backend_helpers import read_selection + selected = read_selection("browser") + except Exception: # pragma: no cover — helpers are in-repo + selected = None + if selected is not None: + return selected == "camofox" + return bool(get_camofox_url()) + + +def _vnc_url_from_health(url: str, resp: Any) -> Optional[str]: + try: + vnc_port = resp.json().get("vncPort") + if isinstance(vnc_port, int) and 1 <= vnc_port <= 65535: + return f"http://{urlsplit(url).hostname or 'localhost'}:{vnc_port}" + except (ValueError, KeyError): + pass + return None + + +def check_camofox_available() -> bool: + """Verify the Camofox server is reachable (and cache its VNC URL once).""" + global _vnc_url, _vnc_url_checked + url = get_camofox_url() + if not url: + return False + try: + resp = requests.get(f"{url}/health", timeout=5) + except Exception: + return False + if resp.status_code == 200: + if get_hermes_home_override() is not None: + if url not in _vnc_url_by_camofox_url: + _vnc_url_by_camofox_url[url] = _vnc_url_from_health(url, resp) + elif not _vnc_url_checked: + _vnc_url = _vnc_url_from_health(url, resp) or _vnc_url + _vnc_url_checked = True + return resp.status_code == 200 + + +def get_vnc_url() -> Optional[str]: + """Return the VNC URL if the Camofox server exposes one, or None.""" + if get_hermes_home_override() is not None: + url = get_camofox_url() + if url not in _vnc_url_by_camofox_url: + check_camofox_available() + return _vnc_url_by_camofox_url.get(url) + if not _vnc_url_checked: + check_camofox_available() + return _vnc_url + + +def _get_camofox_config() -> Dict[str, Any]: + """Return the ``browser.camofox`` config block, or an empty dict.""" + try: + camofox_cfg = load_config().get("browser", {}).get("camofox", {}) + except Exception as exc: + logger.warning("camofox config check failed, defaulting to disabled: %s", exc) + return {} + return camofox_cfg if isinstance(camofox_cfg, dict) else {} + + +def _managed_persistence_enabled(camofox_cfg: Optional[Dict[str, Any]] = None) -> bool: + """``browser.camofox.managed_persistence``: stable profile-scoped userId vs random per session.""" + return bool((_get_camofox_config() if camofox_cfg is None else camofox_cfg).get("managed_persistence")) + + +def _env_or_cfg(env_name: str, camofox_cfg: Dict[str, Any], cfg_key: str, *, secret: bool = False) -> str: + """Env/secret-scope value first, then the ``browser.camofox`` config key, else "".""" + raw = get_secret(env_name, "") if secret else os.getenv(env_name, "") + return (raw or "").strip() or str(camofox_cfg.get(cfg_key) or "").strip() + + +def _camofox_identity_override(task_id: Optional[str], camofox_cfg: Dict[str, Any]) -> Optional[Dict[str, str]]: + """Externally configured identity (integrations owning the visible Camofox browser + share a user ID so Hermes uses the same profile), or None.""" + user_id = _env_or_cfg("CAMOFOX_USER_ID", camofox_cfg, "user_id", secret=True) + if not user_id: + return None + session_key = _env_or_cfg("CAMOFOX_SESSION_KEY", camofox_cfg, "session_key", secret=True) + return {"user_id": user_id, "session_key": session_key or f"task_{(task_id or 'default')[:16]}"} + + +def _flag(env_name: str, camofox_cfg: Dict[str, Any], cfg_key: str) -> bool: + """Boolean toggle: env var wins when set to a valid value, else config key.""" + raw = os.getenv(env_name, "").strip().lower() + if raw in {"1", "true", "yes", "on"}: + return True + if raw in {"0", "false", "no", "off"}: + return False + if raw: + logger.debug("Ignoring invalid boolean env %s=%r", env_name, raw) + return bool(camofox_cfg.get(cfg_key)) + + +def _is_loopback_hostname(hostname: Optional[str]) -> bool: + if not hostname: + return False + host = hostname.strip().strip("[]").lower() + if host in {"localhost", "localhost.localdomain"}: + return True + try: + return ipaddress.ip_address(host).is_loopback + except ValueError: + return False + + +def _rewrite_loopback_url_for_camofox(url: str) -> tuple[str, Optional[Dict[str, str]]]: + """Rewrite loopback page URLs for Docker-hosted Camofox, if configured. + + ``CAMOFOX_URL`` may point at a host-published Docker port, but page URLs are opened by + the browser *inside* the container, where loopback is the container, not the host. + Opt-in (``CAMOFOX_REWRITE_LOOPBACK_URLS`` / config) because non-Docker installs run the + browser on the host. Returns ``(rewritten_url, metadata)``; ``metadata`` is present only + when a rewrite happened so the tool result can disclose the change to the model. + """ + camofox_cfg = _get_camofox_config() + if not _flag("CAMOFOX_REWRITE_LOOPBACK_URLS", camofox_cfg, "rewrite_loopback_urls"): + return url, None + try: + parsed = urlsplit(url) + except ValueError: + return url, None + alias = _env_or_cfg("CAMOFOX_LOOPBACK_HOST_ALIAS", camofox_cfg, "loopback_host_alias") or "host.docker.internal" + if parsed.scheme not in {"http", "https"} or not _is_loopback_hostname(parsed.hostname) or not alias: + return url, None + userinfo = (parsed.username + (f":{parsed.password}" if parsed.password else "") + "@") if parsed.username else "" + host_part = f"[{alias}]" if ":" in alias and not alias.startswith("[") else alias + port_part = f":{parsed.port}" if parsed.port else "" + rewritten = urlunsplit( + SplitResult(parsed.scheme, f"{userinfo}{host_part}{port_part}", parsed.path, parsed.query, parsed.fragment)) + return rewritten, {"from": parsed.hostname or "", "to": alias, "original_url": url, "rewritten_url": rewritten} + + +# ---- Session management ---- +_sessions: Dict[str, Dict[str, Any]] = {} # task_id -> {"user_id": str, "tab_id": str|None, ...} +_sessions_lock = threading.Lock() + + +def _adopt_existing_tab(session: Dict[str, Any]) -> Dict[str, Any]: + """Rehydrate tab_id from an already-open managed tab: gateway restarts empty the + in-memory cache while Camofox still holds the integration-owned tab.""" + if session.get("tab_id") or not session.get("adopt_existing_tab") or not get_camofox_url(): + return session + try: + tabs = _get("/tabs", params=_user_params(session), timeout=5).get("tabs", []) + except Exception as exc: + logger.debug("Camofox tab adoption failed for %s: %s", session.get("user_id"), exc) + return session + dict_tabs = [tab for tab in tabs if isinstance(tab, dict)] if isinstance(tabs, list) else [] + candidates = [tab for tab in dict_tabs if tab.get("listItemId") == session.get("session_key")] or dict_tabs + tab_id = candidates[-1].get("tabId") if candidates else None + if isinstance(tab_id, str) and tab_id: + session["tab_id"] = tab_id + logger.debug("Adopted existing Camofox tab %s for %s", tab_id, session.get("user_id")) + return session + + +def _get_session(task_id: Optional[str]) -> Dict[str, Any]: + """Get or create the task's session. Identity precedence: external override + (CAMOFOX_USER_ID / config) → profile-scoped identity when managed persistence + is on → random ephemeral userId.""" + task_id = task_id or "default" + with _sessions_lock: + if task_id in _sessions: + return _adopt_existing_tab(_sessions[task_id]) + camofox_cfg = _get_camofox_config() + identity = _camofox_identity_override(task_id, camofox_cfg) + if identity is None and _managed_persistence_enabled(camofox_cfg): + identity = get_camofox_identity(task_id) + if identity is None: + identity = {"user_id": f"hermes_{uuid.uuid4().hex[:10]}", "session_key": f"task_{task_id[:16]}"} + managed, adopt = False, False + else: + managed, adopt = True, _flag("CAMOFOX_ADOPT_EXISTING_TAB", camofox_cfg, "adopt_existing_tab") + session = {"user_id": identity["user_id"], "tab_id": None, "session_key": identity["session_key"], + "managed": managed, "adopt_existing_tab": adopt} + _sessions[task_id] = session + return _adopt_existing_tab(session) + + +def _ensure_tab(task_id: Optional[str], url: str = "about:blank") -> Dict[str, Any]: + """Ensure a tab exists for the session, creating one if needed.""" + session = _get_session(task_id) + if not session["tab_id"]: + data = _post("/tabs", {"userId": session["user_id"], "listItemId": session["session_key"], "url": url}) + session["tab_id"] = data.get("tabId") + return session + + +def _drop_session(task_id: Optional[str]) -> Optional[Dict[str, Any]]: + """Remove and return session info.""" + with _sessions_lock: + return _sessions.pop(task_id or "default", None) + + +def camofox_soft_cleanup(task_id: Optional[str] = None) -> bool: + """Drop only the local tracking entry (``True``) for managed profiles, which must + survive across agent tasks; ``False`` for ephemeral sessions so the caller falls back + to :func:`camofox_close`.""" + camofox_cfg = _get_camofox_config() + if _managed_persistence_enabled(camofox_cfg) or _camofox_identity_override(task_id, camofox_cfg): + _drop_session(task_id) + logger.debug("Camofox soft cleanup for task %s (managed persistence)", task_id) + return True + return False + + +# ---- HTTP helpers ---- +def _request(method: str, path: str, timeout: Optional[int] = None, **kwargs: Any) -> requests.Response: + """Issue an authenticated request to camofox and return the raised-for-status response.""" + resp = getattr(requests, method)(f"{get_camofox_url()}{path}", headers=_auth_headers(), + timeout=_get_command_timeout() if timeout is None else timeout, **kwargs) + resp.raise_for_status() + return resp + + +def _post(path: str, body: dict, timeout: Optional[int] = None) -> dict: + return _request("post", path, timeout, json=body).json() + + +def _get(path: str, params: dict = None, timeout: Optional[int] = None) -> dict: + return _request("get", path, timeout, params=params).json() + + +def _get_raw(path: str, params: dict = None, timeout: Optional[int] = None) -> requests.Response: + """GET and return the raw response (for binary data).""" + return _request("get", path, timeout, params=params) + + +def _delete(path: str, body: dict = None, timeout: Optional[int] = None) -> dict: + return _request("delete", path, timeout, json=body).json() + + +# ---- Tool implementations ---- +def _tab_path(session: Dict[str, Any], suffix: str) -> str: + return f"/tabs/{session['tab_id']}/{suffix}" + + +def _user_params(session: Dict[str, Any]) -> Dict[str, str]: + return {"userId": session["user_id"]} + + +def _snapshot_data(session: Dict[str, Any]) -> dict: + return _get(_tab_path(session, "snapshot"), params=_user_params(session)) + + +def _parse_snapshot_images(snapshot: str) -> list[Dict[str, str]]: + """Images from an accessibility snapshot: ``img "alt" [eN]`` entries with the URL on + the following ``/url:`` line (Camofox has no /images endpoint).""" + images = [] + lines = snapshot.split("\n") + for i, line in enumerate(lines): + stripped = line.strip() + if not stripped.startswith(("- img ", "img ")): + continue + alt_match = re.search(r'img\s+"([^"]*)"', stripped) + url_match = re.search(r'/url:\s*(\S+)', lines[i + 1].strip()) if i + 1 < len(lines) else None + alt, src = (alt_match.group(1) if alt_match else ""), (url_match.group(1) if url_match else "") + if alt or src: + images.append({"src": src, "alt": alt}) + return images + + +def _fetch_snapshot(session: Dict[str, Any]) -> tuple[str, int]: + """``(snapshot_text, refs_count)`` truncated like the main browser tool (line boundaries, + full tree stored to cache/web, read_file pointer appended). Lazy import: ``browser_tool`` + imports this module.""" + from tools.browser_tool_snapshot import _truncate_snapshot + from tools.browser_tool import get_browser_snapshot_threshold + data = _snapshot_data(session) + snapshot, threshold = data.get("snapshot", ""), get_browser_snapshot_threshold() + if len(snapshot) > threshold: + snapshot = _truncate_snapshot(snapshot, max_chars=threshold) + return snapshot, data.get("refsCount", 0) + + +def _navigate_tab(task_id: Optional[str], browser_url: str) -> tuple[Dict[str, Any], dict]: + """Open ``browser_url`` in the task's tab (creating it if missing) and return + ``(session, navigate_response)``. A 404 on the existing tab means the server + garbage-collected it — recreate instead of failing.""" + session = _get_session(task_id) + if session["tab_id"]: + try: + data = _post(_tab_path(session, "navigate"), {"userId": session["user_id"], "url": browser_url}, timeout=60) + return session, data + except requests.HTTPError as e: + if e.response is None or e.response.status_code != 404: + raise + logger.warning("Camofox tab %s returned 404 — tab was garbage collected. Creating a fresh tab.", + session["tab_id"]) + session["tab_id"] = None + return _ensure_tab(task_id, browser_url), {"ok": True, "url": browser_url} + + +def camofox_navigate(url: str, task_id: Optional[str] = None) -> str: + """Navigate to a URL via Camofox.""" + try: + browser_url, rewrite_info = _rewrite_loopback_url_for_camofox(url) + session, data = _navigate_tab(task_id, browser_url) + result = {"success": True, "url": data.get("url", browser_url), "title": data.get("title", "")} + if rewrite_info: + result["requested_url"], result["url_rewrite"] = url, rewrite_info + result["warning"] = ("Rewrote loopback URL for Docker-hosted Camofox: " + f"{rewrite_info['from']} -> {rewrite_info['to']}") + vnc = get_vnc_url() + if vnc: + result["vnc_url"] = vnc + result["vnc_hint"] = ("Browser is visible via VNC. " + "Share this link with the user so they can watch the browser live.") + try: # Auto-take a compact snapshot so the model can act immediately. + result["snapshot"], result["element_count"] = _fetch_snapshot(session) + except Exception: + pass # Navigation succeeded; snapshot is a bonus + return json.dumps(result) + except requests.HTTPError as e: + return tool_error(f"Navigation failed: {e}", success=False) + except requests.ConnectionError: + return json.dumps({"success": False, "error": ( + f"Cannot connect to Camofox at {get_camofox_url()}. " + "Is the server running? Start with: npm start (in camofox-browser dir) " + "or: docker run -p 9377:9377 -e CAMOFOX_PORT=9377 jo-inc/camofox-browser")}) + except Exception as e: + return tool_error(str(e), success=False) + + +def _camofox_private_page_block(session: Dict[str, Any], task_id: Optional[str], action: str) -> Optional[str]: + """Blocked payload when the current page is private/internal, else None. + + Mirrors the ``_camofox_eval`` guard in browser_tool.py: page-state reads on a non-local + backend can leak an intranet/metadata page the terminal can't reach. Only active when + the SSRF guard applies (non-local backend, not a local sidecar, ``allow_private_urls`` + unset); fail-open on probe failure like sibling guards. Lazy import (cycle). + """ + from tools.browser_tool_eval_policy import _camofox_current_page_private_url, _eval_ssrf_guard_active + if not _eval_ssrf_guard_active(task_id or "default"): + return None + blocked_url = _camofox_current_page_private_url(session["tab_id"], session["user_id"]) + if not blocked_url: + return None + return json.dumps({"success": False, "error": ( + "Blocked: page URL targets a private or internal address " + f"({blocked_url}). Refusing to {action} on this page in this browser mode.")}, ensure_ascii=False) + + +def _require_tab(task_id: Optional[str], action: Optional[str] = None) -> tuple[Dict[str, Any], Optional[str]]: + """Return ``(session, error_payload)``: error when no tab exists or, if ``action`` given, the page is private.""" + session = _get_session(task_id) + if not session["tab_id"]: + return session, tool_error(_NO_SESSION_ERROR, success=False) + return session, (_camofox_private_page_block(session, task_id, action) if action is not None else None) + + +def _with_tab(task_id: Optional[str], guard_action: Optional[str], body: Callable[[Dict[str, Any]], str]) -> str: + """Require a tab (+ private-page guard when ``guard_action`` is set), then run ``body(session)``; + any exception becomes a ``tool_error``.""" + try: + session, blocked = _require_tab(task_id, guard_action) + if blocked: + return blocked + return body(session) + except Exception as e: + return tool_error(str(e), success=False) + + +def _tab_action(task_id: Optional[str], guard_action: Optional[str], suffix: str, + body: Dict[str, Any], result: Callable[[dict], dict]) -> str: + """Simple tab action: POST ``body`` to ``/tabs//``, build the result.""" + return _with_tab(task_id, guard_action, lambda session: json.dumps( + result(_post(_tab_path(session, suffix), {"userId": session["user_id"], **body})))) + + +def camofox_snapshot(full: bool = False, task_id: Optional[str] = None, user_task: Optional[str] = None) -> str: + """Accessibility tree snapshot. ``user_task`` is deprecated and ignored — + oversized snapshots always truncate-and-store (no LLM summarization).""" + def body(session): + snapshot, refs_count = _fetch_snapshot(session) + return json.dumps({"success": True, "snapshot": snapshot, "element_count": refs_count}) + return _with_tab(task_id, "read a page snapshot", body) + + +def camofox_click(ref: str, task_id: Optional[str] = None) -> str: + """Click an element by ref via Camofox.""" + clean_ref = ref.lstrip("@") # our tool convention prefixes refs with @ + return _tab_action(task_id, "click", "click", {"ref": clean_ref}, + lambda data: {"success": True, "clicked": clean_ref, "url": data.get("url", "")}) + + +def camofox_type(ref: str, text: str, task_id: Optional[str] = None) -> str: + """Type text into an element by ref via Camofox.""" + try: + session, blocked = _require_tab(task_id, "type") + if blocked: + return blocked + clean_ref = ref.lstrip("@") + _post(_tab_path(session, "type"), {"userId": session["user_id"], "ref": clean_ref, "text": text}) + from agent.display import redact_browser_typed_text_for_display, redact_tool_args_for_display + # Match browser_tool.browser_type: the raw text is typed into the page, but the + # returned display value is run through the secret-pattern redactor so API keys / + # tokens don't leak into tool progress or chat history. + display_text = (redact_tool_args_for_display("browser_type", {"text": text}) or {})["text"] + response = {"success": True, "typed": display_text, "element": clean_ref} + return json.dumps(redact_browser_typed_text_for_display(response, text)) + except Exception as e: + from agent.display import redact_browser_typed_text_for_display + return tool_error(redact_browser_typed_text_for_display(str(e), text), success=False) + + +def camofox_scroll(direction: str, task_id: Optional[str] = None) -> str: + """Scroll the page via Camofox.""" + return _tab_action(task_id, None, "scroll", {"direction": direction}, + lambda data: {"success": True, "scrolled": direction}) + + +def camofox_back(task_id: Optional[str] = None) -> str: + """Navigate back via Camofox.""" + return _tab_action(task_id, None, "back", {}, lambda data: {"success": True, "url": data.get("url", "")}) + + +def camofox_press(key: str, task_id: Optional[str] = None) -> str: + """Press a keyboard key via Camofox.""" + return _tab_action(task_id, "press", "press", {"key": key}, lambda data: {"success": True, "pressed": key}) + + +def camofox_close(task_id: Optional[str] = None) -> str: + """Close the browser session via Camofox.""" + try: + session = _drop_session(task_id) + if session: + _delete(f"/sessions/{session['user_id']}") + return json.dumps({"success": True, "closed": True}) + except Exception as e: + return json.dumps({"success": True, "closed": True, "warning": str(e)}) + + +def camofox_get_images(task_id: Optional[str] = None) -> str: + """Get images on the current page via Camofox (parsed from the snapshot).""" + def body(session): + images = _parse_snapshot_images(_snapshot_data(session).get("snapshot", "")) + return json.dumps({"success": True, "images": images, "count": len(images)}) + return _with_tab(task_id, "extract page images", body) + + +def _vision_llm_settings() -> tuple[float, float]: + """``auxiliary.vision`` ``(timeout, temperature)``; defaults 120s / 0.1 on any config error.""" + try: + cfg = cfg_get(load_config(), "auxiliary", "vision", default={}) + return float(cfg.get("timeout", 120)), float(cfg.get("temperature", 0.1)) + except Exception: + return 120.0, 0.1 + + +def _save_screenshot(content: bytes) -> str: + """Write PNG bytes under ``$HERMES_HOME/browser_screenshots`` and return the path.""" + from hermes_constants import get_hermes_home + screenshots_dir = get_hermes_home() / "browser_screenshots" + screenshots_dir.mkdir(parents=True, exist_ok=True) + screenshot_path = str(screenshots_dir / f"browser_screenshot_{uuid.uuid4().hex[:8]}.png") + with open(screenshot_path, "wb") as f: + f.write(content) + return screenshot_path + + +def camofox_vision(question: str, annotate: bool = False, task_id: Optional[str] = None) -> str: + """Take a screenshot and analyze it with vision AI via Camofox.""" + def body(session): + resp = _get_raw(_tab_path(session, "screenshot"), params=_user_params(session)) + screenshot_path = _save_screenshot(resp.content) + img_b64 = base64.b64encode(resp.content).decode("utf-8") + annotation_context = "" + if annotate: + try: + snapshot = _snapshot_data(session).get("snapshot", "") + annotation_context = f"\n\nAccessibility tree (element refs for interaction):\n{snapshot[:3000]}" + except Exception: + pass + # The screenshot itself cannot be redacted, but the text-based accessibility snippet + # sent alongside it must not leak secret values. + from agent.redact import redact_sensitive_text + from agent.auxiliary_client import call_llm + vision_prompt = f"Analyze this browser screenshot and answer: {question}{redact_sensitive_text(annotation_context)}" + timeout, temperature = _vision_llm_settings() + response = call_llm( + messages=[{"role": "user", "content": [ + {"type": "text", "text": vision_prompt}, + {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{img_b64}"}}]}], + task="vision", temperature=temperature, timeout=timeout) + analysis = (response.choices[0].message.content or "").strip() if response.choices else "" + # Redact secrets the vision LLM may have read from the screenshot. + return json.dumps({"success": True, "analysis": redact_sensitive_text(analysis), "screenshot_path": screenshot_path}) + return _with_tab(task_id, "capture a screenshot", body) + + +def camofox_console(clear: bool = False, task_id: Optional[str] = None) -> str: + """Console output is not exposed by the Camofox REST API; return an empty result with a note.""" + return json.dumps({ + "success": True, "console_messages": [], "js_errors": [], "total_messages": 0, "total_errors": 0, + "note": "Console log capture is not available with the Camofox backend. " + "Use browser_snapshot or browser_vision to inspect page state."}) diff --git a/tools/browser_dialog_tool.py b/tools/browser_dialog_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..49194abf64496a5184069fe7b46e8f84f04856cd --- /dev/null +++ b/tools/browser_dialog_tool.py @@ -0,0 +1,132 @@ +"""Agent-facing tool: respond to a native JS dialog captured by the CDP supervisor. + +Response-only: the agent reads ``pending_dialogs`` from ``browser_snapshot``, +then calls ``browser_dialog(action=...)``. Gated on ``_browser_cdp_check`` so it +appears together with ``browser_cdp``. Design: ``website/docs/developer-guide/browser-supervisor.md``. +""" + +from __future__ import annotations + +import json +from typing import Any, Dict, Optional + +from tools.browser_supervisor import SUPERVISOR_REGISTRY +from tools.registry import registry + +BROWSER_DIALOG_SCHEMA: Dict[str, Any] = { + "name": "browser_dialog", + "description": ( + "Respond to a native JavaScript dialog (alert / confirm / prompt / " + "beforeunload) that is currently blocking the page.\n\n" + "**Workflow:** call ``browser_snapshot`` first — if a dialog is open, " + "it appears in the ``pending_dialogs`` field with ``id``, ``type``, " + "and ``message``. Then call this tool with ``action='accept'`` or " + "``action='dismiss'``.\n\n" + "**Prompt dialogs:** pass ``prompt_text`` to supply the response " + "string. Ignored for alert/confirm/beforeunload.\n\n" + "**Multiple dialogs:** if more than one dialog is queued (rare — " + "happens when a second dialog fires while the first is still open), " + "pass ``dialog_id`` from the snapshot to disambiguate.\n\n" + "**Availability:** only present when a CDP-capable backend is " + "attached — Browserbase sessions, local Chromium-family browser via " + "``/browser connect``, or ``browser.cdp_url`` in config.yaml. " + "Not available on Camofox (REST-only) or the default Playwright " + "local browser (CDP port is hidden)." + ), + "parameters": { + "type": "object", + "properties": { + "action": { + "type": "string", + "enum": ["accept", "dismiss"], + "description": ( + "'accept' clicks OK / returns the prompt text. " + "'dismiss' clicks Cancel / returns null from prompt(). " + "For ``beforeunload`` dialogs: 'accept' allows the " + "navigation, 'dismiss' keeps the page." + ), + }, + "prompt_text": { + "type": "string", + "description": ( + "Response string for a ``prompt()`` dialog. Ignored for " + "other dialog types. Defaults to empty string." + ), + }, + "dialog_id": { + "type": "string", + "description": ( + "Specific dialog to respond to, from " + "``browser_snapshot.pending_dialogs[].id``. Required " + "only when multiple dialogs are queued." + ), + }, + }, + "required": ["action"], + }, +} + + +def browser_dialog( + action: str, + prompt_text: Optional[str] = None, + dialog_id: Optional[str] = None, + task_id: Optional[str] = None, +) -> str: + """Respond to a pending dialog on the active task's CDP supervisor.""" + supervisor = SUPERVISOR_REGISTRY.get(task_id or "default") + if supervisor is None: + return json.dumps({ + "success": False, + "error": ( + "No CDP supervisor is attached to this task. Either the " + "browser backend doesn't expose CDP (Camofox, default " + "Playwright) or no browser session has been started yet. " + "Call browser_navigate or /browser connect first." + ), + }) + result = supervisor.respond_to_dialog(action=action, prompt_text=prompt_text, dialog_id=dialog_id) + if result.get("ok"): + return json.dumps({"success": True, "action": action, "dialog": result.get("dialog", {})}) + return json.dumps({"success": False, "error": result.get("error", "unknown error")}) + + +def _browser_dialog_check() -> bool: + """Gate: same as ``browser_cdp`` so the two tools appear/disappear together.""" + from tools.browser_cdp_tool import _browser_cdp_check + + return _browser_cdp_check() + + +registry.register( + name="browser_dialog", + toolset="browser-cdp", + schema=BROWSER_DIALOG_SCHEMA, + handler=lambda args, **kw: browser_dialog(action=args.get("action", ""), prompt_text=args.get("prompt_text"), + dialog_id=args.get("dialog_id"), task_id=kw.get("task_id")), + check_fn=_browser_dialog_check, + emoji="💬", +) + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. +import logging # noqa: F401,E402 + + +_PLUGIN_COMPAT_LAZY = { + 'logger': ('tools.approval', 'logger'), +} + + +def __getattr__(name): # PEP 562 — lazy so no import cycles + target = _PLUGIN_COMPAT_LAZY.get(name) + if target is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + import importlib + from hermes_cli.plugin_compat import warn_once + warn_once(__name__, name, *target) + return getattr(importlib.import_module(target[0]), target[1]) +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/browser_extension_router.py b/tools/browser_extension_router.py new file mode 100644 index 0000000000000000000000000000000000000000..5e73f006c155ec73025d33e468d793fdd9126be1 --- /dev/null +++ b/tools/browser_extension_router.py @@ -0,0 +1,137 @@ +"""Registry-level browser extension router. + +Agent-side half of browser-extension-control: decides, per ``browser_*`` handler +invocation, whether an attached extension controller (via +:mod:`gateway.browser_control_broker`) or the legacy backend executes it. + +Routing contract (see ``tests/tools/test_browser_extension_router.py``): +- Feature off ⇒ legacy, broker never touched, ``fallback()`` called exactly once. +- No server-bound identity ⇒ legacy. +- Bound identity ⇒ authoritative extension lane; missing/ambiguous scope, + disconnect, or capability mismatch fail closed (never jump to another browser). +- Selected controller ⇒ authoritative; its errors propagate, legacy never retried. +- ``args`` is never mutated. + +:func:`routed_browser_handler` resolves the flag and broker lazily on every call +so importing this module never pulls in the gateway and config changes apply +without restart. +""" + +from __future__ import annotations + +import json +import logging +from typing import Any, Callable, Dict, Optional, Tuple + +logger = logging.getLogger(__name__) + + +def _bound_identity() -> Tuple[Optional[str], Optional[str], Optional[str]]: + """(session_id, principal_id, transport_family) from the session context.""" + from gateway.session_context import get_session_env + + return tuple( # type: ignore[return-value] + get_session_env(key, "") or None + for key in ("HERMES_SESSION_ID", "HERMES_BROWSER_CONTROL_PRINCIPAL", + "HERMES_BROWSER_CONTROL_TRANSPORT_FAMILY") + ) + + +def _controller_unavailable(message: str) -> Exception: + from gateway.browser_control_broker import ControllerUnavailable + + return ControllerUnavailable(message) + + +def extension_controller_available(action: str) -> bool: + """Whether this request owns one exact controller capable of ``action``. + Runs during tool-schema assembly inside the request's session context; + consults the process-local broker directly and fails closed on any gap.""" + try: + from gateway.browser_control_broker import browser_control_enabled, get_browser_control_broker + + if not browser_control_enabled(): + return False + session_id, principal_id, transport_family = identity = _bound_identity() + if not all(identity): + return False + broker = get_browser_control_broker() + scope = broker.scope_for_session(session_id=session_id, principal_id=principal_id, transport_family=transport_family) + return scope is not None and broker.select(scope, action) is not None + except Exception: + logger.debug("browser extension availability check failed for %s", action, exc_info=True) + return False + + +def route_browser_tool( + action: str, args: Dict[str, Any], *, fallback: Callable[[], Any], broker: Any, enabled: bool, + session_id: Optional[str] = None, task_id: Optional[str] = None, principal_id: Optional[str] = None, + transport_family: Optional[str] = None, tool_call_id: Optional[str] = "", +) -> Any: + """Route one browser action through the extension-control broker. + + ``broker`` exposes ``scope_for_session(**identity)``, ``select(scope, cap)`` + and ``dispatch(scope, *, action, arguments, tool_call_id)``. ``fallback`` is + called exactly once when the feature is off or no server-bound identity + exists; once a controller is selected its result/exception is final. + """ + if not enabled or not str(principal_id or "").strip() or not str(transport_family or "").strip(): + return fallback() + + identity = dict(session_id=session_id, task_id=task_id, principal_id=principal_id, transport_family=transport_family) + scope = broker.scope_for_session(**identity) + if scope is None: + # A stamped identity only becomes authoritative once a controller has + # registered for the lane; unregistered lanes keep the legacy backend, + # registered-but-offline lanes fail closed. + lane_bound = getattr(broker, "lane_registered", None) + if callable(lane_bound) and not lane_bound(**identity): + return fallback() + raise _controller_unavailable(f"bound browser controller unavailable for {action}") + + if broker.select(scope, action) is None: + raise _controller_unavailable(f"bound browser controller cannot execute {action}") + + # Controller is authoritative: never retry the legacy backend. Registry + # handlers must return a string; keep string results byte-identical and + # serialize decoded JSON values at this boundary. + result = broker.dispatch(scope, action=action, arguments=args, tool_call_id=tool_call_id) + return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False) + + +def current_tool_call_id() -> str: + """Active tool_call_id bound by the agent executor, or ``""`` when none.""" + try: + from tools.approval_context import _approval_tool_call_id + + return _approval_tool_call_id.get() or "" + except Exception: + return "" + + +def routed_browser_handler( + action: str, args: Dict[str, Any], *, fallback: Callable[[], Any], task_id: Optional[str] = None, + session_id: Optional[str] = None, principal_id: Optional[str] = None, + transport_family: Optional[str] = None, tool_call_id: Optional[str] = None, +) -> Any: + """Lazy registry-handler route wrapper for ``browser_*`` tools. + Feature off (or gateway unimportable) ⇒ the legacy handler runs unchanged.""" + try: + from gateway.browser_control_broker import browser_control_enabled, get_browser_control_broker + except Exception as exc: # pragma: no cover - defensive, gateway always present + logger.debug("browser extension router unavailable (%s); using legacy backend", exc) + return fallback() + if not browser_control_enabled(): + return fallback() + + try: + env_session, env_principal, env_transport = _bound_identity() + except Exception: + env_session = env_principal = env_transport = None + + return route_browser_tool( + action, args, fallback=fallback, broker=get_browser_control_broker(), enabled=True, + session_id=session_id or env_session, task_id=task_id, principal_id=principal_id or env_principal, + transport_family=transport_family or env_transport, + tool_call_id=current_tool_call_id() if tool_call_id is None else tool_call_id, + ) diff --git a/tools/browser_supervisor.py b/tools/browser_supervisor.py new file mode 100644 index 0000000000000000000000000000000000000000..db157ef0a1a6742b7921b16bb9211ae4ea051d4a --- /dev/null +++ b/tools/browser_supervisor.py @@ -0,0 +1,562 @@ +"""Persistent CDP supervisor for browser dialog + frame detection. + +One ``CDPSupervisor`` per Hermes ``task_id`` with a reachable CDP endpoint: one +persistent WebSocket, ``Page`` / ``Runtime`` / ``Target`` events on every attached +session (top page + auto-attached OOPIF / worker targets), pending dialogs + frame +tree exposed via a thread-safe snapshot. Not in the tool schema — output reaches the +agent via ``browser_snapshot`` / ``browser_dialog``. Dialog capture and frame tracking +are mixins (``browser_supervisor_dialogs`` / ``browser_supervisor_frames``). +Design spec: ``website/docs/developer-guide/browser-supervisor.md``. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import json +import logging +import threading +import time +from dataclasses import dataclass +from typing import Any, Callable, Dict, List, Optional, Tuple, TYPE_CHECKING + +from tools.browser_supervisor_dialogs import ( + DEFAULT_DIALOG_POLICY, DEFAULT_DIALOG_TIMEOUT_S, RECENT_DIALOGS_MAX, _VALID_POLICIES, DialogRecord, + DialogSupervisionMixin, PendingDialog, +) +from tools.browser_supervisor_frames import FrameInfo, FrameTrackingMixin + +# ``websockets`` costs ~22 ms at import and is only needed once a supervisor connects. +if TYPE_CHECKING: + from websockets.asyncio.client import ClientConnection + +logger = logging.getLogger(__name__) + + +def _redact_cdp_error_text(exc: object) -> str: + """Redact CDP endpoint credentials from an exception's (or URL's) string form. + ``websockets`` bakes the raw URL (``?token=`` / ``user:pass@``) into its exception + messages, so every egress point turning one into log/re-raise text MUST route through + here; falls back to a fixed sentinel if redaction itself raises (err toward masking).""" + try: + from agent.redact import redact_cdp_url + + return redact_cdp_url(str(exc)) + except Exception: + return "" + + +class _LoopUnavailable(RuntimeError): + """The supervisor loop refused new work (closed / shutting down).""" + + +def _schedule(coro, loop, *, timeout: float): + """Run ``coro`` on the supervisor loop from a sync caller and wait for its result.""" + from agent.async_utils import safe_schedule_threadsafe + + fut = safe_schedule_threadsafe(coro, loop) + if fut is None: + raise _LoopUnavailable("Browser supervisor loop unavailable") + return fut.result(timeout=timeout) + + +def _fail(error: str) -> Dict[str, Any]: + return {"ok": False, "error": error} + + +def _err(exc: BaseException) -> Dict[str, Any]: + return _fail(f"{type(exc).__name__}: {exc}") + + +@dataclass(frozen=True) +class SupervisorSnapshot: + """Read-only snapshot of supervisor state for tool handlers.""" + + pending_dialogs: Tuple[PendingDialog, ...] + recent_dialogs: Tuple[DialogRecord, ...] + frame_tree: Dict[str, Any] + active: bool # False if supervisor is detached/stopped + cdp_url: str + task_id: str + + def to_dict(self) -> Dict[str, Any]: + """Serialize for inclusion in ``browser_snapshot`` output.""" + out: Dict[str, Any] = {"pending_dialogs": [d.to_dict() for d in self.pending_dialogs], "frame_tree": self.frame_tree} + if self.recent_dialogs: + out["recent_dialogs"] = [d.to_dict() for d in self.recent_dialogs] + return out + + +class CDPSupervisor(DialogSupervisionMixin, FrameTrackingMixin): + """One supervisor per (task_id, cdp_url) pair. ``start()`` spawns a daemon thread + running its own asyncio loop, connects, attaches to the first page target, enables + domains and auto-attach. ``snapshot()`` / ``respond_to_dialog()`` / ``evaluate_runtime()`` + are sync, thread-safe bridges onto that loop; all CDP I/O lives on the loop.""" + + def __init__(self, task_id: str, cdp_url: str, *, dialog_policy: str = DEFAULT_DIALOG_POLICY, + dialog_timeout_s: float = DEFAULT_DIALOG_TIMEOUT_S) -> None: + if dialog_policy not in _VALID_POLICIES: + raise ValueError(f"Invalid dialog_policy {dialog_policy!r}; must be one of {sorted(_VALID_POLICIES)}") + self.task_id = task_id + self.cdp_url = cdp_url + self.dialog_policy = dialog_policy + self.dialog_timeout_s = float(dialog_timeout_s) + + # State protected by ``_state_lock`` for cross-thread reads. + self._state_lock = threading.Lock() + self._pending_dialogs: Dict[str, PendingDialog] = {} + self._recent_dialogs: List[DialogRecord] = [] + self._frames: Dict[str, FrameInfo] = {} + self._active = False + # Supervisor loop machinery — populated in start(). + self._loop: Optional[asyncio.AbstractEventLoop] = None + self._thread: Optional[threading.Thread] = None + self._ready_event = threading.Event() + self._start_error: Optional[BaseException] = None + self._stop_requested = False + # CDP call tracking (runs on supervisor loop only). + self._next_call_id = 1 + self._pending_calls: Dict[int, asyncio.Future] = {} + self._ws: Optional[ClientConnection] = None + self._page_session_id: Optional[str] = None + # Dialog auto-dismiss watchdog handles (per dialog id) + id generator. + self._dialog_watchdogs: Dict[str, asyncio.TimerHandle] = {} + self._dialog_seq = 0 + + # ── Public sync API ────────────────────────────────────────────────────── + + def start(self, timeout: float = 15.0) -> None: + """Launch the background loop and block until attachment completes; raises what attach failed with (redacted).""" + if self._thread and self._thread.is_alive(): + return + self._ready_event.clear() + self._start_error, self._stop_requested = None, False + self._thread = threading.Thread(target=self._thread_main, name=f"cdp-supervisor-{self.task_id}", daemon=True) + self._thread.start() + if not self._ready_event.wait(timeout=timeout): + self.stop() + raise TimeoutError(f"CDP supervisor did not attach within {timeout}s " + f"(cdp_url={_redact_cdp_error_text(self.cdp_url)[:80]}...)") + if (err := self._start_error) is not None: + self.stop() + # ``err`` is a raw ``websockets`` exception embedding the full cdp_url (token / + # userinfo): re-raise redacted, ``from None`` so the traceback chain leaks nothing. + raise RuntimeError(f"CDP supervisor failed to start: {_redact_cdp_error_text(err)}") from None + + def stop(self, timeout: float = 5.0) -> None: + """Cancel the supervisor task and join the thread.""" + self._stop_requested = True + loop = self._loop + if loop is not None and loop.is_running(): + # Close the WebSocket from inside the loop so ``async for raw in self._ws`` + # returns cleanly, ``_run`` hits its ``finally``, THEN the thread exits. + with contextlib.suppress(Exception): # loop already shutting down / close timed out + _schedule(self._close_ws(), loop, timeout=2.0) + if self._thread is not None: + self._thread.join(timeout=timeout) + self._set_active(False) + + def _set_active(self, value: bool) -> None: + with self._state_lock: + self._active = value + + def snapshot(self) -> SupervisorSnapshot: + """Return an immutable snapshot of current state.""" + with self._state_lock: + return SupervisorSnapshot( + pending_dialogs=tuple(self._pending_dialogs.values()), + recent_dialogs=tuple(self._recent_dialogs[-RECENT_DIALOGS_MAX:]), + frame_tree=self._build_frame_tree_locked(), + active=self._active, cdp_url=self.cdp_url, task_id=self.task_id, + ) + + def respond_to_dialog(self, action: str, *, prompt_text: Optional[str] = None, + dialog_id: Optional[str] = None, timeout: float = 10.0) -> Dict[str, Any]: + """Accept/dismiss a pending dialog (sync bridge onto the supervisor loop). Returns + ``{"ok": True, "dialog"}`` or ``{"ok": False, "error"}`` for recoverable errors.""" + if action not in {"accept", "dismiss"}: + return _fail(f"action must be 'accept' or 'dismiss', got {action!r}") + with self._state_lock: + if not self._active: + return _fail("supervisor is not active") + pending = list(self._pending_dialogs.values()) + if not pending: + return _fail("no dialog is currently open") + if dialog_id: + dialog = self._pending_dialogs.get(dialog_id) + if dialog is None: + return _fail(f"dialog_id {dialog_id!r} not found (known: {sorted(self._pending_dialogs)})") + elif len(pending) > 1: + return _fail(f"{len(pending)} pending dialogs; specify dialog_id. Candidates: {[d.id for d in pending]}") + else: + dialog = pending[0] + loop = self._loop + if loop is None: + return _fail("supervisor loop is not running") + try: + coro = self._handle_dialog_cdp(dialog, accept=(action == "accept"), prompt_text=prompt_text or "") + _schedule(coro, loop, timeout=timeout) + except _LoopUnavailable as e: + return _fail(str(e)) + except Exception as e: + return _err(e) + return {"ok": True, "dialog": dialog.to_dict()} + + def evaluate_runtime(self, expression: str, *, return_by_value: bool = True, + await_promise: bool = True, timeout: float = 10.0) -> Dict[str, Any]: + """Evaluate ``expression`` in the page's Runtime context over the live WS. + Returns ``{"ok": True, "result", "result_type"}`` or ``{"ok": False, "error"}``. + ``return_by_value=True`` JSON-serializes the result (DevTools-console + semantics); non-serializable objects come back as a description string.""" + loop = self._loop + if loop is None or not loop.is_running(): + return _fail("supervisor loop is not running") + with self._state_lock: + active, session_id = self._active, self._page_session_id + if not active: + return _fail("supervisor is not active") + if not session_id: + return _fail("supervisor has no attached page session") + + def _run_eval(by_value: bool) -> Dict[str, Any]: + # userGesture: clipboard / fullscreen APIs need user activation. + params = {"expression": expression, "returnByValue": by_value, + "awaitPromise": await_promise, "userGesture": True} + coro = self._cdp("Runtime.evaluate", params, session_id=session_id, timeout=timeout) + return _schedule(coro, loop, timeout=timeout + 1) + + try: + response = _run_eval(return_by_value) + except Exception as exc: + # Deep-serializing live DOM nodes / NodeLists / Window can blow past + # CDP's recursion guard (``Object reference chain is too long``). + # Retry once with returnByValue=False so Chrome returns the description. + if not (return_by_value and "reference chain is too long" in str(exc).lower()): + return _err(exc) + try: + response = _run_eval(False) + except Exception as exc2: + return _err(exc2) + + # Response: {"result": {"result": {"type", "value", ...}, "exceptionDetails"?}} + result_payload = response.get("result", {}) if isinstance(response, dict) else {} + exception_details = result_payload.get("exceptionDetails") + if exception_details: + exc_text = exception_details.get("text") or "JavaScript exception" + description = (exception_details.get("exception") or {}).get("description") + return _fail(f"{exc_text}: {description}" if description else exc_text) + + result_obj = result_payload.get("result", {}) + result_type = result_obj.get("type", "undefined") + if "value" in result_obj: + value = result_obj["value"] + elif result_type == "undefined": + value = None + else: + # Non-serializable (functions, DOM nodes…) — give the model the browser's description. + value = result_obj.get("description") or result_obj.get("unserializableValue") + return {"ok": True, "result": value, "result_type": result_type} + + def focus_page(self, origin: str, *, accept: Optional[str] = None, timeout: float = 10.0) -> Dict[str, Any]: + """Re-attach the supervisor's page session to an open page target on ``origin`` + (``scheme://host[:port]``). The initial attach picks the FIRST page target, but tools + that open their own tabs (browser_exec) put the login form somewhere else. With + ``accept`` (a JS expression) the first same-origin tab where it evaluates truthy wins, + so a login and a checkout tab on one site resolve to the right one. Returns + ``{"ok": True, "url"}`` or ``{"ok": False, "error"}``; on failure the previous session stays.""" + loop = self._loop + if loop is None or not loop.is_running(): + return _fail("supervisor loop is not running") + + async def _attach(target_id: str) -> str: + attach = await self._cdp("Target.attachToTarget", {"targetId": target_id, "flatten": True}, timeout=timeout) + sid = attach["result"]["sessionId"] + await self._enable_page_domains(sid, timeout=timeout) + await self._install_dialog_bridge(sid) + return sid + + async def _focus() -> Dict[str, Any]: + from agent.vault_store import normalize_origin + targets = (await self._cdp("Target.getTargets", timeout=timeout)).get("result", {}).get("targetInfos", []) + candidates = [] + for t in targets: + url = str(t.get("url") or "") + try: + # origin="" = any http(s) page (used to FIND the login tab before its origin is known) + if t.get("type") == "page" and url.startswith(("http://", "https://")) \ + and (not origin or normalize_origin(url) == origin): + candidates.append((t["targetId"], url)) + except Exception: + continue + for target_id, url in candidates: + sid = await _attach(target_id) + if accept: + probe = await self._cdp("Runtime.evaluate", {"expression": accept, "returnByValue": True}, + session_id=sid, timeout=timeout) + if not probe.get("result", {}).get("result", {}).get("value"): + await self._cdp("Target.detachFromTarget", {"sessionId": sid}, timeout=timeout) + continue + with self._state_lock: + self._page_session_id = sid + return {"ok": True, "url": url} + return _fail(f"no open page on {origin or 'any site'}" + (" with the expected form" if accept and candidates else "")) + + try: + return _schedule(_focus(), loop, timeout=timeout + 1) + except Exception as exc: + return _err(exc) + + # ── Supervisor loop internals ──────────────────────────────────────────── + + def _thread_main(self) -> None: + """Entry point for the supervisor's dedicated thread.""" + loop = asyncio.new_event_loop() + self._loop = loop + try: + asyncio.set_event_loop(loop) + loop.run_until_complete(self._run()) + except BaseException as e: # noqa: BLE001 — propagate via _start_error + if not self._fail_start(e): + logger.warning("CDP supervisor %s crashed: %s", self.task_id, e) + finally: + # Cancel + flush remaining tasks before closing the loop to avoid + # "Task was destroyed but it is pending" warnings. + with contextlib.suppress(Exception): + pending = [t for t in asyncio.all_tasks(loop) if not t.done()] + for t in pending: + t.cancel() + if pending: + loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True)) + with contextlib.suppress(Exception): + loop.close() + self._set_active(False) + + def _fail_start(self, e: BaseException) -> bool: + """Propagate ``e`` to ``start()`` if we never got ready; True if it was consumed.""" + if self._ready_event.is_set(): + return False + self._start_error = e + self._ready_event.set() + return True + + async def _close_ws(self) -> None: + """Detach and close the current WebSocket, swallowing close errors.""" + ws, self._ws = self._ws, None + if ws is not None: + with contextlib.suppress(Exception): + await ws.close() + + async def _run(self) -> None: + """Top-level reconnecting supervisor coroutine. Browserbase tears down the CDP + socket whenever a short-lived client (agent-browser's per-command CDP client) + disconnects, so on drop we reset per-session ids, re-attach, and keep going. + A failure before the first successful attach is fatal for ``start()``.""" + attempt, last_success_at, backoff = 0, 0.0, 0.5 + import websockets # deferred: only supervisors that connect pay the import + while not self._stop_requested: + try: + self._ws = await asyncio.wait_for(websockets.connect(self.cdp_url, max_size=50 * 1024 * 1024), timeout=10.0) + except Exception as e: + attempt += 1 + if self._fail_start(e): + return + logger.warning("CDP supervisor %s: connect failed (attempt %s): %s", + self.task_id, attempt, _redact_cdp_error_text(e)) + await asyncio.sleep(min(backoff, 10.0)) + backoff = min(backoff * 2, 10.0) + continue + + reader_task = asyncio.create_task(self._read_loop(), name="cdp-reader") + try: + # Reset the per-connection page session id; ``_pending_dialogs`` / ``_frames`` + # are deliberately kept — they reconcile as fresh events arrive (worst case a + # stale dialog entry is rejected with "no dialog is showing", logged only). + self._page_session_id = None + await self._attach_initial_page() + self._set_active(True) + last_success_at = time.time() + backoff = 0.5 # reset after a successful attach + self._ready_event.set() + await reader_task + except BaseException as e: + if self._fail_start(e): + raise + logger.warning("CDP supervisor %s: session dropped after %.1fs: %s", + self.task_id, time.time() - last_success_at, _redact_cdp_error_text(e)) + finally: + self._set_active(False) + if not reader_task.done(): + reader_task.cancel() + with contextlib.suppress(asyncio.CancelledError, Exception): + await reader_task + for handle in self._dialog_watchdogs.values(): + handle.cancel() + self._dialog_watchdogs.clear() + await self._close_ws() + + if self._stop_requested: + return + logger.debug("CDP supervisor %s: reconnecting in %.1fs...", self.task_id, backoff) + await asyncio.sleep(backoff) + backoff = min(backoff * 2, 10.0) + + async def _attach_initial_page(self) -> None: + """Find (or create) a page target, attach flattened, enable domains, install dialog bridge.""" + targets = (await self._cdp("Target.getTargets")).get("result", {}).get("targetInfos", []) + page_target = next((t for t in targets if t.get("type") == "page"), None) + if page_target is None: + page_target = (await self._cdp("Target.createTarget", {"url": "about:blank"}))["result"] + attach = await self._cdp("Target.attachToTarget", {"targetId": page_target["targetId"], "flatten": True}) + self._page_session_id = sid = attach["result"]["sessionId"] + await self._enable_page_domains(sid, timeout=10.0) + await self._install_dialog_bridge(sid) + + async def _cdp(self, method: str, params: Optional[Dict[str, Any]] = None, *, + session_id: Optional[str] = None, timeout: float = 10.0) -> Dict[str, Any]: + """Send a CDP command and await its response.""" + if self._ws is None: + raise RuntimeError("supervisor WebSocket is not connected") + call_id, self._next_call_id = self._next_call_id, self._next_call_id + 1 + payload: Dict[str, Any] = {"id": call_id, "method": method} + payload.update({k: v for k, v in (("params", params), ("sessionId", session_id)) if v}) + fut: asyncio.Future = asyncio.get_running_loop().create_future() + self._pending_calls[call_id] = fut + await self._ws.send(json.dumps(payload)) + try: + return await asyncio.wait_for(fut, timeout=timeout) + finally: + self._pending_calls.pop(call_id, None) + + async def _read_loop(self) -> None: + """Continuously dispatch incoming CDP frames (responses → futures, events → handlers).""" + assert self._ws is not None + try: + async for raw in self._ws: + if self._stop_requested: + break + try: + msg = json.loads(raw) + except Exception: + logger.debug("CDP supervisor: non-JSON frame dropped") + continue + if "id" in msg: + fut = self._pending_calls.pop(msg["id"], None) + if fut is None or fut.done(): + continue + if "error" in msg: + fut.set_exception(RuntimeError(f"CDP error on id={msg['id']}: {msg['error']}")) + else: + fut.set_result(msg) + elif handler := self._EVENT_HANDLERS.get(msg.get("method")): + result = handler(self, msg.get("params", {}), msg.get("sessionId")) + if result is not None: + await result + except Exception as e: + logger.debug("CDP read loop exited: %s", e) + + # CDP event → handler(self, params, session_id). Async handlers return an + # awaitable that ``_read_loop`` awaits; sync handlers return None. + _EVENT_HANDLERS: Dict[str, Callable[..., Any]] = { + **DialogSupervisionMixin.EVENT_HANDLERS, **FrameTrackingMixin.EVENT_HANDLERS + } + + +class _SupervisorRegistry: + """Process-global (task_id → supervisor) map with idempotent start/stop (``SUPERVISOR_REGISTRY``).""" + + def __init__(self) -> None: + self._lock = threading.Lock() + self._by_task: Dict[str, CDPSupervisor] = {} + + def get(self, task_id: str) -> Optional[CDPSupervisor]: + with self._lock: + return self._by_task.get(task_id) + + def _pop(self, task_id: str) -> Optional[CDPSupervisor]: + with self._lock: + return self._by_task.pop(task_id, None) + + def get_or_start(self, task_id: str, cdp_url: str, *, dialog_policy: str = DEFAULT_DIALOG_POLICY, + dialog_timeout_s: float = DEFAULT_DIALOG_TIMEOUT_S, start_timeout: float = 15.0) -> CDPSupervisor: + """Idempotently ensure a supervisor runs for ``(task_id, cdp_url)``; one bound to a + different ``cdp_url`` or unhealthy (dead thread / stopped loop) is stopped and replaced.""" + with self._lock: + existing = self._by_task.get(task_id) + if existing is not None: + thread, loop = existing._thread, existing._loop + healthy = thread is not None and thread.is_alive() and loop is not None and loop.is_running() + if existing.cdp_url == cdp_url and healthy: + return existing + self._by_task.pop(task_id, None) + if existing is not None: + existing.stop() + + supervisor = CDPSupervisor(task_id=task_id, cdp_url=cdp_url, + dialog_policy=dialog_policy, dialog_timeout_s=dialog_timeout_s) + supervisor.start(timeout=start_timeout) + with self._lock: + # Guard against a concurrent get_or_start from another thread. + already = self._by_task.get(task_id) + if already is not None and already.cdp_url == cdp_url: + supervisor.stop() + return already + self._by_task[task_id] = supervisor + return supervisor + + def stop(self, task_id: str) -> None: + supervisor = self._pop(task_id) + if supervisor is not None: + supervisor.stop() + + def stop_all(self) -> None: + """Stop every running supervisor. For shutdown / test teardown.""" + with self._lock: + items = list(self._by_task.values()) + self._by_task.clear() + for supervisor in items: + supervisor.stop() + + +SUPERVISOR_REGISTRY = _SupervisorRegistry() + + +__all__ = ["CDPSupervisor", "SUPERVISOR_REGISTRY", "SupervisorSnapshot", "_SupervisorRegistry"] + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. + +CONSOLE_HISTORY_MAX = 50 + +@dataclass +class ConsoleEvent: + """Ring buffer entry for console + exception traffic.""" + + ts: float + level: str # "log" | "error" | "warning" | "exception" + text: str + url: Optional[str] = None + + +_PLUGIN_COMPAT_LAZY = { + 'DIALOG_BRIDGE_HOST': ('tools.browser_supervisor_dialogs', 'DIALOG_BRIDGE_HOST'), + 'DIALOG_BRIDGE_URL_PATTERN': ('tools.browser_supervisor_dialogs', 'DIALOG_BRIDGE_URL_PATTERN'), + 'DIALOG_POLICY_AUTO_ACCEPT': ('tools.browser_supervisor_dialogs', 'DIALOG_POLICY_AUTO_ACCEPT'), + 'DIALOG_POLICY_AUTO_DISMISS': ('tools.browser_supervisor_dialogs', 'DIALOG_POLICY_AUTO_DISMISS'), + 'DIALOG_POLICY_MUST_RESPOND': ('tools.browser_supervisor_dialogs', 'DIALOG_POLICY_MUST_RESPOND'), + 'FRAME_TREE_MAX_ENTRIES': ('tools.browser_supervisor_frames', 'FRAME_TREE_MAX_ENTRIES'), + 'FRAME_TREE_MAX_OOPIF_DEPTH': ('tools.browser_supervisor_frames', 'FRAME_TREE_MAX_OOPIF_DEPTH'), +} + + +def __getattr__(name): # PEP 562 — lazy so no import cycles + target = _PLUGIN_COMPAT_LAZY.get(name) + if target is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + import importlib + from hermes_cli.plugin_compat import warn_once + warn_once(__name__, name, *target) + return getattr(importlib.import_module(target[0]), target[1]) +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/browser_supervisor_dialogs.py b/tools/browser_supervisor_dialogs.py new file mode 100644 index 0000000000000000000000000000000000000000..cc6a8ad56a358ce573f29cd7530a33d06a49eab0 --- /dev/null +++ b/tools/browser_supervisor_dialogs.py @@ -0,0 +1,307 @@ +"""Dialog capture + response half of the CDP supervisor. + +Two capture paths feed one ``PendingDialog`` queue: native ``Page.javascriptDialogOpening`` +events (answered with ``Page.handleJavaScriptDialog``), and the injected *dialog bridge* — +a page script rewriting alert/confirm/prompt into a sync XHR to a magic host we intercept +via the CDP ``Fetch`` domain and answer with ``Fetch.fulfillRequest``. The bridge works on +Browserbase (whose CDP proxy auto-dismisses native dialogs) because the native dialog never fires. +``DialogSupervisionMixin`` relies on state ``CDPSupervisor.__init__`` sets. +""" + +from __future__ import annotations + +import asyncio +import base64 +import json +import logging +import time +from dataclasses import dataclass +from typing import Any, Callable, Dict, Optional +from urllib.parse import parse_qs, urlparse + +# Logger-name parity with the origin module (records must look unchanged). +logger = logging.getLogger("tools.browser_supervisor") + + +def _redact_supervisor_text(value: str) -> str: + """Redact page-originated text before exposing supervisor snapshots.""" + from agent.redact import redact_sensitive_text + + return redact_sensitive_text(value, force=True) + + +def _trim_ring(events: list, keep: int) -> list: + """Cap a ring buffer at ``keep`` entries once it overflows to 2x (slack reduces churn).""" + return events[-keep:] if len(events) > keep * 2 else events + + +_REDACTED_FIELDS = frozenset({"message", "default_prompt"}) + + +def _dialog_dict(obj: Any, keys: tuple) -> Dict[str, Any]: + """Snapshot dict of ``keys`` with page-originated text fields redacted.""" + return {k: _redact_supervisor_text(getattr(obj, k)) if k in _REDACTED_FIELDS else getattr(obj, k) for k in keys} + + +DIALOG_POLICY_MUST_RESPOND = "must_respond" +DIALOG_POLICY_AUTO_DISMISS = "auto_dismiss" +DIALOG_POLICY_AUTO_ACCEPT = "auto_accept" +_VALID_POLICIES = frozenset( + {DIALOG_POLICY_MUST_RESPOND, DIALOG_POLICY_AUTO_DISMISS, DIALOG_POLICY_AUTO_ACCEPT} +) +DEFAULT_DIALOG_POLICY = DIALOG_POLICY_MUST_RESPOND +DEFAULT_DIALOG_TIMEOUT_S = 300.0 + +# Last N closed dialogs kept so agents on backends that auto-dismiss server-side +# (Browserbase) can still observe that a dialog fired. +RECENT_DIALOGS_MAX = 20 + +# Magic host the bridge XHRs to; intercepted via CDP Fetch before any network +# resolution, so it never has to exist. Keep ASCII + URL-safe (Fetch patterns gate on it). +DIALOG_BRIDGE_HOST = "hermes-dialog-bridge.invalid" +DIALOG_BRIDGE_URL_PATTERN = f"http://{DIALOG_BRIDGE_HOST}/*" + +# Injected into every frame via Page.addScriptToEvaluateOnNewDocument. Sync GET with +# query params so the Fetch interceptor never parses a body; unreachable bridge → null +# so the page still sees *some* behavior. onbeforeunload is left native (can't be +# prompted synchronously without racing navigation); the native path still records it. +_DIALOG_BRIDGE_SCRIPT = r""" +(() => { + if (window.__hermesDialogBridgeInstalled) return; + window.__hermesDialogBridgeInstalled = true; + const ENDPOINT = "http://hermes-dialog-bridge.invalid/"; + function ask(kind, message, defaultPrompt) { + try { + const xhr = new XMLHttpRequest(); + const params = new URLSearchParams({ + kind: String(kind || ""), + message: String(message == null ? "" : message), + default_prompt: String(defaultPrompt == null ? "" : defaultPrompt), + }); + xhr.open("GET", ENDPOINT + "?" + params.toString(), false); // sync + xhr.send(null); + if (xhr.status !== 200) return null; + let parsed; + try { parsed = JSON.parse(xhr.responseText || ""); } catch (e) { return null; } + if (kind === "alert") return undefined; + if (kind === "confirm") return Boolean(parsed && parsed.accept); + if (kind === "prompt") { + if (!parsed || !parsed.accept) return null; + return parsed.prompt_text == null ? "" : String(parsed.prompt_text); + } + return null; + } catch (e) { + return null; + } + } + window.alert = function(message) { ask("alert", message, ""); }; + window.confirm = function(message) { + const r = ask("confirm", message, ""); + return r === null ? false : Boolean(r); + }; + window.prompt = function(message, def) { + const r = ask("prompt", message, def == null ? "" : def); + return r === null ? null : String(r); + }; +})(); +""" + + +@dataclass +class PendingDialog: + """A JS dialog currently open on some frame's session.""" + + id: str + type: str # "alert" | "confirm" | "prompt" | "beforeunload" + message: str + default_prompt: str + opened_at: float + cdp_session_id: str # which attached CDP session the dialog fired in + frame_id: Optional[str] = None + # Bridge XHR path: respond via Fetch.fulfillRequest, NOT Page.handleJavaScriptDialog. + bridge_request_id: Optional[str] = None + + def to_dict(self) -> Dict[str, Any]: + return _dialog_dict(self, ("id", "type", "message", "default_prompt", "opened_at", "frame_id")) + + +@dataclass +class DialogRecord: + """A dialog that was opened and then handled (kept briefly in ``recent_dialogs``).""" + + id: str + type: str + message: str + opened_at: float + closed_at: float + closed_by: str # "agent" | "auto_policy" | "remote" | "watchdog" + frame_id: Optional[str] = None + + def to_dict(self) -> Dict[str, Any]: + return _dialog_dict(self, ("id", "type", "message", "opened_at", "closed_at", "closed_by", "frame_id")) + + +class DialogSupervisionMixin: + """Dialog event handling for ``CDPSupervisor`` (all methods run on its loop).""" + + async def _cdp_quiet(self, method: str, params: Dict[str, Any], *, session_id: Optional[str], + timeout: float, what: str) -> None: + """Best-effort CDP call: failures are logged at debug and swallowed.""" + try: + await self._cdp(method, params, session_id=session_id, timeout=timeout) + except Exception as e: + logger.debug("%s failed (%s): %s", method, what, e) + + async def _install_dialog_bridge(self, session_id: str) -> None: + """Install the dialog-bridge init script + Fetch interceptor on a session. Idempotent at + the CDP level (Chromium de-dupes identical add-script calls; Fetch.enable replaces prior + patterns); the final Runtime.evaluate injects into the already-loaded document so + existing pages pick up the override on reconnect.""" + sid = (session_id or "")[:16] + steps = ( + ("Page.addScriptToEvaluateOnNewDocument", {"source": _DIALOG_BRIDGE_SCRIPT, "runImmediately": True}, + 5.0, f"dialog bridge sid={sid}"), + ("Fetch.enable", {"patterns": [{"urlPattern": DIALOG_BRIDGE_URL_PATTERN, "requestStage": "Request"}], + "handleAuthRequests": False}, 5.0, f"dialog bridge sid={sid}"), + ("Runtime.evaluate", {"expression": _DIALOG_BRIDGE_SCRIPT, "returnByValue": True}, + 3.0, f"dialog bridge inject sid={sid}"), + ) + for method, params, timeout, what in steps: + await self._cdp_quiet(method, params, session_id=session_id, timeout=timeout, what=what) + + # ── Capture ────────────────────────────────────────────────────────────── + + async def _on_dialog_opening(self, params: Dict[str, Any], session_id: Optional[str]) -> None: + self._admit_dialog( + type=str(params.get("type") or ""), message=str(params.get("message") or ""), + default_prompt=str(params.get("defaultPrompt") or ""), session_id=session_id, frame_id=params.get("frameId"), + ) + + async def _on_fetch_paused(self, params: Dict[str, Any], session_id: Optional[str]) -> None: + """Bridge XHR captured mid-flight — materialize as a pending dialog. The page's JS + thread is blocked on the XHR until we Fetch.fulfillRequest (agent or watchdog); + requests for other hosts are forwarded unchanged.""" + url = str(params.get("request", {}).get("url") or "") + request_id = params.get("requestId") + if not request_id: + return + if DIALOG_BRIDGE_HOST not in url: + await self._cdp_quiet("Fetch.continueRequest", {"requestId": request_id}, + session_id=session_id, timeout=3.0, what="passthrough") + return + q = {k: v[0] for k, v in parse_qs(urlparse(url).query).items()} + self._admit_dialog( + type=q.get("kind") or "alert", message=q.get("message", ""), default_prompt=q.get("default_prompt", ""), + session_id=session_id, frame_id=params.get("frameId"), bridge_request_id=str(request_id), + ) + + def _admit_dialog(self, *, type: str, message: str, default_prompt: str, session_id: Optional[str], + frame_id: Optional[str], bridge_request_id: Optional[str] = None) -> None: + """Create the dialog and apply the policy: auto-respond, or queue + arm the watchdog. + Auto policies archive FIRST (tagged ``auto_policy``) so the ``closed`` event that + follows our own response isn't re-archived as ``remote``.""" + self._dialog_seq += 1 + dialog = PendingDialog( + id=f"d-{self._dialog_seq}", type=type, message=message, default_prompt=default_prompt, + opened_at=time.time(), cdp_session_id=session_id or self._page_session_id or "", + frame_id=frame_id, bridge_request_id=bridge_request_id, + ) + auto = {DIALOG_POLICY_AUTO_DISMISS: (False, ""), DIALOG_POLICY_AUTO_ACCEPT: (True, default_prompt)}.get( + self.dialog_policy + ) + if auto is not None: + with self._state_lock: + self._archive_dialog_locked(dialog, "auto_policy") + asyncio.create_task(self._respond_quiet(dialog, accept=auto[0], prompt_text=auto[1])) + return + with self._state_lock: + self._pending_dialogs[dialog.id] = dialog + self._dialog_watchdogs[dialog.id] = asyncio.get_running_loop().call_later( + self.dialog_timeout_s, + lambda: asyncio.create_task(self._dialog_timeout_expired(dialog.id)), + ) + + # ── Responding ─────────────────────────────────────────────────────────── + + async def _respond(self, dialog: PendingDialog, *, accept: bool, prompt_text: Optional[str]) -> None: + """Bridge-fulfill for XHR-captured dialogs (swallows failures so the page + unblocks), else native CDP — ``promptText`` only for prompt dialogs when + given; raises on CDP failure.""" + session_id = dialog.cdp_session_id or None + if dialog.bridge_request_id: + body = json.dumps({"accept": bool(accept), "dialog_id": dialog.id, + "prompt_text": (prompt_text or "") if dialog.type == "prompt" else ""}).encode() + await self._cdp_quiet( + "Fetch.fulfillRequest", + {"requestId": dialog.bridge_request_id, "responseCode": 200, + "responseHeaders": [{"name": "Content-Type", "value": "application/json"}, + {"name": "Access-Control-Allow-Origin", "value": "*"}], + "body": base64.b64encode(body).decode()}, + session_id=session_id, timeout=5.0, what=f"bridge fulfill {dialog.id}", + ) + return + params: Dict[str, Any] = {"accept": accept} + if prompt_text is not None and dialog.type == "prompt": + params["promptText"] = prompt_text + await self._cdp("Page.handleJavaScriptDialog", params, session_id=session_id, timeout=5.0) + + async def _respond_quiet(self, dialog: PendingDialog, *, accept: bool, prompt_text: Optional[str]) -> None: + """Auto-policy / watchdog response (already archived by the caller); failures logged only.""" + try: + await self._respond(dialog, accept=accept, prompt_text=prompt_text) + except Exception as e: + logger.debug("auto response failed for %s: %s", dialog.id, e) + + async def _handle_dialog_cdp(self, dialog: PendingDialog, *, accept: bool, prompt_text: str) -> None: + """Agent response path. The dialog is retired regardless of outcome — a CDP + error usually means it already closed (browser auto-dismissed after navigation).""" + try: + await self._respond(dialog, accept=accept, prompt_text=prompt_text) + finally: + self._retire_dialog(dialog.id, "agent") + + async def _dialog_timeout_expired(self, dialog_id: str) -> None: + with self._state_lock: + dialog = self._pending_dialogs.get(dialog_id) + if dialog is None: + return + logger.warning("CDP supervisor %s: dialog %s (%s) auto-dismissed after %ss timeout", + self.task_id, dialog_id, dialog.type, self.dialog_timeout_s) + # Archive with watchdog tag BEFORE unblocking the page. + self._retire_dialog(dialog_id, "watchdog") + await self._respond_quiet(dialog, accept=False, prompt_text=None) + + # ── Bookkeeping ────────────────────────────────────────────────────────── + + def _retire_dialog(self, dialog_id: str, closed_by: str) -> None: + """Remove a pending dialog (archiving it with ``closed_by``) and cancel its watchdog.""" + with self._state_lock: + dialog = self._pending_dialogs.pop(dialog_id, None) + if dialog is not None: + self._archive_dialog_locked(dialog, closed_by) + handle = self._dialog_watchdogs.pop(dialog_id, None) + if handle is not None: + handle.cancel() + + def _archive_dialog_locked(self, dialog: PendingDialog, closed_by: str) -> None: + """Move a pending dialog to the recent_dialogs ring buffer. Must hold state_lock.""" + record = DialogRecord(id=dialog.id, type=dialog.type, message=dialog.message, opened_at=dialog.opened_at, + closed_at=time.time(), closed_by=closed_by, frame_id=dialog.frame_id) + self._recent_dialogs = _trim_ring([*self._recent_dialogs, record], RECENT_DIALOGS_MAX) + + async def _on_dialog_closed(self, params: Dict[str, Any], session_id: Optional[str]) -> None: + # ``Page.javascriptDialogClosed`` carries only ``result``/``userInput``: match by + # session id and clear the oldest native dialog on it (the JS thread blocks while + # a dialog is up, so at most one is in flight). Bridge dialogs resolve via Fetch. + with self._state_lock: + candidate = next((d.id for d in self._pending_dialogs.values() + if d.cdp_session_id == session_id and d.bridge_request_id is None), None) + if candidate: + self._retire_dialog(candidate, "remote") + + # CDP event → handler(self, params, session_id); merged into CDPSupervisor._EVENT_HANDLERS. + EVENT_HANDLERS: Dict[str, Callable[..., Any]] = { + "Page.javascriptDialogOpening": _on_dialog_opening, + "Page.javascriptDialogClosed": _on_dialog_closed, + "Fetch.requestPaused": _on_fetch_paused, + } diff --git a/tools/browser_tool_eval_policy.py b/tools/browser_tool_eval_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..558339212f4e1a953833bb63d19e5781a4581904 --- /dev/null +++ b/tools/browser_tool_eval_policy.py @@ -0,0 +1,167 @@ +"""browser_console(expression=...) policy: SSRF guard gating, private-URL probes, +and the opt-in sensitive-primitive denylist. + +Facade-owned state is read through ``_bt`` (``tools.browser_tool``, resolved per call) — no import cycle. +""" + +import re +from typing import Optional +from utils import is_truthy_value +from tools.browser_tool_origin import origin_module as _origin +from tools import browser_tool_cloud as _cloud +from tools import browser_tool_session as _session + + +def _eval_ssrf_guard_active(effective_task_id: str) -> bool: + """Return True when eval-driven private-network access must be guarded. + + Same gating as ``browser_navigate`` / ``browser_snapshot`` / ``browser_vision``: the SSRF guard + only matters for non-local backends (cloud browser, or a containerized terminal whose + browser-on-host reaches networks the terminal can't); skipped for local sidecars / ``allow_private_urls``. + """ + _bt = _origin() + return not _cloud._is_local_backend() and not _bt._is_local_sidecar_key(effective_task_id) and not _cloud._allow_private_urls() + + +def _url_blocked(_bt, url: str) -> bool: + """True when ``url`` hits the always-blocked cloud-metadata floor or fails the SSRF guard.""" + return _bt._is_always_blocked_url(url) or not _bt._is_safe_url(url) + + +# URL-shaped literals embedded in a JS expression (http/https only). fetch/XHR/navigate +# to a private host never updates ``location.href``, so the post-eval page-URL recheck +# can't see it; pre-screen the literals instead. +_JS_URL_LITERAL_RE = re.compile(r"""https?://[^\s'"`)\]<>]+""", re.IGNORECASE) + + +def _expression_targets_private_url(expression: str) -> Optional[str]: + """Return the first private/always-blocked ``http(s)://`` literal in a JS expression (best-effort), else None.""" + _bt = _origin() + literals = _JS_URL_LITERAL_RE.findall(expression) if isinstance(expression, str) else [] + return next((c for c in (m.rstrip(".,;") for m in literals) if _url_blocked(_bt, c)), None) + + +def _current_page_private_url(effective_task_id: str) -> Optional[str]: + """Return the current page URL when it targets a private/internal address (e.g. after a prior + ``location.href = '...'`` eval). Fail-open on probe failure, matching the snapshot/vision guards.""" + _bt = _origin() + try: + url_result = _session._run_browser_command(effective_task_id, "eval", ["window.location.href"], timeout=5, _engine_override="auto") + if url_result.get("success"): + current_url = url_result.get("data", {}).get("result", "").strip().strip('"').strip("'") + if current_url and _url_blocked(_bt, current_url): + return current_url + except Exception as exc: + _bt.logger.debug("_current_page_private_url: probe failed (%s)", exc) + return None + + +_RISKY_BROWSER_EVAL_PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = ( + (re.compile(r"\bdocument\s*\.\s*cookie\b", re.I), "document.cookie"), + (re.compile(r"\b(?:localStorage|sessionStorage)\b", re.I), "web storage"), + (re.compile(r"\bindexedDB\b", re.I), "IndexedDB"), + (re.compile(r"\bcaches\s*\.\s*(?:open|match|keys)\b", re.I), "Cache Storage"), + (re.compile(r"\bnavigator\s*\.\s*(?:clipboard|credentials|serviceWorker)\b", re.I), "navigator sensitive API"), + (re.compile(r"\b(?:fetch|XMLHttpRequest|WebSocket|EventSource)\s*\(", re.I), "network request"), + (re.compile(r"\bnavigator\s*\.\s*sendBeacon\s*\(", re.I), "network beacon"), + (re.compile(r"\bdocument\s*\.\s*forms\b.*\bvalue\b", re.I | re.S), "form value extraction"), + (re.compile(r"\bquerySelector(?:All)?\s*\([^)]*(?:input|textarea|password)[^)]*\).*\bvalue\b", re.I | re.S), "form value extraction"), +) + +_JS_STRING_LITERAL_RE = re.compile(r"""'(?:\\.|[^'\\])*'|\"(?:\\.|[^\"\\])*\"|`(?:\\.|[^`\\])*`""", re.S) + + +_SENSITIVE_BROWSER_EVAL_TOKENS: tuple[tuple[str, str], ...] = ( + ("cookie", "document.cookie"), + ("localStorage", "web storage"), ("sessionStorage", "web storage"), + ("indexedDB", "IndexedDB"), ("caches", "Cache Storage"), + ("clipboard", "navigator sensitive API"), ("credentials", "navigator sensitive API"), + ("serviceWorker", "navigator sensitive API"), + ("fetch", "network request"), ("XMLHttpRequest", "network request"), + ("WebSocket", "network request"), ("EventSource", "network request"), + ("sendBeacon", "network beacon"), +) + + +def _browser_eval_flag(key: str) -> bool: + """Read boolean ``browser.`` (default False) through the origin's config reader.""" + _bt = _origin() + return _bt._browser_cfg(key, False, lambda v: is_truthy_value(v, default=False), f"browser.{key} from config") + + +def _allow_unsafe_browser_evaluate() -> bool: + """Whether sensitive browser JS evaluation is explicitly allowed (overrides ``restrict_evaluate``).""" + return _browser_eval_flag("allow_unsafe_evaluate") + + +def _restrict_browser_evaluate() -> bool: + """Whether the sensitive-primitive eval denylist is enabled (off by default). + + It blocks the *names* of common primitives (``fetch``, ``cookie``, ``querySelector(...input...)``), + not actual exfiltration, so it also blocks much legitimate DOM extraction; egress is still gated + by the SSRF/private-URL guards in ``_browser_eval`` regardless. Opt in via + ``browser.restrict_evaluate: true`` (e.g. hostile pages with a logged-in profile). + """ + return _browser_eval_flag("restrict_evaluate") + + +def _decode_js_string_literal(literal: str) -> str: + """Best-effort decode of a JS string literal (not a parser): normalizes escapes like ``"co\\x6fkie"``.""" + if len(literal) < 2: + return literal + try: + return bytes(literal[1:-1], "utf-8").decode("unicode_escape") + except Exception: + return literal[1:-1] + + +def _decoded_js_string_literals(expression: str) -> list[str]: + return [_decode_js_string_literal(match.group(0)) for match in _JS_STRING_LITERAL_RE.finditer(expression)] + + +def _sensitive_browser_eval_token_reason(expression: str) -> Optional[str]: + """Risk reason for direct or quoted sensitive primitives: direct spellings alone miss + ``document["cookie"]`` / ``globalThis["fetch"]``, so tokens are also matched inside the decoded, + concatenated string literals (catches ``document["coo" + "kie"]``).""" + literals = "".join(_decoded_js_string_literals(expression)).lower() + return next((reason for token, reason in _SENSITIVE_BROWSER_EVAL_TOKENS + if re.search(rf"\b{re.escape(token)}\b", expression, re.I) or token.lower() in literals), None) + + +def _risky_browser_eval_reason(expression: str) -> Optional[str]: + """Return a human-readable reason if a JS expression uses risky primitives.""" + if not expression: + return None + hit = next((reason for pattern, reason in _RISKY_BROWSER_EVAL_PATTERNS if pattern.search(expression)), None) + return hit or _sensitive_browser_eval_token_reason(expression) + + +def _enforce_browser_eval_policy(expression: str) -> Optional[str]: + """Block sensitive browser JS evaluation when the opt-in denylist is on (opt-in because it gates on + primitive *names*; private-address egress is enforced separately in ``_browser_eval``).""" + if not _restrict_browser_evaluate() or _allow_unsafe_browser_evaluate(): + return None + reason = _risky_browser_eval_reason(expression) + if not reason: + return None + return ("Blocked: browser_console(expression=...) tried to use sensitive browser " + f"JavaScript primitive ({reason}) while browser.restrict_evaluate is " + "enabled. Use browser_snapshot/browser_get_images/browser_console " + "without expression for normal inspection, or set " + "browser.restrict_evaluate: false in config.yaml to allow programmatic evaluation.") + + +def _camofox_current_page_private_url(tab_id: str, user_id: str) -> Optional[str]: + """Camofox analogue of ``_current_page_private_url`` (evaluate endpoint instead of the CLI). Fail-open + on probe failure, matching the snapshot/vision guards — do not make fail-closed without the sibling.""" + _bt = _origin() + try: + from tools.browser_camofox import _post + data = _post(f"/tabs/{tab_id}/evaluate", body={"expression": "window.location.href", "userId": user_id}) + current_url = str(data.get("result") if isinstance(data, dict) else data or "") + current_url = current_url.strip().strip('"').strip("'") + if current_url and _url_blocked(_bt, current_url): + return current_url + except Exception as exc: + _bt.logger.debug("_camofox_current_page_private_url: probe failed (%s)", exc) + return None diff --git a/tools/browser_tool_lightpanda_fallback.py b/tools/browser_tool_lightpanda_fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..f1f86aa855da8fd3b4a2522bd2ea636104291138 --- /dev/null +++ b/tools/browser_tool_lightpanda_fallback.py @@ -0,0 +1,195 @@ +"""Lightpanda engine status and the automatic Chrome fallback for browser commands +that Lightpanda cannot serve (screenshots, empty snapshots, failed commands). + +Facade-owned state is read through ``_bt`` (``tools.browser_tool``, resolved per call) — no import cycle. +""" + +import json +import os +import shutil +import subprocess +from typing import Any, Dict, List, Optional, Tuple +from tools.browser_tool_origin import origin_module as _origin +from tools import browser_tool_cdp as _cdp +from tools import browser_tool_cloud as _cloud +from tools import browser_tool_install as _install +from tools import browser_tool_session as _session + +# Commands where Chrome can meaningfully produce a different result. Session-management +# commands (close, record) are tied to the engine's daemon and can't be retried elsewhere. +_FALLBACK_ELIGIBLE = frozenset({"open", "snapshot", "screenshot", "eval", "click", + "fill", "scroll", "back", "press", "console", "errors"}) + + +def _using_lightpanda_engine() -> bool: + """Return True when local browser commands are configured for Lightpanda.""" + return _cloud._get_browser_engine() == "lightpanda" + + +def lightpanda_engine_status() -> Tuple[bool, str]: + """Whether ``browser.engine: lightpanda`` is actually in effect, and why. + + ``(False, "")`` when the engine isn't lightpanda; else the reason names the setting shadowing + it or the driver running it. Mirrors ``_should_inject_engine`` / ``_resolve_backend_cdp`` + precedence with config-only gates (no network I/O) for ``/browser status`` / ``hermes doctor``. + """ + _bt = _origin() + if not _using_lightpanda_engine(): + return False, "" + if _cdp._get_cdp_override_raw(): + return False, "a CDP override is active (/browser connect or browser.cdp_url)" + if _bt._is_camofox_mode(): + return False, "Camofox is the selected browser (CAMOFOX_URL)" + # Real-profile before cloud provider: browser_exec resolves real-profile before + # the backend, so with both set the real-profile toggle claims the session. + if _cloud._use_real_profile(): + return False, "browser.use_real_profile is on (Lightpanda cannot load a Chromium profile)" + try: + provider = _cloud._get_cloud_provider() + except Exception: + provider = None + if provider is not None: + try: + name = provider.display_name + except Exception: + name = type(provider).__name__ + return False, f"cloud provider {name} is selected (browser.cloud_provider, or auto-detected from credentials)" + if not _bt._is_browser_use_cli_mode(): + return True, "built-in browser tools: agent-browser --engine lightpanda" + try: + from tools.browser_use_cli import _read_browser_cfg, is_legacy_browser_use_cloud_config + if is_legacy_browser_use_cloud_config(_read_browser_cfg()): + return False, "Browser Use cloud (BROWSER_USE_API_KEY) is selected" + except Exception as e: + _bt.logger.debug("legacy Browser Use cloud check failed: %s", e) + return True, "Browser Use mode: Hermes spawns `lightpanda serve` per session" + + +def _lightpanda_fallback_reason(engine: str, command: str, result: Dict[str, Any]) -> Optional[str]: + """User-visible reason a Lightpanda result needs the Chrome fallback (copied into the result), or None.""" + if engine != "lightpanda" or command not in _FALLBACK_ELIGIBLE: + return None + if not result.get("success"): + return f"Lightpanda {command!r} failed ({str(result.get('error') or 'command failed').strip()}); retried with Chrome." + data = result.get("data", {}) + if command == "snapshot" and len((data.get("snapshot", "") or "").strip()) < 20: # couldn't render + return "Lightpanda returned an empty/too-short snapshot; retried with Chrome." + if command == "screenshot" and data.get("path", ""): + # Lightpanda returns a ~17 KB placeholder PNG (panda logo at 1920x1080); real Chromium is 100 KB+. + try: + size = os.path.getsize(data["path"]) + except OSError: + return "Lightpanda screenshot file was missing/unreadable; retried with Chrome." + if size < 20480: + _origin().logger.debug("Lightpanda screenshot is suspiciously small (%d bytes), " + "triggering Chrome fallback", size) + return f"Lightpanda screenshot was suspiciously small ({size} bytes); " "retried with Chrome." + return None + + +def _needs_lightpanda_fallback(engine: str, command: str, result: Dict[str, Any]) -> bool: + """Check if a Lightpanda result should trigger an automatic Chrome fallback.""" + return _lightpanda_fallback_reason(engine, command, result) is not None + + +def _annotate_lightpanda_fallback(result: Dict[str, Any], reason: str) -> Dict[str, Any]: + """Add a user-visible Chrome fallback warning to a browser command result.""" + warning = "⚠ Lightpanda fallback: Chrome was used for this browser action. " f"{reason}" + fields = {"fallback_warning": warning, "browser_engine": "chrome", + "browser_engine_fallback": {"from": "lightpanda", "to": "chrome", "reason": reason}} + annotated = {**result, **fields} + data = annotated.get("data") + if isinstance(data, dict): + annotated["data"] = data = dict(data) + for key, value in fields.items(): + data.setdefault(key, dict(value) if isinstance(value, dict) else value) + return annotated + + +def _copy_fallback_warning(target: Dict[str, Any], result: Dict[str, Any]) -> Dict[str, Any]: + """Copy browser fallback metadata from an internal result into a tool response.""" + if result.get("fallback_warning"): + target["fallback_warning"] = result["fallback_warning"] + target["browser_engine"] = result.get("browser_engine") + target["browser_engine_fallback"] = result.get("browser_engine_fallback") + return target + + +def _run_chrome_fallback_command(task_id: str, command: str, args: List[str], timeout: int) -> Dict[str, Any]: + """Run a browser command in a temporary Chrome session at the current URL. + + agent-browser locks the engine when a named daemon starts, so ``--engine chrome`` on the + Lightpanda session is ignored: fresh temp Chrome session -> same URL -> ``command`` -> tear down. + """ + _bt = _origin() + import uuid + # 1. Current URL from the Lightpanda session. ``get url`` is not fallback-eligible, + # so this can't recurse; the explicit override strips Chromium-only env flags. + url_result = _session._run_browser_command(task_id, "get", ["url"], timeout=10, _engine_override="lightpanda") + current_url = str(url_result.get("data", {}).get("url", "")).strip() if url_result.get("success") else None + if not current_url: + _bt.logger.warning("Chrome fallback: could not determine current URL from LP session") + return {"success": False, "error": "Chrome fallback failed: could not determine current URL"} + + # 2. Temporary Chrome session (bypasses _get_session_info's cache). + tmp_session = f"h_cfb_{uuid.uuid4().hex[:8]}" + try: + browser_cmd = _install._find_agent_browser() + except FileNotFoundError as e: + return {"success": False, "error": str(e)} + + if not _install._chromium_installed(): + if _install._running_in_docker(): + hint = ("Chrome fallback requires Chromium, but it is missing. You're running in Docker — " + "pull the latest image: docker pull ghcr.io/nousresearch/hermes-agent:latest") + else: + hint = ("Chrome fallback requires Chromium, but it is missing. Install it with: " + "npx agent-browser install --with-deps (or: npx playwright install --with-deps chromium)") + return {"success": False, "error": hint} + + base_args = _session._agent_browser_argv(browser_cmd) + ["--engine", "chrome", "--session", tmp_session, "--json"] + task_socket_dir = _session._prepare_session_socket_dir(tmp_session) + # Bypasses _run_browser_command, so apply the same Chromium sandbox policy explicitly. + browser_env = _session._agent_browser_command_env(task_socket_dir) + _session._apply_chromium_sandbox_args(browser_env) + + def _run_tmp(cmd: str, cmd_args: List[str]) -> Dict[str, Any]: + proc = _session._popen_agent_browser(base_args + [cmd] + cmd_args, browser_env, task_socket_dir, cmd) + stdout_path = os.path.join(task_socket_dir, f"_stdout_{cmd}") + stderr_path = os.path.join(task_socket_dir, f"_stderr_{cmd}") + try: + proc.wait(timeout=timeout) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + return {"success": False, "error": f"Chrome fallback '{cmd}' timed out"} + try: + with open(stdout_path, encoding="utf-8") as f: + stdout = f.read().strip() + if stdout: + return json.loads(stdout.split("\n")[-1]) + except Exception as exc: + _bt.logger.debug("Chrome fallback tmp cmd '%s' error: %s", cmd, exc) + finally: + _session._unlink_command_output_files(stdout_path, stderr_path) + return {"success": False, "error": f"Chrome fallback '{cmd}' failed"} + + try: + # 3. Navigate Chrome to the same URL, then 4. run the requested command. + nav = _run_tmp("open", [current_url]) + if not nav.get("success"): + _bt.logger.warning("Chrome fallback: navigate failed: %s", nav.get("error")) + return {"success": False, "error": f"Chrome fallback navigate failed: {nav.get('error')}"} + return _run_tmp(command, args) + finally: + # 5. Tear down the temporary Chrome session and its socket directory. + try: + _run_tmp("close", []) + except Exception: + pass + shutil.rmtree(task_socket_dir, ignore_errors=True) + + +def _chrome_fallback_screenshot(task_id: str, args: List[str], timeout: int) -> Dict[str, Any]: + """Take a screenshot using a temporary Chrome session.""" + return _run_chrome_fallback_command(task_id, "screenshot", args, timeout) diff --git a/tools/browser_tool_origin.py b/tools/browser_tool_origin.py new file mode 100644 index 0000000000000000000000000000000000000000..1fe7a9491f7f7b3a46f9240b11a9ce10d56ab285 --- /dev/null +++ b/tools/browser_tool_origin.py @@ -0,0 +1,87 @@ +"""Origin-module lookup shared by the ``tools.browser_tool_*`` extraction modules. + +Extracted code reads facade-owned state (caches, locks, session tables, facade-defined +helpers) *through* ``tools.browser_tool`` and must not import it at import time (cycle) — +hence the lazy :func:`origin_module` and the :data:`origin` proxy. +""" + +import sys +from types import ModuleType + +_ORIGIN_NAME = "tools.browser_tool" + + +class _NamespaceView: + """Live view over a module namespace whose module object is gone (a test purged + ``sys.modules``): the old code still runs with its own globals, so hit *those*.""" + + __slots__ = ("_g",) + + def __init__(self, g): + object.__setattr__(self, "_g", g) + + def __getattr__(self, name): + try: + return self._g[name] + except KeyError: + raise AttributeError(name) from None + + def __setattr__(self, name, value): + self._g[name] = value + + +def _module_for_globals(g: dict): + """The module object whose namespace is ``g`` (or a live view over it).""" + import tools + + for mod in (sys.modules.get(_ORIGIN_NAME), getattr(tools, "browser_tool", None)): + if mod is not None and mod.__dict__ is g: + return mod + return _NamespaceView(g) + + +def origin_module(_depth: int = 2): + """The ``tools.browser_tool`` instance the *calling* moved function belongs to, mirroring + what in-file code would see: (1) the nearest enclosing frame executing origin code (the + exact module copy, even after a test purged/reloaded ``sys.modules``); (2) an origin + module referenced from a calling frame's globals; (3) ``sys.modules`` / ``tools`` + package attribute / fresh import. ``_depth`` is the frame of the moved function's caller.""" + try: + start = sys._getframe(_depth) + except ValueError: # called directly by the interpreter (atexit callback) + start = None + frame = start + while frame is not None: + if frame.f_globals.get("__name__") == _ORIGIN_NAME: + return _module_for_globals(frame.f_globals) + frame = frame.f_back + frame = start + while frame is not None: + for value in list(frame.f_globals.values()): + if isinstance(value, ModuleType) and getattr(value, "__name__", None) == _ORIGIN_NAME: + return value + frame = frame.f_back + mod = sys.modules.get(_ORIGIN_NAME) + if mod is None: + import tools + + mod = getattr(tools, "browser_tool", None) + if mod is None: + import tools.browser_tool as mod + return mod + + +class _OriginProxy: + """Module-level ``_bt`` stand-in: every attribute read/write forwards to the origin + module resolved at that moment.""" + + __slots__ = () + + def __getattr__(self, name): + return getattr(origin_module(3), name) + + def __setattr__(self, name, value): + setattr(origin_module(3), name, value) + + +origin = _OriginProxy() diff --git a/tools/browser_tool_session.py b/tools/browser_tool_session.py new file mode 100644 index 0000000000000000000000000000000000000000..4b9b353b3e034f46b65fb8a9b908aad678fa1319 --- /dev/null +++ b/tools/browser_tool_session.py @@ -0,0 +1,614 @@ +"""agent-browser session management: daemon spawn, per-backend session creation +(local/lightpanda/cdp/cloud), cached lookup, command execution + output interpretation. + +Split out of ``tools/browser_tool.py``. Facade-owned state is read through ``_bt`` (``tools.browser_tool``, resolved per call) — no import cycle. +""" + +import json +import logging +import os +import shutil +import subprocess +import uuid +from pathlib import Path +from typing import Any, Dict, List, Optional + +from hermes_cli._subprocess_compat import windows_hide_flags +from tools.browser_tool_origin import origin as _bt +from tools import browser_tool_cdp as _cdp +from tools import browser_tool_cloud as _cloud +from tools import browser_tool_install as _install +from tools import browser_tool_lifecycle as _lifecycle +from tools import browser_tool_lightpanda_fallback as _lp +from tools import browser_tool_real_profile as _real_profile +from tools import browser_tool_snapshot as _snapshot + +_DOCKER_PULL = "docker pull ghcr.io/nousresearch/hermes-agent:latest" +_CHROMIUM_INSTALL = "npx agent-browser install --with-deps (or: npx playwright install --with-deps chromium)" +_CHROMIUM_MISSING_DOCKER_HINT = ("Chromium browser is missing. You're running in Docker — pull the latest image " + f"to get the bundled Chromium: {_DOCKER_PULL}") +_CHROMIUM_MISSING_HINT = f"Chromium browser is missing. Install it with: {_CHROMIUM_INSTALL}" + + +def _needs_chromium_sandbox_bypass() -> bool: + """True when Chromium needs --no-sandbox to start reliably (root, Docker, AppArmor userns).""" + if hasattr(os, "geteuid") and os.geteuid() == 0: + return True + if _install._running_in_docker(): + return True + try: + with open("/proc/sys/kernel/apparmor_restrict_unprivileged_userns", encoding="utf-8") as f: + return f.read().strip() == "1" + except OSError: + return False + + +def _apply_chromium_sandbox_args(browser_env: Dict[str, str]) -> None: + """Add required Chromium sandbox flags without overriding user settings.""" + if ("AGENT_BROWSER_ARGS" not in browser_env and "AGENT_BROWSER_CHROME_FLAGS" not in browser_env + and _needs_chromium_sandbox_bypass()): + _bt.logger.debug("browser: sandbox bypass needed (root/docker/AppArmor userns) — injecting --no-sandbox") + browser_env["AGENT_BROWSER_ARGS"] = "--no-sandbox,--disable-dev-shm-usage" + + +def _read_command_output_files(stdout_path: str, stderr_path: str) -> tuple[str, str]: + """Best-effort read of agent-browser stdout/stderr temp files.""" + out = [] + for path in (stdout_path, stderr_path): + try: + with open(path, "r", encoding="utf-8") as f: + out.append(f.read().strip()) + except OSError: + out.append("") + return out[0], out[1] + + +def _unlink_command_output_files(*paths: str) -> None: + for path in paths: + try: + os.unlink(path) + except OSError: + pass + + +def _format_browser_timeout_error( + command: str, timeout: int, stdout: str, stderr: str +) -> str: + """Actionable timeout message from captured daemon output.""" + parts = [f"Command timed out after {timeout} seconds"] + detail = (stderr or stdout or "").strip() + if detail: + parts.append(detail[:1500]) + + if "sandbox" in f"{stderr}\n{stdout}".lower(): + parts.append("Chromium sandbox launch failed. Set AGENT_BROWSER_ARGS=" + "'--no-sandbox,--disable-dev-shm-usage' in your environment, " + "or run: npx agent-browser install --with-deps") + elif command == "open" and _cloud._is_local_mode(): + if _install._running_in_docker(): + parts.append("The browser daemon may still be starting or Chromium may be " + f"missing. Pull the latest image: {_DOCKER_PULL}") + else: + parts.append("The browser daemon may still be starting, or Chromium may be " + f"missing system libraries. Install/repair with: {_CHROMIUM_INSTALL}") + return "\n".join(parts) + + +def _agent_browser_argv(browser_cmd: str) -> list: + """Command prefix to invoke agent-browser (concrete binary, or the npx sentinel expanded). + + npx is resolved through the same PATH cascade as ``_find_agent_browser`` (a bare + ``which("npx")`` would let a broken system npx shadow a healthy managed one); if + absent the bare name gives a readable ``FileNotFoundError``. ``--ignore-scripts``: + the spec is a floating range — a compromised future patch must not run install scripts. + """ + if _install._is_npx_agent_browser_sentinel(browser_cmd): + _npx_bin = _install._resolve_npx_bin() or "npx" + return [_npx_bin, "--ignore-scripts", "--prefer-offline", "-y", _bt.AGENT_BROWSER_NPX_SPEC] + return [browser_cmd] + + +def _prepare_session_socket_dir(session_name: str) -> str: + """Create the per-session socket dir (parallel workers must not share one) and claim it + with our PID BEFORE first use — another hermes process's orphan reaper rmtree's any + ownerless agent-browser-* dir in the shared tmpdir.""" + socket_dir = os.path.join(_bt._socket_safe_tmpdir(), f"agent-browser-{session_name}") + os.makedirs(socket_dir, mode=0o700, exist_ok=True) + _lifecycle._write_owner_pid(socket_dir, session_name) + return socket_dir + + +def _agent_browser_command_env(socket_dir: str) -> Dict[str, str]: + """Credential-scrubbed env for one command: PATH fallbacks, the session socket dir, and + daemon-side idle self-termination (agent-browser 0.24+) mirroring the Python janitor + unless the user set ``AGENT_BROWSER_IDLE_TIMEOUT_MS`` explicitly.""" + env = _bt._build_browser_env() + env["PATH"] = _install._merge_browser_path(env.get("PATH", "")) + env["AGENT_BROWSER_SOCKET_DIR"] = socket_dir + if "AGENT_BROWSER_IDLE_TIMEOUT_MS" not in env: + env["AGENT_BROWSER_IDLE_TIMEOUT_MS"] = str(_bt.BROWSER_SESSION_INACTIVITY_TIMEOUT * 1000) + return env + + +def _popen_agent_browser(argv: List[str], env: Dict[str, str], socket_dir: str, tag: str) -> "subprocess.Popen": + """Spawn agent-browser with stdout/stderr redirected to ``socket_dir/_std{out,err}_``. + + Temp files, not pipes: the CLI forks a daemon that inherits its fds, so pipes never + see EOF until the timeout. Windows: CREATE_NO_WINDOW only (CREATE_NEW_PROCESS_GROUP + cancels asyncio's running task on 3.11), STARTF_USESTDHANDLES + close_fds so the child + gets ONLY our three handles (leaked console handles kill the Rust daemon grandchild). + """ + fds = [os.open(os.path.join(socket_dir, f"_{slot}_{tag}"), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + for slot in ("stdout", "stderr")] + try: + _popen_extra: dict = {} + if os.name == "nt": + _si = subprocess.STARTUPINFO() + _si.dwFlags |= subprocess.STARTF_USESTDHANDLES + _popen_extra = {"creationflags": windows_hide_flags(), "close_fds": True, "startupinfo": _si} + return subprocess.Popen(argv, stdout=fds[0], stderr=fds[1], stdin=subprocess.DEVNULL, env=env, **_popen_extra) + finally: + for fd in fds: + os.close(fd) + + +def _session_record(prefix: str, cdp_url: Optional[str], features: Dict[str, Any]) -> Dict[str, Any]: + """Fresh session dict with a random ``_`` session name.""" + return {"session_name": f"{prefix}_{uuid.uuid4().hex[:10]}", "bb_session_id": None, + "cdp_url": cdp_url, "features": features} + + +def _create_local_session(task_id: str, allow_real_profile: bool = True) -> Dict[str, str]: + """Local Chromium session; consented real-profile CDP attach when allowed. + + Real-profile fails closed on resolver/launch errors (a consented user must never be + silently downgraded to a throwaway). The hybrid private-URL sidecar passes + ``allow_real_profile=False``: the user's cookie jar must not reach an arbitrary + internal host the model chose. + """ + if allow_real_profile: + cdp_url, err = _real_profile._real_profile_cdp() + if err: + raise RuntimeError(err) + if cdp_url: + info = _session_record("rp", _cdp._resolve_cdp_override(cdp_url), {"local": True, "real_profile": True}) + _bt.logger.info("Created real-profile local session %s for task %s", info["session_name"], task_id) + return info + + # Browser Use mode + ``browser.engine: lightpanda`` drives a Hermes-spawned + # ``lightpanda serve`` (the built-in tools are hidden in that mode). + if _bt._is_browser_use_cli_mode() and _lp._using_lightpanda_engine(): + return _create_lightpanda_session(task_id) + + info = _session_record("h", None, {"local": True}) + _bt.logger.info("Created local browser session %s for task %s", info["session_name"], task_id) + return info + + +def _create_lightpanda_session(task_id: str) -> Dict[str, Any]: + """Spawn ``lightpanda serve`` for this session key (Browser Use mode).""" + from tools.browser_lightpanda import launch_lightpanda + + info = _session_record("lp", None, {"local": True, "lightpanda": True}) + server, err = launch_lightpanda(info["session_name"], block_private_networks=not _cloud._is_local_backend()) + if err: + raise RuntimeError(err) + info["cdp_url"] = server.cdp_url + _bt.logger.info("Created Lightpanda session %s (port %s) for task %s", info["session_name"], server.port, task_id) + return info + + +def _local_backend_process_dead(session_info: Dict[str, Any]) -> bool: + """True for a Lightpanda session whose ``lightpanda serve`` is gone.""" + if not (session_info.get("features") or {}).get("lightpanda"): + return False + from tools.browser_lightpanda import get_server + + server = get_server(session_info.get("session_name", "")) + return server is None or not server.is_alive() + + +def _create_cdp_session(task_id: str, cdp_url: str) -> Dict[str, str]: + """Session connecting to a user-supplied CDP endpoint.""" + info = _session_record("cdp", cdp_url, {"cdp_override": True}) + _bt.logger.info("Created CDP browser session %s → %s for task %s", + info["session_name"], _bt._sanitize_url_for_logs(cdp_url), task_id) + return info + + +def _create_cloud_session_or_fallback(task_id: str, provider) -> Dict[str, Any]: + """Cloud session; fall back to local Chromium (marked degraded) on failure. ``cdp_url`` + is resolved here because some providers return an HTTP discovery URL, not a websocket.""" + try: + session_info = provider.create_session(task_id) + if not session_info or not isinstance(session_info, dict): + raise ValueError(f"Cloud provider returned invalid session: {session_info!r}") + if session_info.get("cdp_url"): + session_info = dict(session_info) + session_info["cdp_url"] = _cdp._resolve_cdp_override(str(session_info["cdp_url"])) + return session_info + except Exception as e: + provider_name = type(provider).__name__ + _bt.logger.warning("Cloud provider %s failed (%s); attempting fallback to local Chromium for task %s", + provider_name, e, task_id, exc_info=True) + try: + session_info = _create_local_session(task_id) + except Exception as local_error: + raise RuntimeError(f"Cloud provider {provider_name} failed ({e}) and local " + f"fallback also failed ({local_error})") from e + if isinstance(session_info, dict): # mark degraded for observability + session_info = {**session_info, "fallback_from_cloud": True, "fallback_reason": str(e), + "fallback_provider": provider_name} + return session_info + + +def _create_session_for_key(task_id: str, force_local: bool) -> Dict[str, Any]: + """Fresh session for ``task_id`` (runs OUTSIDE the lock: cloud mode makes a network call). + Precedence: CDP override > hybrid local sidecar (never real-profile) > cloud > local.""" + cdp_override = _cdp._get_cdp_override() + if cdp_override and not force_local: + return _create_cdp_session(task_id, cdp_override) + if force_local: + return _create_local_session(task_id, allow_real_profile=False) + provider = _cloud._get_cloud_provider() + if provider is None: + return _create_local_session(task_id) + return _create_cloud_session_or_fallback(task_id, provider) + + +def _get_session_info(task_id: Optional[str] = None) -> Dict[str, Any]: + """Get or create session info for a session key (thread-safe); also starts the + inactivity thread and touches activity. A ``::local`` key forces local Chromium + even with a cloud provider configured.""" + if task_id is None: + task_id = "default" + + _lifecycle._start_browser_cleanup_thread() + _lifecycle._update_session_activity(task_id) + + with _bt._cleanup_lock: + existing_session = _bt._active_sessions.get(task_id) + + def _replacement_after_teardown() -> Optional[Dict[str, Any]]: + # Teardown removes the activity entry; re-touch so the reaper tracks the + # replacement. Another thread may already have re-created it — reuse that. + _lifecycle._update_session_activity(task_id) + with _bt._cleanup_lock: + replacement = _bt._active_sessions.get(task_id) + return replacement if replacement is not None and replacement is not existing_session else None + + if existing_session is not None: + # Suspect recycle: a command timeout marked this session; the expensive recycle + # lives here at next use, not on the timeout path (mark must stay cheap). + if not _bt._browser_session_backend(task_id).ensure_healthy(): + replacement = _replacement_after_teardown() + if replacement is not None: + return replacement + existing_session = None + elif not _lifecycle._session_has_expired(existing_session) and not _local_backend_process_dead(existing_session): + return existing_session + else: + _bt.logger.info("Replacing expired or dead browser session for task %s", task_id) + _lifecycle._cleanup_single_browser_session(task_id) + replacement = _replacement_after_teardown() + if replacement is not None: + return replacement + + force_local = _bt._is_local_sidecar_key(task_id) + session_info = _create_session_for_key(task_id, force_local) + + with _bt._cleanup_lock: + if task_id in _bt._active_sessions: # created concurrently during the network call — don't leak ours + return _bt._active_sessions[task_id] + session_info = dict(session_info) + session_info.setdefault("session_key", task_id) + session_info.setdefault("owner_task_id", _bt._bare_task_id_for_session_key(task_id)) + _bt._active_sessions[task_id] = session_info + _bt._suspect_browser_sessions.pop(task_id, None) # brand-new session is healthy by definition + + # Lazy-start the CDP supervisor (idempotent). Skip local sidecars (no CDP URL) and + # Lightpanda sessions (Browser Use mode hides the tools that consume supervisor state). + if not force_local and not (session_info.get("features") or {}).get("lightpanda"): + _cdp._ensure_cdp_supervisor(task_id) + + return session_info + + +def _discard_timed_out_browser_session(task_id: str, session_info: Dict[str, Any], task_socket_dir: str) -> None: + """Drop a stuck client generation without losing cloud cleanup state.""" + with _bt._cleanup_lock: + if _bt._active_sessions.get(task_id) is not session_info: + return + _cdp._stop_cdp_supervisor(task_id) + if session_info.get("bb_session_id") or session_info.get("cdp_url"): + replacement = dict(session_info) + replacement["session_name"] = f"h_{uuid.uuid4().hex[:10]}" + replacement.pop("_first_nav", None) + _bt._active_sessions[task_id] = replacement + else: + _bt._active_sessions.pop(task_id, None) + _bt._session_last_activity.pop(task_id, None) + + bare_task_id = _bt._bare_task_id_for_session_key(task_id) + if _bt._last_active_session_key.get(bare_task_id) == task_id: + _bt._last_active_session_key.pop(bare_task_id, None) + + session_name = str(session_info.get("session_name") or "") + if session_name and os.path.isfile(os.path.join(task_socket_dir, f"{session_name}.pid")): + daemon_pid = _read_browser_daemon_pid(task_socket_dir, session_name) + if daemon_pid is None: # corrupt pid file + _bt.logger.debug("Could not kill timed-out browser daemon for %s", session_name) + return + if not _lifecycle._verify_reapable_browser_daemon(daemon_pid, task_socket_dir, session_name): + return + try: + # Tree-kill: terminating only the daemon PID leaks the Chromium tree. + # See #68139. + from agent import deadline as _deadline + + _deadline.kill_process_tree(daemon_pid) + except (ProcessLookupError, PermissionError, OSError): + _bt.logger.debug("Could not kill timed-out browser daemon for %s", session_name) + return + shutil.rmtree(task_socket_dir, ignore_errors=True) + + +def _read_browser_daemon_pid(task_socket_dir: str, session_name: str) -> Optional[int]: + """Read the agent-browser daemon PID for a session (best-effort).""" + pid_file = os.path.join(task_socket_dir, f"{session_name}.pid") + try: + return int(Path(pid_file).read_text(encoding="utf-8").strip()) + except (OSError, ValueError): + return None + + +def _browser_daemon_responsive(task_socket_dir: str, probe_timeout_s: float = 1.0) -> bool: + """Cheap liveness probe: a connect to the daemon's unix control socket proves the accept + loop is alive (the command wedged page/CDP-side). Windows named pipes can't be probed → + report unresponsive (tree-kill + respawn is the safe recovery).""" + if os.name == "nt": + return False + import socket as socket_mod + + if not hasattr(socket_mod, "AF_UNIX"): + return False + try: + entries = os.listdir(task_socket_dir) + except OSError: + return False + for entry in (e for e in entries if e.endswith(".sock")): + try: + with socket_mod.socket(socket_mod.AF_UNIX, socket_mod.SOCK_STREAM) as s: + s.settimeout(probe_timeout_s) + s.connect(os.path.join(task_socket_dir, entry)) + return True + except OSError: + continue + return False + + +def _handle_browser_command_timeout(task_id: str, session_info: Dict[str, Any], task_socket_dir: str) -> None: + """Recover session state after a command timeout. + + Cloud/CDP: no daemon to probe — replace the stuck client generation now (same + ``bb_session_id`` so cloud cleanup works). Local daemon alive (PID live, verified, + socket accepts): only the command wedged — mark suspect, recycle at next use. + Local daemon wedged/dead: tree-kill and evict now (Chromium children would leak). + Both local branches ``mark_suspect`` first so the poisoned-cache invariant holds + even if eviction races another thread's replacement. + + See #68139, #72205. + * **Local daemon alive** (PID readable, process alive, identity-verified as ours, control socket accepts + a connection): the *command* wedged — page hang, stuck navigation — but the daemon itself is fine. + Killing it would be overkill and slow. Mark the session suspect only; the next use recycles it through + ``ensure_healthy`` → clean agent-browser ``close`` → fresh session. Tree-kill the daemon's process tree + via ``agent.deadline.kill_process_tree`` and evict the cache entry now; the next browser call respawns + from scratch. See #72206. + """ + if session_info.get("bb_session_id") or session_info.get("cdp_url"): + _discard_timed_out_browser_session(task_id, session_info, task_socket_dir) + return + + _bt._browser_session_backend(task_id).mark_suspect("browser command timed out; session may be poisoned") + + session_name = str(session_info.get("session_name") or "") + daemon_pid = _read_browser_daemon_pid(task_socket_dir, session_name) if session_name else None + daemon_alive = ( + daemon_pid is not None + and _lifecycle._pid_exists(daemon_pid) + and _lifecycle._verify_reapable_browser_daemon(daemon_pid, task_socket_dir, session_name) + and _browser_daemon_responsive(task_socket_dir) + ) + if daemon_alive: + _bt.logger.warning("browser daemon for %s is alive after command timeout; session " + "marked suspect and will be recycled at next use", task_id) + return + + _bt.logger.warning("browser daemon for %s is wedged or dead after command timeout; " + "tree-killing and evicting the session", task_id) + _discard_timed_out_browser_session(task_id, session_info, task_socket_dir) + # The poisoned entry is gone either way; the flag must not poison a session + # created later under the same key. + _bt._suspect_browser_sessions.pop(task_id, None) + + +def _interpret_browser_command_output(command: str, stdout: str, stderr: str, returncode: int) -> Dict[str, Any]: + """Finished agent-browser process output → result dict. Empty stdout with rc=0 is a + broken state (stale daemon) reported as failure except for ``_EMPTY_OK_COMMANDS``; + non-JSON output is an error except ``screenshot``, whose path is recovered from prose.""" + if stderr and stderr.strip(): + level = logging.WARNING if returncode != 0 else logging.DEBUG + _bt.logger.log(level, "browser '%s' stderr: %s", command, stderr.strip()[:500]) + + stdout_text = stdout.strip() + if not stdout_text: + if returncode != 0: + error_msg = stderr.strip() if stderr else f"Command failed with code {returncode}" + _bt.logger.warning("browser '%s' failed (rc=%s): %s", command, returncode, error_msg[:300]) + return {"success": False, "error": error_msg} + if command not in _bt._EMPTY_OK_COMMANDS: + _bt.logger.warning("browser '%s' returned empty output (rc=0)", command) + return {"success": False, "error": f"Browser command '{command}' returned no output"} + return {"success": True, "data": {}} + + try: + parsed = json.loads(stdout_text) + except json.JSONDecodeError: + raw = stdout_text[:2000] + _bt.logger.warning("browser '%s' returned non-JSON output (rc=%s): %s", command, returncode, raw[:500]) + if command == "screenshot": + combined_text = "\n".join(part for part in [stdout_text, (stderr or "").strip()] if part) + recovered_path = _snapshot._extract_screenshot_path_from_text(combined_text) + if recovered_path and Path(recovered_path).exists(): + _bt.logger.info("browser 'screenshot' recovered file from non-JSON output: %s", recovered_path) + return {"success": True, "data": {"path": recovered_path, "raw": raw}} + return {"success": False, "error": f"Non-JSON output from agent-browser for '{command}': {raw}"} + + # Empty snapshot content is a common sign of daemon/CDP issues. + if command == "snapshot" and parsed.get("success"): + snap_data = parsed.get("data", {}) + if not snap_data.get("snapshot") and not snap_data.get("refs"): + _bt.logger.warning("snapshot returned empty content. Possible stale daemon or CDP connection issue. " + "returncode=%s", returncode) + return parsed + + +def _browser_command_preflight() -> Dict[str, Any]: + """Fail fast before spawning (missing CLI, Termux gap, interrupt, no Chromium in local + mode — else every call hangs for command_timeout). Error result, or ``{"browser_cmd": path}``.""" + try: + browser_cmd = _install._find_agent_browser() + except FileNotFoundError as e: + _bt.logger.warning("agent-browser CLI not found: %s", e) + return {"success": False, "error": str(e)} + + if _install._requires_real_termux_browser_install(browser_cmd): + error = _install._termux_browser_install_error() + _bt.logger.warning("browser command blocked on Termux: %s", error) + return {"success": False, "error": error} + + # Skip when engine=lightpanda — LP doesn't need Chromium for navigation. + if ( + _cloud._is_local_mode() + and not _install._chromium_installed() + and _cloud._get_browser_engine() != "lightpanda" + and not _install._maybe_autoinstall_chromium() + ): + hint = _CHROMIUM_MISSING_DOCKER_HINT if _install._running_in_docker() else _CHROMIUM_MISSING_HINT + _bt.logger.warning("browser command blocked: %s", hint) + return {"success": False, "error": hint} + + from tools.interrupt import is_interrupted + if is_interrupted(): + return {"success": False, "error": "Interrupted"} + return {"browser_cmd": browser_cmd} + + +def _spawn_and_collect( + task_id: str, session_info: Dict[str, Any], cmd_parts: List[str], + command: str, engine: str, timeout: int, +) -> Dict[str, Any]: + """Run the prepared agent-browser argv once and interpret its output (handles timeout).""" + task_socket_dir = _prepare_session_socket_dir(session_info["session_name"]) + _bt.logger.debug("browser cmd=%s task=%s socket_dir=%s (%d chars)", + command, task_id, task_socket_dir, len(task_socket_dir)) + browser_env = _agent_browser_command_env(task_socket_dir) + + # Lightpanda rejects Chromium-only launch flags: strip current and legacy vars; + # Chrome commands and fallback use the shared Chromium policy. + if engine == "lightpanda": + stripped = [browser_env.pop(k, None) for k in ("AGENT_BROWSER_ARGS", "AGENT_BROWSER_CHROME_FLAGS")] + if any(v is not None for v in stripped): + _bt.logger.debug("browser: stripped Chromium-only AGENT_BROWSER_ARGS/AGENT_BROWSER_CHROME_FLAGS " + "for Lightpanda command %s (agent-browser rejects them with --engine lightpanda)", + command) + else: + _apply_chromium_sandbox_args(browser_env) + + stdout_path = os.path.join(task_socket_dir, f"_stdout_{command}") + stderr_path = os.path.join(task_socket_dir, f"_stderr_{command}") + proc = _popen_agent_browser(cmd_parts, browser_env, task_socket_dir, command) + + try: + proc.wait(timeout=timeout) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + stdout, stderr = _read_command_output_files(stdout_path, stderr_path) + _unlink_command_output_files(stdout_path, stderr_path) + _handle_browser_command_timeout(task_id, session_info, task_socket_dir) + if stderr and stderr.strip(): + _bt.logger.warning("browser '%s' stderr after timeout: %s", command, stderr.strip()[:500]) + _bt.logger.warning("browser '%s' timed out after %ds (task=%s, socket_dir=%s)", + command, timeout, task_id, task_socket_dir) + return {"success": False, "error": _format_browser_timeout_error(command, timeout, stdout, stderr)} + with open(stdout_path, "r", encoding="utf-8") as f: + stdout = f.read() + with open(stderr_path, "r", encoding="utf-8") as f: + stderr = f.read() + _unlink_command_output_files(stdout_path, stderr_path) + return _interpret_browser_command_output(command, stdout, stderr, proc.returncode) + + +def _run_browser_command( + task_id: str, + command: str, + args: List[str] = None, + timeout: Optional[int] = None, + _engine_override: Optional[str] = None, +) -> Dict[str, Any]: + """Run one agent-browser CLI command against the task's session; returns its parsed JSON. + ``timeout=None`` reads ``browser.command_timeout``; ``_engine_override`` forces an engine + for this call only (Lightpanda fallback retries with Chrome without touching global state).""" + if timeout is None: + timeout = _bt._safe_command_timeout() + args = args or [] + + preflight = _browser_command_preflight() + if "browser_cmd" not in preflight: + return preflight + browser_cmd = preflight["browser_cmd"] + + try: + session_info = _get_session_info(task_id) + except Exception as e: + _bt.logger.warning("Failed to create browser session for task=%s: %s", task_id, e) + return {"success": False, "error": f"Failed to create browser session: {str(e)}"} + # Cleanup stops the supervisor before closing the backend; keep it stopped. + if command != "close" and session_info.get("cdp_url"): + _cdp._ensure_cdp_supervisor(task_id) + + # Cloud/CDP: ``--cdp `` (NEVER with --session: agent-browser >=0.13 + # would create a local browser and silently ignore --cdp). Local: ``--session ``. + # Engine injection keys off the resolved session backend, not global provider + # state: hybrid routing can create a local sidecar while a cloud provider stays configured. + engine = _engine_override or _cloud._get_browser_engine() + if session_info.get("cdp_url"): + backend_args = ["--cdp", session_info["cdp_url"]] + else: + backend_args = ["--session", session_info["session_name"]] + if _cloud._is_headed_mode(): + backend_args.append("--headed") + if engine != "auto" and not _bt._is_camofox_mode(): + backend_args += ["--engine", engine] + + cmd_parts = _agent_browser_argv(browser_cmd) + backend_args + ["--json", command] + args + + try: + result = _spawn_and_collect(task_id, session_info, cmd_parts, command, engine, timeout) + except Exception as e: + _bt.logger.warning("browser '%s' exception: %s", command, e, exc_info=True) + result = {"success": False, "error": str(e)} + + # Lightpanda automatic Chrome fallback — runs for ALL exit paths (timeout, + # empty, non-JSON, nonzero rc, parsed). + fallback_reason = _lp._lightpanda_fallback_reason(engine, command, result) + if fallback_reason: + _bt.logger.info("Lightpanda fallback: retrying '%s' with Chrome (task=%s): %s", command, task_id, fallback_reason) + if command == "screenshot": # separate Chrome session to the same URL + fallback_result = _lp._chrome_fallback_screenshot(task_id, args or [], timeout) + else: + fallback_result = _lp._run_chrome_fallback_command(task_id, command, args, timeout) + return _lp._annotate_lightpanda_fallback(fallback_result, fallback_reason) + + return result diff --git a/tools/browser_tool_snapshot.py b/tools/browser_tool_snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..5a1329a7d36913244412ab4d4220f8cecd68c3ef --- /dev/null +++ b/tools/browser_tool_snapshot.py @@ -0,0 +1,125 @@ +"""Snapshot post-processing for the browser tools: truncate-and-store of oversized +accessibility trees, model-boundary secret redaction, screenshot-path recovery. + +Facade-owned state is read through ``_bt`` (``tools.browser_tool``, resolved per call) — no import cycle. +""" + +import re +from typing import Any, Optional +from tools.browser_tool_origin import origin as _bt + + +_SCREENSHOT_PATH_PATTERNS = ( + r"Screenshot saved to ['\"](?P/[^'\"]+?\.png)['\"]", + r"Screenshot saved to (?P/\S+?\.png)(?:\s|$)", + r"(?P/\S+?\.png)(?:\s|$)", +) + + +def _extract_screenshot_path_from_text(text: str) -> Optional[str]: + """Extract a screenshot file path from agent-browser human-readable output.""" + if not text: + return None + + for pattern in _SCREENSHOT_PATH_PATTERNS: + match = re.search(pattern, text) + if match: + path = match.group("path").strip().strip("'\"") + if path: + return path + return None + + +def _store_full_snapshot(snapshot_text: str) -> Optional[str]: + """Write a full snapshot to cache/web and return its path (None on failure — best-effort). + + Mirrors ``web_tools._store_full_text``: cache/web is mounted read-only into + remote backends, so read_file can page through the complete tree on any + backend. The stored copy is force-redacted (page-rendered secrets must not + hit disk unmasked) and named by content hash so identical snapshots dedupe. + """ + try: + import hashlib + from hermes_constants import get_hermes_dir + from agent.redact import redact_sensitive_text + + content = redact_sensitive_text(snapshot_text, force=True) + if len(content) > _bt.MAX_STORED_SNAPSHOT_CHARS: + content = ( + content[:_bt.MAX_STORED_SNAPSHOT_CHARS] + + f"\n\n[... stored copy truncated at {_bt.MAX_STORED_SNAPSHOT_CHARS:,} chars " + f"of {len(content):,} ...]" + ) + from tools.spill_safety import ensure_spill_dir, write_text_exclusive + + cache_dir = get_hermes_dir("cache/web", "web_cache") + ensure_spill_dir(cache_dir, private=False) + digest = hashlib.sha256(content.encode("utf-8")).hexdigest()[:10] + path = cache_dir / f"browser-snapshot-{digest}.txt" + # Deterministic filename in a well-known dir: refuse symlinks (lstat-unlink + + # exclusive create); same-content re-snapshots legitimately overwrite. Not + # private: cache/web is bind-mounted into remote backends' container UID. + write_text_exclusive(path, content, private=False, overwrite=True) + return str(path) + except Exception as exc: # noqa: BLE001 + _bt.logger.debug("Failed to store full browser snapshot: %s", exc) + return None + + +def _truncate_snapshot(snapshot_text: str, max_chars: Optional[int] = None) -> str: + """Truncate a snapshot at line boundaries (never mid-element) to ``max_chars``. + + Defaults to ``browser.snapshot_threshold``. The full snapshot is stored to + cache/web and the appended note tells the agent how to page through it + with read_file — element refs beyond the cut are in the file, not lost. + """ + if max_chars is None: + max_chars = _bt.get_browser_snapshot_threshold() + if len(snapshot_text) <= max_chars: + return snapshot_text + + stored_path = _store_full_snapshot(snapshot_text) + if stored_path: + # Agent-visible path: read_file runs inside the active backend (#72389). + from tools.credential_files import to_agent_visible_cache_path + stored_path = to_agent_visible_cache_path(stored_path) + + lines = snapshot_text.split('\n') + result: list[str] = [] + chars = 0 + # Reserve space for the truncation note (the stored-path variant is the + # longer of the two). Clamp so tiny max_chars values still keep content. + reserve = min(110 + len(stored_path or ""), max_chars // 2) + for line in lines: + if chars + len(line) + 1 > max_chars - reserve: + break + result.append(line) + chars += len(line) + 1 + remaining = len(lines) - len(result) + if remaining > 0: + if stored_path: + next_line = len(result) + 1 + result.append( + f'\n[... {remaining} more lines truncated — full snapshot: ' + f'read_file path="{stored_path}" offset={next_line} limit=200]' + ) + else: + result.append(f'\n[... {remaining} more lines truncated, use browser_snapshot for full content]') + return '\n'.join(result) + + +def _redact_browser_output(value: Any) -> Any: + """Force-redact secrets in browser-originated data (snapshots, console, eval + results can carry page-rendered keys/cookies/tokens). Tool output is a model + boundary, so this applies even when global log redaction is disabled.""" + from agent.redact import redact_sensitive_text + + if isinstance(value, str): + return redact_sensitive_text(value, force=True) + if isinstance(value, list): + return [_redact_browser_output(item) for item in value] + if isinstance(value, tuple): + return tuple(_redact_browser_output(item) for item in value) + if isinstance(value, dict): + return {_redact_browser_output(key): _redact_browser_output(item) for key, item in value.items()} + return value diff --git a/tools/browser_tool_vision.py b/tools/browser_tool_vision.py new file mode 100644 index 0000000000000000000000000000000000000000..561790c1583888453c6433ab01b3597c11b04cb9 --- /dev/null +++ b/tools/browser_tool_vision.py @@ -0,0 +1,143 @@ +"""browser_vision helpers: Lightpanda pre-route, native provider vision, auxiliary-LLM screenshot analysis. + +Split out of ``tools/browser_tool.py``. Facade-owned state is read through ``_bt`` (``tools.browser_tool``, resolved per call) — no import cycle. +""" + +import os +import shutil +from pathlib import Path +from typing import Any, Dict, Optional, Tuple + +from hermes_cli.config import cfg_get +from tools.browser_tool_origin import origin as _bt +from tools import browser_tool_cloud as _cloud +from tools import browser_tool_lightpanda_fallback as _lp + + +def _vision_mode_label() -> str: + _cp = _cloud._get_cloud_provider() + return "local" if _cp is None else f"cloud ({_cp.display_name})" + + +def _lightpanda_vision_preroute( + effective_task_id: str, annotate: bool, screenshot_path: Path, +) -> Tuple[bool, Optional[str], Path]: + """Capture the vision screenshot via the Chrome fallback when Lightpanda is the engine + (it has no graphical renderer). Returns ``(prerouted, fallback_warning, path)``; + on fallback failure ``prerouted`` is False and the caller takes the normal + screenshot path (forcing Chrome) so the standard fallback metadata still applies.""" + engine = _cloud._get_browser_engine() + if engine != "lightpanda" or not _cloud._should_inject_engine(engine): + return False, None, screenshot_path + _bt.logger.debug("browser_vision: pre-routing screenshot to Chrome (engine=lightpanda)") + screenshot_args = ["--annotate"] if annotate else [] + fb_result = _lp._chrome_fallback_screenshot(effective_task_id, screenshot_args, _bt._get_command_timeout()) + fb_result = _lp._annotate_lightpanda_fallback(fb_result, _bt._LP_VISION_FALLBACK_REASON) + if not fb_result.get("success"): + _bt.logger.warning("Lightpanda Chrome fallback vision screenshot failed: %s", fb_result.get("error")) + return False, None, screenshot_path + fb_path = fb_result.get("data", {}).get("path", "") + if fb_path and os.path.exists(fb_path): + import uuid as uuid_mod + from hermes_constants import get_hermes_dir + + screenshots_dir = get_hermes_dir("cache/screenshots", "browser_screenshots") + screenshots_dir.mkdir(parents=True, exist_ok=True) + persistent_path = screenshots_dir / f"browser_screenshot_{uuid_mod.uuid4().hex}.png" + shutil.copy2(fb_path, persistent_path) + screenshot_path = persistent_path + return True, fb_result.get("fallback_warning"), screenshot_path + + +def _native_vision_result( + screenshot_path: Path, question: str, annotate: bool, + result: Dict[str, Any], lp_fallback_warning: Optional[str], +) -> Dict[str, Any]: + """Multimodal tool-result envelope: the main model inspects the pixels itself. + + The embed is baked into history and re-sent every later turn, so apply the same + proactive resize as vision_analyze's native path (skipped when already under + both caps; without Pillow it fails open to the raw bytes). + """ + from tools.vision_tools import ( + _EMBED_MAX_DIMENSION, + _EMBED_TARGET_BYTES, + _build_native_vision_tool_result, + _resize_image_for_vision, + ) + + data_url = _resize_image_for_vision(screenshot_path, mime_type="image/png", max_base64_bytes=_EMBED_TARGET_BYTES, + max_dimension=_EMBED_MAX_DIMENSION, force_jpeg=True) + native_result = _build_native_vision_tool_result(image_url=str(screenshot_path), question=question, + image_data_url=data_url, + image_size_bytes=screenshot_path.stat().st_size) + meta = native_result.setdefault("meta", {}) + meta["screenshot_path"] = str(screenshot_path) + if lp_fallback_warning: + meta["fallback_warning"] = lp_fallback_warning + if annotate and result.get("data", {}).get("annotations"): + meta["annotations"] = result["data"]["annotations"] + native_result["text_summary"] = f"{native_result.get('text_summary', '')} Screenshot path: {screenshot_path}".strip() + return native_result + + +def _analyze_screenshot_with_aux_llm(screenshot_path: Path, question: str) -> str: + """One-shot aux vision-LLM analysis (not baked into history), secret-redacted. + + Full resolution first; on a size-related provider rejection the image is + downscaled once and retried. ``auxiliary.vision.timeout/temperature`` — local + vision models can take well over 30s, so the default timeout is generous. + """ + import base64 + + vision_prompt = ( + f"You are analyzing a screenshot of a web browser.\n\n" + f"User's question: {question}\n\n" + f"Provide a detailed and helpful answer based on what you see in the screenshot. " + f"If there are interactive elements, describe them. If there are verification challenges " + f"or CAPTCHAs, describe what type they are and what action might be needed. " + f"Focus on answering the user's specific question." + ) + _screenshot_bytes = screenshot_path.read_bytes() + _screenshot_b64 = base64.b64encode(_screenshot_bytes).decode("ascii") + data_url = f"data:image/png;base64,{_screenshot_b64}" + vision_model = _bt._get_vision_model() + _bt.logger.debug("browser_vision: analysing screenshot (%d bytes)", len(_screenshot_bytes)) + + vision_timeout = 120.0 + vision_temperature = 0.1 + try: + from hermes_cli.config import load_config + _vision_cfg = cfg_get(load_config(), "auxiliary", "vision", default={}) + if _vision_cfg.get("timeout") is not None: + vision_timeout = float(_vision_cfg["timeout"]) + if _vision_cfg.get("temperature") is not None: + vision_temperature = float(_vision_cfg["temperature"]) + except Exception: + pass + + from agent.auxiliary_client import call_llm # lazy: heavy client, only needed on the vision path + + call_kwargs = { + "task": "vision", "temperature": vision_temperature, "timeout": vision_timeout, + "messages": [{"role": "user", "content": [ + {"type": "text", "text": vision_prompt}, + {"type": "image_url", "image_url": {"url": data_url}}, + ]}], + } + if vision_model: + call_kwargs["model"] = vision_model + try: + response = call_llm(**call_kwargs) + except Exception as _api_err: + from tools.vision_tools import _is_image_size_error, _resize_image_for_vision, _RESIZE_TARGET_BYTES + if not (_is_image_size_error(_api_err) and len(data_url) > _RESIZE_TARGET_BYTES): + raise + _bt.logger.info("Vision API rejected screenshot (%.1f MB); auto-resizing to ~%.0f MB and retrying...", + len(data_url) / (1024 * 1024), _RESIZE_TARGET_BYTES / (1024 * 1024)) + data_url = _resize_image_for_vision(screenshot_path, mime_type="image/png") + call_kwargs["messages"][0]["content"][1]["image_url"]["url"] = data_url + response = call_llm(**call_kwargs) + + from agent.redact import redact_sensitive_text # the LLM may have read secrets off the screenshot + return redact_sensitive_text((response.choices[0].message.content or "").strip()) diff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a52ac1b0bbe13d4db27fc1a627b1f8d09d7fcfec --- /dev/null +++ b/tools/browser_use_cli.py @@ -0,0 +1,793 @@ +"""Use the Browser Use CLI 3.0 (https://browser-use.com) for browser automation + +When browser.backend is "browser-use", the model gets ``browser_exec`` tool +instead of default browser tools +""" + +import contextlib +import importlib +import json +import logging +import os +import re +import shutil +import signal +import subprocess +import time +from pathlib import Path +from typing import Any, Callable, Dict, List, Optional, Tuple + +from hermes_constants import get_hermes_home +from utils import is_truthy_value + +logger = logging.getLogger(__name__) + +_BACKEND_KEY = "browser-use" +BACKEND_DISABLED = "off" + +# Cloud daemon names become the BU_NAME env var +_SESSION_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$") + +# Set on the env dict by the CDP resolvers when the resolved browser is EXCLUSIVE to this named session +# (per-name provider / named BU cloud / Lightpanda). Popped before the subprocess launches — never exported. +_PRIVATE_BROWSER_SENTINEL = "_HERMES_BU_PRIVATE_BROWSER" + +# Prepended to the model's code for named sessions on SHARED browsers (a /browser connect CDP override): the +# harness daemon attaches to the first existing page at startup, so two fresh named daemons can land on the +# SAME tab. Steering each onto a tab it created prevents clobbering. Runs once per daemon (marker keyed by +# BU_NAME + daemon pid). +_OWN_TAB_PREAMBLE = """\ +# hermes: pin this named session to its own tab (once per daemon process) +def _hermes_ensure_own_tab(): + import os as _os, tempfile as _tf + _name = _os.environ.get("BU_NAME", "default") + try: + # Key the marker by the daemon's pid so a daemon restart (which + # re-attaches to the first shared page) re-pins automatically, + # while agent-driven tab switches mid-session are left alone. + from browser_harness import _ipc as _bipc + _dpid = _bipc.pid_path(_name).read_text().strip() or "0" + except Exception: + _dpid = "0" + _uid = _os.getuid() if hasattr(_os, "getuid") else 0 + _marker = _os.path.join( + _tf.gettempdir(), "hermes-bu-owntab-%s-%s-%s" % (_uid, _name, _dpid) + ) + if _os.path.exists(_marker): + return + try: + # Force a fresh target: new_tab() would REUSE a blank current tab, + # which is exactly the tab a sibling daemon may also hold. + _tid = cdp("Target.createTarget", url="about:blank").get("targetId") + if _tid: + switch_tab(_tid) + except Exception: + pass # best-effort: worst case is pre-fix behavior + try: + open(_marker, "w").close() + except OSError: + pass +_hermes_ensure_own_tab() +del _hermes_ensure_own_tab +""" + +_DEFAULT_TIMEOUT_S = 300 +_MIN_TIMEOUT_S = 5 +_MAX_TIMEOUT_S = 1800 +_STDERR_CAP_CHARS = 4000 + +_TASK_ID_SAFE_RE = re.compile(r"[^A-Za-z0-9._-]+") # filesystem-safe task ids +# Screenshot paths printed by capture_screenshot(): POSIX or Windows drive-letter absolute. +_IMAGE_PATH_RE = re.compile(r"((?:[A-Za-z]:[\\/]|/)[^\s\"']+?\.(?:png|jpe?g|webp))", re.IGNORECASE) +# http(s) URL literals in exec code checked against browser_navigate's policy +_URL_RE = re.compile(r"https?://[^\s'\"\\)]+", re.IGNORECASE) +_FHS_BIN_DIRS = ("/usr/local/sbin", "/usr/local/bin", "/usr/sbin", "/usr/bin", "/sbin", "/bin") + + +def _quiet(fn: Callable[[], Any], default: Any, log_prefix: str = "") -> Any: + """``fn()``, or ``default`` on any exception (debug-logged when ``log_prefix`` is set).""" + try: + return fn() + except Exception as e: + if log_prefix: + logger.debug("%s: %s", log_prefix, e) + return default + + +def _lazy_call(module: str, name: str, default: Any, log_prefix: str) -> Any: + """Call ``module.name()`` resolved at call time (tests stub the module / patch the + attribute); on any failure log ``log_prefix`` and return ``default``.""" + return _quiet(lambda: getattr(importlib.import_module(module), name)(), default, log_prefix) + + +def _camofox_active(context: str = "") -> bool: + return _lazy_call("tools.browser_camofox", "is_camofox_mode", False, f"Camofox activity check failed{context}") + + +def _real_profile_consented() -> bool: + return _lazy_call("tools.browser_tool_cloud", "_use_real_profile", False, "real-profile consent lookup failed") + + +def _set_cdp_env(env: dict, cdp: str) -> None: + """Export a CDP endpoint under the BU_CDP_* contract (http(s) → URL, else WS).""" + env["BU_CDP_URL" if cdp.startswith(("http://", "https://")) else "BU_CDP_WS"] = cdp + + +def _has_cdp_env(env: dict) -> bool: + return bool(env.get("BU_CDP_WS") or env.get("BU_CDP_URL")) + + +def _export_session_cdp(env: dict, get_session_info: Callable[[str], Any], cache_key: str, + fail_msg: Callable[[Exception], str], no_cdp_msg: str) -> Optional[str]: + """Export the CDP endpoint from ``get_session_info(cache_key)``; error string on failure / no CDP.""" + try: + cdp = str((get_session_info(cache_key) or {}).get("cdp_url") or "") + except Exception as e: + return fail_msg(e) + if not cdp: + return no_cdp_msg + _set_cdp_env(env, cdp) + return None + + +def _blocked_url_in_code(code: str) -> Optional[str]: + """Return an error if a URL literal fails the built-in navigation checks.""" + from tools.browser_tool import evaluate_url_safety + return next((err.get("error", "Blocked: unsafe URL") for err in map(evaluate_url_safety, _URL_RE.findall(code or "")) if err), None) + + +def _base_subprocess_env() -> dict: + from tools.browser_tool import _build_browser_env + env = _build_browser_env() + # The CLI runs under its own Python (uv tool / uvx); an inherited PYTHONPATH/PYTHONHOME + # (Hermes's venv) wins over its site-packages → wrong-ABI C-extensions and a crash. + # PYTHONPATH/PYTHONHOME inherited from the agent process point at Hermes's venv site-packages, and a + # child interpreter honors them ahead of its own site-packages — so the CLI imports compiled + # C-extensions (e.g. pydantic_core) built for the wrong interpreter and crashes on ABI mismatch (#83427, + # #84841, #86006, #86104). Strip both — the CLI manages its own environment and never needs Hermes's + # import path. + env.pop("PYTHONPATH", None) + env.pop("PYTHONHOME", None) + env["PATH"] = _floor_subprocess_path(env.get("PATH", "")) + env.setdefault("ANONYMIZED_TELEMETRY", "false") + return env + + +def _floor_subprocess_path(path: str) -> str: + """Guarantee core system dirs on the CLI subprocess PATH: profile workers (kanban bots, cron) can inherit + a PATH of only version-manager dirs, and the uv binary's POSIX sh trampoline resolves ``dirname``/``realpath`` + via PATH (exit 127 without /usr/bin). Reuses browser_tool's ``_merge_browser_path`` floor, else appends + FHS bin dirs. Windows .cmd shims don't trampoline: no-op there.""" + if os.name == "nt": + return path + with contextlib.suppress(Exception): + from tools.browser_tool_install import _merge_browser_path + return _merge_browser_path(path or "") + parts = [p for p in (path or "").split(os.pathsep) if p] + return os.pathsep.join(parts + [d for d in _FHS_BIN_DIRS if d not in set(parts) and os.path.isdir(d)]) + + +def _read_browser_cfg() -> dict: + """Return the ``browser:`` config section, or {} on any failure.""" + try: + from hermes_cli.config import cfg_get, read_raw_config + cfg = cfg_get(read_raw_config(), "browser", default={}) + return cfg if isinstance(cfg, dict) else {} + except Exception as e: + logger.debug("Could not read browser config section: %s", e) + return {} + + +def _use_gateway(browser_cfg: dict) -> bool: + """True when the browser section selects the Nous Tool Gateway — by the current ``hermes tools`` + picker row (``cloud_provider: nous``) or the pre-picker ``use_gateway: true`` flag. Reading only + the legacy flag missed every picker-configured gateway, and the direct-API branch it fell into + holds no credentials in managed mode (#108310).""" + if is_truthy_value(browser_cfg.get("use_gateway"), default=False): + return True + try: + from tools.tool_backend_helpers import NOUS_MANAGED_PROVIDER + except Exception: # pragma: no cover — helper ships with the package + return False + return str(browser_cfg.get("cloud_provider") or "").strip().lower() == NOUS_MANAGED_PROVIDER + + +def get_browser_backend() -> str: + """Configured browser backend key ("" = unset → default). YAML 1.1 parses an + unquoted ``off`` as False — that must mean BACKEND_DISABLED, not "unset".""" + raw = _read_browser_cfg().get("backend") + return (BACKEND_DISABLED if raw is False else "") if isinstance(raw, bool) else str(raw or "").strip().lower() + + +def is_legacy_browser_use_cloud_config(browser_cfg: dict) -> bool: + """True for pre-CLI direct-API Browser Use cloud configs. An explicit backend or + a non-Browser-Use cloud_provider wins; Camofox is selected via env var, not + cloud_provider, so a Camofox user with a stray BROWSER_USE_API_KEY keeps it.""" + if not isinstance(browser_cfg, dict) or browser_cfg.get("backend"): + return False + provider = str(browser_cfg.get("cloud_provider") or "").strip().lower() + if provider not in {"browser-use", ""} or _use_gateway(browser_cfg) or _camofox_active(" during migration"): + return False + # Profile credential: a multiplexed secondary must not inherit the default's cloud mode. + from agent.secret_scope import get_secret + return bool(get_secret("BROWSER_USE_API_KEY", "")) + + +def is_browser_use_cli_mode() -> bool: + """True when the Browser Use CLI replaces the built-in browser stack. Browser Use mode is the DEFAULT: + unset ``browser.backend`` ("") enables it whenever the CLI is runnable (installed binary or uvx); + ``browser.backend: off`` keeps the built-in browser_* tools. Camofox always falls back to the built-in + tools (Firefox, custom HTTP API, no CDP surface for the harness).""" + if _camofox_active(): + return False + backend = get_browser_backend() + return backend == _BACKEND_KEY if backend else (is_legacy_browser_use_cloud_config(_read_browser_cfg()) or _find_cli() is not None) + + +def default_downgrade_notice() -> Optional[str]: + """One-line notice when ``browser.backend`` is unset but the CLI is not runnable, so + the session fell back to the built-in tools. Rate-limited to once per 24h via a stamp file.""" + try: + if get_browser_backend() or _camofox_active() or _find_cli() is not None: + return None # explicit choice / Camofox / CLI present — nothing downgraded + stamp = Path(get_hermes_home()) / "cache" / ".browser_use_default_notice" + with contextlib.suppress(OSError): + if 0 <= time.time() - stamp.stat().st_mtime < 24 * 3600: + return None + with contextlib.suppress(OSError): + stamp.parent.mkdir(parents=True, exist_ok=True) + stamp.touch() + return ("Browser Use CLI not found — using the built-in browser tools. Run `hermes tools` " + "(Browser Automation → Browser Use) to install it, or `browser.backend: off` in config.yaml to silence this.") + except Exception as e: # pragma: no cover — a notice must never break startup + logger.debug("browser-use downgrade notice failed: %s", e) + return None + + +def _managed_bin_dir() -> str: + """$HERMES_HOME/bin — where install.sh puts uv/uvx and install_cli() links browser-use.""" + return str(Path(get_hermes_home()) / "bin") + + +def _find_cli() -> Optional[List[str]]: + """Locate the browser-use CLI, or None when it can't be run. MANAGED-FIRST: Hermes' own ``$HERMES_HOME/bin`` + copy always wins so every session drives one Hermes-controlled binary; PATH and the user-level tool dir + (~/.local/bin, or uv's %APPDATA%/uv/bin on Windows — Desktop/TUI workers may start with a minimal PATH + that omits it) are fallbacks; uvx zero-install (same probe order) is last.""" + if os.name == "nt": + appdata = os.environ.get("APPDATA") + user_bin = str(Path(appdata) / "uv" / "bin") if appdata else None + else: + user_bin = str(Path(os.path.expanduser("~")) / ".local" / "bin") + probe_paths = [p for p in (_managed_bin_dir(), None, user_bin) if p is None or p] # None = PATH + for name, argv in (("browser-use", lambda b: [b]), ("uvx", lambda b: [b, "browser-use"])): + for probe_path in probe_paths: + found = shutil.which(name, path=probe_path) + if found: + return argv(found) + return None + + +def install_cli(timeout_s: int = 600) -> Tuple[bool, str]: + """Install the browser-use CLI via ``uv tool install`` (managed uv via ``ensure_uv`` → uv on PATH), linking + the binary into ``$HERMES_HOME/bin`` (``UV_TOOL_BIN_DIR``) so ``_find_cli()`` resolves it for every profile. + Returns ``(ok, message)``; never raises. MANAGED-FIRST: only the managed copy short-circuits — a browser-use + on PATH is a user-level side install and must not block provisioning the canonical copy (version drift).""" + bin_dir = _managed_bin_dir() + managed = shutil.which("browser-use", path=bin_dir) + if managed: + return True, f"browser-use CLI already installed ({managed})" + + def _managed_uv() -> Optional[str]: + from hermes_cli.managed_uv import ensure_uv + return str(ensure_uv() or "") or None + uv_bin = _quiet(_managed_uv, None, "Managed uv bootstrap unavailable") or shutil.which("uv") + if not uv_bin: + return False, ("uv is not available and could not be bootstrapped. Install uv " + "(https://docs.astral.sh/uv/) and run `uv tool install browser-use`.") + env = {**os.environ, "UV_NO_CONFIG": "1"} + try: + Path(bin_dir).mkdir(parents=True, exist_ok=True) + env["UV_TOOL_BIN_DIR"] = bin_dir + except OSError as e: + logger.debug("Could not prepare %s: %s", bin_dir, e) + + try: + result = subprocess.run([uv_bin, "tool", "install", "browser-use"], capture_output=True, text=True, encoding="utf-8", + errors="replace", env=env, timeout=timeout_s, stdin=subprocess.DEVNULL) + except subprocess.TimeoutExpired: + return False, f"`uv tool install browser-use` timed out after {timeout_s}s" + except Exception as e: + return False, f"Failed to run `uv tool install browser-use`: {e}" + + if result.returncode != 0: + tail = "\n".join((result.stderr or result.stdout or "").strip().splitlines()[-3:]) + return False, f"`uv tool install browser-use` failed:\n{tail}" + found = _find_cli() + if not found or len(found) != 1: + return False, ("install reported success but the browser-use binary is still not resolvable — " + "run `uv tool install browser-use` manually") + return True, f"browser-use CLI installed ({found[0]})" + + +def _workspace_dir(task_id: Optional[str]) -> Optional[str]: + """Stable per-task scratch dir that persists across browser_exec calls""" + if os.environ.get("BH_AGENT_WORKSPACE"): + return os.environ["BH_AGENT_WORKSPACE"] + try: + safe = _TASK_ID_SAFE_RE.sub("_", str(task_id or "default"))[:80] or "default" + path = Path(get_hermes_home()) / "cache" / "browser-use" / "workspace" / safe + path.mkdir(parents=True, exist_ok=True) + return str(path) + except Exception as e: + logger.debug("browser_exec workspace unavailable: %s", e) + return None + + +def _find_screenshot(stdout: str, since: float) -> Optional[str]: + """Last screenshot path printed during this exec that exists and was written after + the exec started, or None.""" + for path in reversed(_IMAGE_PATH_RE.findall(stdout or "")): + try: + if os.path.isfile(path) and os.path.getmtime(path) >= since - 1: + return path + except OSError: + continue + return None + + +def _native_screenshot_result(result: Dict[str, Any], path: str) -> Optional[Dict[str, Any]]: + """Build a multimodal tool result attaching path for vision models""" + try: + from tools.vision_tools import (_EMBED_MAX_DIMENSION, _EMBED_TARGET_BYTES, + _resize_image_for_vision, _should_use_native_vision_fast_path) + if not _should_use_native_vision_fast_path(): + return None + # History-reuse cap: this data URL bakes into the tool result and is re-sent every later turn — + # same policy as the vision_analyze / browser_vision native embeds. + data_url = _resize_image_for_vision(Path(path), mime_type="image/png", max_base64_bytes=_EMBED_TARGET_BYTES, + max_dimension=_EMBED_MAX_DIMENSION, force_jpeg=True) + text = json.dumps(result, ensure_ascii=False) + attached = text + "\n\nThe screenshot from this call is attached — inspect it with your native vision." + return {"_multimodal": True, "text_summary": text, "meta": {"screenshot_path": path, "native_vision": True}, + "content": [{"type": "text", "text": attached}, {"type": "image_url", "image_url": {"url": data_url}}]} + except Exception as e: + logger.debug("Native screenshot attach failed (falling back to text): %s", e) + return None + + +def _served_profile_tag() -> str: + """``""`` outside a served-profile scope (every legacy key stays byte-identical); under a + multiplexed turn, the routed profile's home key — one profile's browser must never be handed + to another that happens to use the same session name or task id (#110032).""" + from hermes_constants import get_hermes_home_override, hermes_home_key + return "" if get_hermes_home_override() is None else hermes_home_key() + + +def _backend_cache_key(task_id: Optional[str], session_name: str = "") -> str: + """Session-cache key for a backend browser: named sessions get their own; served profiles get their own.""" + key = f"bu-named-{session_name}" if session_name else (task_id or "browser-exec-default") + tag = _served_profile_tag() + return f"{key}@{tag}" if tag else key + + +def _resolve_lightpanda_cdp(env: dict, task_id: Optional[str], session_name: str = "") -> Optional[str]: + """Point the harness at a Hermes-spawned ``lightpanda serve`` (``browser.engine: lightpanda`` and + nothing of higher precedence claimed the session). Each cache key gets its own process via the + legacy ``_get_session_info()`` (cache, reaper, atexit): private browser, own-tab preamble skipped.""" + try: + from tools.browser_tool_session import _get_session_info + from tools.browser_tool_lightpanda_fallback import _using_lightpanda_engine + if not _using_lightpanda_engine(): + return None + except Exception as e: # stubbed browser_tool in tests / engine lookup failure + logger.debug("browser engine lookup failed: %s", e) + return None + err = _export_session_cdp( + env, _get_session_info, _backend_cache_key(task_id, session_name), + lambda e: (f"Lightpanda could not be started: {e} Set browser.engine to auto " + "to use local Chrome, or switch backends via `hermes tools` → Browser Automation."), + "Lightpanda session returned no CDP endpoint. Set browser.engine to auto to use local Chrome.", + ) + if err is None: + env[_PRIVATE_BROWSER_SENTINEL] = "1" + return err + + +def _resolve_managed_chromium_cdp(env: dict, task_id: Optional[str], session_name: str = "") -> Optional[str]: + """Point the harness at Hermes' packaged Chromium, launched through agent-browser for this cache key — + the same browser the built-in tools drive. Left alone, the harness discovers the user's INSTALLED + Chrome on its default profile, which needs the chrome://inspect toggle + an Allow popup per run and + is blocked outright on Chrome >=136; on a headless box it just reports ``chrome-not-running``. + ``get cdp-url`` runs through ``_run_browser_command`` (legacy cache, inactivity reaper, atexit, Chromium + preflight/auto-install) on EVERY call: it launches the browser cold, follows a relaunch, and refreshes + the agent-browser daemon's idle timer, which never sees the harness's direct CDP traffic.""" + try: + from tools.browser_tool_session import _run_browser_command + from tools.browser_tool import _get_open_command_timeout + except Exception as e: # pragma: no cover — stubbed browser_tool in tests + logger.debug("managed chromium resolution unavailable: %s", e) + return None + res = _run_browser_command(_backend_cache_key(task_id, session_name), "get", ["cdp-url"], + timeout=_get_open_command_timeout(first_open=True)) + cdp = str(((res or {}).get("data") or {}).get("cdpUrl") or "") if (res or {}).get("success") else "" + if not cdp: + return (f"The local browser could not be started: {(res or {}).get('error') or 'agent-browser returned no CDP endpoint'} " + "Run `hermes tools` → Browser Automation to (re)install Chromium, or switch backends.") + _set_cdp_env(env, cdp) + env[_PRIVATE_BROWSER_SENTINEL] = "1" # one Chromium per cache key: nothing to share a tab with + return None + + +def _resolve_local_engine_cdp(env: dict, task_id: Optional[str], session_name: str = "") -> Optional[str]: + """Local engine (no provider / override): ``browser.engine: lightpanda`` or the packaged Chromium.""" + err = _resolve_lightpanda_cdp(env, task_id, session_name) + if err or _has_cdp_env(env): + return err + return _resolve_managed_chromium_cdp(env, task_id, session_name) + + +def _resolve_backend_cdp(env: dict, task_id: Optional[str], session_name: str = "") -> Optional[str]: + """Point the harness at the configured backend's CDP endpoint; error string on failure. + + Precedence: (1) ``BU_CDP_WS``/``BU_CDP_URL`` already in env (operator override); (2) ``BROWSER_CDP_URL`` + env / ``browser.cdp_url`` (``/browser connect``); (3) a cloud provider via the legacy ``_get_session_info()`` + so browser_exec shares the SAME session machinery (per-task cache, expiry, reaper, atexit); + (4) the local engine — ``browser.engine: lightpanda`` or Hermes' packaged Chromium via agent-browser + (never the harness's own discovery of the user's installed Chrome); (5) BU direct-API configs → None: + the CLI reaches BU cloud natively (BU_AUTOSPAWN). ``session_name`` (BU_NAME) keys the session cache so + each name gets its OWN browser — what makes named sessions concurrent-safe. + """ + if _has_cdp_env(env): + return None + try: + from tools.browser_tool_cloud import _get_cloud_provider + from tools.browser_tool_session import _get_session_info + from tools.browser_tool_cdp import _get_cdp_override + except Exception as e: # pragma: no cover — stubbed browser_tool in tests + logger.debug("browser_tool backend resolution unavailable: %s", e) + return None + override = _quiet(_get_cdp_override, "") + if override: + _set_cdp_env(env, override) + return None + provider = _quiet(_get_cloud_provider, None, "Cloud provider lookup failed") + if provider is None: + return _resolve_local_engine_cdp(env, task_id, session_name) + + # Browser Use direct-API configs: the CLI talks to BU cloud natively (BU_AUTOSPAWN / auth login) — the + # legacy provider would create a second, redundant session. Nous-gateway configs (cloud_provider: nous + # from the picker, or the pre-picker use_gateway: true) DO resolve through the provider: the gateway + # provisions the browser server-side and returns its CDP URL. + provider_key = str(getattr(provider, "name", "") or "").strip().lower() + if provider_key == _BACKEND_KEY and not _use_gateway(_read_browser_cfg()): + env[_PRIVATE_BROWSER_SENTINEL] = "1" # named BU cloud browsers are exclusive to their daemon + return None + + provider_name = type(provider).__name__ + err = _export_session_cdp( + env, _get_session_info, _backend_cache_key(task_id, session_name), + lambda e: (f"Cloud browser provider {provider_name} failed to provide a session: {e}. " + "Fix the provider configuration or switch backends via `hermes tools` → Browser Automation."), + f"Cloud browser provider {provider_name} returned no CDP endpoint, so Browser Use mode " + "cannot drive it. Switch to the built-in browser tools for this provider.", + ) + # A provider browser keyed bu-named- is exclusive to this session — the + # own-tab preamble would just leak a blank tab into it. + if err is None and session_name: + env[_PRIVATE_BROWSER_SENTINEL] = "1" + return err + + +def _resolve_real_profile_cdp(env: dict, force_local: bool) -> Optional[str]: + """Point the harness at the user's real-profile copy-browser (a SNAPSHOT of their default Chromium + profile, hermes_cli.browser_connect) when consented. Two ways in: the effective backend is already local + (no provider, CDP override, or legacy BU cloud config) → silent upgrade; or ``force_local`` (consent-gated + ``local`` arg) → the user's browser even under a cloud backend. Operator overrides (BU_CDP_* env, + /browser connect, ``browser.cdp_url``) own the session either way. Fail closed: a launch error is + returned so a consented user is never silently downgraded.""" + if not _real_profile_consented() or _has_cdp_env(env): + return None + try: + from tools.browser_tool_cdp import _get_cdp_override_raw + from tools.browser_tool_cloud import _get_cloud_provider + from tools.browser_tool_real_profile import _real_profile_cdp + except Exception as e: # pragma: no cover — stubbed browser_tool in tests + logger.debug("real-profile backend resolution unavailable: %s", e) + return None + if _quiet(_get_cdp_override_raw, ""): + return None + # Only auto-upgrade genuinely-local attaches; any cloud path (provider, provider lookup failure, or + # legacy BU cloud config) stays on its backend unless the model passes local=true. + if not force_local and (_quiet(_get_cloud_provider, object()) is not None + or is_legacy_browser_use_cloud_config(_read_browser_cfg())): + return None + cdp, err = _real_profile_cdp() + if cdp and not err: + _set_cdp_env(env, cdp) + return err or None + + +def _attach_vault_supervisor(env: dict, task_id: Optional[str]) -> None: + """Attach the per-task CDP supervisor to the browser this exec drives so ``browser_vault_fill`` has + a secret-capable WebSocket (never argv) into the SAME browser. Only CDP-routed backends expose an + endpoint; BU direct-cloud (BU_AUTOSPAWN) does not, and the vault tools report ``supervisor_required``.""" + cdp = env.get("BU_CDP_WS") or env.get("BU_CDP_URL") + if not cdp: + return + try: + from tools.browser_supervisor import SUPERVISOR_REGISTRY + from tools.browser_tool_cdp import _get_dialog_policy_config, _resolve_cdp_override + policy, timeout_s = _get_dialog_policy_config() + SUPERVISOR_REGISTRY.get_or_start(task_id=task_id or "default", cdp_url=_resolve_cdp_override(cdp), + dialog_policy=policy, dialog_timeout_s=timeout_s) + except Exception as exc: + logger.debug("browser_exec: CDP supervisor attach failed (non-fatal): %s", exc) + + +def _route_backend(env: dict, session: str, task_id: Optional[str], local: bool) -> Optional[str]: + """Resolve where the harness connects; returns an error string or None. Real-profile consent runs + BEFORE provider resolution so a hit short-circuits the cloud path via the BU_CDP_* env contract. Named + sessions compose with the backend: BU_NAME namespaces the harness daemon (IPC socket, log, pid) and on + provider backends additionally keys its own cloud browser.""" + rp_err = _resolve_real_profile_cdp(env, force_local=local) + if rp_err: + return rp_err + # local=True is only served by the real-profile route; consent off must not pretend. + if local and not _has_cdp_env(env) and not _real_profile_consented(): + return ("local=true was requested but browser.use_real_profile is off. Enable it in config.yaml " + "(browser.use_real_profile: true) or the desktop Settings → Browser section, then retry.") + return _resolve_backend_cdp(env, task_id, session_name=session) + + +def _group_popen_kwargs() -> dict: + """Popen kwargs starting the CLI in its own process group (a new session on POSIX) so a + timeout can take down every process that inherited the capture pipes, not just the CLI + child. Windows also hides the console the .cmd shim would flash (as browser_tool does).""" + def _flags() -> dict: + from hermes_cli._subprocess_compat import windows_hide_flags + si = subprocess.STARTUPINFO() + si.dwFlags |= subprocess.STARTF_USESHOWWINDOW + return {"creationflags": windows_hide_flags() | getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0), + "startupinfo": si} + return _quiet(_flags, {}, "Windows hide-flags unavailable") if os.name == "nt" else {"start_new_session": True} + + +def _clamp_timeout(timeout_s: Any) -> int: + try: + return max(_MIN_TIMEOUT_S, min(int(timeout_s), _MAX_TIMEOUT_S)) + except (TypeError, ValueError): + return _DEFAULT_TIMEOUT_S + + +# After a whole-group SIGKILL, every pipe holder is dead, so the drain below is normally +# instant; the deadline only guards against a process outside the group still holding a pipe. +_POST_KILL_DRAIN_S = 10.0 + + +def _kill_cli_process_group(proc) -> None: + """SIGKILL the CLI's whole process group (POSIX; ``start_new_session`` made pgid == pid) or, + on Windows, its process tree via ``taskkill /T /F`` — the only group-wide kill it offers.""" + if os.name == "nt": + from hermes_cli._subprocess_compat import windows_hide_flags + with contextlib.suppress(OSError, subprocess.SubprocessError): + subprocess.run(["taskkill", "/T", "/F", "/PID", str(proc.pid)], stdin=subprocess.DEVNULL, + capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10, + check=False, creationflags=windows_hide_flags()) + return + with contextlib.suppress(ProcessLookupError, PermissionError): + os.killpg(proc.pid, signal.SIGKILL) # windows-footgun: ok — POSIX only, the nt branch returned above + + +def _run_cli_killing_process_group(cmd, code, env, timeout): + """Run the CLI in its own process group and kill the whole group on timeout. + + ``subprocess.run`` only kills the direct child on ``TimeoutExpired``; a grandchild that + inherited the stdout/stderr pipes (browser_harness daemon / Chrome helper) is orphaned + still holding them, and on Windows ``run()``'s unbounded post-kill ``communicate()`` then + blocks on pipe EOF forever — so the tool call, plus its activity heartbeat, wedges (#106244). + """ + proc = subprocess.Popen( + cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, encoding="utf-8", errors="replace", env=env, **_group_popen_kwargs(), + ) + try: + stdout, stderr = proc.communicate(input=code, timeout=timeout) + except subprocess.TimeoutExpired: + _kill_cli_process_group(proc) + with contextlib.suppress(subprocess.TimeoutExpired): + proc.communicate(timeout=_POST_KILL_DRAIN_S) + raise + return subprocess.CompletedProcess(cmd, proc.returncode, stdout, stderr) + + +def browser_exec(code: str, session: str = "", timeout_s: int = _DEFAULT_TIMEOUT_S, + task_id: Optional[str] = None, local: bool = False): + """Run Python code through the browser-use CLI, and return its output""" + from tools.registry import tool_error, tool_result + if not code or not code.strip(): + return tool_error("No code provided. Pass Python that uses the pre-imported helpers, e.g. new_tab(\"https://example.com\") then print(page_info()).") + + blocked = _blocked_url_in_code(code) + if blocked: + return tool_error(blocked) + + cmd = _find_cli() + if not cmd: + return tool_error("browser-use CLI not found on PATH, and uvx is unavailable for a zero-install run. " + "Install it with `uv tool install browser-use` (or `pipx install browser-use`), " + "then run `browser-use --doctor` to verify the setup.") + + env = _base_subprocess_env() + if session: + if not _SESSION_RE.match(session): + return tool_error(f"Invalid session name {session!r}: use 1-64 letters, digits, " + "dashes, or underscores (e.g. 'r7k2').") + env["BU_NAME"] = session + route_err = _route_backend(env, session, task_id, bool(local)) + if route_err: + return tool_error(route_err) + _attach_vault_supervisor(env, task_id) + + # SHARED browser (/browser connect CDP override): pin each named session to its own tab (see + # _OWN_TAB_PREAMBLE). Private per-name browsers skip this — nothing to collide with. + private_browser = env.pop(_PRIVATE_BROWSER_SENTINEL, None) # always pop: never exported to the CLI + if session and not private_browser: + code = _OWN_TAB_PREAMBLE + code + + workspace = _workspace_dir(task_id) + if workspace: + env["BH_AGENT_WORKSPACE"] = workspace + + # BU_AUTOSPAWN makes the CLI start a Browser Use cloud browser when no local + # Chrome/CDP endpoint is reachable (their API key authenticates it) + if "BU_AUTOSPAWN" not in env and is_legacy_browser_use_cloud_config(_read_browser_cfg()): + env["BU_AUTOSPAWN"] = "1" + + timeout = _clamp_timeout(timeout_s) + started = time.time() + try: + proc = _run_cli_killing_process_group(cmd, code, env, timeout) + except subprocess.TimeoutExpired: + return tool_error(f"browser-use exec timed out after {timeout}s. The daemon may still be working; retry " + f"with a larger timeout_s (max {_MAX_TIMEOUT_S}), or split the work into several calls that " + "append to workspace files — anything already written to the workspace is preserved.") + except OSError as e: + return tool_error(f"Failed to launch browser-use CLI: {e}") + + result = {"success": proc.returncode == 0, "exit_code": proc.returncode, "output": proc.stdout} + if workspace: + result["workspace"] = workspace + if session: + result["session"] = session + stderr = (proc.stderr or "").strip() + if len(stderr) > _STDERR_CAP_CHARS: + stderr = stderr[:_STDERR_CAP_CHARS] + "\n… (stderr truncated)" + if stderr: + result["stderr"] = stderr + screenshot = _find_screenshot(proc.stdout, started) + if screenshot: + result["screenshot_path"] = screenshot + native = _native_screenshot_result(result, screenshot) + if native is not None: + return native + return tool_result(result) + + +_HEADER_BASE = ( + "Drive a real web browser via the Browser Use CLI: `code` runs as full Python (stdlib available) " + "with pre-imported browser helpers; stdout comes back in the result. Start `code` with a one-line " + "comment describing the step for the user in plain language, max 60 chars " + "(e.g. `# Searching Amazon for paper towels`) — the UI shows it as the step label.\n\n" + "STATE: the browser session and workspace persist across calls; Python variables do NOT (fresh " + "interpreter each call). The workspace dir is $BH_AGENT_WORKSPACE (also `workspace` in every result); " + "functions defined in agent_helpers.py there are auto-imported into every call. For multi-item tasks " + "('all N products / every entry'), append each batch to a JSON/CSV file in the workspace, then read it " + "back and aggregate in code — dedupe/count/sort with Python, not in your head — and verify the " + "collected count against what was asked before answering.\n\n" + "Batch each sub-procedure (navigate, wait, extract, act) into one call — do not spend a call per " + "action — but for long extractions prefer several medium calls that append to workspace files over " + "one giant call, so progress survives timeouts." +) + +_HEADER_VISION = ( + " Screenshots are attached to your context automatically: when the exec output contains a " + "capture_screenshot() path, the image arrives with this tool's result and you inspect it directly " + "with your own vision — never send browser screenshots to a separate vision tool." +) + +_HEADER_TEXT_ONLY = ( + " Your model cannot view images, so work text-first: page_info() for state, js() for " + "reading/extracting DOM text, fill_input(selector, text) for inputs, and " + "js(\"document.querySelector('…').click()\") for clicks — skip the screenshot-driven workflow described below." +) + +# Appended when the local engine is Lightpanda: no graphical renderer, and one CDP +# connection holds one page — a second Target.createTarget fails with +# TargetAlreadyLoaded (drop the new_tab() sentence once lightpanda-io/browser#1962 lands). +_HEADER_LIGHTPANDA = ( + " The local engine is Lightpanda (no graphical renderer, one page per session): capture_screenshot() " + "is unavailable, so work text-first; navigate with new_tab(url) exactly once, then goto_url(url) for " + "every later navigation — a second new_tab() fails with TargetAlreadyLoaded." +) + +# Pinned quick-reference for the CLI's pre-imported helpers, replacing the live +# ``browser-use skill`` fetch (uncontrolled third-party text in every schema: version +# drift, supply-chain exposure, byte-unstable prompt). A/B benchmarked ~equal. +_HELPERS_DIGEST = ( + "\n\nHELPERS (pre-imported): new_tab(url) opens/navigates (use for the FIRST navigation), goto_url(url) " + "navigates the current tab, wait_for_load() after navigation, page_info() summarizes the current page " + "state, js(expr) evaluates a JS expression and returns its value (js('document.title'); wrap function " + "bodies as js('(() => {...})()') — a bare '() => {...}' returns the function itself, uncalled), " + "fill_input(selector, text) types into inputs, click_at_xy(x, y) clicks viewport coordinates, " + "capture_screenshot() saves and prints a screenshot path, cdp('Domain.method', **kwargs) is raw CDP — " + "cdp('Accessibility.getFullAXTree')['nodes'] lists every element's role/name/backendDOMNodeId (filter " + "in Python before printing; it is thousands of nodes), then cdp('DOM.getBoxModel', backendNodeId=n) " + "gives click coordinates. ensure_real_tab() recovers from a stale/internal tab. Login walls: never guess " + "credentials; see the vault note below if present, otherwise stop and ask the user." +) + + +def _description_header() -> str: + """Header tailored to whether the active model can see images natively""" + if _lazy_call("tools.browser_tool_lightpanda_fallback", "lightpanda_engine_status", (False, ""), + "lightpanda engine status unavailable")[0]: # no screenshots, whatever the model sees + return _HEADER_BASE + _HEADER_TEXT_ONLY + _HEADER_LIGHTPANDA + vision = _lazy_call("tools.vision_tools", "_should_use_native_vision_fast_path", False, "") + return _HEADER_BASE + (_HEADER_VISION if vision else _HEADER_TEXT_ONLY) + + +def _dynamic_schema_overrides() -> dict: + overrides: dict = {"description": _description_header() + _HELPERS_DIGEST} + # ``local`` exists ONLY when the user consented to real-profile browsing — everyone + # else's schema carries zero extra surface. The caller memoizes on config.yaml mtime, + # so toggling consent applies next session, not mid-chat. + if _real_profile_consented(): + props = dict(BROWSER_EXEC_SCHEMA["parameters"]["properties"]) + props["local"] = { + "type": "boolean", "default": False, + "description": ("Drive the user's own local browser (a Hermes-managed copy of their real " + "default-Chromium profile, logins/cookies included) instead of the configured " + "cloud browser backend. Use when the user asks to act as themselves — their " + "accounts, their sessions. No-op when the backend is already local. Default false."), + } + overrides["parameters"] = {**BROWSER_EXEC_SCHEMA["parameters"], "properties": props} + return overrides + + +BROWSER_EXEC_SCHEMA = { + "name": "browser_exec", + # Static fallback description, used only when the CLI (and uvx) is unavailable + "description": (_HEADER_BASE + _HELPERS_DIGEST + + "\n\n(The browser-use CLI is not installed yet. Install it with `uv tool install browser-use`.)"), + "parameters": { + "type": "object", + "properties": { + "code": {"type": "string", "description": "Python code to execute using the pre-imported browser helpers. Use print(...) for any data you need back."}, + "session": {"type": "string", "description": "Named isolated browser session — its own daemon and (on cloud backends) own browser, so concurrent tasks don't share tabs. Reuse the same name on every related call; omit for the shared default session."}, + "timeout_s": {"type": "integer", "default": _DEFAULT_TIMEOUT_S, + "description": f"Max seconds to wait for the code to finish (default {_DEFAULT_TIMEOUT_S}, max {_MAX_TIMEOUT_S})."}, + }, + "required": ["code"], + }, +} + + +# browser_exec is additionally gated at tool-definition time — sessions whose toolsets +# lack ``terminal`` never see it (model_tools._compute_tool_definitions). check_fn only +# answers "is Browser Use mode configured"; surface policy lives with the session. +from tools.registry import registry + +registry.register( + name="browser_exec", + toolset="browser-use", + schema=BROWSER_EXEC_SCHEMA, + handler=lambda args, **kw: browser_exec( + code=args.get("code", ""), session=args.get("session", "") or "", + timeout_s=args.get("timeout_s", _DEFAULT_TIMEOUT_S), task_id=kw.get("task_id"), + local=bool(args.get("local", False)), + ), + check_fn=is_browser_use_cli_mode, + dynamic_schema_overrides=_dynamic_schema_overrides, + emoji="🌐", +) diff --git a/tools/clarify_gateway.py b/tools/clarify_gateway.py new file mode 100644 index 0000000000000000000000000000000000000000..e33a5ff083bdbdb012d3a68b1ef6bf10c33dd116 --- /dev/null +++ b/tools/clarify_gateway.py @@ -0,0 +1,308 @@ +"""Gateway-side clarify primitive (blocking event-based queue). The agent runs on a worker +thread while the event loop handles the user's reply, so a pending clarify is stored +module-level (same shape as ``tools.approval``) and the agent thread blocks on an ``Event`` +until an adapter button callback or the gateway text-intercept resolves it, or the timeout +fires. Adapters render inline buttons (an "Other" row flips the entry into text-capture +mode) or a numbered-list text fallback.""" + +from __future__ import annotations +import json +import logging +import threading +import time +from dataclasses import dataclass, field +from typing import Callable, Dict, List, Optional + +logger = logging.getLogger(__name__) + + +@dataclass +class _ClarifyEntry: + """One pending clarify request inside a gateway session.""" + clarify_id: str + session_key: str + question: str + choices: Optional[List[str]] + multi_select: bool = False + event: threading.Event = field(default_factory=threading.Event) + response: Optional[str] = None + awaiting_text: bool = False # set when user picked "Other" or clarify is open-ended + + +_lock = threading.RLock() +_entries: Dict[str, _ClarifyEntry] = {} # clarify_id -> entry (button callbacks) +_session_index: Dict[str, List[str]] = {} # session_key -> [clarify_id] FIFO (text intercept, cleanup) +# Per-session notify callbacks (gateway -> adapter bridge); mirrors tools.approval. Tests clear it. +_notify_cbs: Dict[str, Callable[[_ClarifyEntry], None]] = {} + +# Outcomes for typed clarify replies. Gateway cancels the pending prompt on +# free prose (deadlock break) but keeps it armed for a retryable bad selection. +TEXT_RESOLVED = "resolved" +TEXT_REJECTED_PROSE = "rejected_prose" +TEXT_REJECTED_SELECTION = "rejected_selection" +TEXT_NO_PENDING = "no_pending" + + +def register(clarify_id: str, session_key: str, question: str, choices: Optional[List[str]], + multi_select: bool = False) -> _ClarifyEntry: + """Register a pending clarify request; caller then blocks on ``wait_for_response``. + Open-ended (no choices) entries start in text mode: the next message IS the response.""" + entry = _ClarifyEntry(clarify_id, session_key, question, list(choices) if choices else None, + bool(multi_select) and bool(choices), awaiting_text=not bool(choices)) + with _lock: + _entries[clarify_id] = entry + _session_index.setdefault(session_key, []).append(clarify_id) + return entry + + +def wait_for_response(clarify_id: str, timeout: float) -> Optional[str]: + """Block until the entry resolves or ``timeout`` (``<= 0`` = unlimited) elapses; None on + timeout/unknown id. Polls in 1s slices so the inactivity heartbeat keeps firing (a + single long ``Event.wait`` would let the gateway watchdog kill a live prompt).""" + with _lock: + entry = _entries.get(clarify_id) + if entry is None: + return None + try: + from tools.environments.base import touch_activity_if_due + except Exception: # pragma: no cover - optional + touch_activity_if_due = None + deadline = None if timeout is None or float(timeout) <= 0.0 else time.monotonic() + float(timeout) + activity_state = {"last_touch": time.monotonic(), "start": time.monotonic()} + while True: + remaining = 1.0 if deadline is None else deadline - time.monotonic() + if remaining <= 0 or entry.event.wait(timeout=min(1.0, remaining)): + break + # Periodic activity touch so the gateway's inactivity timeout doesn't kill the agent during long + # code execution (#10807). + if touch_activity_if_due is not None: + touch_activity_if_due(activity_state, "waiting for user clarify response") + with _lock: + _entries.pop(clarify_id, None) # regardless of outcome + ids = _session_index.get(entry.session_key) or [] + if clarify_id in ids: + ids.remove(clarify_id) + if not ids: + _session_index.pop(entry.session_key, None) + return entry.response + + +def resolve_gateway_clarify(clarify_id: str, response: str) -> bool: + """Unblock the waiter on ``clarify_id``; False if already resolved/expired/unknown.""" + with _lock: + entry = _entries.get(clarify_id) + if entry is None or entry.event.is_set(): + return False + entry.response = str(response) if response is not None else "" + entry.event.set() + return True + + +def get_pending_for_session(session_key: str, *, include_choice_prompts: bool = False) -> Optional[_ClarifyEntry]: + """Oldest pending entry awaiting free text (open-ended, or after "Other"); + ``include_choice_prompts=True`` returns the oldest unresolved entry of any kind (user + typed at an active choice prompt: resolve it rather than queue a follow-up turn).""" + with _lock: + for cid in _session_index.get(session_key) or []: + entry = _entries.get(cid) + if entry is not None and (include_choice_prompts or entry.awaiting_text): + return entry + return None + + +def _match_label(text: str, choices: List[str]) -> Optional[str]: + """Stripped choice text matching ``text`` case-insensitively, ignoring the '(Recommended)' + suffix the first choice carries by the time it reaches adapters; None if no match.""" + from tools.clarify_tool import strip_recommended + wanted = strip_recommended(text).casefold() + for choice in choices: + if strip_recommended(str(choice)).casefold() == wanted: + return str(choice).strip() + return None + + +def _split_tokens(text: str) -> Optional[List[str]]: + """Comma-separated tokens, or space-separated all-numeric tokens ("1 3"); else None.""" + if "," in text: + return [t.strip() for t in text.split(",") if t.strip()] + parts = text.split() + return parts if len(parts) > 1 and all(p.isdigit() for p in parts) else None + + +def _is_int(text: str) -> bool: + try: + int(text) + return True + except ValueError: + return False + + +def _selection_attempt_tokens(text: str, choices: Optional[List[str]] = None) -> Optional[List[str]]: + """Tokens when ``text`` looks like a typed selection (bare int, comma list, + all-numeric space list); None for free prose so the gateway can release the + clarify. Comma-list labels may span up to the longest choice's word count.""" + stripped = str(text).strip() + if not stripped: + return None + tokens = _split_tokens(stripped) + if tokens is None: + digits = stripped[1:] if stripped.startswith("-") else stripped + return [stripped] if digits.isdigit() or _is_int(stripped) else None + if "," not in stripped or not tokens: + return tokens or None + max_words = max(1, max((len(str(c).split()) for c in choices or []), default=1)) + return tokens if all(t.isdigit() or len(t.split()) <= max_words for t in tokens) else None + + +def _coerce_text_response(entry: _ClarifyEntry, response: str) -> Optional[str]: + """Accepted value for a typed reply, or None on any rejection.""" + return _coerce_text_response_detailed(entry, response)[0] + + +def _coerce_text_response_detailed(entry: _ClarifyEntry, response: str) -> tuple[Optional[str], Optional[str]]: + """Map a typed reply to ``(value, None)`` or ``(None, reason)``: ``"invalid_selection"`` + (selection-shaped but out of range/unrecognised — keep the clarify armed for a retry) or + ``"prose"`` (free text on a native choice prompt — the gateway may cancel and route normally + so a redirect-to-steer path cannot deadlock behind the waiting tool). Open-ended entries and + ``awaiting_text`` accept any text; numeric picks and exact labels always resolve; multi-select + returns a JSON array string (decoded tool-side); one bad token rejects the whole reply.""" + text = str(response).strip() + if not entry.choices: + return text, None + if entry.multi_select: + coerced = _coerce_multi_select_text(entry, text) + selection_shaped = _selection_attempt_tokens(text, entry.choices) is not None + else: + # Out-of-range / non-canonical integer is a failed selection, not prose. + selection_shaped = _is_int(text) + idx = int(text) - 1 if selection_shaped else -1 + coerced = entry.choices[idx] if 0 <= idx < len(entry.choices) else _match_label(text, entry.choices) + if coerced is not None: + return coerced, None + if entry.awaiting_text: + return text, None + return None, "invalid_selection" if selection_shaped else "prose" + + +def _coerce_multi_select_text(entry: _ClarifyEntry, text: str) -> Optional[str]: + """Parse "1,3" / "1 3" / "staging, prod" into a JSON array of choice labels; + None when any token is out of range or unrecognised (reject the whole reply).""" + choices, selected = entry.choices or [], [] + if not text: + return None + tokens = _split_tokens(text) + for token in [text] if tokens is None else tokens: + if token.isdigit(): + idx = int(token) - 1 + label = str(choices[idx]).strip() if 0 <= idx < len(choices) else None + else: + label = _match_label(token, choices) + if label is None: + return None + if label not in selected: + selected.append(label) + return json.dumps(selected, ensure_ascii=False) if selected else None + + +def attempt_text_response_for_session(session_key: str, response: str) -> str: + """Try to resolve the oldest pending clarify from typed text; returns a TEXT_* outcome.""" + entry = get_pending_for_session(session_key, include_choice_prompts=True) + if entry is None: + return TEXT_NO_PENDING + coerced, reason = _coerce_text_response_detailed(entry, response) + if coerced is None: + return TEXT_REJECTED_SELECTION if reason == "invalid_selection" else TEXT_REJECTED_PROSE + if resolve_gateway_clarify(entry.clarify_id, coerced): + return TEXT_RESOLVED + return TEXT_NO_PENDING # lost a race with a button/callback resolution — no work left + + +def resolve_text_response_for_session(session_key: str, response: str) -> bool: + """True only when the typed reply was accepted and the waiter unblocked.""" + return attempt_text_response_for_session(session_key, response) == TEXT_RESOLVED + + +def mark_awaiting_text(clarify_id: str) -> bool: + """Flip an entry into text-capture mode (user picked 'Other'); False if unknown.""" + with _lock: + entry = _entries.get(clarify_id) + if entry is not None: + entry.awaiting_text = True + return entry is not None + + +def has_pending(session_key: str) -> bool: + """True when this session has at least one pending clarify entry.""" + with _lock: + return any(_entries.get(cid) is not None for cid in _session_index.get(session_key) or []) + + +def clear_session(session_key: str) -> int: + """Drop every pending clarify for a session (``/new``, shutdown, cached-agent eviction) so + blocked agent threads don't outlive it; returns how many were cancelled. Cancelled waiters + see "" (callers tell it from a real reply only via their own timeout bookkeeping; most treat + any falsy result as no response). First-writer-wins: an already-set entry was answered for + real, so it is dropped but its response preserved. The loop stays inside the lock so a button + callback cannot slip between pop and check; entries go regardless of state so a cleared + session is never resurrected by late callbacks.""" + with _lock: + cancelled = 0 + for entry in (_entries.pop(cid, None) for cid in list(_session_index.pop(session_key, []) or [])): + if entry is None or entry.event.is_set(): + continue + entry.response = "" + entry.event.set() + cancelled += 1 + return cancelled + + +def resolve_clarify_timeout(config: dict) -> int: + """Clarify timeout (seconds): legacy ``clarify.timeout`` if explicitly set, else + ``agent.clarify_timeout``, else 3600 — the single source of truth for every surface + (gateway, CLI, TUI). ``<= 0`` is kept verbatim (unlimited); non-numeric -> 3600.""" + raw = (config.get("clarify") or {}).get("timeout") + if raw is None: + raw = (config.get("agent") or {}).get("clarify_timeout", 3600) + try: + return int(raw) + except (TypeError, ValueError): + return 3600 + + +def get_clarify_timeout() -> int: + """Clarify timeout from config.yaml; 0/negative = unlimited. Default 3600: long enough + that a user who stepped away still finds a live entry when they tap, short enough that + an abandoned prompt eventually unblocks the agent thread instead of pinning the guard. + + The old 600s default evicted the entry mid-think, so a late tap landed on a dead entry and the agent + hung on ``running: clarify`` (#32762). + """ + try: + from hermes_cli.config import load_config + return resolve_clarify_timeout(load_config() or {}) + except Exception: + return 3600 + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. + +def get_notify(session_key: str) -> Optional[Callable[[_ClarifyEntry], None]]: + with _lock: + return _notify_cbs.get(session_key) + +def register_notify(session_key: str, cb: Callable[[_ClarifyEntry], None]) -> None: + """Register a per-session notify callback used by ``clarify_callback``.""" + with _lock: + _notify_cbs[session_key] = cb + +def unregister_notify(session_key: str) -> None: + """Drop the per-session notify callback and cancel any pending clarify entries.""" + with _lock: + _notify_cbs.pop(session_key, None) + # Cancel any pending entries so blocked threads unwind when the run + # ends (interrupt, completion, gateway shutdown). + clear_session(session_key) +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/clarify_tool.py b/tools/clarify_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..7cf852221f2fb2ca8382d08e79763421baf2a388 --- /dev/null +++ b/tools/clarify_tool.py @@ -0,0 +1,311 @@ +"""Clarify tool: structured multiple-choice / open-ended questions to the user. +Schema, validation and a thin dispatcher; the UI lives in a platform-provided +callback (cli.py, gateway/run.py, tui_gateway).""" + +import inspect +import json +from typing import Dict, List, Optional, Callable + +MAX_CHOICES = 4 # the UI always appends an "Other (type your answer)" row +MAX_QUESTIONS = 5 # independent questions per batch call +# Canonical timeout sentinel. The CLI returns this exact text; the batch loop +# treats it (like ``None``) as "the user walked away" and aborts remaining questions. +TIMEOUT_RESPONSE = ("The user did not provide a response within the time limit. " + "Use your best judgement to make the choice and proceed.") +# Applied to the first choice here (not per-surface) so every adapter renders it identically. +RECOMMENDED_LABEL = "(Recommended)" +_UNAVAILABLE = "Clarify tool is not available in this execution context." + + +def _flatten_choice(c) -> str: + """Coerce one choice to display text. LLMs sometimes emit dict-shaped choices and ``str(c)`` + would leak the repr onto every surface and back as the answer; unwrap order ``label`` > + ``description`` > ``text`` > ``title`` (``name``/``value`` excluded: raw component enums, + not labels). No match -> "" and dropped: no choice beats a garbage label.""" + if isinstance(c, str): + return c.strip() + if isinstance(c, dict): + return next((v.strip() for k in ("label", "description", "text", "title") + if isinstance(v := c.get(k), str) and v.strip()), "") + if isinstance(c, (list, tuple)): + return " ".join(_flatten_choice(x) for x in c).strip() + return "" if c is None else str(c).strip() + + +def mark_recommended(choices: List[str]) -> List[str]: + """Suffix the first choice (schema says best-first) with RECOMMENDED_LABEL; idempotent, + and a lone choice is left untouched (nothing to prefer it over).""" + first = str(choices[0]).strip() if choices else "" + if len(choices) < 2 or first != strip_recommended(first): + return choices + return [f"{first} {RECOMMENDED_LABEL}"] + list(choices[1:]) + + +def strip_recommended(text: str) -> str: + """Remove the recommendation label so presentation never leaks into ``user_response``.""" + stripped = str(text).strip() + if stripped.casefold().endswith(RECOMMENDED_LABEL.casefold()): + return stripped[: -len(RECOMMENDED_LABEL)].strip() + return stripped + + +def _accepts_kwarg(callback, name: str) -> bool: + """Signature-inspect (never a TypeError retry, which could re-prompt the user) whether + ``callback`` takes ``name`` or ``**kwargs``; non-introspectable callables are legacy.""" + try: + params = inspect.signature(callback).parameters + except (TypeError, ValueError): + return False + return name in params or any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()) + + +def _invoke_callback(callback, question, choices, multi_select): + """Invoke the platform callback, passing multi_select if supported.""" + if _accepts_kwarg(callback, "multi_select"): + return callback(question, choices, multi_select=multi_select) + return callback(question, choices) + + +def _json_as(raw: str, kind): + """``json.loads(raw)`` when it decodes to an instance of ``kind``, else None.""" + try: + parsed = json.loads(raw) + except json.JSONDecodeError: + return None + return parsed if isinstance(parsed, kind) else None + + +def _parse_multi_select_response(raw_response) -> List[str]: + """Parse a list / JSON array / comma-separated reply into stripped non-empty strings.""" + items = raw_response + if not isinstance(items, list): + raw = str(items).strip() + items = _json_as(raw, list) if raw.startswith("[") else None + if items is None: + items = raw.split(",") + return [str(r).strip() for r in items if str(r).strip()] + + +def _clean_answer(raw, multi: bool): + """Strip presentation (the label, multi-select JSON) from a locked answer.""" + return [strip_recommended(r) for r in _parse_multi_select_response(raw)] if multi else strip_recommended(raw) + + +def _clean_choices(choices: list) -> Optional[List[str]]: + """Flatten, drop empties, cap at MAX_CHOICES; None when nothing survives (open-ended).""" + cleaned = [s for s in (_flatten_choice(c) for c in choices) if s] + return cleaned[:MAX_CHOICES] or None + + +def _is_timeout(raw) -> bool: + return raw is None or (isinstance(raw, str) and raw.strip() == TIMEOUT_RESPONSE) + + +# ============================================================================= Batch (multi-question) +# support — issue #18450 ============================================================================= +def _normalize_questions(questions) -> tuple: + """Validate the ``questions`` batch param -> ``(normalized, error)``; an empty list gives + ``(None, None)`` (fall back to the single-question path). Entries carry ``qid`` (stable + wire id ``q`` surfaces key answers by; the model's ``id`` is unvalidated text, only + echoed), ``question``, decorated ``choices``, bare ``choices_offered``, ``multi_select``.""" + if not isinstance(questions, list): + return None, "questions must be an array of question objects." + if not questions: + return None, None + if len(questions) > MAX_QUESTIONS: + return None, f"questions supports at most {MAX_QUESTIONS} items." + normalized = [] + for index, item in enumerate(questions): + if isinstance(item, str): # tolerate bare-string items: LLMs sometimes send ["Q1?", "Q2?"] + item = {"question": item} + if not isinstance(item, dict): + return None, f"questions[{index}] must be an object with a 'question'." + text = str(item.get("question") or "").strip() + if not text: + return None, f"questions[{index}].question must be non-empty text." + choices = item.get("choices") + if choices is not None: + if not isinstance(choices, list): + return None, f"questions[{index}].choices must be a list." + choices = _clean_choices(choices) + normalized.append({ + "qid": f"q{index}", "id": str(item.get("id") or "").strip() or None, "question": text, + "choices": mark_recommended(list(choices)) if choices else None, + "choices_offered": list(choices) if choices else None, + "multi_select": bool(item.get("multi_select")) and bool(choices)}) + return normalized, None + + +def _batch_result(normalized: List[dict], answers: dict, timed_out: bool) -> str: + """Batch result JSON; unanswered -> "". The top-level ``timed_out`` flag (present only when + true) tells the agent whether blanks are deliberate skips or the user walking away.""" + responses = [] + for entry in normalized: + raw = answers.get(entry["qid"]) + responses.append({ + **({"id": entry["id"]} if entry["id"] else {}), + "question": entry["question"], "choices_offered": entry["choices_offered"], + "user_response": _clean_answer(raw, entry["multi_select"]) if raw else ""}) + result: Dict[str, object] = {"responses": responses} + if timed_out: + result["timed_out"] = True + return json.dumps(result, ensure_ascii=False) + + +def _run_batch(normalized: List[dict], callback, question: str) -> str: + """Dispatch a validated batch. Batch-capable callbacks (``questions`` kwarg) get the + whole list once and reply ``{"answers": {qid: raw}, "timed_out"?}`` as a dict or JSON + string (the tui_gateway bridge only carries strings); any other falsy/unparseable reply + is a cancel-all (mirrors the single-question skip). Legacy callbacks are looped per + question: an empty answer is a skip, a timeout (``None`` or the sentinel) means the user + walked away so the loop aborts instead of pestering them; earlier answers are kept.""" + answers: dict = {} + timed_out = False + if _accepts_kwarg(callback, "questions"): + raw = callback(question, None, questions=normalized) + timed_out = _is_timeout(raw) + if isinstance(raw, str): + raw = _json_as(raw, dict) # the sentinel is not JSON -> None, timed_out stays True + if isinstance(raw, dict): + answers = dict(raw.get("answers") or {}) + timed_out = bool(raw.get("timed_out")) + return _batch_result(normalized, answers, timed_out) + for entry in normalized: + raw = _invoke_callback(callback, entry["question"], entry["choices"], entry["multi_select"]) + if _is_timeout(raw): + timed_out = True + break + answers[entry["qid"]] = raw + return _batch_result(normalized, answers, timed_out) + + +def clarify_tool(question: str, choices: Optional[List[str]] = None, multi_select: bool = False, + questions: Optional[List[dict]] = None, callback: Optional[Callable] = None) -> str: + """Ask one question (``question``/``choices``/``multi_select``) or a batch (``questions`` + wins when non-empty). ``callback(question, choices, multi_select=False) -> str`` is + platform injected (batch-capable ones also take ``questions=``). Returns result JSON. + + Args: question: The question text to present. choices: Up to 4 predefined answer choices. When + omitted the question is purely open-ended. multi_select: When True, the user can select multiple choices + (checkboxes). The ``user_response`` in the output JSON will be a list of strings instead of a single + string. Has no effect when ``choices`` is omitted. questions: Up to 5 independent questions asked as + one batch (issue #18450). When present (non-empty), the single ``question``/``choices``/``multi_select`` + parameters are ignored and the result JSON is ``{"responses": [...]}`` (plus ``"timed_out": true`` when + the user stopped answering partway). callback: Platform-provided function that handles the actual UI + interaction. Batch-capable platforms additionally accept a ``questions`` keyword and receive the + normalized list in one call; platforms without it are looped one question at a time. Injected by the + agent runner (cli.py / gateway). + """ + if questions is not None: + normalized, error = _normalize_questions(questions) + if error: + return tool_error(error) + if normalized: + if callback is None: + return tool_error(_UNAVAILABLE) + try: + return _run_batch(normalized, callback, str(question or "").strip()) + except Exception as exc: + return tool_error(f"Failed to get user input: {exc}") + # Empty questions array → fall through to the single-question path. + if not question or not question.strip(): + return tool_error("No question provided. Pass questions=[{question: '...', " + "choices?: [...], multi_select?: bool}, ...] — a single question " + "is a one-entry array.") + question = question.strip() + if choices is not None: + if not isinstance(choices, list): + return tool_error("choices must be a list of strings.") + choices = _clean_choices(choices) + if callback is None: + return tool_error(_UNAVAILABLE) + # The bare list goes back to the agent; the "(Recommended)" label is presentation only. + shown = mark_recommended(choices) if choices is not None else None + try: + raw_response = _invoke_callback(callback, question, shown, multi_select) + except Exception as exc: + return tool_error(f"Failed to get user input: {exc}") + return json.dumps({"question": question, "choices_offered": choices, + "user_response": _clean_answer(raw_response, multi_select and choices is not None)}, + ensure_ascii=False) + + +def check_clarify_requirements() -> bool: + """Clarify tool has no external requirements -- always available.""" + return True + + +CLARIFY_SCHEMA = { + "name": "clarify", + "description": ( + "Ask the user one or more questions when you need a decision, " + "clarification, or feedback before proceeding. Pass every question " + f"in `questions` (1-{MAX_QUESTIONS} entries) — a single question is a " + "one-entry array, and several INDEPENDENT questions belong in ONE " + "call (one form beats a chain of clarify calls; if one answer would " + "change another question, ask separately). Per question: " + f"single-select (up to {MAX_CHOICES} choices — put your recommended " + "option FIRST, the UI marks it '(Recommended)' and auto-appends an " + "'Other' free-text row), multi-select (multi_select=true), or " + "open-ended (omit choices). Options go ONLY in `choices`, never " + "enumerated inside the question text (choices render as pickable " + "rows; options written into the question are dead prose the user " + "can't click). Result: {responses: [...]} in question order (plus " + "timed_out=true if the user stopped part-way). Prefer deciding " + "low-stakes questions yourself; don't use this for dangerous-command " + "confirmation (the terminal tool handles that)." + ), + "parameters": { + "type": "object", + "properties": { + "questions": { + "type": "array", + "minItems": 1, + "maxItems": MAX_QUESTIONS, + "description": ( + "The question(s). Each: question text (options excluded), " + "optional choices (recommended first; omit for free-text), " + "optional multi_select. Responses come back in question " + "order with the question text echoed." + ), + "items": { + "type": "object", + "properties": { + "question": {"type": "string"}, + "choices": { + "type": "array", + "items": {"type": "string"}, + "maxItems": MAX_CHOICES, + }, + "multi_select": {"type": "boolean"}, + }, + "required": ["question"], + }, + }, + # NOTE: the handler also accepts (unadvertised): a per-question + # `id` (echoed in the matching response — redundant since rows + # carry the question text and preserve order), and the legacy + # single-question shape (`question` + `choices` + `multi_select` + # at top level; a top-level `question` beside `questions` is the + # batch form's title). One documented way to call. + }, + "required": ["questions"], + }, +} + +# --- Registry --- +from tools.registry import registry, tool_error + +registry.register( + name="clarify", + toolset="clarify", + schema=CLARIFY_SCHEMA, + handler=lambda args, **kw: clarify_tool( + question=args.get("question", ""), + choices=args.get("choices"), + multi_select=args.get("multi_select", False), + questions=args.get("questions"), + callback=kw.get("callback")), + check_fn=check_clarify_requirements, + emoji="❓", +) diff --git a/tools/close_preview_tool.py b/tools/close_preview_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..d04c5a3b4ddae94a4a66160f80b7280d2766ce46 --- /dev/null +++ b/tools/close_preview_tool.py @@ -0,0 +1,64 @@ +"""Close the Hermes desktop GUI's preview pane, or one tab (``preview.close``). +Registration lives in `desktop_preview`. The renderer drops the matching tab — or +the whole pane when no url is given — only for the window that asked.""" + +from tools import desktop_ui +from tools.open_preview_tool import _normalize_target + + +def close_preview_tool(url: str = "") -> str: + """Ask the desktop GUI to close the preview pane, or the tab for ``url``.""" + target = _normalize_target(url or "") + return desktop_ui.emit_or_error( + "preview.close", {"url": target}, "Failed to close the preview pane: ", + "The preview pane is only available in the Hermes desktop app.", {"success": True, "url": target}, + ) + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. +import json # noqa: F401,E402 + +CLOSE_PREVIEW_SCHEMA = { + "name": "close_preview", + "description": ( + "Close the preview pane beside the chat in the Hermes desktop app, or one " + "tab inside it. Use this when the user asks to close, hide, or dismiss the " + "preview — e.g. \"close the preview pane\", \"close cnn.com\", \"hide the " + "preview\". Omit url to close the whole pane (every tab). Pass a web URL, " + "localhost address, or file path to close only that tab. Counterpart of " + "open_preview." + ), + "parameters": { + "type": "object", + "properties": { + "url": { + "type": "string", + "description": ( + "Optional. The tab to close: a web URL (https://… or a bare " + "domain), a localhost URL, or a file path. Omit to close the " + "whole preview pane." + ), + }, + }, + }, +} + + +_PLUGIN_COMPAT_LAZY = { + 'registry': ('tools.registry', 'registry'), + 'tool_error': ('tools.registry', 'tool_error'), +} + + +def __getattr__(name): # PEP 562 — lazy so no import cycles + target = _PLUGIN_COMPAT_LAZY.get(name) + if target is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + import importlib + from hermes_cli.plugin_compat import warn_once + warn_once(__name__, name, *target) + return getattr(importlib.import_module(target[0]), target[1]) +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/code_execution_rpc.py b/tools/code_execution_rpc.py new file mode 100644 index 0000000000000000000000000000000000000000..eae6ccc6d88164675be0381aa41c36915a68f76f --- /dev/null +++ b/tools/code_execution_rpc.py @@ -0,0 +1,183 @@ +"""Host-side RPC servers for execute_code sandboxes. + +Two transports share one request pipeline (token check → allow-list → call +budget → dispatch under output silence → log): ``_rpc_server_loop`` serves the +local UDS/TCP socket, ``_rpc_poll_loop`` polls a remote filesystem for request +files via ``env.execute()``. +""" + +import base64 +import json +import logging +import secrets +import shlex +import socket +import threading +import time + +from agent.thread_scoped_output import thread_scoped_silence +from tools.registry import tool_error + +# Logger name kept as the origin module's so existing log expectations hold. +logger = logging.getLogger("tools.code_execution_tool") + +# Terminal parameters that must not be used from ephemeral sandbox scripts. +_TERMINAL_BLOCKED_PARAMS = {"background", "pty", "notify", "notify_on_complete", "watch_patterns"} + + +def _default_dispatch(task_id): + from model_tools import handle_function_call + return lambda tool_name, tool_args: handle_function_call(tool_name, tool_args, task_id=task_id) + + +def _rpc_token_ok(request: dict, rpc_token: str) -> bool: + """Constant-time token check; an empty server token fails closed. Compared as bytes: + compare_digest raises TypeError on a non-ASCII str, and the token is script-supplied JSON.""" + return bool(rpc_token) and secrets.compare_digest( + str(request.get("token") or "").encode(), rpc_token.encode() + ) + + +def _handle_rpc_request(request: dict, *, allowed_tools: frozenset, tool_call_counter: list, + max_tool_calls: int, dispatch, tool_call_log: list, call_start: float, + where: str) -> str: + """Enforce allow-list + budget, then dispatch one authenticated request. Only a dispatched + call consumes budget and is logged; refusals are free.""" + tool_name = request.get("tool", "") + tool_args = request.get("args", {}) + if tool_name not in allowed_tools: + return tool_error(f"Tool '{tool_name}' is not available in execute_code. " + f"Available: {', '.join(sorted(allowed_tools))}") + if tool_call_counter[0] >= max_tool_calls: + return tool_error(f"Tool call limit reached ({max_tool_calls}). " + "No more tool calls allowed in this execution.") + if tool_name == "terminal" and isinstance(tool_args, dict): + for param in _TERMINAL_BLOCKED_PARAMS: + tool_args.pop(param, None) + # Silence handler status prints so they don't leak into the CLI spinner. + try: + with thread_scoped_silence(): + result = dispatch(tool_name, tool_args) + except Exception as exc: + logger.error("Tool call failed in %s: %s", where, exc, exc_info=True) + result = tool_error(str(exc)) + tool_call_counter[0] += 1 + tool_call_log.append({"tool": tool_name, "args_preview": str(tool_args)[:80], + "duration": round(time.monotonic() - call_start, 2)}) + return result + + +def _rpc_server_loop(server_sock: socket.socket, task_id: str, tool_call_log: list, + tool_call_counter: list, max_tool_calls: int, allowed_tools: frozenset, + stop_event: threading.Event, rpc_token: str, dispatch=None): + """Accept one client and serve newline-delimited JSON requests until it disconnects, idles + 300s, or the call limit is reached. ``tool_call_counter`` is a mutable ``[int]``. ``dispatch`` + overrides how an allowed, budgeted call runs: per-call sandboxes use the default (the thread + carries the cell's context); session kernels rebind each call to the CURRENT cell's authority. + """ + if dispatch is None: + dispatch = _default_dispatch(task_id) + conn = None + try: + server_sock.settimeout(0.05) + while not stop_event.is_set(): + try: + conn, _ = server_sock.accept() + break + except socket.timeout: + continue + if conn is None: + return + conn.settimeout(300) + buf = b"" + while True: + try: + chunk = conn.recv(65536) + except socket.timeout: + break + if not chunk: + break + buf += chunk + while b"\n" in buf: + line, buf = buf.split(b"\n", 1) + line = line.strip() + if not line: + continue + call_start = time.monotonic() + try: + request = json.loads(line.decode()) + except (json.JSONDecodeError, UnicodeDecodeError) as exc: + resp = tool_error(f"Invalid RPC request: {exc}") + else: + resp = _handle_rpc_request( + request, allowed_tools=allowed_tools, tool_call_counter=tool_call_counter, + max_tool_calls=max_tool_calls, dispatch=dispatch, tool_call_log=tool_call_log, + call_start=call_start, where="sandbox", + ) if _rpc_token_ok(request, rpc_token) else tool_error("Unauthorized RPC request") + conn.sendall((resp + "\n").encode()) + except socket.timeout: + logger.debug("RPC listener socket timeout") + except OSError as e: + logger.debug("RPC listener socket error: %s", e, exc_info=True) + finally: + if conn: + try: + conn.close() + except OSError as e: + logger.debug("RPC conn close error: %s", e) + + +def _rpc_poll_loop(env, rpc_dir: str, task_id: str, tool_call_log: list, tool_call_counter: list, + max_tool_calls: int, allowed_tools: frozenset, stop_event: threading.Event, + rpc_token: str): + """Poll the remote filesystem for request files and answer them. Background thread; each + ``env.execute()`` is an independent process, so this is safe alongside the script-execution + thread. Malformed or unauthorized requests are removed without a response.""" + dispatch = _default_dispatch(task_id) + poll_interval = 0.1 + quoted_rpc_dir = shlex.quote(rpc_dir) + while not stop_event.is_set(): + try: + ls_result = env.execute(f"ls -1 {quoted_rpc_dir}/req_* 2>/dev/null || true", cwd="/", timeout=10) + output = ls_result.get("output", "").strip() + if not output: + stop_event.wait(poll_interval) + continue + req_files = sorted(f for f in (line.strip() for line in output.split("\n")) + if f and not f.endswith(".tmp") and "/req_" in f) + for req_file in req_files: + if stop_event.is_set(): + break + call_start = time.monotonic() + quoted_req_file = shlex.quote(req_file) + read_result = env.execute(f"cat {quoted_req_file}", cwd="/", timeout=10) + try: + request = json.loads(read_result.get("output", "")) + except (json.JSONDecodeError, ValueError): + logger.debug("Malformed RPC request in %s", req_file) + env.execute(f"rm -f {quoted_req_file}", cwd="/", timeout=5) + continue + if not _rpc_token_ok(request, rpc_token): + logger.debug("Unauthorized RPC request in %s", req_file) + env.execute(f"rm -f {quoted_req_file}", cwd="/", timeout=5) + continue + tool_result = _handle_rpc_request( + request, allowed_tools=allowed_tools, tool_call_counter=tool_call_counter, + max_tool_calls=max_tool_calls, dispatch=dispatch, tool_call_log=tool_call_log, + call_start=call_start, where="remote sandbox", + ) + # Write the response atomically (tmp + rename) via echo piping — + # Modal doesn't reliably deliver stdin_data to chained commands. + quoted_res_file = shlex.quote(f"{rpc_dir}/res_{request.get('seq', 0):06d}") + encoded_result = base64.b64encode(tool_result.encode("utf-8")).decode("ascii") + env.execute( + f"echo '{encoded_result}' | base64 -d > {quoted_res_file}.tmp" + f" && mv {quoted_res_file}.tmp {quoted_res_file}", + cwd="/", timeout=60, + ) + env.execute(f"rm -f {quoted_req_file}", cwd="/", timeout=5) + except Exception as e: + if not stop_event.is_set(): + logger.debug("RPC poll error: %s", e, exc_info=True) + if not stop_event.is_set(): + stop_event.wait(poll_interval) diff --git a/tools/cronjob_job_args.py b/tools/cronjob_job_args.py new file mode 100644 index 0000000000000000000000000000000000000000..aaa9503f77f7aea411586b7363576b174108e8b4 --- /dev/null +++ b/tools/cronjob_job_args.py @@ -0,0 +1,420 @@ +"""Cron job argument normalization, validation and result shaping (re-exported by +tools/cronjob_tools.py).""" + +import logging +from typing import Any, Dict, List, Optional, Union + +from cron.jobs import effective_job_state + +# Logger parity with the origin module. +logger = logging.getLogger("tools.cronjob_tools") + + +def _origin_from_env() -> Optional[Dict[str, str]]: + from gateway.session_context import get_session_env + origin_platform = get_session_env("HERMES_SESSION_PLATFORM") + origin_chat_id = get_session_env("HERMES_SESSION_CHAT_ID") + if not (origin_platform and origin_chat_id): + return None + thread_id = get_session_env("HERMES_SESSION_THREAD_ID") or None + # Slack stamps every TOP-LEVEL message's own id as the session thread (a per-message + # KEY, not a location); persisting it would pin all future deliveries inside an + # ephemeral thread, so thread == creating message id is synthetic and dropped. + if thread_id and origin_platform == "slack": + message_id = get_session_env("HERMES_SESSION_MESSAGE_ID") or None + if message_id and str(thread_id) == str(message_id): + logger.debug( + "Cron origin: dropping synthetic per-message Slack " + "thread_id=%s (== creation message id)", thread_id) + thread_id = None + if thread_id: + logger.debug( + "Cron origin captured thread_id=%s for %s:%s", + thread_id, origin_platform, origin_chat_id) + return { + "platform": origin_platform, "chat_id": origin_chat_id, + "chat_name": get_session_env("HERMES_SESSION_CHAT_NAME") or None, "thread_id": thread_id, + # Lets a delivery mirror resolve the participant's session in per-user-isolated groups. + "user_id": get_session_env("HERMES_SESSION_USER_ID") or None, + # Workspace/server scope (Slack team, Discord guild...): Slack session keys embed it, + # so a continuable cron seed built without it would never resolve a scoped reply. + "scope_id": get_session_env("HERMES_SESSION_SCOPE_ID") or None, + } + + +def _local_delivery_notice(job: Dict[str, Any], user_deliver: Optional[str]) -> Optional[str]: + """Notice when a created job won't deliver anywhere: CLI/TUI sessions have no capturable + origin, so deliver='origin' (or omitted) saves output but never delivers it. None when the + user explicitly asked for ``local`` or the job resolves to a real target. + + TUI/CLI sessions cannot be captured as a cron ``origin`` (no ``HERMES_SESSION_PLATFORM``/``CHAT_ID`` is + set for them), so a ``deliver="origin"`` request — or an omitted ``deliver`` that defaults to + origin-or-local — produces a job that runs and saves output to ``last_output`` but is never delivered + back into the session. This is by design (there is no live-delivery channel for local sessions), but + silently dropping the user's "tell me when it runs" intent is the trap reported in 51568. Surface it at + create time so the agent can relay it instead of promising a delivery that never happens. See #51568. + """ + if (user_deliver or "").strip().lower() == "local": + return None + try: + from cron.scheduler import _resolve_delivery_targets + if _resolve_delivery_targets(job): + return None + except Exception: # resolution unavailable — fall back to the origin signal + if job.get("origin"): + return None + return ( + "This is a local-only cron job: its output is saved (view it with " + "cronjob(action='list')) but will NOT be delivered back into this " + "session — CLI/TUI sessions have no live-delivery channel. To be " + "notified when it runs, recreate or update the job with deliver set to " + "a gateway-connected platform, e.g. deliver='telegram' or deliver='all'.") + + +def _mode_guidance_notes(job: Dict[str, Any], user_deliver: Optional[str]) -> List[str]: + """Mode guidance echoed once in the create/update response (not in the schema, which is + paid for on every API call).""" + notes: List[str] = [] + if job.get("monitor_script") or job.get("monitor_url"): + notes.append( + "Monitor mode: the source runs first each tick and its output is " + "hashed as exact bytes — unchanged output suppresses the agent run " + "(silent no_change tick), changed output injects a MONITOR CHANGE " + "DETECTED diff into the prompt. The first tick always runs as " + "baseline. The source must emit STABLE output (no timestamps, no " + "random ordering) or every tick will look changed.") + if job.get("no_agent"): + notes.append( + "no_agent mode: stdout is delivered verbatim; EMPTY stdout sends " + "nothing at all (watchdog pattern — script should stay quiet when " + "there is nothing to report). Non-zero exit or timeout sends an " + "error alert. prompt/skills are ignored.") + _deliver = (user_deliver or "").strip().lower() + if _deliver: + if "all" in _deliver.split(","): + notes.append( + "deliver='all' resolves at fire time and never includes " + "bot-chat targets — channels connected later are picked up " + "automatically.") + if _deliver.startswith("bot-chat:"): + notes.append("Targeting another profile's Bot Chat costs that bot an agent turn per run.") + # platform:chat_id with no thread segment loses topic targeting. + for target in _deliver.split(","): + parts = target.strip().split(":") + if ( + len(parts) == 2 + and parts[0] not in ("bot-chat", "sms") + and parts[1] + and not parts[1].startswith("#")): + notes.append( + f"deliver target '{target.strip()}' has no :thread_id " + "segment — on thread/topic platforms the delivery lands in " + "the main chat, not a topic.") + break + return notes + + +def _split_monitor_arg( + monitor: Optional[str], + monitor_script: Optional[str], + monitor_url: Optional[str]) -> tuple: + """Resolve the model-facing ``monitor`` field into the stored ``(monitor_script, + monitor_url)`` pair. http(s):// is a URL, anything else a script path (a legal script path + never starts with a URL scheme). None = unchanged, '' = clear; setting one source clears + the other so switching transports never trips mutual exclusion; an explicit ``monitor`` + wins over the legacy alias fields.""" + if monitor is None: + return monitor_script, monitor_url + value = monitor.strip() + if not value: + return "", "" + if value.lower().startswith(("http://", "https://")): + return "", value + return value, "" + + +def _repeat_display(job: Dict[str, Any]) -> str: + rep = job.get("repeat") or {} + times, completed = rep.get("times"), rep.get("completed", 0) + if times is None: + return "forever" + if times == 1: + return "once" if completed == 0 else "1/1" + return f"{completed}/{times}" if completed else f"{times} times" + + +def _clean_str_list(items: Any) -> List[str]: + """Stripped, non-empty ``str(item)`` values from a str-or-iterable (order kept).""" + if items is None: + return [] + if isinstance(items, str): + items = [items] + return [s for s in (str(i).strip() for i in items) if s] + + +def _canonical_skills(skill: Optional[str] = None, skills: Optional[Any] = None) -> List[str]: + if skills is None: + skills = [skill] if skill else [] + elif isinstance(skills, str): + skills = [skills] + # `item or ""`: a None entry must drop out, not stringify to "None". + return list(dict.fromkeys(_clean_str_list(item or "" for item in skills))) + + +def _normalize_optional_job_value(value: Optional[Any], *, strip_trailing_slash: bool = False) -> Optional[str]: + if value is None: + return None + text = str(value).strip() + if strip_trailing_slash: + text = text.rstrip("/") + return text or None + + +def _normalize_deliver_param(value: Any) -> Optional[str]: + """Canonical string form of ``deliver``; None for None/empty. MCP clients may pass a list + (``["telegram"]``) which the scheduler's ``str(deliver).split(",")`` would mangle.""" + if value is None: + return None + if isinstance(value, (list, tuple)): + return ",".join(_clean_str_list(value)) or None + return str(value).strip() or None + + +def _validate_bot_chat_deliver(deliver: Optional[str]) -> Optional[str]: + """Validate ``bot-chat[:]`` deliver elements at create time: Bot Chat delivery is + machine-local, so the profile must exist where the scheduler fires (Desktop rosters may + show same-named profiles from other machines). Returns an error string or None.""" + if not deliver: + return None + try: + from cron.scheduler_delivery import parse_bot_chat_deliver_token + from hermes_cli.profiles import normalize_profile_name, profile_exists + except Exception: + return None # best-effort; resolution re-checks at fire time + for part in str(deliver).split(","): + profile_arg = parse_bot_chat_deliver_token(part.strip()) + if not profile_arg: + continue # not a bot-chat token, or bare token (own profile) + try: + canon = normalize_profile_name(profile_arg) + except Exception: + return f"invalid bot-chat profile name '{profile_arg}'" + if not profile_exists(canon): + return ( + f"bot-chat delivery profile '{profile_arg}' not found on this " + "gateway's machine. Bot Chat delivery is machine-local — use a " + "profile that exists here (hermes profile list), or omit the " + "name (deliver='bot-chat') for the job's own profile.") + return None + + +def _resolve_cron_context_deliver(deliver: Optional[str]) -> Optional[str]: + """Resolve ``origin`` to a concrete target for creates made FROM a cron run (the creating + session is ephemeral, so by fire time there is no origin). Non-cron sessions: unchanged. + Cron sessions: ``origin`` (or omitted) becomes the creating run's ``platform:chat_id[:thread]`` + from HERMES_CRON_AUTO_DELIVER_*, or ``local`` when it has no concrete target; other + elements pass through. Otherwise the scheduler would guess a home channel.""" + from gateway.session_context import get_session_env + from utils import is_truthy_value + if not is_truthy_value(get_session_env("HERMES_CRON_SESSION", "")): + return deliver + + def _creator_target() -> str: + platform = get_session_env("HERMES_CRON_AUTO_DELIVER_PLATFORM", "").strip() + chat_id = get_session_env("HERMES_CRON_AUTO_DELIVER_CHAT_ID", "").strip() + if not platform or not chat_id: + return "local" + thread_id = get_session_env("HERMES_CRON_AUTO_DELIVER_THREAD_ID", "").strip() + return f"{platform}:{chat_id}:{thread_id}" if thread_id else f"{platform}:{chat_id}" + + if deliver is None: + return _creator_target() + resolved = [_creator_target() if p.lower() == "origin" else p for p in _clean_str_list(str(deliver).split(","))] + # Order-preserving de-dup: 'origin,local' with a local creator -> 'local'. + return ",".join(dict.fromkeys(resolved)) or None + + +def _validate_cron_base_url( + provider: Optional[Any], base_url: Optional[Any]) -> Optional[str]: + """Reject pairing a named provider's stored credential with an off-host base_url (a + prompt-injected job could exfil the key). Allowed: no override; bare 'custom' (pure BYOK, + key derived from the base_url); an override whose host matches the named provider's own + endpoint. Everything else fails closed. Returns an error string if blocked, else None.""" + bu = _normalize_optional_job_value(base_url, strip_trailing_slash=True) + if not bu: + return None + prov = _normalize_optional_job_value(provider) + if not prov: # no provider inherits the default provider's stored key — same primitive + return ( + "base_url override requires an explicit provider. Set provider to a " + "configured custom provider to use a custom endpoint.") + try: + from hermes_cli.runtime_provider import ( + has_named_custom_provider, + resolve_requested_provider, + _get_named_custom_provider) + from hermes_cli.auth import PROVIDER_REGISTRY + from utils import base_url_host_matches, base_url_hostname + except Exception: + return f"Unable to validate base_url override for provider {prov!r}; refused." + + if prov.lower() == "custom": # pure BYOK: key keyed by THIS base_url, never a stored secret + return None + if has_named_custom_provider(prov): + # A NAMED custom provider's STORED key is still sent to an override base_url. + try: + cp = _get_named_custom_provider(prov) + except Exception: + cp = None + cfg_host = base_url_hostname((cp or {}).get("base_url", "")) if cp else "" + if cfg_host and base_url_host_matches(bu, cfg_host): + return None + return ( + f"base_url {bu!r} is not allowed for provider {prov!r}. A named " + f"custom provider's stored credential may only be sent to its own " + f"configured endpoint ({cfg_host or 'unknown'}).") + try: + resolved = resolve_requested_provider(prov) + except Exception: + resolved = prov + pconfig = PROVIDER_REGISTRY.get(resolved) if isinstance(resolved, str) else None + known_host = base_url_hostname(getattr(pconfig, "inference_base_url", "") if pconfig else "") + if known_host and base_url_host_matches(bu, known_host): + return None + # Fail closed: named providers with stored credentials AND unknown names we cannot host-match. + return ( + f"base_url {bu!r} is not allowed for provider {prov!r}. A named " + f"provider's stored credential may only be sent to its own endpoint; " + f'use a configured custom provider (provider="custom") for a custom base_url.') + + +def _validate_cron_script_path(script: Optional[str]) -> Optional[str]: + """Scripts must be relative paths within HERMES_HOME/scripts/ (absolute / ~ / drive-letter + rejected — prompt-injection guard). Error string if blocked, else None; empty = clear.""" + if not script or not script.strip(): + return None + + from hermes_constants import get_hermes_home + raw = script.strip() + if raw.startswith(("/", "~")) or (len(raw) >= 2 and raw[1] == ":"): + return ( + f"Script path must be relative to ~/.hermes/scripts/. " + f"Got absolute or home-relative path: {raw!r}. " + f"Place scripts in ~/.hermes/scripts/ and use just the filename.") + + from tools.path_security import validate_within_dir + scripts_dir = get_hermes_home() / "scripts" + scripts_dir.mkdir(parents=True, exist_ok=True) + if validate_within_dir(scripts_dir / raw, scripts_dir): + return f"Script path escapes the scripts directory via traversal: {raw!r}" + return None + + +def _apply_continuity( + context_from: Optional[Union[str, List[str]]], + continuity: bool) -> Optional[List[str]]: + """continuity=True ensures "self" is in context_from; False removes it; others untouched.""" + refs = _clean_str_list(context_from) + has_self = any(r.lower() == "self" for r in refs) + if continuity and not has_self: + refs.append("self") + elif not continuity and has_self: + refs = [r for r in refs if r.lower() != "self"] + return refs or None + + +def _validate_context_from_refs(refs: List[Any]) -> Optional[str]: + """Error string if any non-"self" ref names a missing job ("self" resolves to the job's + own id at run time, so it can't be checked — the job doesn't exist yet at create).""" + from cron.jobs import get_job as _get_job + for ref_id in refs: + if isinstance(ref_id, str) and ref_id.strip().lower() == "self": + continue + if not _get_job(ref_id): + return ( + f"context_from job '{ref_id}' not found. " + "Use cronjob(action='list') to see available jobs.") + return None + + +# Optional fields echoed by _format_job only when truthy (order = JSON key order). +_FORMAT_JOB_OPTIONAL_KEYS = ( + "script", "reasoning_effort", "monitor_script", "monitor_url", + "monitor_state", "no_agent", "enabled_toolsets", "workdir") + + +def _format_job(job: Dict[str, Any]) -> Dict[str, Any]: + from agent.redact import redact_sensitive_text + + prompt = str(job.get("prompt") or "") + skills = _canonical_skills(job.get("skill"), job.get("skills")) + job_id = str(job.get("id") or "unknown") + name = str(job.get("name") or prompt[:50] or (skills[0] if skills else "") or job_id or "cron job") + result = { + "job_id": job_id, + "name": name, + "skill": skills[0] if skills else None, + "skills": skills, + "prompt_preview": prompt[:100] + "..." if len(prompt) > 100 else prompt, + "model": job.get("model"), + "provider": job.get("provider"), + "base_url": job.get("base_url"), + "schedule": job.get("schedule_display") or "?", + "repeat": _repeat_display(job), + "deliver": job.get("deliver", "local"), + "next_run_at": job.get("next_run_at"), + "last_run_at": job.get("last_run_at"), + "last_status": job.get("last_status"), + "last_delivery_error": job.get("last_delivery_error"), + "last_delivery_unverified": job.get("last_delivery_unverified"), + "last_fire_error": job.get("last_fire_error"), + "last_error": redact_sensitive_text( + job["last_error"], force=True, redact_url_credentials=True, + ) if job.get("last_error") else job.get("last_error"), + "enabled": job.get("enabled", True), + # Derive from enabled so half-paused records never render as paused. + "state": effective_job_state(job), + "paused_at": job.get("paused_at"), + "paused_reason": job.get("paused_reason"), + } + for key in _FORMAT_JOB_OPTIONAL_KEYS: + if job.get(key): + result[key] = True if key == "no_agent" else job[key] + stored_refs = job.get("context_from") or [] + if isinstance(stored_refs, str): + stored_refs = [stored_refs] + is_self = lambda r: str(r).strip().lower() == "self" or r == job.get("id") # noqa: E731 + if any(is_self(r) for r in stored_refs): + result["continuity"] = True + external_refs = [r for r in stored_refs if not is_self(r)] + if external_refs: + result["context_from"] = external_refs + if isinstance(job.get("attach_to_session"), bool): + result["attach_to_session"] = job["attach_to_session"] + return result + + +def _gateway_liveness_notice(plural: bool = False) -> dict: + """``gateway_running``/``warning`` payload via the shared CLI helper so CLI and tool agree + on "scheduler active". False -> warning (no gateway process), None -> probe failed. + + Thin adapter over the shared CLI helper ``hermes_cli.cron._builtin_gateway_liveness`` (#87033) so the + CLI and this tool can never disagree about what "scheduler active" means. ``plural`` rewords the warning + for multi-job results (the ``list`` action). + """ + try: + from hermes_cli.cron import _builtin_gateway_liveness + _gw = _builtin_gateway_liveness() + except Exception: + return {"gateway_running": None} + if _gw is False: + subject = "these jobs are saved" if plural else "this job is saved" + return { + "gateway_running": False, + "warning": ( + f"The Hermes gateway is not running — {subject} " + "but will NOT fire until the gateway is started " + "(hermes gateway install / hermes gateway start). " + "Tell the user the task is scheduled but not active yet."), + } + return {"gateway_running": None if _gw is None else True} diff --git a/tools/daemon_pool.py b/tools/daemon_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..5682a8f6ae103a421c1081b69ee6f9272957acdf --- /dev/null +++ b/tools/daemon_pool.py @@ -0,0 +1,56 @@ +"""Shared daemon-thread ThreadPoolExecutor. + +Stdlib workers are non-daemon AND registered in ``_threads_queues``, whose atexit +hook joins every worker even after ``shutdown(wait=False)`` — one wedged worker +(tool blocked on network I/O, hung provider, stuck subagent) blocks interpreter +exit forever. This variant spawns daemon workers and skips that registration. +Use it for best-effort/interruptible work that must never hold the process open; +NOT for work that must complete before exit (durable writes belong on foreground +threads with explicit bounded joins). +""" + +from __future__ import annotations + +import threading +import weakref +from concurrent.futures import ThreadPoolExecutor +from concurrent.futures.thread import _worker +from contextvars import copy_context + +__all__ = ["DaemonThreadPoolExecutor"] + + +class DaemonThreadPoolExecutor(ThreadPoolExecutor): + """ThreadPoolExecutor variant whose workers do not block process exit.""" + + def submit(self, fn, /, *args, **kwargs): + """Submit a callable, propagating the caller's contextvars. Stdlib only does + this from 3.14; on 3.11-3.13 a bare worker starts with an EMPTY Context and + drops profile secret scope / HERMES_HOME override — under the multiplexed + gateway a credential read then fails closed with ``UnscopedSecretError``. + Unconditional: on 3.14+ ``ctx.run`` re-applies the same context (no-op).""" + ctx = copy_context() + + def _run_with_context(*call_args, **call_kwargs): + return ctx.run(fn, *call_args, **call_kwargs) + return super().submit(_run_with_context, *args, **kwargs) + + def _adjust_thread_count(self) -> None: + # Mirrors CPython's implementation (3.8–3.13) with two changes: + # daemon=True and no _threads_queues registration. + if self._idle_semaphore.acquire(timeout=0): + return + + def weakref_cb(_, q=self._work_queue): + q.put(None) + num_threads = len(self._threads) + if num_threads < self._max_workers: + thread_name = "%s_%d" % (self._thread_name_prefix or self, num_threads) + # Carry the active profile into the review thread so MEMORY.md / skill review writes land in the + # right profile (#54937). + t = threading.Thread( + name=thread_name, target=_worker, daemon=True, + args=(weakref.ref(self, weakref_cb), self._work_queue, self._initializer, self._initargs), + ) + t.start() + self._threads.add(t) diff --git a/tools/delegate_tool_progress.py b/tools/delegate_tool_progress.py new file mode 100644 index 0000000000000000000000000000000000000000..46e913f88e6fd407efce851b8f03c466ca15a705 --- /dev/null +++ b/tools/delegate_tool_progress.py @@ -0,0 +1,392 @@ +"""Child progress relay, console formatting and child system-prompt construction for delegate_task.""" + +from __future__ import annotations + +import logging +import enum +import os +import threading +from contextlib import contextmanager +from typing import Any, Dict, List, Optional +from tools.delegate_tool_registry import _active_subagents, _active_subagents_lock + +logger = logging.getLogger("tools.delegate_tool") # log-record parity with the origin module + +# Terminal child statuses that mean "the subagent did NOT deliver a usable result". Shared by the CLI spinner echo, +# the gateway failure notice, and the parent-facing failure summary so every surface agrees. +SUBAGENT_FAILURE_STATUSES = frozenset({"failed", "error", "timeout"}) + +@contextmanager +def _quiet(log_message: Optional[str], *log_args: Any, exc_info: bool = False): + """Best-effort block: any Exception is swallowed (never reaches the run) and, when ``log_message`` is given, + logged at debug — the exception fills a trailing unsatisfied ``%s``.""" + try: + yield + except Exception as exc: + if log_message is None: + return + if log_message.count("%") > len(log_args): + log_args = log_args + (exc,) + logger.debug(log_message, *log_args, exc_info=exc_info) + +def _safe_progress(cb: Any, event_type: Any, *args: Any, **kwargs: Any) -> None: + """Invoke a child progress callback; relay failures never reach the run.""" + if cb: + with _quiet("Progress callback %s failed: %s", event_type): + cb(event_type, *args, **kwargs) + +def _clean_error_text(error: Any, max_chars: int = 200) -> str: + """Reduce an error payload (traceback / JSON wall) to one clean line: the exception message (last line of a + traceback) or the first non-empty line, hard-capped in length.""" + lines = [ln.strip() for ln in str(error or "").strip().splitlines() if ln.strip()] + if not lines: + return "" + line = lines[-1] if lines[0].startswith("Traceback") else lines[0] + return line[: max_chars - 3] + "..." if len(line) > max_chars else line + +def format_subagent_failure_line( + goal: Optional[str], status: Optional[str], error: Any = None, duration_seconds: Any = None, +) -> str: + """One clean, human-readable line describing a failed subagent, rendered + directly to the user (CLI spinner echo, gateway platform notice), e.g. + ``⚠️ Subagent failed — "research competitor pricing": Error code: 404 (after 12s)``.""" + goal_label = (goal or "").strip().replace("\n", " ") + if len(goal_label) > 60: + goal_label = goal_label[:57] + "..." + line = f"⚠️ Subagent {'timed out' if status == 'timeout' else 'failed'}" + if goal_label: + line += f' — "{goal_label}"' + err = _clean_error_text(error) + if err: + line += f": {err}" + if isinstance(duration_seconds, (int, float)) and duration_seconds > 0: + line += f" (after {round(duration_seconds)}s)" + return line + + +class DelegateEvent(str, enum.Enum): + """Formal delegation progress event types. The relay normalises incoming legacy strings (``tool.started``, + ``_thinking``, …) to these via ``_LEGACY_EVENT_MAP``; external consumers (gateway SSE, ACP adapter, CLI) still + receive the legacy strings during the deprecation window. TASK_SPAWNED / TASK_COMPLETED / TASK_FAILED are + reserved for future orchestrator lifecycle events, not emitted yet.""" + + TASK_SPAWNED = "delegate.task_spawned" + TASK_PROGRESS = "delegate.task_progress" + TASK_COMPLETED = "delegate.task_completed" + TASK_FAILED = "delegate.task_failed" + TASK_THINKING = "delegate.task_thinking" + TASK_TOOL_STARTED = "delegate.tool_started" + TASK_TOOL_COMPLETED = "delegate.tool_completed" + +# Legacy child-agent event strings → DelegateEvent. +_LEGACY_EVENT_MAP: Dict[str, DelegateEvent] = { + "_thinking": DelegateEvent.TASK_THINKING, + "reasoning.available": DelegateEvent.TASK_THINKING, + "tool.started": DelegateEvent.TASK_TOOL_STARTED, + "tool.completed": DelegateEvent.TASK_TOOL_COMPLETED, + "subagent_progress": DelegateEvent.TASK_PROGRESS, +} + +# Event → _ChildProgressRelay method name. Lifecycle strings are emitted by the orchestrator itself (not +# DelegateEvent). Any other DelegateEvent (TASK_TOOL_STARTED and the reserved TASK_* values) takes the tool-started +# path; None means "recognised but ignored". +_LIFECYCLE_EVENTS = frozenset({"subagent.start", "subagent.complete", "subagent.text"}) +_EVENT_HANDLERS: Dict[Any, Optional[str]] = { + "subagent.start": "_on_start", + "subagent.complete": "_on_complete", + "subagent.text": "_on_text", + DelegateEvent.TASK_THINKING: "_on_thinking", + DelegateEvent.TASK_PROGRESS: "_on_progress", + DelegateEvent.TASK_TOOL_COMPLETED: None, +} + +def _normalize_event(event_type: Any) -> Any: + """Lifecycle string / DelegateEvent / legacy string / ``delegate.*`` string + → dispatch key; None for unknown events.""" + if isinstance(event_type, DelegateEvent) or (isinstance(event_type, str) and event_type in _LIFECYCLE_EVENTS): + return event_type + try: + return _LEGACY_EVENT_MAP.get(event_type) or DelegateEvent(event_type) + except (ValueError, TypeError): + return None + +_CONTEXT_FILES_INTRO = ( + "\nThe workspace's project context files are reproduced below. Their conventions and invariants are binding for " + "your work in this workspace.\n\n" +) +_COMPLETION_INSTRUCTIONS = ( + "\nComplete this task using the tools available to you. When finished, provide a clear, concise summary of:\n" + "- What you did\n- What you found or accomplished\n- Any files you created or modified\n- Any issues encountered\n\n" + "Important workspace rule: Never assume a repository lives at /workspace/... or any other container-style path " + "unless the task/context explicitly gives that path. If no exact local path is provided, discover it first before " + "issuing git/workdir-specific commands.\n\n" + "Keep your final summary tight: lead with outcomes, prefer bullet points over paragraphs, and don't replay your " + "whole process. Your response is returned to the parent agent as a summary, and overlong summaries crowd out the " + "parent's context window." +) +_ORCHESTRATOR_BLOCK = ( + "\n## Subagent Spawning (Orchestrator Role)\n" + "You have access to the `delegate_task` tool and CAN spawn your own subagents to parallelize independent work.\n\n" + "WHEN to delegate:\n" + "- The goal decomposes into 2+ independent subtasks that can run in parallel (e.g. research A and B simultaneously).\n" + "- A subtask is reasoning-heavy and would flood your context with intermediate data.\n\n" + "WHEN NOT to delegate:\n" + "- Single-step mechanical work — do it directly.\n" + "- Trivial tasks you can execute in one or two tool calls.\n" + "- Re-delegating your entire assigned goal to one worker (that's just pass-through with no value added).\n\n" + "Coordinate your workers' results and synthesize them before reporting back to your parent. You are responsible " + "for the final summary, not your workers.\n\n" +) +_LEAF_CHILDREN_NOTE = ( + "Your own children MUST be leaves (cannot delegate further) because they would be at the depth floor — you cannot " + "pass role='orchestrator' to your own delegate_task calls." +) +_NESTED_CHILDREN_NOTE = ( + "Your own children can themselves be orchestrators or leaves, depending on the `role` you pass to delegate_task. " + "Default is 'leaf'; pass role='orchestrator' explicitly when a child needs to further decompose its work." +) + +def _build_child_system_prompt( + goal: str, context: Optional[str] = None, *, workspace_path: Optional[str] = None, role: str = "leaf", + max_spawn_depth: int = 2, child_depth: int = 1, +) -> str: + """Focused system prompt for a child agent. role='orchestrator' appends a delegation-capability block (modeled on + OpenClaw's buildSubagentSystemPrompt); its depth note is literal truth grounded in the passed config so the LLM + can't confabulate nesting.""" + parts = ["You are a focused subagent working on a specific delegated task.", "", f"YOUR TASK:\n{goal}"] + if context and context.strip(): + parts.append(f"\nCONTEXT:\n{context}") + if workspace_path and str(workspace_path).strip(): + parts.append( + "\nWORKSPACE PATH:\n" + f"{workspace_path}\n" + "Use this exact path for local repository/workdir operations unless the task explicitly says otherwise." + ) + # Project context files (AGENTS.md / CLAUDE.md / .cursorrules ...) via the SAME discovery/priority/cap logic + # as the main agent's prompt: children are built with skip_context_files=True, so without this a subagent + # works in a repo blind to its conventions. SOUL.md is skipped (identity belongs to the parent). + # workspace_path comes only from explicit sources (_resolve_workspace_hint, never bare getcwd), so the + # install-tree-fallback leak doesn't apply. Best-effort. + _ctx_files = "" + with _quiet("subagent: workspace context-files load failed", exc_info=True): + # See #64590. + from agent.prompt_builder import build_context_files_prompt + _ctx_files = build_context_files_prompt(cwd=str(workspace_path), skip_soul=True) + if _ctx_files.strip(): + parts.append(_CONTEXT_FILES_INTRO + _ctx_files.strip()) + parts.append(_COMPLETION_INSTRUCTIONS) + if role == "orchestrator": + child_note = _LEAF_CHILDREN_NOTE if child_depth + 1 >= max_spawn_depth else _NESTED_CHILDREN_NOTE + parts.append( + _ORCHESTRATOR_BLOCK + + f"NOTE: You are at depth {child_depth}. The delegation tree is capped at max_spawn_depth={max_spawn_depth}. " + + child_note + ) + return "\n".join(parts) + +def _resolve_workspace_hint(parent_agent) -> Optional[str]: + """Best-effort local workspace hint for child prompts: only a concrete + absolute directory is ever injected (never a fake container path).""" + from agent.runtime_cwd import scope_terminal_cwd + candidates = [ + scope_terminal_cwd(), getattr(getattr(parent_agent, "_subdirectory_hints", None), "working_dir", None), + getattr(parent_agent, "terminal_cwd", None), getattr(parent_agent, "cwd", None), + ] + for candidate in filter(None, candidates): + with _quiet(None): + text = os.path.abspath(os.path.expanduser(str(candidate))) + if os.path.isabs(text) and os.path.isdir(text): + return text + return None + +_BATCH_ORDINALS: Dict[str, Dict[str, int]] = {} +_BATCH_ORDINALS_LOCK = threading.Lock() + +def format_batch_tag(delegation_id: Optional[str], parent_agent: Any = None) -> str: + """Short human tag for a delegation batch: the parent's first fan-out is ``set 1``, its next distinct + delegation id ``set 2``. Several batches (a parent's fan-out plus a child's nested fan-out, or two + concurrent tools) print interleaved ``[n/N]`` lines to one console; without a tag ``✓ [3/3]`` and ``✓ [3/9]`` + are indistinguishable, and a raw hex slice is unreadable. Ordinals are scoped per parent conversation + (``parent_agent.session_id``): one process hosts many conversations and every child's own fan-out, so a + process-wide counter showed a user's second wave as ``set 20``. Empty string when no id is known so callers + can concatenate unconditionally.""" + if not isinstance(delegation_id, str) or not delegation_id: + return "" + scope = str(getattr(parent_agent, "session_id", None) or "") + with _BATCH_ORDINALS_LOCK: + ordinals = _BATCH_ORDINALS.setdefault(scope, {}) + n = ordinals.setdefault(delegation_id, len(ordinals) + 1) + return f"set {n}" + +def _batch_prefix(delegation_id: Optional[str], task_index: int, task_count: int, parent_agent: Any = None) -> str: + """``[set 2 · 3/9] `` for batch children, ``[set 2] `` for a lone child, + ``[3/9] `` / ``""`` when the batch id is unknown.""" + tag = format_batch_tag(delegation_id, parent_agent) + if task_count > 1: + inner = f"{tag} · {task_index + 1}/{task_count}" if tag else f"{task_index + 1}/{task_count}" + return f"[{inner}] " + return f"[{tag}] " if tag else "" + +def _emit_parent_console(parent_agent, line: str) -> None: + """Emit a progress line through ``parent_agent._safe_print`` when available so headless stdio hosts (ACP, gateway + API) can redirect it to stderr; a bare ``print()`` would land on stdout and corrupt JSON-RPC framing.""" + printer = getattr(parent_agent, "_safe_print", None) + if callable(printer): + with _quiet(None): + printer(line) + return + print(line) + +def _print_completion_line(parent_agent: Any, spinner_ref: Any, line: str, console_line: Optional[str] = None) -> None: + """Above-spinner line when a spinner exists (console fallback if it raises), else console + (``console_line`` when given, else the line indented two spaces).""" + if spinner_ref: + with _quiet(None): + spinner_ref.print_above(line) + return + _emit_parent_console(parent_agent, f" {line}" if console_line is None else console_line) + +def _short(text: str, n: int) -> str: + return (text[:n] + "...") if len(text) > n else text + + +class _ChildProgressRelay: + """Callable relaying one child's events to the parent display. CLI: prints tree-view lines above the parent's + delegation spinner. Gateway: batches tool names (``_BATCH_SIZE``) and relays to the parent's progress callback, + threading the identity kwargs (subagent_id, parent_id, depth, model, toolsets) into every event so the TUI can + rebuild the live spawn tree and route per-branch controls back by ``subagent_id``.""" + + _BATCH_SIZE = 5 + + def __init__( + self, task_index: int, goal: str, spinner: Any, parent_cb: Any, task_count: int, + subagent_id, parent_id, depth, model, toolsets, session_ref, + ) -> None: + self.task_index, self.task_count, self.goal_label = task_index, task_count, (goal or "").strip() + # session_ref is a SHARED dict filled in later by the caller — keep the identity. + self.spinner, self.parent_cb, self.session_ref = spinner, parent_cb, session_ref if session_ref is not None else {} + self.subagent_id, self.parent_id, self.depth, self.model, self.toolsets = ( + subagent_id, parent_id, depth, model, toolsets + ) + self.batch: List[str] = [] + self.tool_count = 0 # per-subagent running counter + + def _prefix(self) -> str: + # The batch tag is resolved lazily from session_ref: the relay is built + # before delegate_task stamps ``_delegation_id`` on the child. The parent + # scope rides in the same ref so ordinals match the parent's own lines. + return _batch_prefix( + self.session_ref.get("delegation_id"), self.task_index, self.task_count, + parent_agent=self.session_ref.get("_parent_scope"), + ) + + def _identity_kwargs(self) -> Dict[str, Any]: + kw: Dict[str, Any] = {"task_index": self.task_index, "task_count": self.task_count, "goal": self.goal_label} + kw.update({k: getattr(self, k) for k in ("subagent_id", "parent_id", "depth", "model") if getattr(self, k) is not None}) + if self.toolsets is not None: + kw["toolsets"] = list(self.toolsets) + # child_session_id / delegation_id are filled into the shared ref once + # the child exists, so every relayed event lets UIs open its session. + for src, dst in (("session_id", "child_session_id"), ("delegation_id", "delegation_id")): + if self.session_ref.get(src): + kw[dst] = str(self.session_ref[src]) + kw["tool_count"] = self.tool_count + return kw + + def _relay(self, event_type: str, tool_name: str = None, preview: str = None, args=None, **kwargs): + if self.parent_cb: + # kwargs override identity (e.g. status, duration_seconds). + with _quiet("Parent callback failed: %s"): + self.parent_cb(event_type, tool_name, preview, args, **{**self._identity_kwargs(), **kwargs}) + + def _tree_line(self, text: str) -> None: + """Print one tree-view line above the CLI spinner (no-op without a spinner).""" + if self.spinner: + with _quiet("Spinner print_above failed: %s"): + self.spinner.print_above(f" {self._prefix()}├─ {text}") + + def _flush(self) -> None: + """Flush remaining batched tool names to the gateway.""" + if self.parent_cb and self.batch: + self._relay("subagent.progress", preview=f"🔀 {self._prefix()}{', '.join(self.batch)}") + self.batch.clear() + + # ── Lifecycle events emitted by the orchestrator itself ── + def _on_start(self, tool_name, preview, args, kwargs): + if self.goal_label: + self._tree_line(f"🔀 {_short(self.goal_label, 55)}") + self._relay("subagent.start", preview=preview or self.goal_label or "", **kwargs) + + def _on_complete(self, tool_name, preview, args, kwargs): + # Failed child: echo one clean reason line into the CLI tree so the human + # sees WHY, not just a vanished branch (gateway renders off the relayed event). + if kwargs.get("status") in SUBAGENT_FAILURE_STATUSES: + self._tree_line(format_subagent_failure_line( + self.goal_label, kwargs.get("status"), error=kwargs.get("summary") or preview, + duration_seconds=kwargs.get("duration_seconds"), + )) + self._relay("subagent.complete", preview=preview, **kwargs) + + def _on_text(self, tool_name, preview, args, kwargs): + # Streamed child reply text, relayed verbatim for gateway watch windows; + # inert on CLI/TUI (their progress handlers ignore non-tool events). + self._relay("subagent.text", preview=preview) + + # ── DelegateEvent handlers ── + def _on_thinking(self, tool_name, preview, args, kwargs): + text = preview or tool_name or "" + self._tree_line(f'💭 "{_short(text, 55)}"') + self._relay("subagent.thinking", preview=text) + + def _on_progress(self, tool_name, preview, args, kwargs): + # Pre-batched summary from a nested orchestrator's grandchild arrives in the tool_name slot: render distinctly + # (no tool-emoji lookup) and relay upward without re-batching. + summary_text = tool_name or preview or "" + if summary_text: + self._tree_line(f"🔀 {summary_text}") + if self.parent_cb: + with _quiet("Parent callback relay failed: %s"): + self.parent_cb("subagent_progress", f"{self._prefix()}{summary_text}") + + def _on_tool_started(self, tool_name, preview, args, kwargs): + self.tool_count += 1 + if self.subagent_id is not None: + with _active_subagents_lock: + rec = _active_subagents.get(self.subagent_id) + if rec is not None: + rec["tool_count"] = self.tool_count + rec["last_tool"] = tool_name or "" + if self.spinner: + from agent.display import get_tool_emoji + line = f"{get_tool_emoji(tool_name or '')} {tool_name}" + short = _short(preview, 35) if preview else "" + self._tree_line(f'{line} "{short}"' if short else line) + if self.parent_cb: + self._relay("subagent.tool", tool_name, preview, args) + self.batch.append(tool_name or "") + if len(self.batch) >= self._BATCH_SIZE: + self._flush() + + def __call__(self, event_type, tool_name: str = None, preview: str = None, args=None, **kwargs): + key = _normalize_event(event_type) + method = None if key is None else _EVENT_HANDLERS.get(key, "_on_tool_started") + if method is not None: + getattr(self, method)(tool_name, preview, args, kwargs) + +def _build_child_progress_callback( + task_index: int, goal: str, parent_agent, task_count: int = 1, *, subagent_id: Optional[str] = None, + parent_id: Optional[str] = None, depth: Optional[int] = None, model: Optional[str] = None, + toolsets: Optional[List[str]] = None, session_ref: Optional[Dict[str, Any]] = None, +) -> Optional[callable]: + """Relay for one child's events (see ``_ChildProgressRelay``), or None when the parent has neither a spinner nor a + progress callback — the child then runs with no progress callback at all (zero behavior change).""" + spinner = getattr(parent_agent, "_delegate_spinner", None) + parent_cb = getattr(parent_agent, "tool_progress_callback", None) + if not spinner and not parent_cb: + return None + if session_ref is not None: + # Not an identity kwarg (underscore-prefixed, never relayed); only scopes the batch ordinal. + session_ref["_parent_scope"] = parent_agent + return _ChildProgressRelay( + task_index, goal, spinner, parent_cb, task_count, subagent_id, parent_id, depth, model, toolsets, session_ref, + ) diff --git a/tools/delegate_tool_tasks.py b/tools/delegate_tool_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..0def5aeb8098feef301ca63965c449715cd52f7b --- /dev/null +++ b/tools/delegate_tool_tasks.py @@ -0,0 +1,162 @@ +"""delegate_task input validation: tasks=[...] / legacy goal normalisation, per-task output schemas and images.""" + +from __future__ import annotations + +import json +import re +from typing import Any, Dict, List, Optional + +# Placeholder shapes for batch goal validation: bare 'TODO' / 'task N' labels, or unexpanded template markers. The +# marker regex is deliberately NARROW — only snake_case / space-separated placeholder identifiers (``, +# `{file path}`, ``), the shape LLM templates leave behind. Bare single-word brackets must never be +# rejected: legitimate goals are full of generics (`Vec`), HTML tags (`
`), dict snippets (`{"key": 1}`), glob +# braces (`{a,b}`) and f-string style (`{i}`). +# See #81141. +_PLACEHOLDER_GOAL_RE = re.compile(r"^(todo|task\s*\d+)$", re.IGNORECASE) +_TEMPLATE_MARKER_RE = re.compile( + r"<[A-Za-z][A-Za-z0-9]*(?:[ _-][A-Za-z0-9]+)+>|\{[A-Za-z][A-Za-z0-9]*(?:[ _-][A-Za-z0-9]+)+\}" +) +_MIN_BATCH_GOAL_LEN = 10 + +def _recover_tasks_from_json_string(tasks: Any) -> tuple[Optional[List[Dict[str, Any]]], Optional[str]]: + """``(parsed_list, None)`` for a JSON-array string, ``(None, error)`` for a bad string, ``(None, None)`` otherwise.""" + if not isinstance(tasks, str): + return None, None + raw = tasks.strip() + if not raw: + return None, "Provide either 'goal' (single task) or 'tasks' (batch)." + try: + parsed = json.loads(raw) + except json.JSONDecodeError as exc: + return None, f"tasks must be a JSON array of task objects; received a string that could not be parsed as JSON ({exc.msg})." + if not isinstance(parsed, list): + return None, f"tasks must be a JSON array of task objects; parsed {type(parsed).__name__} instead." + return parsed, None + +def _validate_batch_tasks(task_list: List[Dict[str, Any]]) -> Optional[str]: + """Batch-only quality gate beyond per-task goal presence; actionable error or None. No minimum count: a one-entry + array is the canonical single-task shape (legacy top-level `goal` is wrapped into one). Duplicate goals are + deliberately NOT rejected — identical-goal fan-outs (best-of-N / ensemble sampling) are legitimate and blocking + them broke real workflows. The too-short check applies only to multi-task fan-outs (terse goals there are + usually unexpanded templates); a SINGLE task legitimately uses short goals ("Fix the tests"). + + See #81141. + """ + for i, task in enumerate(task_list): + goal = str(task.get("goal", "")).strip() + if _PLACEHOLDER_GOAL_RE.match(" ".join(goal.lower().split())): + return ( + f"Task {i} has a placeholder goal ({goal!r}). Replace it " + "with a specific, self-contained description of what the subagent should accomplish." + ) + marker = _TEMPLATE_MARKER_RE.search(goal) + if marker: + return ( + f"Task {i} goal contains an unexpanded template marker " + f"({marker.group(0)!r}). Substitute the real value before " + "calling delegate_task — subagents cannot resolve placeholders." + ) + if len(goal) < _MIN_BATCH_GOAL_LEN and len(task_list) >= 2: + return ( + f"Task {i} goal is too short ({goal!r}). Write a specific, " + f"self-contained goal of at least {_MIN_BATCH_GOAL_LEN} characters so the subagent knows " + "exactly what to do." + ) + return None + +def _normalize_task_list( + goal, context, tasks, output_schema, top_role: str, max_children: int +) -> tuple[Optional[List[Dict[str, Any]]], Optional[str]]: + """``(task_list, None)`` from ``tasks=[...]`` or the legacy single ``goal``, else ``(None, error)``.""" + recovered_tasks, tasks_error = _recover_tasks_from_json_string(tasks) + if tasks_error: + return None, tasks_error + if recovered_tasks is not None: + tasks = recovered_tasks + # Small models emit tasks=[] alongside a single goal: treat as "no batch". + if isinstance(tasks, list) and not tasks: + tasks = None + + if tasks and isinstance(tasks, list): + if len(tasks) > max_children: + return None, ( + f"Too many tasks: {len(tasks)} provided, but max_concurrent_children is {max_children}. " + f"Either reduce the task count, split into multiple delegate_task calls, or increase " + f"delegation.max_concurrent_children in config.yaml." + ) + task_list = tasks + elif goal and isinstance(goal, str) and goal.strip(): + task_list = [{"goal": goal, "context": context, "role": top_role}] + if output_schema is not None: + task_list[0]["output_schema"] = output_schema + else: + return None, ( + "No tasks provided. Pass tasks=[{goal: '...', context: '...'}, " + "...] — one entry per subagent (a single task is a one-entry array)." + ) + + for i, task in enumerate(task_list): + if not isinstance(task, dict): + return None, f"Task {i} must be an object, got {type(task).__name__}." + if not task.get("goal", "").strip(): + return None, f"Task {i} is missing a 'goal'." + # The single-goal form is exempt from the batch gate (short goals are valid there). + batch_error = _validate_batch_tasks(task_list) if isinstance(tasks, list) else None + return (None, batch_error) if batch_error else (task_list, None) + +def _coerce_task_schemas( + task_list: List[Dict[str, Any]], output_schema: Optional[Dict[str, Any]] +) -> tuple[List[Optional[Dict[str, Any]]], Optional[str]]: + """Per-task coerced output schemas. A malformed output_schema fails the whole call before any child spawns; + schema-less tasks resolve to None and take no new code paths downstream.""" + from tools.delegation_output_schema import coerce_output_schema + task_schemas: List[Optional[Dict[str, Any]]] = [] + for i, task in enumerate(task_list): + raw_schema = task.get("output_schema") + if raw_schema is None and len(task_list) == 1 and output_schema is not None: + raw_schema = output_schema + coerced_schema, schema_err = coerce_output_schema(raw_schema) + if schema_err: + return [], f"Task {i} output_schema invalid: {schema_err}" + task_schemas.append(coerced_schema) + return task_schemas, None + +# Per-task image ceiling: enough for screenshots/mocks while keeping the child's first request small. +_MAX_TASK_IMAGES = 8 + +def _normalize_task_images(task: dict, i: int) -> tuple[Optional[List[str]], Optional[str]]: + """``(cleaned_list_or_None, None)`` for a task's optional ``images`` (local paths, http(s) or data: URLs), else + ``(None, error)``. A bare string is wrapped into a one-entry list (small models emit scalars for arrays).""" + raw = task.get("images") + if raw is None: + return None, None + if isinstance(raw, str): + raw = [raw] + if not isinstance(raw, list): + return None, f"Task {i} 'images' must be an array of local file paths or http(s) URLs." + cleaned: List[str] = [] + for item in raw: + if not isinstance(item, str) or not item.strip(): + return None, f"Task {i} 'images' entries must be non-empty strings (local file paths or http(s) URLs)." + cleaned.append(item.strip()) + if len(cleaned) > _MAX_TASK_IMAGES: + return None, ( + f"Task {i} has {len(cleaned)} images; the per-task limit is {_MAX_TASK_IMAGES}. " + "Trim to the images the child actually needs to see." + ) + return (cleaned or None), None + +def _coerce_task_images( + task_list: List[Dict[str, Any]], images: Optional[List[str]] +) -> tuple[List[Optional[List[str]]], Optional[str]]: + """Per-task validated image lists; a malformed list fails the whole call before any child spawns. The legacy + top-level ``images`` applies to a single task only, like ``output_schema``.""" + task_images: List[Optional[List[str]]] = [] + for i, task in enumerate(task_list): + if task.get("images") is None and len(task_list) == 1 and images is not None: + task = {**task, "images": images} + cleaned, err = _normalize_task_images(task, i) + if err: + return [], err + task_images.append(cleaned) + return task_images, None diff --git a/tools/delegation_live_log.py b/tools/delegation_live_log.py new file mode 100644 index 0000000000000000000000000000000000000000..d2d2e0325ef0fa47a5386184406e35ebb417e541 --- /dev/null +++ b/tools/delegation_live_log.py @@ -0,0 +1,315 @@ +"""Live, tail-able transcripts for delegated subagents. + +One append-only log per child under ``/cache/delegation/live/ +/task-.log``, pre-created with a header at dispatch (so +``tail -f`` attaches immediately); paths are returned from ``delegate_task``. +``cache/delegation`` is mounted read-only into remote terminal backends, so +every line written here must be credential-redacted. Never raises into the +agent loop; append mode per write (close() is the flush); 7-day retention. +""" + +from __future__ import annotations + +import json +import logging +import shutil +import threading +import time +import uuid +from contextlib import contextmanager +from pathlib import Path +from typing import Any, Dict, List, Optional + +logger = logging.getLogger(__name__) + +LIVE_RETENTION_DAYS = 7 + +# Per-line truncation budgets (chars): the .log is a compact operational view; +# the child's SessionDB transcript and summary spill files carry full text. +_ASSISTANT_MAX = 600 +_THINKING_MAX = 300 +_ARGS_MAX = 220 +_RESULT_MAX = 400 +_KICKOFF_MAX = 500 +# Stream deltas are buffered and flushed as one assistant line when another +# event type arrives (or on completion); capped so a huge reply can't hold memory. +_STREAM_BUFFER_FLUSH_CHARS = 4000 +_TIME_FMT = "%Y-%m-%d %H:%M:%S" + + +def live_transcript_root() -> Path: + """Root directory for live transcripts (profile-safe, never ~/.hermes).""" + from hermes_constants import get_hermes_dir + return get_hermes_dir("cache/delegation", "delegation_cache") / "live" + + +@contextmanager +def _best_effort(what: str): + """Swallow and debug-log any failure: nothing here may reach the agent loop.""" + try: + yield + except Exception as exc: # noqa: BLE001 + logger.debug("Live transcript %s failed: %s", what, exc) + + +def _one_line(text: Any, limit: int) -> str: + """Collapse to a single line and truncate with an elided-chars note.""" + s = " ".join(str(text or "").split()) + if len(s) > limit: + s = s[:limit] + f" …(+{len(s) - limit} chars)" + return s + + +def _redact(text: str) -> str: + """Mask credentials (``force=True``: safety boundary, even when the global + toggle is off); if the redactor is unavailable, withhold rather than leak.""" + if not text: + return text + try: + from agent.redact import redact_sensitive_text + return redact_sensitive_text(text, force=True) or "" + except Exception: # pragma: no cover - core module; never leak on failure + return "[line withheld: redaction unavailable]" + + +def _joined(*parts: str) -> str: + return " ".join(filter(None, parts)) + + +def _dump_json(path: Path, payload: Dict[str, Any]) -> None: + path.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8") + + +class LiveTranscriptWriter: + """Append-only event log for ONE subagent task. Best-effort: the first write + failure flips ``_ok`` off and later calls become debug-logged no-ops.""" + + def __init__(self, delegation_id: str, task_index: int, goal: str, + context: Optional[str] = None, root: Optional[Path] = None): + self.delegation_id = delegation_id + self.task_index = task_index + self._ok = False + self._lock = threading.Lock() + self._stream_buf: List[str] = [] + self._stream_len = 0 + self.path: Optional[Path] = None + with _best_effort(f"init ({delegation_id} task {task_index})"): + goal_line = _one_line(goal, _KICKOFF_MAX) + d = (root if root is not None else live_transcript_root()) / delegation_id + d.mkdir(parents=True, exist_ok=True) + path = d / f"task-{task_index}.log" + path.write_text( + "=== Hermes subagent live transcript ===\n" + f"delegation: {delegation_id} task: {task_index}\n" + f"goal: {_redact(goal_line)}\n" # header bypasses event(), so redact here too + f"started: {time.strftime(_TIME_FMT)}\n" + "(append-only; streams while the subagent runs — tail -f me)\n" + + "=" * 40 + "\n", encoding="utf-8") + self.path, self._ok = path, True + self.event("user", "kickoff: " + goal_line + + (f" | context: {_one_line(context, _KICKOFF_MAX)}" if context else "")) + + def event(self, role: str, text: str) -> None: + """Append one ``HH:MM:SS role | text`` line. Single choke point: every typed + helper funnels through here so one redaction covers everything.""" + if not self._ok or self.path is None: + return + line = f"{time.strftime('%H:%M:%S')} {role:<9}| {_redact(text)}\n" + try: + with self._lock, open(self.path, "a", encoding="utf-8") as fh: + fh.write(line) + except Exception as exc: + self._ok = False + logger.debug("Live transcript write failed (%s): %s", self.path, exc) + + def _line(self, role: str, text: str, limit: int) -> None: + if t := _one_line(text, limit): + self.event(role, t) + + def assistant_text(self, text: str) -> None: + self._line("assistant", text, _ASSISTANT_MAX) + + def thinking(self, text: str) -> None: + self._line("think", text, _THINKING_MAX) + + def tool_start(self, name: str, args_preview: Any = None) -> None: + self.flush_stream() + self.event("tool", f"-> {name or '?'}({_one_line(args_preview, _ARGS_MAX)})") + + def tool_result(self, name: str, result: Any = None, + duration: Any = None, is_error: bool = False) -> None: + status = "ERROR" if is_error else "ok" + try: + dur = "" if duration is None else f" {float(duration):.1f}s" + except (TypeError, ValueError): + dur = "" + self.event("result", f"{name or '?'} {status}{dur}: {_one_line(result, _RESULT_MAX)}") + + def marker(self, text: str) -> None: + """Lifecycle marker: start / final / error / interrupt / budget.""" + self.flush_stream() + self.event("final", _one_line(text, _ASSISTANT_MAX)) + + def add_stream_delta(self, delta: str) -> None: + """Buffer streamed assistant reply text; flushed as one line.""" + if not delta or not self._ok: + return + self._stream_buf.append(delta) + self._stream_len += len(delta) + if self._stream_len >= _STREAM_BUFFER_FLUSH_CHARS: + self.flush_stream() + + def flush_stream(self) -> None: + if self._stream_buf: + text, self._stream_buf, self._stream_len = "".join(self._stream_buf), [], 0 + self.assistant_text(text) + + def _on_complete(self, tool_name, preview, args, kwargs): + dur = kwargs.get("duration_seconds") + summary = kwargs.get("summary") or preview + self.marker(_joined( + f"status={kwargs.get('status', '?')}", + f"duration={dur}s" if dur is not None else "", + f"summary: {_one_line(summary, _RESULT_MAX)}" if summary else "")) + + # Event demux (the tool_progress_callback surface): handler(self, tool_name, preview, args, kwargs). + _OBSERVERS = { + "tool.started": lambda s, n, p, a, kw: s.tool_start(str(n or ""), p if p else a), + "tool.completed": lambda s, n, p, a, kw: s.tool_result( + str(n or ""), result=kw.get("result"), duration=kw.get("duration"), + is_error=bool(kw.get("is_error"))), + # Fired as cb("_thinking", ) — text rides in the tool_name slot. + "_thinking": lambda s, n, p, a, kw: s.thinking(str(n or p or "")), + # cb("reasoning.available", "_thinking", , None) + "reasoning.available": lambda s, n, p, a, kw: s.thinking(str(p or "")), + "subagent.text": lambda s, n, p, a, kw: s.add_stream_delta(str(p or "")), + "subagent.start": lambda s, n, p, a, kw: s.event("start", _one_line(p, _KICKOFF_MAX)), + "subagent.complete": _on_complete} + + def observe(self, event_type: Any, tool_name: Any = None, preview: Any = None, + args: Any = None, **kwargs: Any) -> None: + """Map a child tool_progress_callback event onto transcript lines. + Unknown events are ignored. Never raises (event() swallows I/O).""" + handler = self._OBSERVERS.get(str(event_type or "")) + if handler is not None: + handler(self, tool_name, preview, args, kwargs) + + def finalize(self, entry: Dict[str, Any]) -> None: + """Terminal marker with exit-reason detail subagent.complete lacks.""" + exit_reason = entry.get("exit_reason") + self.marker(_joined( + f"end status={entry.get('status', '?')}", + f"exit_reason={exit_reason}" if exit_reason else "", + "(iteration budget exhausted)" if exit_reason == "max_iterations" else "", + f"error: {_one_line(entry['error'], _RESULT_MAX)}" if entry.get("error") else "")) + + +def wrap_progress_callback(inner_cb, writer: LiveTranscriptWriter): + """Wrap a child's tool_progress_callback (may be None) so events also land in + the log; writer failures never propagate. Preserves the ``_flush`` contract.""" + + def _cb(event_type, tool_name=None, preview=None, args=None, **kwargs): + with _best_effort("observe"): + writer.observe(event_type, tool_name, preview, args, **kwargs) + if inner_cb is not None: + inner_cb(event_type, tool_name, preview, args, **kwargs) + + def _flush(): + with _best_effort("flush"): + writer.flush_stream() + if callable(getattr(inner_cb, "_flush", None)): + inner_cb._flush() + + _cb._flush = _flush + return _cb + + +def create_live_transcripts( + task_list: List[Dict[str, Any]], context: Optional[str] = None, + delegation_id: Optional[str] = None, model: Optional[str] = None, + provider: Optional[str] = None, +) -> tuple[Optional[str], List[Optional[LiveTranscriptWriter]], List[str]]: + """One pre-headered writer per task + a manifest.json; prunes stale dirs. + Returns ``(delegation_id, writers, paths)``; on any top-level failure + ``(None, [None]*n, [])`` so delegation proceeds untouched.""" + n = len(task_list) + prune_stale_live_dirs() # best-effort; never raises + with _best_effort("creation"): + # Same id shape as async_delegation's so the dir name matches the handle. + deleg_id = delegation_id or f"deleg_{uuid.uuid4().hex[:8]}" + made = [LiveTranscriptWriter(deleg_id, i, str(t.get("goal", "")), context=t.get("context") or context) + for i, t in enumerate(task_list)] + writers: List[Optional[LiveTranscriptWriter]] = [w if w.path is not None else None for w in made] + paths: List[str] = [str(w.path) for w in made if w.path is not None] + if not paths: + return None, [None] * n, [] + _write_manifest(deleg_id, task_list, paths, model=model, provider=provider) + return deleg_id, writers, paths + return None, [None] * n, [] + + +def _manifest_path(delegation_id: str) -> Path: + return live_transcript_root() / delegation_id / "manifest.json" + + +def _write_manifest(delegation_id: str, task_list: List[Dict[str, Any]], + paths: List[str], model: Optional[str] = None, + provider: Optional[str] = None) -> None: + with _best_effort("manifest write"): + _dump_json(_manifest_path(delegation_id), { + "delegation_id": delegation_id, "started": time.strftime(_TIME_FMT), + "task_count": len(task_list), "model": model, "provider": provider, + "tasks": [{ + "index": i, + # Same mounted dir as the .log files, so the goal needs the same redaction. + "goal": _redact(str(t.get("goal", ""))[:500]), + "log": paths[i] if i < len(paths) else None, + "status": "running"} for i, t in enumerate(task_list)]}) + + +def update_manifest_statuses(delegation_id: Optional[str], + results: List[Dict[str, Any]]) -> None: + """Best-effort per-task status update once the batch has aggregated.""" + if not delegation_id: + return + with _best_effort("manifest update"): + mp = _manifest_path(delegation_id) + manifest = json.loads(mp.read_text(encoding="utf-8")) + by_index = {r.get("task_index"): r for r in results if isinstance(r, dict)} + for task in manifest.get("tasks", []): + r = by_index.get(task.get("index")) + if r is not None: + task["status"] = r.get("status", task.get("status")) + if r.get("exit_reason"): + task["exit_reason"] = r["exit_reason"] + manifest["completed"] = time.strftime(_TIME_FMT) + _dump_json(mp, manifest) + + +def prune_stale_live_dirs(max_age_days: int = LIVE_RETENTION_DAYS) -> int: + """Remove live/ dirs older than the retention window. Best-effort.""" + removed = 0 + with _best_effort("pruning"): + root = live_transcript_root() + if not root.is_dir(): + return 0 + cutoff = time.time() - max_age_days * 86400 + for child in root.iterdir(): + try: + if child.is_dir() and child.stat().st_mtime < cutoff: + shutil.rmtree(child, ignore_errors=True) + removed += 1 + except OSError: + continue + return removed + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. + +def new_live_delegation_id() -> str: + """Same shape as async_delegation's ids so the dir name matches the handle.""" + return f"deleg_{uuid.uuid4().hex[:8]}" +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/delegation_output_schema.py b/tools/delegation_output_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..ea9833b1d8eb651a2a17b31c05621cadd8c65849 --- /dev/null +++ b/tools/delegation_output_schema.py @@ -0,0 +1,116 @@ +"""Structured-output schema helpers for delegate_task. + +Optional per-task ``output_schema`` (a JSON Schema object): the child gets an +OUTPUT CONTRACT block appended to its context, the parent validates the final +answer with jsonschema, and on failure sends exactly ONE bounded retry turn +carrying the validation errors verbatim (more retries make frontier models +drop fields that were right the first time; the schema is never re-pasted). +""" + +from __future__ import annotations + +import json +import logging +from typing import Any, Dict, List, Optional, Tuple + +logger = logging.getLogger(__name__) + + +def coerce_output_schema(raw: Any) -> Tuple[Optional[Dict[str, Any]], Optional[str]]: + """``(schema, None)`` when usable, ``(None, error)`` when not; ``None`` input + passes through as ``(None, None)`` (no schema requested).""" + if raw is None: + return None, None + if isinstance(raw, str): + # Models sometimes double-encode the schema as a JSON string. + try: + raw = json.loads(raw) + except (ValueError, TypeError): + return None, "output_schema must be a JSON Schema object, got a non-JSON string." + if not isinstance(raw, dict): + return None, "output_schema must be a JSON Schema object." + if not isinstance(raw, dict): + return None, f"output_schema must be a JSON Schema object, got {type(raw).__name__}." + try: + from jsonschema.validators import validator_for # type: ignore[import-untyped] + validator_for(raw).check_schema(raw) + except ImportError: + # Degrade to accepting the dict as-is so delegation still works without jsonschema. + logger.debug("jsonschema unavailable; skipping output_schema meta-validation") + except Exception as exc: + return None, f"output_schema is not a valid JSON Schema: {exc}" + return raw, None + + +def append_output_contract(context: Optional[str], schema: Dict[str, Any]) -> str: + """Append the explicit output contract block to a child's context.""" + try: + schema_text = json.dumps(schema, indent=2, ensure_ascii=False) + except (TypeError, ValueError): + schema_text = str(schema) + block = ("OUTPUT CONTRACT (machine-validated):\n" + "Your FINAL response must be a single JSON object that validates " + "against this JSON Schema. No prose before or after the JSON; a " + "```json code fence is acceptable but not required.\n" f"{schema_text}") + base = (context or "").rstrip() + return f"{base}\n\n{block}" if base else block + + +def extract_json_candidate(text: str) -> str: + """Strip markdown fences and prose around the outermost ``{...}``/``[...]``.""" + raw = (text or "").strip() + if raw.startswith("```"): + raw = raw.split("\n", 1)[-1] + if raw.rstrip().endswith("```"): + raw = raw.rstrip()[: -3] + raw = raw.strip() + if raw.lower().startswith("json\n"): + raw = raw.split("\n", 1)[1] + for opener, closer in (("{", "}"), ("[", "]")): + if raw.startswith(opener): + return raw + start = raw.find(opener) + end = raw.rfind(closer) + if start >= 0 and end > start: + return raw[start : end + 1] + return raw + + +def validate_output(text: str, schema: Dict[str, Any]) -> Tuple[bool, List[str]]: + """``(True, [])`` or ``(False, errors)`` with strings suitable for the retry turn.""" + candidate = extract_json_candidate(text or "") + if not candidate.strip(): + return False, ["Response was empty — expected a JSON object matching the schema."] + try: + parsed = json.loads(candidate) + except (ValueError, TypeError) as exc: + return False, [f"Response is not valid JSON: {exc}"] + try: + from jsonschema.validators import validator_for # type: ignore[import-untyped] + except ImportError: + logger.debug("jsonschema unavailable; accepting parsed JSON without validation") + return True, [] + validator = validator_for(schema)(schema) + errors = sorted(validator.iter_errors(parsed), key=lambda e: list(e.absolute_path)) + rendered = [ # bound error volume for the retry prompt + "$" + "".join(f"[{p}]" if isinstance(p, int) else f".{p}" for p in err.absolute_path) + f": {err.message}" + for err in errors[:10]] + return not rendered, rendered + + +def build_retry_message(errors: List[str]) -> str: + """Single bounded retry turn: errors verbatim, schema deliberately NOT re-pasted.""" + error_block = "\n".join(f"- {e}" for e in errors) + return ("Your previous final response was rejected by the output contract " + "validator. Validation errors:\n" f"{error_block}\n\n" + "Reply with ONLY the corrected JSON object matching the OUTPUT " + "CONTRACT schema from your task context. No prose, no explanations.") + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. + +MAX_SCHEMA_RETRIES = 1 +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/desktop_ui.py b/tools/desktop_ui.py new file mode 100644 index 0000000000000000000000000000000000000000..6f9b013430177c1fc92a9c51d7a708b3b0305344 --- /dev/null +++ b/tools/desktop_ui.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Bridge desktop-only tools to Hermes-desktop renderer events. + +The desktop ``tui_gateway`` installs an emitter via :func:`set_emitter`; elsewhere it +stays ``None`` and tools report "desktop only". Routing keys off ``HERMES_UI_SESSION_ID`` +so the event lands on the window that owns the turn (the sink is lock-guarded). +""" + +import json +from typing import Callable, Optional + +from gateway.session_context import get_session_env +from tools.registry import tool_error + +# (sid, event, payload) sink, installed by the desktop gateway. +_emit: Optional[Callable[[str, str, dict], None]] = None + + +def set_emitter(fn: Optional[Callable[[str, str, dict], None]]) -> None: + """Install (or clear) the renderer-event sink. Called by the desktop gateway.""" + global _emit + _emit = fn + + +def available() -> bool: + """True when running under the desktop app (an emitter is wired).""" + return _emit is not None + + +def user_enabled(setting: str, default: bool) -> bool: + """Read a desktop Appearance switch from ``display.``. The renderer mirrors + these toggles onto the CONNECTED gateway's config, so this is the user's real answer + for local/SSH/URL/cloud gateways alike; ``check_fn``s use it to withdraw a tool from + the schema. Unreadable config -> ``default`` so a shipped-on feature does not vanish + on a transient read error.""" + try: + from hermes_cli.config import load_config_readonly + display = load_config_readonly().get("display") + except Exception: + return default + if not isinstance(display, dict) or setting not in display: + return default + return bool(display.get(setting)) + + +def emit(event: str, payload: dict) -> bool: + """Route ``event`` to the window owning the current turn; False when no emitter.""" + if _emit is None: + return False + _emit(get_session_env("HERMES_UI_SESSION_ID", ""), event, payload) + return True + + +def emit_or_error(event: str, payload: dict, fail_prefix: str, desktop_only: str, result: dict) -> str: + """Emit ``event``; ``tool_error`` text on failure (``fail_prefix`` + exception, or + ``desktop_only`` when no emitter), else ``result`` as JSON. Calls ``emit`` via the + module attribute so tests can patch it.""" + try: + ok = emit(event, payload) + except Exception as exc: + return tool_error(f"{fail_prefix}{exc}") + return json.dumps(result, ensure_ascii=False) if ok else tool_error(desktop_only) + + +def passthrough_json(raw) -> str: + """Desktop answers with a JSON object; pass it through, else wrap the raw text.""" + try: + return json.dumps(json.loads(raw), ensure_ascii=False) + except (TypeError, ValueError): + return json.dumps({"text": str(raw)}, ensure_ascii=False) diff --git a/tools/env_probe.py b/tools/env_probe.py new file mode 100644 index 0000000000000000000000000000000000000000..6805eb807818501cf996b5709c5fc33be39657a8 --- /dev/null +++ b/tools/env_probe.py @@ -0,0 +1,255 @@ +"""Local-environment toolchain probe for the system prompt: when the terminal backend +is local, one deterministic line about Python tooling (python3/python versions, missing +pip, pip bound to another Python, PEP 668) so models don't discover it by hitting +walls. Cached per process; "" when clean. Remote backends are skipped (the sandbox has +its own probe in agent/prompt_builder). Toggle: ``agent.environment_probe`` in config.yaml.""" + +from __future__ import annotations + +import logging +import shutil +import subprocess +import tempfile +import threading +from typing import Optional + +from hermes_cli._subprocess_compat import windows_hide_flags + +logger = logging.getLogger(__name__) + +# Concurrency model: exactly ONE background worker runs the probe; ``_PROBE_DONE`` +# signals completion. Callers block at most ``_PROBE_WAIT_TIMEOUT`` s then fail open +# with "" — a stuck probe (e.g. a Windows pipe wedged by an orphaned pip descendant) +# can degrade only the probe line, never system-prompt construction. +# Module-level cache. The probe result is deterministic for the lifetime of the process — Python install +# state doesn't change mid-session in any way that would matter for the system prompt. See #67964. +_CACHE_LOCK = threading.Lock() +_CACHED_LINE: Optional[str] = None # None = not probed yet; "" = probed, nothing to say. +_PROBE_DONE = threading.Event() +_PROBE_THREAD: Optional[threading.Thread] = None +_PROBE_GEN = 0 # bumped on reset so a stale worker can't publish into the fresh generation +_PROBE_WAIT_TIMEOUT = 10.0 # healthy runtime ~0.5s +_WAIT_ALREADY_TIMED_OUT = False # after one full wait, later callers only peek + +# Keep in sync with agent/prompt_builder.py:_REMOTE_TERMINAL_BACKENDS. +# Duplicated rather than imported to avoid a circular import. +_REMOTE_BACKENDS = frozenset({ + "docker", "singularity", "modal", "daytona", "ssh", "managed_modal", + "vercel_sandbox", +}) + + +def _plugin_backend_is_remote(backend: str) -> bool: + """Whether a plugin-registered terminal backend is remote (fail-soft).""" + if not backend or backend in _REMOTE_BACKENDS or backend == "local": + return False + try: + from agent.terminal_env_registry import provider_flag + + return bool(provider_flag(backend, "is_remote", False)) + except Exception: + return False + + +def _run(cmd: list[str], timeout: float = 3.0) -> tuple[int, str, str]: + """Run a short subprocess -> (returncode, stdout, stderr); failures (binary + missing, timeout, OSError) return (-1, "", ""). Output goes through temp + files, not pipes, so ``timeout`` bounds the *whole* call even on native Windows: a + console-script launcher (``pip.exe``) can spawn a descendant that inherits the + captured handles and outlives its parent; with OS pipes ``communicate()``'s reader + threads block until that grandchild closes the write end (a warm probe could hang + ~28 min holding ``_CACHE_LOCK``). Temp files make ``wait()`` cover only the child.""" + try: + with tempfile.TemporaryFile() as out_f, tempfile.TemporaryFile() as err_f: + try: + result = subprocess.run( + cmd, stdout=out_f, stderr=err_f, timeout=timeout, check=False, + # CREATE_NO_WINDOW (0 on POSIX): pythonw hosts would flash a console + stdin=subprocess.DEVNULL, creationflags=windows_hide_flags()) + except subprocess.TimeoutExpired: + return -1, "", "timeout" + out_f.seek(0) + err_f.seek(0) + return (result.returncode, out_f.read().decode("utf-8", "replace").strip(), + err_f.read().decode("utf-8", "replace").strip()) + except FileNotFoundError: + return -1, "", "not found" + except OSError as exc: + return -1, "", f"oserror: {exc}" + + +def _py_out(binary: str, *args: str) -> Optional[str]: + """stdout of `` *args`` when the binary is on PATH and exits 0, else None.""" + if not shutil.which(binary): + return None + rc, out, _err = _run([binary, *args]) + return out if rc == 0 else None + + +def _python_version_of(binary: str) -> Optional[str]: + """Return a short version string like ``3.12.4`` for ``binary``, or None.""" + code = "import sys; print('.'.join(map(str, sys.version_info[:3])))" + return _py_out(binary, "-c", code) or None + + +def _has_pip_module(binary: str) -> bool: + """True if `` -m pip --version`` succeeds.""" + return _py_out(binary, "-m", "pip", "--version") is not None + + +def _detect_pep668(binary: str) -> bool: + """True when ```` is PEP-668 externally-managed (``EXTERNALLY-MANAGED`` + marker next to the stdlib, as Debian/Ubuntu ship).""" + code = ("import os; print('yes' if os.path.exists(os.path.join(" + "os.path.dirname(os.__file__), 'EXTERNALLY-MANAGED')) else 'no')") + return (_py_out(binary, "-c", code) or "").strip() == "yes" + + +def _pip_python_version() -> Optional[str]: + """If ``pip`` is on PATH, the Python version it's bound to — the trailing + ``(python X.Y)`` of ``pip --version`` (e.g. ``"3.12"``), else None.""" + out = _py_out("pip", "--version") or "" + if "(python " in out and out.endswith(")"): + return out.rsplit("(python ", 1)[1][:-1].strip() + return None + + +def _resolve_terminal_backend() -> str: + """Scope-aware terminal backend name (``local`` when unresolvable).""" + try: + from tools.terminal_scope import terminal_env + + return (terminal_env("TERMINAL_ENV") or "local").strip().lower() + except Exception: # never let policy resolution break prompt building + logger.debug("terminal backend resolution failed", exc_info=True) + return "local" + + +def _build_probe_line() -> str: + """Build the one-liner; "" when nothing notable is detected — the goal is to + save the model from an avoidable wall, not narrate a healthy environment.""" + py3_ver = _python_version_of("python3") + py_ver = _python_version_of("python") # for systems with a `python` alias + py3_has_pip = _has_pip_module("python3") if py3_ver else False + pip_bound_to = _pip_python_version() + py3_pep668 = _detect_pep668("python3") if py3_ver else False + # Bare which() is correct here (unlike Hermes's own uv call sites): this reports + # the environment *the model will see* in the terminal tool, whose PATH includes + # the Hermes-managed $HERMES_HOME/bin via local.py. + has_uv = shutil.which("uv") is not None + + mismatch = bool(pip_bound_to and py3_ver and not py3_ver.startswith(pip_bound_to)) + if py3_ver is not None and py3_has_pip and not mismatch and (not py3_pep668 or has_uv): + return "" + # Compact factual summary; ONE line so it doesn't dominate the prompt. + bits: list[str] = [] + if py3_ver: + bits.append(f"python3={py3_ver}" + ("" if py3_has_pip else " (no pip module)")) + else: + bits.append("python3=missing") + if py_ver and py_ver != py3_ver: + bits.append(f"python={py_ver}") + elif not py_ver and py3_ver: + # Common on Debian/Ubuntu — stop the model typing `python`. + bits.append("python=missing (use python3)") + if pip_bound_to: + if mismatch: + bits.append(f"pip→python{pip_bound_to} (mismatch)") + elif not py3_has_pip: + bits.append(f"pip→python{pip_bound_to}") # pip script works, `-m pip` doesn't + elif not py3_has_pip: + # (when `pip` is off PATH but `python3 -m pip` works, say nothing) + bits.append("pip=missing") + if py3_pep668: + bits.append("PEP 668=yes (use venv or uv)") + if has_uv: + bits.append("uv=installed") + return "Python toolchain: " + ", ".join(bits) + "." + + +def get_environment_probe_line(*, force_refresh: bool = False) -> str: + """Return the cached probe line (building it on first call); "" when the + environment is clean, so the prompt assembler drops the section. Waits at most + ``_PROBE_WAIT_TIMEOUT`` on the single worker, then fails open with "". + ``force_refresh`` is for tests. + + A wedged probe subprocess (#67964) therefore can never block system-prompt construction — at worst the + toolchain line is absent from prompts built while the probe is stuck. + """ + global _WAIT_ALREADY_TIMED_OUT + if force_refresh: + _reset_cache_for_tests() + # Resolve the backend HERE, in the caller's context: under gateway multiplexing the + # routed profile's backend lives in the per-turn terminal scope, which the worker + # thread does not inherit. Remote backends answer "" without consulting the cache + # — the cached line describes the HOST toolchain. + # See #68559. + backend = _resolve_terminal_backend() + if backend in _REMOTE_BACKENDS or _plugin_backend_is_remote(backend): + return "" + if _PROBE_DONE.is_set(): + return _CACHED_LINE or "" + _ensure_probe_started() + wait_timeout = 0.05 if _WAIT_ALREADY_TIMED_OUT else _PROBE_WAIT_TIMEOUT + if not _PROBE_DONE.wait(timeout=wait_timeout): + # Probe stuck or pathologically slow: the line is a nice-to-have, + # blocking prompt construction is an outage. Fail open. + if not _WAIT_ALREADY_TIMED_OUT: + _WAIT_ALREADY_TIMED_OUT = True + logger.warning( + "env_probe did not finish within %.0fs; building the system " + "prompt without the Python toolchain line", _PROBE_WAIT_TIMEOUT) + return "" + return _CACHED_LINE or "" + + +def _probe_worker(gen: int) -> None: + """Body of the single probe thread — computes and publishes the line.""" + global _CACHED_LINE + try: + line = _build_probe_line() + except Exception as exc: # never let probe failure propagate + logger.debug("env_probe failed: %s", exc) + line = "" + with _CACHE_LOCK: + if gen != _PROBE_GEN: + return # superseded by a reset (tests) — discard stale result + _CACHED_LINE = line + _PROBE_DONE.set() + + +def _ensure_probe_started() -> None: + """Start the probe worker if it isn't running and hasn't finished.""" + global _PROBE_THREAD + with _CACHE_LOCK: + if _PROBE_DONE.is_set() or (_PROBE_THREAD is not None and _PROBE_THREAD.is_alive()): + return + _PROBE_THREAD = threading.Thread( + target=_probe_worker, args=(_PROBE_GEN,), name="env-probe", daemon=True) + _PROBE_THREAD.start() + + +def warm_environment_probe_async() -> None: + """Start the probe in the background so the first system-prompt build doesn't + pay the ~0.5s of subprocess calls on the time-to-first-token path. Idempotent; + ``get_environment_probe_line`` waits (bounded) on the same worker.""" + _ensure_probe_started() + + +def _reset_cache_for_tests() -> None: + """Test helper — clear the cache between probe scenarios.""" + global _CACHED_LINE, _PROBE_THREAD, _PROBE_GEN, _WAIT_ALREADY_TIMED_OUT + with _CACHE_LOCK: + _CACHED_LINE = None + _PROBE_DONE.clear() + _PROBE_THREAD = None + _PROBE_GEN += 1 + _WAIT_ALREADY_TIMED_OUT = False + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. +import os # noqa: F401,E402 +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/feishu_doc_tool.py b/tools/feishu_doc_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..0fca3f0d9a7dc2df7f43f803c136beb477b08fdf --- /dev/null +++ b/tools/feishu_doc_tool.py @@ -0,0 +1,95 @@ +"""Feishu Document Tool -- read document content via Feishu/Lark API. + +Provides ``feishu_doc_read`` for reading document content as plain text. +Uses the same lazy-import + BaseRequest pattern as feishu_comment.py. +""" + +from tools.feishu_lark import ( # noqa: F401 (set_client/get_client are imported by feishu_comment) + _check_feishu, + build_request, + get_client, + raw_body, + set_client) +from tools.registry import registry, tool_error, tool_result + +_RAW_CONTENT_URI = "/open-apis/docx/v1/documents/:document_id/raw_content" + +FEISHU_DOC_READ_SCHEMA = { + "name": "feishu_doc_read", + "description": ( + "Read the full content of a Feishu/Lark document as plain text. " + "Useful when you need more context beyond the quoted text in a comment." + ), + "parameters": { + "type": "object", + "properties": { + "doc_token": { + "type": "string", + "description": "The document token (from the document URL or comment context).", + }, + }, + "required": ["doc_token"], + }, +} + + +def _handle_feishu_doc_read(args: dict, **kwargs) -> str: + doc_token = args.get("doc_token", "").strip() + if not doc_token: + return tool_error("doc_token is required") + client = get_client() + if client is None: + return tool_error("Feishu client not available (not in a Feishu comment context)") + try: + request = build_request("GET", _RAW_CONTENT_URI, paths={"document_id": doc_token}) + except ImportError: + return tool_error("lark_oapi not installed") + + # Handlers run synchronously in a worker thread (no event loop): call the blocking client. + response = client.request(request) + code = getattr(response, "code", None) + if code != 0: + return tool_error(f"Failed to read document: code={code} msg={getattr(response, 'msg', 'unknown error')}") + + body = raw_body(response) + if body is not None: + try: + return tool_result(success=True, content=body.get("data", {}).get("content", "")) + except AttributeError: + pass + data = getattr(response, "data", None) # fallback: the typed response.data + if data: + content = data.get("content", "") if isinstance(data, dict) else getattr(data, "content", str(data)) + return tool_result(success=True, content=content) + return tool_error("No content returned from document API") + + +registry.register( + name="feishu_doc_read", toolset="feishu_doc", schema=FEISHU_DOC_READ_SCHEMA, handler=_handle_feishu_doc_read, + check_fn=_check_feishu, requires_env=[], is_async=False, description="Read Feishu document content", + emoji="\U0001f4c4") + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. +import json # noqa: F401,E402 +import logging # noqa: F401,E402 +import threading # noqa: F401,E402 + + +_PLUGIN_COMPAT_LAZY = { + 'logger': ('tools.approval', 'logger'), +} + + +def __getattr__(name): # PEP 562 — lazy so no import cycles + target = _PLUGIN_COMPAT_LAZY.get(name) + if target is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + import importlib + from hermes_cli.plugin_compat import warn_once + warn_once(__name__, name, *target) + return getattr(importlib.import_module(target[0]), target[1]) +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/file_operations_common.py b/tools/file_operations_common.py new file mode 100644 index 0000000000000000000000000000000000000000..b15c0d36cf12530b223a526c59be58506592ab9c --- /dev/null +++ b/tools/file_operations_common.py @@ -0,0 +1,279 @@ +"""Result dataclasses and pure text helpers shared by ``tools.file_operations`` +and its search/lint mixins. Leaf module (imports nothing from ``tools`` at module +scope) so nothing cycles. The ``to_dict`` output of every class here IS tool +behavior — key names, order and omission rules are pinned by tests and read by +the model. +""" + +import re +from dataclasses import dataclass, field +from typing import Any, ClassVar, Dict, List, Optional + + +@dataclass +class ReadResult: + """Result from reading a file.""" + content: str = "" + total_lines: int = 0 + file_size: int = 0 + truncated: bool = False + hint: Optional[str] = None + is_binary: bool = False + is_image: bool = False + base64_content: Optional[str] = None + mime_type: Optional[str] = None + dimensions: Optional[str] = None # For images: "WIDTHxHEIGHT" + error: Optional[str] = None + similar_files: List[str] = field(default_factory=list) + + def to_dict(self) -> dict: + return {k: v for k, v in self.__dict__.items() if v is not None and v != []} + + +@dataclass +class WriteResult: + """Result from writing a file.""" + bytes_written: int = 0 + dirs_created: bool = False + # True when the on-disk sha256 matched the intended content; None when the + # backend couldn't verify (no sha256sum). A mismatch is a hard error, never a flag. + verified: Optional[bool] = None + lint: Optional[Dict[str, Any]] = None + # LSP semantic diagnostics, kept separate from ``lint`` (syntax) so the model + # reads the two as independent signals. None when LSP is off/inapplicable. + lsp_diagnostics: Optional[str] = None + error: Optional[str] = None + warning: Optional[str] = None + + def to_dict(self) -> dict: + return {k: v for k, v in self.__dict__.items() if v is not None} + + +@dataclass +class PatchResult: + """Result from patching a file.""" + success: bool = False + diff: str = "" + files_modified: List[str] = field(default_factory=list) + files_created: List[str] = field(default_factory=list) + files_deleted: List[str] = field(default_factory=list) + lint: Optional[Dict[str, Any]] = None + lsp_diagnostics: Optional[str] = None # see WriteResult.lsp_diagnostics + error: Optional[str] = None + # Success-shaped no-op: the edit was already present, nothing written; ``note`` says why. + no_change: bool = False + note: Optional[str] = None + + # Emission order is part of the output contract. + _DICT_FIELDS: ClassVar[tuple] = ( + "diff", "files_modified", "files_created", "files_deleted", + "lint", "lsp_diagnostics", "error", + ) + + def to_dict(self) -> dict: + result: Dict[str, Any] = {"success": self.success} + if self.no_change: + result["no_change"] = True + if self.note: + result["note"] = self.note + for key in self._DICT_FIELDS: + value = getattr(self, key) + if value: + result[key] = value + return result + + +@dataclass +class SearchMatch: + """A single search match.""" + path: str + line_number: int + content: str + mtime: float = 0.0 # Modification time for sorting + + +@dataclass +class SearchResult: + """Result from searching.""" + matches: List[SearchMatch] = field(default_factory=list) + files: List[str] = field(default_factory=list) + counts: Dict[str, int] = field(default_factory=dict) + total_count: int = 0 + truncated: bool = False + limit_reason: Optional[str] = None + warning: Optional[str] = None + error: Optional[str] = None + + # Below this many matches the verbose array is already compact enough that + # a path-grouping header would cost more tokens than it saves. + _DENSIFY_MIN_MATCHES: ClassVar[int] = 5 + + def _densify_matches(self) -> Optional[str]: + """Lossless path-grouped text block: path once, then `` : `` + rows. Relies on rg/grep emitting a file's hits consecutively. None when + too few matches to be worth it.""" + if len(self.matches) < self._DENSIFY_MIN_MATCHES: + return None + lines: list[str] = [] + current_path: Optional[str] = None + for m in self.matches: + if m.path != current_path: + lines.append(m.path) + current_path = m.path + # rstrip only: leading indentation is meaningful code and kept verbatim. + lines.append(f" {m.line_number}: {m.content.rstrip()}") + return "\n".join(lines) + + def to_dict(self, densify: bool = False) -> dict: + result: dict[str, object] = {"total_count": self.total_count} + if self.matches: + dense = self._densify_matches() if densify else None + if dense is not None: + # Self-describing so the model never guesses the block's shape. + result["matches_format"] = ( + "path-grouped: each file path on its own line, followed by " + "indented ': ' rows for matches in that file" + ) + result["matches_text"] = dense + else: + result["matches"] = [ + {"path": m.path, "line": m.line_number, "content": m.content} for m in self.matches + ] + if self.files: + result["files"] = self.files + if self.counts: + result["counts"] = self.counts + if self.truncated: + result["truncated"] = True + result["total_count_is_lower_bound"] = True + for key in ("limit_reason", "warning", "error"): + value = getattr(self, key) + if value: + result[key] = value + return result + + +@dataclass +class LintResult: + """Result from linting a file.""" + success: bool = True + skipped: bool = False + output: str = "" + message: str = "" + + def to_dict(self) -> dict: + if self.skipped: + return {"status": "skipped", "message": self.message} + result = {"status": "ok" if self.success else "error", "output": self.output} + if self.message: + result["message"] = self.message + return result + + +@dataclass +class ExecuteResult: + """Result from executing a shell command.""" + stdout: str = "" + exit_code: int = 0 + + +# --------------------------------------------------------------------------- +# Pure text helpers (no I/O) +# --------------------------------------------------------------------------- + +_OSC_SEQUENCE_RE = re.compile(r"\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)") +_FENCE_MARKER_RE = re.compile(r"'?\x07?__HERMES_FENCE_[A-Za-z0-9]+__\x07?'?") + + +def _strip_terminal_fence_leaks(text: str) -> str: + """Strip leaked terminal fence wrappers (OSC sequences, fence markers) from + command output; drops lines that were nothing but wrapper.""" + if not text: + return text + cleaned_lines: List[str] = [] + for line in text.splitlines(keepends=True): + had_terminal_wrapper = "__HERMES_FENCE_" in line or "\x1b]" in line + cleaned = _FENCE_MARKER_RE.sub("", _OSC_SEQUENCE_RE.sub("", line)).replace("\x07", "") + if had_terminal_wrapper and cleaned.strip("'\r\n\t ") == "": + continue + cleaned_lines.append(cleaned) + return "".join(cleaned_lines) + + +def _detect_line_ending(sample: str) -> Optional[str]: + """Dominant line ending of ``sample`` (``\\r\\n`` if any CRLF in the first 4KB, + else ``\\n``), or None for empty/single-line content. Preserves a file's + endings across write_file/patch: bare-LF tool args would otherwise silently + normalize CRLF files, and patch would produce mixed endings.""" + head = sample[:4096] if sample else "" + if "\r\n" in head: + return "\r\n" + if "\n" in head: + return "\n" + return None + + +def _normalize_line_endings(text: str, target: str) -> str: + """Convert every line ending (CRLF, lone CR, LF) in ``text`` to ``target``. + Idempotent. Collapses to LF first — separate replacements would + double-convert CRLF → LFLF.""" + lf_normalized = text.replace("\r\n", "\n").replace("\r", "\n") + if target == "\n": + return lf_normalized + if target == "\r\n": + return lf_normalized.replace("\n", "\r\n") + return text + + +# UTF-8 BOM (EF BB BF == U+FEFF), prepended by some Windows editors. Stripped on +# read so the model never sees a phantom first character (and patch's first-line +# match works), restored on write when the on-disk file had one. +_UTF8_BOM = "\ufeff" + + +def _strip_bom(text: str) -> tuple[str, bool]: + """Return (text-without-leading-BOM, had_bom). Only a leading BOM is + stripped; mid-content U+FEFF is legitimate data.""" + if _has_bom(text): + return text[len(_UTF8_BOM):], True + return text, False + + +def _has_bom(text: Optional[str]) -> bool: + """True if ``text`` begins with a UTF-8 BOM.""" + return bool(text) and text.startswith(_UTF8_BOM) + + +# --------------------------------------------------------------------------- +# Pagination clamps +# --------------------------------------------------------------------------- + +DEFAULT_READ_OFFSET = 1 +DEFAULT_READ_LIMIT = 2000 +DEFAULT_SEARCH_OFFSET = 0 +DEFAULT_SEARCH_LIMIT = 50 + + +def _coerce_int(value: Any, default: int) -> int: + """Best-effort integer coercion for tool pagination inputs.""" + try: + return int(value) + except (TypeError, ValueError): + return default + + +def normalize_read_pagination(offset: Any = DEFAULT_READ_OFFSET, + limit: Any = DEFAULT_READ_LIMIT) -> tuple[int, int]: + """Clamp read_file pagination so invalid values can never reach a sed range + like ``0,-1p`` (schemas declare bounds, but not every caller enforces them). + The ``limit`` ceiling is ``tool_output.max_lines`` from config.yaml.""" + from tools.tool_output_limits import get_max_lines + normalized_offset = max(1, _coerce_int(offset, DEFAULT_READ_OFFSET)) + normalized_limit = max(1, min(_coerce_int(limit, DEFAULT_READ_LIMIT), get_max_lines())) + return normalized_offset, normalized_limit + + +def normalize_search_pagination(offset: Any = DEFAULT_SEARCH_OFFSET, + limit: Any = DEFAULT_SEARCH_LIMIT) -> tuple[int, int]: + """Return safe search pagination bounds for shell head/tail pipelines.""" + return max(0, _coerce_int(offset, DEFAULT_SEARCH_OFFSET)), max(1, _coerce_int(limit, DEFAULT_SEARCH_LIMIT)) diff --git a/tools/file_operations_lint.py b/tools/file_operations_lint.py new file mode 100644 index 0000000000000000000000000000000000000000..edc4e4e1f1732a919aa028f8ba4af02fdd5d470b --- /dev/null +++ b/tools/file_operations_lint.py @@ -0,0 +1,295 @@ +"""Syntax-lint and LSP-diagnostics tier for ``tools.file_operations``. + +``ShellFileOperations`` inherits ``LintMixin``; module constants and in-process +linters are pure functions importable from this module. +""" + +import ast +import json +import os +import tomllib +from typing import Callable, Dict, Optional + +from tools.file_operations_common import LintResult + +# Shell linters by extension (external toolchain). ``.tsx`` is deliberately absent: +# it hits the "No linter" skip and LSP covers it when enabled. +LINTERS = { + '.py': 'python -m py_compile {file} 2>&1', + '.js': 'node --check {file} 2>&1', + '.ts': 'npx tsc --noEmit {file} 2>&1', + '.go': 'go vet {file} 2>&1', + '.rs': 'rustfmt --check {file} 2>&1', +} + +# Per-file shell linters that flood phantom errors on real projects (single-file +# ``tsc`` ignores tsconfig, ``go vet`` fails outside a module, ``rustfmt --check`` +# is style-only): skipped when an LSP server claims the file. py_compile / +# node --check are file-local and correct so always run. +_SHELL_LINTER_LSP_REDUNDANT = frozenset({'.ts', '.go', '.rs'}) + +# Output substrings (case-insensitive) meaning the linter binary exists but could +# not run → ``skipped`` so the write isn't flagged and the LSP tier still runs. +_LINTER_UNUSABLE_PATTERNS = { + 'npx': ( + 'this is not the tsc command you are looking for', # tsc not installed locally + 'could not determine executable to run', + 'not found in npm registry', + ), + 'rustfmt': ( + 'no input filename given', # outside a Cargo project + 'error: not a workspace', + ), + 'go': ( + 'cannot find package', # outside a module / GOPATH + 'go: cannot find main module', + ), +} + + +def _looks_like_linter_unusable(base_cmd: str, output: str) -> bool: + """True iff ``output`` from ``base_cmd`` (first word of the linter cmd) says the tool itself couldn't run.""" + patterns = _LINTER_UNUSABLE_PATTERNS.get(base_cmd) + if not patterns: + return False + lower = output.lower() + return any(p in lower for p in patterns) + + +def _lint_json_inproc(content: str) -> tuple[bool, str]: + """In-process JSON syntax check. Returns (ok, error_message).""" + try: + json.loads(content) + return True, "" + except json.JSONDecodeError as e: + return False, f"JSONDecodeError: {e.msg} (line {e.lineno}, column {e.colno})" + except Exception as e: # noqa: BLE001 — any parse failure is a lint failure + return False, f"{type(e).__name__}: {e}" + + +def _lint_yaml_inproc(content: str) -> tuple[bool, str]: + """In-process YAML syntax check; ``__SKIP__`` when PyYAML is missing. Syntax-only + (``yaml.parse``), NOT ``safe_load``: loading rejects valid multi-doc streams and + app tags (``!Sub``, ``!vault``), and this is a fail-closed WRITE gate.""" + try: + import yaml as _yaml + except ImportError: + return True, "__SKIP__" + try: + for _event in _yaml.parse(content): + pass + return True, "" + except _yaml.YAMLError as e: + return False, f"YAMLError: {e}" + except Exception as e: # noqa: BLE001 + return False, f"{type(e).__name__}: {e}" + + +def _lint_toml_inproc(content: str) -> tuple[bool, str]: + """In-process TOML syntax check (stdlib tomllib).""" + try: + tomllib.loads(content) + return True, "" + except Exception as e: # TOMLDecodeError is a ValueError subclass + return False, f"{type(e).__name__}: {e}" + + +def _lint_python_inproc(content: str) -> tuple[bool, str]: + """In-process Python syntax check via ast.parse (py_compile's scope, no subprocess).""" + try: + ast.parse(content) + return True, "" + except SyntaxError as e: + loc = f" (line {e.lineno}, column {e.offset})" if e.lineno else "" + return False, f"{type(e).__name__}: {e.msg}{loc}" + except Exception as e: # noqa: BLE001 + return False, f"{type(e).__name__}: {e}" + + +# In-process linters, preferred over shell linters (no subprocess). Each returns +# (ok, error); error ``"__SKIP__"`` = unavailable dependency, counts as "no linter". +LINTERS_INPROC: Dict[str, Callable[[str], tuple[bool, str]]] = { + '.py': _lint_python_inproc, + '.json': _lint_json_inproc, + '.yaml': _lint_yaml_inproc, + '.yml': _lint_yaml_inproc, + '.toml': _lint_toml_inproc, +} + +# Extensions where write_file REFUSES on a parse failure. ``.py`` is excluded on +# purpose: test fixtures use ``*.py`` paths as a stand-in for arbitrary text, so +# Python keeps the non-blocking lint-delta report. +_FAIL_CLOSED_INPROC_EXTS = frozenset({'.json', '.yaml', '.yml', '.toml'}) + + +class LintMixin: + """Post-write syntax lint + LSP diagnostics. Requires ``_exec``, + ``_has_command``, ``_escape_shell_arg``, ``_escape_native_tool_arg`` and + ``env`` from the host class.""" + + def _check_lint(self, path: str, content: Optional[str] = None) -> LintResult: + """Syntax-check ``path``: in-process linter when one matches the + extension (``content`` avoids a re-read), else the shell linter table.""" + ext = os.path.splitext(path)[1].lower() + inproc = LINTERS_INPROC.get(ext) + if inproc is not None: + if content is None: + read_result = self._exec(f"cat {self._escape_shell_arg(path)} 2>/dev/null") + if read_result.exit_code != 0: + return LintResult(skipped=True, message=f"Failed to read {path} for lint") + content = read_result.stdout + ok, err = inproc(content) + if err == "__SKIP__": + return LintResult(skipped=True, message=f"No linter available for {ext} (missing dependency)") + return LintResult(success=ok, output="" if ok else err) + if ext not in LINTERS: + return LintResult(skipped=True, message=f"No linter for {ext} files") + # Single-file tsc can't read tsconfig.json and floods phantom TS2307/TS2339 + # errors the delta filter misreports as "pre-existing"; let the LSP tier speak. + if ext == '.ts' and self._has_ancestor_tsconfig(path): + return LintResult(skipped=True, message=( + "Project tsconfig.json detected — per-file tsc skipped " + "(single-file tsc can't resolve project aliases/globals; " + "use the LSP tier or `tsc -p tsconfig.json` for real " + "diagnostics)." + )) + if ext in _SHELL_LINTER_LSP_REDUNDANT and self._lsp_will_handle(path): + return LintResult(skipped=True, message=f"LSP server handles {ext} — shell linter skipped") + linter_cmd = LINTERS[ext] + base_cmd = linter_cmd.split()[0] + if not self._has_command(base_cmd): + return LintResult(skipped=True, message=f"{base_cmd} not available") + # Native Windows binaries need C:/... not MSYS /c/... (→ phantom ENOENT). + result = self._exec(linter_cmd.replace("{file}", self._escape_native_tool_arg(path)), timeout=30) + if result.exit_code != 0 and _looks_like_linter_unusable(base_cmd, result.stdout): + from tools.ansi_strip import strip_ansi + cleaned = strip_ansi(result.stdout).strip() + # Collapse to one line — the npx banner is multi-line ASCII art. + first_line = next((ln.strip() for ln in cleaned.splitlines() if ln.strip()), cleaned[:120]) + return LintResult(skipped=True, message=f"{base_cmd} not usable: {first_line[:200]}") + return LintResult(success=result.exit_code == 0, output=result.stdout.strip()) + + def _check_lint_delta(self, path: str, pre_content: Optional[str], + post_content: Optional[str] = None) -> LintResult: + """Post-write lint; when it fails and ``pre_content`` is known, report only + errors this edit introduced (pre-existing lines filtered out). Semantic + (LSP) diagnostics are a separate channel — see ``_maybe_lsp_diagnostics``.""" + post = self._check_lint(path, content=post_content) + if post.success or post.skipped or pre_content is None: + return post + pre = self._check_lint(path, content=pre_content) + if pre.success or pre.skipped or not pre.output: + return post # pre-write was clean (or unlintable): all post errors are new + # Single-error parsers stop at the first error, so if every post error already + # existed we can't prove the edit is clean — say nothing new was introduced. + pre_lines = {ln.strip() for ln in pre.output.splitlines() if ln.strip()} + post_lines = [ln for ln in post.output.splitlines() if ln.strip() and ln.strip() not in pre_lines] + if not post_lines: + return LintResult(success=False, output=post.output, message=( + "Pre-existing lint errors — this edit didn't introduce new ones but the file is still broken.")) + return LintResult(success=False, output=( + "New lint errors introduced by this edit " + "(pre-existing errors filtered out):\n" + "\n".join(post_lines) + )) + + def _lsp_local_only(self) -> bool: + """True iff wired to a local backend. LSP servers run on the host and + can't see files inside Docker/Modal/SSH/Daytona sandboxes.""" + env = getattr(self, "env", None) # tests may build via __new__ without __init__ + if env is None: + return False + try: + from tools.environments.local import LocalEnvironment + except Exception: # noqa: BLE001 + return False + return isinstance(env, LocalEnvironment) + + def _lsp_service(self): + """The active LSPService, or None on a non-local backend / any failure. + LSP is an enrichment layer and must never break a write.""" + if not self._lsp_local_only(): + return None + try: + from agent.lsp import get_service + return get_service() + except Exception: # noqa: BLE001 + return None + + def _lsp_handles_extension(self, ext: str) -> bool: + """True iff some registered LSP server claims ``ext`` (static registry + only; safe on remote backends). Decides whether pre-write content is + worth capturing for the line-shift map.""" + if not ext: + return False + try: + from agent.lsp.servers import SERVERS + except Exception: # noqa: BLE001 + return False + return any(ext.lower() in srv.extensions for srv in SERVERS) + + def _has_ancestor_tsconfig(self, path: str) -> bool: + """True iff a tsconfig.json exists in ``path``'s directory or any ancestor. + Host-side walk, local backend only: on a remote backend this answers False so + the shell linter still runs — never suppress lint on a probe that couldn't answer.""" + if not self._lsp_local_only(): + return False + try: + d = os.path.dirname(os.path.abspath(path)) + while not os.path.isfile(os.path.join(d, "tsconfig.json")): + parent = os.path.dirname(d) + if parent == d: + return False + d = parent + return True + except Exception: # noqa: BLE001 + return False + + def _lsp_call(self, method: str, path: str, default): + """``svc.(path)`` on the active service; ``default`` when there is + no service or the call raises (LSP never breaks a write).""" + svc = self._lsp_service() + if svc is None: + return default + try: + return getattr(svc, method)(path) + except Exception: # noqa: BLE001 + return default + + def _lsp_will_handle(self, path: str) -> bool: + """True iff the LSP service is active AND ``enabled_for(path)`` (workspace + detection, disabled-server set, broken-pair short-circuit). Any failure → + False so the shell linter still runs.""" + return bool(self._lsp_call("enabled_for", path, False)) + + def _snapshot_lsp_baseline(self, path: str) -> None: + """Capture pre-edit LSP diagnostics so the post-write delta is correct. Silent on failure.""" + self._lsp_call("snapshot_baseline", path, None) + + def _maybe_lsp_diagnostics(self, path: str, *, pre_content: Optional[str] = None, + post_content: Optional[str] = None) -> str: + """Formatted LSP diagnostics introduced by this edit, or "" when LSP is + unavailable/disabled/clean. With both pre and post content a line-shift map + remaps baseline diagnostics into post-edit coordinates; otherwise every + pre-existing diagnostic below an inserted line would look new.""" + svc = self._lsp_service() + if svc is None or not svc.enabled_for(path): + return "" + line_shift = None + if pre_content is not None and post_content is not None and pre_content != post_content: + try: + from agent.lsp.range_shift import build_line_shift + line_shift = build_line_shift(pre_content, post_content) + except Exception: # noqa: BLE001 + line_shift = None + try: + diagnostics = svc.get_diagnostics_sync(path, delta=True, line_shift=line_shift) + except Exception: # noqa: BLE001 + return "" + if not diagnostics: + return "" + try: + from agent.lsp.reporter import report_for_file, truncate + block = report_for_file(path, diagnostics) + return truncate("LSP diagnostics introduced by this edit:\n" + block) if block else "" + except Exception: # noqa: BLE001 + return "" diff --git a/tools/file_operations_search.py b/tools/file_operations_search.py new file mode 100644 index 0000000000000000000000000000000000000000..c97fe6ace17b3b58f5d2bc8a0f70c48058b1bf09 --- /dev/null +++ b/tools/file_operations_search.py @@ -0,0 +1,938 @@ +"""Content/file search tier for ``tools.file_operations``. + +``ShellFileOperations`` inherits ``SearchMixin``; module-level helpers are pure +(no I/O). +""" + +import os +import posixpath +import re +import shlex +import subprocess +import sys +import threading +import time +from pathlib import Path +from typing import Any, List, Optional + +from agent.search_policy import SEARCH_PRUNE_DIR_NAMES +from tools import interrupt as tool_interrupt +from tools.file_operations_common import ExecuteResult, SearchMatch, SearchResult + +_MACOS_TCC_PROTECTED_HOME_DIRS = ( + "Desktop", "Documents", "Downloads", "Library", "Movies", "Music", "Pictures", +) + + +def _macos_protected_search_exclusions( + path: str, *, cwd: Optional[str] = None, home: Optional[str] = None, platform: Optional[str] = None, +) -> List[str]: + """Protected home dirs (relative to ``path``) below a broad macOS search root. + + Only an ANCESTOR search (``$HOME``, ``/Users``) gets exclusions, so recursive + tools never trigger unattended TCC prompts; a search rooted inside a + protected dir stays allowed. + """ + if (platform or sys.platform) != "darwin": + return [] + root = Path(path).expanduser() + if not root.is_absolute(): + root = Path(cwd or os.getcwd()) / root + root = Path(os.path.normpath(str(root))) + home_path = Path(os.path.normpath(str(Path(home or Path.home()).expanduser()))) + exclusions: List[str] = [] + for dirname in _MACOS_TCC_PROTECTED_HOME_DIRS: + try: + relative = (home_path / dirname).relative_to(root) + except ValueError: + continue + if relative.parts: + exclusions.append(relative.as_posix()) + return exclusions + + +# --- Filename-walk admission: one walk per (backend, root) at a time -------------- + +_FILENAME_SEARCH_ADMISSION = threading.Condition() +_ACTIVE_FILENAME_SEARCH_ROOTS: set[tuple[str, str, str]] = set() +_FILENAME_SEARCH_WAIT_SECONDS = 0.05 + + +def _normalized_filename_search_root(env: Any, root: str, fallback_cwd: str) -> str: + """Normalize a filename-walk root without resolving remote paths locally.""" + from tools.environments.local import LocalEnvironment, _IS_WINDOWS, _msys_to_windows_path + + cwd = getattr(env, "cwd", None) or fallback_cwd + if isinstance(env, LocalEnvironment): + if _IS_WINDOWS: + root = _msys_to_windows_path(root) + cwd = _msys_to_windows_path(cwd) + if not os.path.isabs(root): + root = os.path.join(cwd, root) + return os.path.normcase(os.path.abspath(os.path.normpath(root))) + if not posixpath.isabs(root): + root = posixpath.join(cwd, root) + return posixpath.normpath(root) + + +def _filename_search_root_keys(env: Any, roots: List[str], fallback_cwd: str) -> tuple[tuple[str, str, str], ...]: + """Unique backend/root admission keys in deterministic order.""" + env_type = type(env) + return tuple(sorted({ + (env_type.__module__, env_type.__qualname__, _normalized_filename_search_root(env, root, fallback_cwd)) + for root in roots})) + + +def _acquire_filename_search_roots(keys: tuple[tuple[str, str, str], ...]) -> bool: + """Atomically claim every key, polling for thread-scoped interruption.""" + with _FILENAME_SEARCH_ADMISSION: + while any(key in _ACTIVE_FILENAME_SEARCH_ROOTS for key in keys): + if tool_interrupt.is_interrupted(): + return False + _FILENAME_SEARCH_ADMISSION.wait(_FILENAME_SEARCH_WAIT_SECONDS) + if tool_interrupt.is_interrupted(): + return False + if tool_interrupt.is_interrupted(): + return False + return tool_interrupt.run_if_not_interrupted(lambda: _ACTIVE_FILENAME_SEARCH_ROOTS.update(keys)) + + +def _release_filename_search_roots(keys: tuple[tuple[str, str, str], ...]) -> None: + """Release a completed walk and leave no idle per-root state behind.""" + with _FILENAME_SEARCH_ADMISSION: + _ACTIVE_FILENAME_SEARCH_ROOTS.difference_update(keys) + _FILENAME_SEARCH_ADMISSION.notify_all() + + +_ADMISSION_INTERRUPTED_ERROR = ( + "File search was interrupted while waiting for another filename " + "search on the same root. Retry when ready.") + +_SEARCH_TIMEOUT_MARKER_RE = re.compile(r"\n?\[Command timed out after \d+s\]\s*$") + + +def _search_stdout_and_limit(result: ExecuteResult) -> tuple[str, Optional[str]]: + """Return stdout cleaned for parsing and a limit reason for search timeouts.""" + if result.exit_code == 124: + return _SEARCH_TIMEOUT_MARKER_RE.sub("", result.stdout), "search_timeout" + return result.stdout, None + + +# A real rg/grep output line is a whitespace-free path token followed by ``:`` +# (match/count), ``-`` (context), or nothing (files_only); tool diagnostics +# ("rg: ...", indented carets) never match. +_SEARCH_OUTPUT_RE = re.compile(r'^([A-Za-z]:)?[^\s:][^\n]*?[:\-]\d|^[^\s:][^\s]*$') + + +def _split_tool_diagnostics(output: str) -> tuple[str, str]: + """Separate rg/grep diagnostic lines from real match output → ``(diagnostics, payload)``. + ``_exec`` merges stderr into stdout; classifying by SHAPE lets the exit-2 guard + tell a pure failure (no payload) from a partial one (one unreadable file, others + matched) and guarantees error text is never parsed as a match.""" + diagnostics: list[str] = [] + payload: list[str] = [] + for line in output.split('\n'): + if not line.strip(): + continue + # Prefix check first: a match path can contain "-" (".../pytest-686/..."). + if line.lstrip().startswith(("rg: ", "grep: ")): + diagnostics.append(line) + elif line == "--" or _SEARCH_OUTPUT_RE.match(line): + payload.append(line) + else: + diagnostics.append(line) + return '\n'.join(diagnostics), '\n'.join(payload) + + +def _parse_search_context_line(line: str) -> tuple[str, int, str] | None: + """Parse a ``path-line-content`` context line using the RIGHTMOST numeric + separator (filenames may contain ``--`` segments): + ``dir/file-12-name.py-8-context`` → (``dir/file-12-name.py``, 8, ``context``).""" + if not line or line == "--": + return None + match = None + for candidate in re.finditer(r'-(\d+)-', line): + match = candidate + if match is None or match.start() == 0: + return None + return line[:match.start()], int(match.group(1)), line[match.end():] + + +_REGEX_NEWLINE_ESCAPE_RE = re.compile(r"(? bool: + """True when a content regex wants to match a newline: a literal newline or a + ``\\n`` escape with an ODD number of backslashes (``\\\\n`` is a literal + backslash+n and must not count).""" + return "\n" in pattern or bool(_REGEX_NEWLINE_ESCAPE_RE.search(pattern)) + + +def _is_line_oriented_newline_error(error: Optional[str]) -> bool: + """Return True for rg's hard error when multiline mode is required.""" + return bool(error) and "literal \"\\n\" is not allowed" in error and "--multiline" in error + + +def _maybe_warn_line_oriented_newline_pattern(result: SearchResult, pattern: str) -> SearchResult: + """Attach a newline-regex warning only when search found no usable results.""" + if result.total_count != 0 or not _pattern_has_regex_newline(pattern): + return result + if result.error and not _is_line_oriented_newline_error(result.error): + return result + result.error = None + result.warning = ( + "0 results found. Note: search_files content search is line-oriented " + "and does not run ripgrep with -U/--multiline, so `\\n` in the regex " + "does not match line breaks. Use context=N to inspect neighboring " + "lines, or escape as `\\\\n` when searching for a literal backslash+n.") + return result + + +# Match lines are "file:lineno:content". Windows paths carry a drive letter +# ("C:\path"), so a naive split(":") breaks — the regex handles both. +_MATCH_LINE_RE = re.compile(r'^([A-Za-z]:)?(.*?):(\d+):(.*)$') + +# Output-mode → engine flag (identical for rg and grep). +_OUTPUT_MODE_FLAGS = {"files_only": "-l", "count": "-c"} + + +def _parse_search_output(result, output_mode: str, limit: int, offset: int, + context: int, warning: Optional[str] = None) -> SearchResult: + """Parse rg/grep ``| head`` output into a SearchResult (shared by both engines). + Exit codes: 0=matches, 1=none, 2=error — but both tools return 2 on PARTIAL + errors (one unreadable file), so an error is surfaced only when exit==2 AND no + usable payload remains. ``warning`` is attached to files_only/content results.""" + stdout, limit_reason = _search_stdout_and_limit(result) + diagnostics, payload = _split_tool_diagnostics(stdout) + if result.exit_code == 2 and not payload.strip(): + error_msg = diagnostics.strip() or result.stdout.strip() or "Search error" + return SearchResult(error=f"Search failed: {error_msg}", total_count=0) + lines = [ln for ln in payload.strip().split('\n') if ln] + if output_mode == "files_only": + return SearchResult( + files=lines[offset:offset + limit], total_count=len(lines), + truncated=bool(limit_reason), limit_reason=limit_reason, warning=warning) + if output_mode == "count": + counts = {} + for line in lines: + if ':' in line: + path, n = line.rsplit(':', 1) + try: + counts[path] = int(n) + except ValueError: + pass + return SearchResult( + counts=counts, total_count=sum(counts.values()), + truncated=bool(limit_reason), limit_reason=limit_reason) + matches = [] + for line in lines: + if line == "--": + continue + m = _MATCH_LINE_RE.match(line) + if m: + matches.append(SearchMatch( + path=(m.group(1) or '') + m.group(2), line_number=int(m.group(3)), content=m.group(4)[:500], + )) + continue + # Context lines only when requested, to avoid false positives on dashy paths. + if context > 0: + parsed = _parse_search_context_line(line) + if parsed: + matches.append(SearchMatch(path=parsed[0], line_number=parsed[1], content=parsed[2][:500])) + total = len(matches) + return SearchResult( + matches=matches[offset:offset + limit], total_count=total, + truncated=total > offset + limit or bool(limit_reason), limit_reason=limit_reason, warning=warning, + ) + + +def _posix_roots(roots: List[str]) -> bool: + """Darwin-only: every root is POSIX-shaped (no drive letter / backslash).""" + return sys.platform == "darwin" and all( + not re.match(r"^[A-Za-z]:[\\/]", root) and "\\" not in root for root in roots) + + +class SearchMixin: + """File-name and content search via rg with find/grep fallbacks. Requires + ``_exec``, ``_has_command``, ``_expand_path``, ``_escape_shell_arg``, + ``_escape_native_tool_arg``, ``env``, ``cwd``, ``_command_cache``, + ``_rg_resolution_cache`` and ``_rg_modified_capability`` from the host class.""" + + # --- rg resolution -------------------------------------------------------- + + def _resolve_command(self, cmd: str) -> Optional[str]: + """Resolve an executable in the command host's namespace. Ordinary commands + keep the bool hit/miss cache; rg alone caches successful resolved paths and + re-probes misses so a mid-session install becomes visible (with off-PATH + Windows candidates: cargo, scoop, winget).""" + if cmd != "rg": + return cmd if self._has_command(cmd) else None + cached = self._rg_resolution_cache.get(cmd) + if cached: + return cached + result = self._exec("command -v rg 2>/dev/null") + if result.exit_code == 0 and result.stdout.strip(): + resolved = result.stdout.strip().splitlines()[0] + if resolved == "yes": # compatibility with old boolean-probe fakes + resolved = "rg" + self._rg_resolution_cache[cmd] = resolved + return resolved + from tools.environments.local import LocalEnvironment, _IS_WINDOWS + + if _IS_WINDOWS and isinstance(self.env, LocalEnvironment): + user_profile = os.environ.get("USERPROFILE") or str(Path.home()) + local_app_data = os.environ.get("LOCALAPPDATA") + scoop = os.environ.get("SCOOP") or os.path.join(user_profile, "scoop") + candidates = [ + os.path.join(user_profile, ".cargo", "bin", "rg.exe"), + os.path.join(scoop, "shims", "rg.exe"), + ] + if local_app_data: + candidates.append(os.path.join(local_app_data, "Microsoft", "WinGet", "Links", "rg.exe")) + for candidate in candidates: + if os.path.isfile(candidate): + resolved = candidate.replace("\\", "/") + self._rg_resolution_cache[cmd] = resolved + return resolved + return None + + _RG_VERSION_RE = re.compile( + r"(?m)^ripgrep\s+((?:0|[1-9]\d*))\." + r"(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)" + r"(?:-(?:(?:0|[1-9]\d*)|(?:[0-9A-Za-z-]*[A-Za-z-]" + r"[0-9A-Za-z-]*))(?:\.(?:(?:0|[1-9]\d*)|" + r"(?:[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)))*)?" + r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?" + r"(?:\s+\(rev [^)]+\))?\s*$") + + def _modified_rg_capability_error(self, executable: str) -> Optional[str]: + """Cached actionable error unless rg can sort exactly (full SemVer, >= 14).""" + if executable in self._rg_modified_capability: + return self._rg_modified_capability[executable] + result = self._exec(f"{self._quote_executable(executable)} --version", timeout=10) + match = self._RG_VERSION_RE.search(result.stdout or "") + if result.exit_code == 0 and match and int(match.group(1)) >= 14: + error = None + else: + error = ("Exact modification-time order requires ripgrep 14 or newer; " + "upgrade ripgrep or use order='discovery'.") + self._rg_modified_capability[executable] = error + return error + + # --- native rg transport (local POSIX) -------------------------------------- + + def _run_rg_native(self, argv: List[str], fetch_limit: int, timeout: int, + merge_stderr: bool = False) -> ExecuteResult: + """Run ``argv`` (shell-quoted rg words) natively and stop reading after + ``fetch_limit`` lines — the ``| head -n`` of the shell pipeline without the + two bash spawns. ``shlex.split`` undoes the escaping the builders apply for + the shell path, so both transports see identical arguments. Exit code and + stdout follow the shell contract (rg 0/1/2; 124 on timeout with partial + output; 130 on interrupt), so ``_parse_search_output`` is shared. Once the + bound is reached rg is killed like ``head`` closing the pipe would. + ``merge_stderr`` mirrors the shell path's stderr handling: merged for content + search (diagnostics feed the error message), discarded (``2>/dev/null``) for + file lists and probes.""" + from tools.environments.local import _kill_process_group_posix, _make_run_env + cwd = getattr(self.env, "cwd", None) or self.cwd + args = shlex.split(" ".join(argv)) + try: + proc = subprocess.Popen( + args, cwd=cwd, env=_make_run_env(self.env.env), stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT if merge_stderr else subprocess.DEVNULL, + start_new_session=True) + except OSError as exc: + return ExecuteResult(stdout=f"rg: {exc}", exit_code=2) + + # Drain on a thread so a silent rg (huge tree, no hits yet) cannot pin the + # caller past the deadline or past a /stop; the waiter below owns both. + lines: List[bytes] = [] + bounded = threading.Event() + + def _drain() -> None: + for raw in proc.stdout: + lines.append(raw) + if len(lines) >= fetch_limit: + bounded.set() + break + + drainer = threading.Thread(target=_drain, daemon=True) + drainer.start() + deadline = time.monotonic() + timeout + exit_code: Optional[int] = None + while True: + drainer.join(0.05) + if not drainer.is_alive() or bounded.is_set(): + break + if tool_interrupt.is_interrupted(): + exit_code = 130 + break + if time.monotonic() > deadline: + exit_code = 124 + break + if proc.poll() is None: + _kill_process_group_posix(proc) # native lane is POSIX-only (gate above) + proc.wait() + drainer.join() + proc.stdout.close() + stdout = b"".join(lines).decode("utf-8", errors="replace") + if exit_code == 124: + return ExecuteResult(stdout=stdout + f"\n[Command timed out after {timeout}s]", exit_code=124) + if exit_code == 130: + return ExecuteResult(stdout=stdout + "\n[Command interrupted]", exit_code=130) + # A killed-at-bound rg reports a signal (negative returncode); head would have + # left the pipeline at 0 unless rg itself already failed. + return ExecuteResult(stdout=stdout, exit_code=0 if bounded.is_set() else proc.returncode) + + def _run_rg_bounded(self, words: List[str], fetch_limit: int, timeout: int, *, + merge_stderr: bool = False, native_ok: bool = True, + shell_prefix: str = "") -> ExecuteResult: + """Run an rg command (shell-quoted words) and keep the first ``fetch_limit`` + lines: natively on a local POSIX host, else through the backend shell as + `` | head -n N``. ``native_ok=False`` keeps a form the native + lane cannot express (the multi-root ``cd`` prefix); ``shell_prefix`` is shell-only.""" + if native_ok and self._native_read_enabled(): + return self._run_rg_native(words, fetch_limit, timeout, merge_stderr=merge_stderr) + stderr = "" if merge_stderr else " 2>/dev/null" + return self._exec(f"{shell_prefix}{' '.join(words)}{stderr} | head -n {fetch_limit}", timeout=timeout) + + def _quote_executable(self, executable: str) -> str: + """Quote an executable without leaking controller path semantics.""" + if re.fullmatch(r"[A-Za-z0-9_.-]+", executable): + return executable + from tools.environments.local import LocalEnvironment + + if isinstance(self.env, LocalEnvironment): + return self._escape_native_tool_arg(executable) + return "'" + executable.replace("'", "'\"'\"'") + "'" + + # --- macOS protected-folder exclusions -------------------------------------- + + def _macos_search_exclusions(self, path: str) -> List[str]: + """Protected descendants to prune for this search root, if any. Gated on + ``env.is_local``: ``sys.platform``/``_HOME`` describe the CONTROLLER, but the + search runs on ``env``'s host. Envs without the flag default to local + semantics; pruning is a warning-carrying skip, never data loss.""" + env = getattr(self, "env", None) + if env is not None and getattr(env, "is_local", True) is False: + return [] + from tools import file_operations as _fo # lazy: _HOME is monkeypatched there + cwd = getattr(self.env, "cwd", None) or self.cwd + return _macos_protected_search_exclusions(path, cwd=cwd, home=_fo._HOME, platform=sys.platform) + + def _protected_prune_paths(self, path: str) -> List[str]: + """Absolute-ish protected paths for find's ``-path ... -prune``.""" + return [os.path.normpath(os.path.join(path, item)) for item in self._macos_search_exclusions(path)] + + def _effective_macos_search_exclusions(self, roots: List[str]) -> List[tuple[str, str, str]]: + """Unique ``(root, relative, absolute)`` exclusions across ``roots``, never + pruning a root the caller chose explicitly.""" + cwd = getattr(self.env, "cwd", None) or self.cwd + use_posix_paths = _posix_roots(roots) + + def normalized(root: str) -> str: + if use_posix_paths: + return posixpath.normpath(root if posixpath.isabs(root) else posixpath.join(cwd, root)) + return os.path.normcase(os.path.abspath(os.path.normpath(root))) + + normalized_roots = [normalized(root) for root in roots] + explicit_roots = set(normalized_roots) + seen = set() + effective = [] + for root, normalized_root in zip(roots, normalized_roots): + for relative in self._macos_search_exclusions(root): + if use_posix_paths: + absolute = key = posixpath.normpath(posixpath.join(normalized_root, relative)) + else: + absolute = os.path.normpath(os.path.join(root, relative)) + key = os.path.normcase(os.path.abspath(absolute)) + if key in explicit_roots or key in seen: + continue + seen.add(key) + effective.append((root, relative, absolute)) + return effective + + @staticmethod + def _macos_protected_search_warning(paths: List[str]) -> str: + skipped = ", ".join(os.path.basename(item) for item in paths) + return ("Skipped macOS protected folders during broad search to avoid " + f"an unattended privacy prompt: {skipped}. Search a protected " + "folder directly when access is intentional.") + + def _prune_expr(self, protected_paths: List[str]) -> str: + """find ``\\( -path A -o -path B \\) -prune`` clause for the protected dirs.""" + terms = " -o ".join(f"-path {self._escape_shell_arg(item)}" for item in protected_paths) + return f"\\( {terms} \\) -prune" + + def _rg_exclusion_globs(self, path: str) -> List[str]: + """``--glob '!/**'`` pairs excluding protected dirs from an rg run.""" + out: List[str] = [] + for item in self._macos_search_exclusions(path): + out.extend(["--glob", self._escape_shell_arg(f"!{item}/**")]) + return out + + def _path_exists_probe(self, path: str) -> str: + """Stdout of the existence probe: contains "exists" or "not_found".""" + if self._native_read_enabled(): + full = path if os.path.isabs(path) else os.path.join(getattr(self.env, "cwd", None) or self.cwd, path) + return "exists" if os.path.exists(full) else "not_found" + return self._exec(f"test -e {self._escape_shell_arg(path)} && echo exists || echo not_found").stdout + + def _dispatch_search(self, pattern: str, path: str, target: str, + file_glob: Optional[str], limit: int, offset: int, + output_mode: str, context: int, order: str = "discovery") -> SearchResult: + if target == "files": + return self._search_files(pattern, path, limit, offset, order) + return self._search_content(pattern, path, file_glob, limit, offset, output_mode, context) + + def _path_not_found_result(self, path: str) -> SearchResult: + """Error result for a missing search root, with nearby-entry suggestions.""" + parent = os.path.dirname(path) or "." + basename_query = os.path.basename(path) + hint_parts = [f"Path not found: {path}"] + parent_check = self._exec(f"test -d {self._escape_shell_arg(parent)} && echo yes || echo no") + if "yes" in parent_check.stdout and basename_query: + ls_result = self._exec(f"ls -1 {self._escape_shell_arg(parent)} 2>/dev/null | head -20") + if ls_result.exit_code == 0 and ls_result.stdout.strip(): + lq = basename_query.lower() + candidates = [ + os.path.join(parent, e) for e in ls_result.stdout.strip().split('\n') + if e and (lq in e.lower() or e.lower() in lq or e.lower().startswith(lq[:3]))] + if candidates: + hint_parts.append("Similar paths: " + ", ".join(candidates[:5])) + return SearchResult(error=". ".join(hint_parts), total_count=0) + + def _try_multi_path_search(self, pattern: str, path: str, target: str, + file_glob: Optional[str], limit: int, offset: int, + output_mode: str, context: int, + order: str = "discovery") -> Optional[SearchResult]: + """Recover a not-found ``path`` that is really several paths in one string. + Commas explicitly delimit paths (internal spaces preserved); without commas + split on whitespace. Search every existing part, merge, and note skipped + parts. None when it doesn't look like a multi-path string.""" + if "," in path: + parts = [part.strip() for part in path.split(",") if part.strip()] + else: + parts = path.split() + if len(parts) < 2: + return None + existing, missing = [], [] + for p in parts: + expanded = self._expand_path(p) + (existing if "exists" in self._path_exists_probe(expanded) else missing).append(expanded) + if not existing: + return None + if target == "files": + # One global traversal across roots so modified ordering and pagination + # are exact; root admission wraps the actual rg/find invocation. + merged = self._search_files(pattern, existing, limit, offset, order) + else: + merged = SearchResult() + for root in existing: + sub = self._search_content(pattern, root, file_glob, limit, offset, output_mode, context) + if sub.error: + return sub + merged.matches.extend(sub.matches) + merged.files.extend(sub.files) + merged.counts.update(sub.counts) + merged.total_count += sub.total_count + merged.truncated = merged.truncated or sub.truncated + merged.matches = merged.matches[:limit] + merged.files = merged.files[:limit] + note = f"path contained {len(parts)} entries; searched {len(existing)} that exist" + if missing: + note += "; skipped missing: " + ", ".join(missing[:3]) + if len(missing) > 3: + note += f" (+{len(missing) - 3} more)" + warning_parts = [note] + if not merged.error: + protected_paths = [absolute for _r, _rel, absolute in self._effective_macos_search_exclusions(existing)] + if protected_paths: + warning_parts.append(self._macos_protected_search_warning(protected_paths)) + merged.warning = " ".join(warning_parts) + return merged + + def _search_prune_glob_args(self) -> str: + """rg globs pruning known heavyweight recursive subtrees. Both forms are + needed: globs are relative to each rg root, so ``**/name/**`` alone misses an + explicitly selected ``name/`` root. Names come from the shared scan policy — + no second search-only list.""" + globs = [] + for dirname in sorted(SEARCH_PRUNE_DIR_NAMES): + for prefix in ("", "**/"): + globs.extend(("--glob", self._escape_shell_arg(f"!{prefix}{dirname}/**"))) + return " ".join(globs) + + # (rg flags, message template) probes for a 0-match content search, in order. + # The fixed-string probe only runs when the pattern has regex metacharacters. + _ZERO_MATCH_PROBES = ( + ("-i", "0 exact matches, but {total} case-insensitive match(es) in {n} file(s): " + "{paths} — the pattern's casing may be wrong."), + # rg skips dotdirs and .gitignore'd files by default; say so instead of a bare zero. + ("--hidden --no-ignore", "0 matches in visible files, but {total} match(es) in {n} " + "hidden or gitignored file(s): {paths} — these are excluded by default."), + ("-F", "0 regex matches, but {total} literal match(es) in {n} file(s): {paths} — the " + "pattern contains regex metacharacters that likely need escaping " + "(or pass a simpler substring)."), + ) + + def _zero_match_probe(self, pattern: str, path: str, file_glob: Optional[str]) -> Optional[str]: + """Steering hint for a 0-match content search, or None: a bare zero gives the + model nothing to act on, so run cheap count-only rg probes (case-insensitive, + hidden/ignored, fixed-string) and report the first that hits.""" + rg_executable = self._resolve_command('rg') + if not rg_executable: + return None + rg = self._quote_executable(rg_executable) + has_meta = bool(re.search(r"[.\[\](){}?*+^$\\|]", pattern)) + glob_expr = f" --glob {self._escape_shell_arg(file_glob)}" if file_glob else "" + for flags, template in self._ZERO_MATCH_PROBES: + if flags == "-F" and not has_meta: + continue + # The hidden/ignored probe keeps --no-ignore so project-local ignored + # files stay diagnosable, but prunes heavyweight trees before rg recurses. + if flags.startswith("--hidden"): + glob_expr_probe = f"{glob_expr} {self._search_prune_glob_args()}" + else: + glob_expr_probe = glob_expr + probe_words = [rg, flags, "--count-matches", glob_expr_probe, + self._escape_shell_arg(pattern), self._escape_native_tool_arg(path)] + probe = self._run_rg_bounded(probe_words, 50, timeout=30) + total, per_file = 0, [] + for line in (probe.stdout or "").strip().splitlines(): + p, _sep, n = line.rpartition(":") + if n.isdigit(): + total += int(n) + per_file.append(p) + if total > 0: + extra = len(per_file) - 5 + paths = ", ".join(per_file[:5]) + (f" (+{extra} more)" if extra > 0 else "") + return template.format(total=total, n=len(per_file), paths=paths) + return None + + def _is_broad_local_search_root(self, path: str) -> bool: + """Whether a no-rg LOCAL root (filesystem root, $HOME or an ancestor of it) is + unsafe for recursive find. Controller paths never classify remotes.""" + from tools.environments.local import LocalEnvironment, _IS_WINDOWS, _msys_to_windows_path + + if not isinstance(self.env, LocalEnvironment): + return False + + def normalized(value: str) -> str: + if _IS_WINDOWS: + value = _msys_to_windows_path(value).replace("\\", "/") + if not os.path.isabs(value): + value = os.path.join(getattr(self.env, "cwd", None) or self.cwd, value) + return os.path.normcase(os.path.abspath(value)) + + from tools import file_operations as _fo # lazy: _HOME is monkeypatched there + root = normalized(path) + home = normalized(_fo._HOME) + drive = os.path.splitdrive(root)[0] + anchor = drive + os.sep if drive else os.path.abspath(os.sep) + if root == os.path.normcase(anchor): + return True + try: + common = os.path.commonpath([root, home]) + except ValueError: + return False + return root == home or common == root + + def _search_files(self, pattern: str, path: str | List[str], limit: int, offset: int, + order: str = "discovery") -> SearchResult: + """Search for files by name (glob-like) across one or more roots: rg --files, + else a bounded find. ``order``: "discovery" (fast, bounded) or "modified" + (exact global newest-first; needs rg 14+ or GNU find).""" + search_pattern = pattern if (not pattern.startswith('**/') and '/' not in pattern) \ + else pattern.split('/')[-1] + roots = [path] if isinstance(path, str) else path + if not roots: + return SearchResult(error="File search requires at least one search root in 'path'.") + + # Prefer ripgrep: bounded parallel traversal with ignore semantics. Resolve + # the engine and exact-order capability BEFORE admission so a queued request + # does not occupy a root while doing command discovery. + if self._has_command("rg"): + rg_executable = self._resolve_command("rg") or "rg" + if order == "modified": + capability_error = self._modified_rg_capability_error(rg_executable) + if capability_error: + return SearchResult(error=capability_error) + keys = _filename_search_root_keys(self.env, roots, self.cwd) + if not _acquire_filename_search_roots(keys): + return SearchResult(error=_ADMISSION_INTERRUPTED_ERROR) + try: + return self._search_files_rg(search_pattern, path, limit, offset, order, + rg_executable=rg_executable) + finally: + _release_filename_search_roots(keys) + + # A local find rooted at/above $HOME or a filesystem root can take minutes and + # prompt on protected paths: refuse before invoking find. + if any(self._is_broad_local_search_root(root) for root in roots): + return SearchResult(error=( + "Broad local file search without ripgrep is disabled because " + "find cannot keep this traversal safely bounded. Install " + "ripgrep or search a narrower directory.")) + if not self._has_command("find"): + return SearchResult( + error="File search requires 'rg' (ripgrep) or 'find'. " + "Install ripgrep for best results: " + "https://github.com/BurntSushi/ripgrep#installation") + + # Prune hidden descendant dirs (and hidden files, matching rg's default) while + # still allowing an explicitly selected hidden root; dash-prefixed roots get + # ``./`` so find doesn't parse them as options. + find_roots = [f"./{root}" if root.startswith("-") else root for root in roots] + q_roots = [self._escape_shell_arg(root) for root in find_roots] + root_exemptions = "".join(f" ! -path {root}" for root in q_roots) + hidden_prune = f" \\( -type d -name '.*'{root_exemptions} \\) -prune -o" + protected_paths = [absolute for _r, _rel, absolute in self._effective_macos_search_exclusions(roots)] + protected_prune = f" {self._prune_expr(protected_paths)} -o" if protected_paths else "" + fetch_limit = offset + limit + 1 + base = (f"find {' '.join(q_roots)}{protected_prune}{hidden_prune} -type f " + f"! -name '.*' -name {self._escape_shell_arg(search_pattern)}") + if order == "modified": + cmd = "set -o pipefail; " + base + f" -printf '%T@ %p\\n' 2>/dev/null | sort -rn | head -n {fetch_limit}" + else: + cmd = "set -o pipefail; " + base + f" -print 2>/dev/null | head -n {fetch_limit}" + + keys = _filename_search_root_keys(self.env, roots, self.cwd) + if not _acquire_filename_search_roots(keys): + return SearchResult(error=_ADMISSION_INTERRUPTED_ERROR) + try: + result = self._exec(cmd, timeout=60) + finally: + _release_filename_search_roots(keys) + stdout, limit_reason = _search_stdout_and_limit(result) + + # Parse BEFORE classifying exit 141: under pipefail a bounded producer gets + # SIGPIPE when head closes after fetch_limit rows — benign only when the + # payload proves the bound was reached; a shorter payload is a hard failure. + raw_files: List[str] = [] + for line in stdout.splitlines(): + if order == "modified": + parts = line.split(" ", 1) + if len(parts) != 2 or not parts[0].replace(".", "", 1).isdigit(): + continue + raw_files.append(parts[1]) + elif line: + raw_files.append(line) + bounded_sigpipe = result.exit_code == 141 and len(raw_files) >= fetch_limit + if result.exit_code not in {0, 124} and not bounded_sigpipe: + if order == "modified": + return SearchResult(error=( + "Exact modification-time order requires GNU find with " + "-printf support; install ripgrep 14+ or use order='discovery'.")) + return SearchResult(error="File search failed while running bounded find traversal.") + + from tools.environments.local import LocalEnvironment, _IS_WINDOWS, _msys_to_windows_path + if _IS_WINDOWS and isinstance(self.env, LocalEnvironment): + raw_files = [_msys_to_windows_path(file_path) for file_path in raw_files] + return SearchResult( + files=raw_files[offset:offset + limit], total_count=len(raw_files), + truncated=len(raw_files) > offset + limit or bool(limit_reason), limit_reason=limit_reason) + + def _search_files_rg(self, pattern: str, path: str | List[str], limit: int, offset: int, + order: str = "discovery", rg_executable: Optional[str] = None) -> SearchResult: + """File-name search via ``rg --files`` (respects .gitignore, skips hidden dirs, + parallel walk). Discovery order stays bounded and fast; exact modification-time + ordering is explicit because it scans globally.""" + # Wrap bare names so -g matches at any depth (equivalent to find -name). + glob_pattern = f"*{pattern}" if ('/' not in pattern and not pattern.startswith('*')) else pattern + roots = [path] if isinstance(path, str) else path + fetch_limit = limit + offset + 1 + effective_exclusions = self._effective_macos_search_exclusions(roots) + scoped_common = None + command_roots = roots + if len(roots) > 1 and effective_exclusions and _posix_roots(roots): + # Several roots: rg globs are root-relative, so cd to the common ancestor + # and express roots + exclusions relative to it. + cwd = getattr(self.env, "cwd", None) or self.cwd + absolute_roots = [ + posixpath.normpath(root if posixpath.isabs(root) else posixpath.join(cwd, root)) + for root in roots] + scoped_common = posixpath.commonpath(absolute_roots) + command_roots = [posixpath.relpath(root, scoped_common) for root in absolute_roots] + exclusion_terms = [ + f"--glob {self._escape_shell_arg(f'!{posixpath.relpath(absolute, scoped_common)}/**')}" + for _r, _rel, absolute in effective_exclusions] + else: + exclusion_terms = [ + f"--glob {self._escape_shell_arg(f'!{relative}/**')}" + for _r, relative, _abs in effective_exclusions] + exclusion_globs = " ".join(dict.fromkeys(exclusion_terms)) + exclusion_args = f" {exclusion_globs}" if exclusion_globs else "" + rg_executable = rg_executable or self._resolve_command("rg") + if not rg_executable: + return SearchResult(error="File search requires ripgrep (rg).") + if order == "modified": + capability_error = self._modified_rg_capability_error(rg_executable) + if capability_error: + return SearchResult(error=capability_error) + rg = self._quote_executable(rg_executable) + sort_arg = " --sortr=modified" if order == "modified" else "" + root_args = " ".join(self._escape_native_tool_arg(root) for root in command_roots) + cd_prefix = f"cd {self._escape_shell_arg(scoped_common)} && " if scoped_common else "" + # ``--`` terminates options so a dash-prefixed root is never parsed as a flag. + rg_cmd = (f"{rg} --files{sort_arg} -g {self._escape_shell_arg(glob_pattern)}" + f"{exclusion_args} -- {root_args}") + result = self._run_rg_bounded([rg_cmd], fetch_limit, timeout=60, native_ok=not scoped_common, + shell_prefix=f"set -o pipefail; {cd_prefix}") + stdout, limit_reason = _search_stdout_and_limit(result) + all_files = [f for f in stdout.splitlines() if f] + if scoped_common: + all_files = [ + f if posixpath.isabs(f) else posixpath.normpath(posixpath.join(scoped_common, f)) + for f in all_files] + bounded_sigpipe = result.exit_code == 141 and len(all_files) >= fetch_limit + if result.exit_code not in {0, 1, 124} and not bounded_sigpipe: + if order == "modified": + return SearchResult(error=( + "Exact modification-time order failed; ripgrep 14+ is " + "required. Upgrade ripgrep or use order='discovery'.")) + return SearchResult(error="File search failed while running ripgrep.") + return SearchResult( + files=all_files[offset:offset + limit], total_count=len(all_files), + truncated=len(all_files) > offset + limit or bool(limit_reason), limit_reason=limit_reason) + + def _search_content(self, pattern: str, path: str, file_glob: Optional[str], + limit: int, offset: int, output_mode: str, context: int) -> SearchResult: + """Content search: rg, else grep; attaches zero-match steering hints.""" + used_rg = self._has_command('rg') + if used_rg: + result = self._search_with_rg(pattern, path, file_glob, limit, offset, output_mode, context, + rg_executable=self._resolve_command("rg") or "rg") + elif self._has_command('grep'): + result = self._search_with_grep(pattern, path, file_glob, limit, offset, output_mode, context) + else: + return SearchResult( + error="Content search requires ripgrep (rg) or grep. " + "Install ripgrep: https://github.com/BurntSushi/ripgrep#installation") + if (not result.error and result.total_count == 0 + and not result.matches and not result.files and not result.counts): + try: + hint = self._zero_match_probe(pattern, path, file_glob) + except Exception: + hint = None + if hint: + result.warning = hint if not result.warning else f"{result.warning} {hint}" + # rg auto-enables --multiline for \n patterns, so the line-oriented + # explanation only applies to the grep fallback. + if used_rg: + return result + return _maybe_warn_line_oriented_newline_pattern(result, pattern) + + def _run_search_pipeline(self, cmd_parts: List[str], output_mode: str, limit: int, + offset: int, context: int, warning: Optional[str] = None, + line_cap: bool = False) -> SearchResult: + """Run ``cmd_parts | head -n `` under pipefail and parse. Extra + rows report the true total (context mode also emits "--" separators, so + grab 200 more). pipefail keeps the engine's exit 2 alive across ``| head`` + (a truncating head makes rg exit 0 / grep 141, which the ==2 guard ignores). + ``line_cap`` appends ``| cut -c1-2000`` for engines without --max-columns + (grep): bounds giant single-line matches at the pipe layer; skipped for + files_only/count where lines are paths/counts.""" + fetch_limit = limit + offset + (200 if context > 0 else 0) + if line_cap: # grep/find pipelines: shell only, with the column cap + parts = cmd_parts + ["|", "head", "-n", str(fetch_limit)] + if output_mode not in ("files_only", "count"): + parts += ["|", "cut", "-c1-2000"] + result = self._exec("set -o pipefail; " + " ".join(parts), timeout=60) + else: + result = self._run_rg_bounded(cmd_parts, fetch_limit, timeout=60, merge_stderr=True, + shell_prefix="set -o pipefail; ") + return _parse_search_output(result, output_mode, limit, offset, context, warning=warning) + + def _search_with_rg(self, pattern: str, path: str, file_glob: Optional[str], + limit: int, offset: int, output_mode: str, context: int, + rg_executable: Optional[str] = None) -> SearchResult: + """Search using ripgrep.""" + rg_executable = rg_executable or self._resolve_command("rg") + if not rg_executable: + return SearchResult(error="Content search requires ripgrep (rg).") + cmd_parts = [self._quote_executable(rg_executable), "--line-number", "--no-heading", "--with-filename"] + # Giant-single-line containment (cline#13525): a match inside a multi-MB + # single-line dump makes rg emit the ENTIRE line (``head -n`` counts lines). + # --max-columns bounds each printed line at the rg layer; --max-columns-preview + # keeps a truncated prefix so the model still sees the hit. 2000 cols exceeds + # the 500-char content clamp, so nothing previously visible is lost. + if output_mode not in ("files_only", "count"): + cmd_parts.extend(["--max-columns", "2000", "--max-columns-preview"]) + # A regex \n hard-errors in line-oriented mode; enable -U up front and say so. + multiline = _pattern_has_regex_newline(pattern) + if multiline: + cmd_parts.append("--multiline") + if context > 0: + cmd_parts.extend(["-C", str(context)]) + cmd_parts.extend(self._rg_exclusion_globs(path)) + if file_glob: + cmd_parts.extend(["--glob", self._escape_shell_arg(file_glob)]) + if output_mode in _OUTPUT_MODE_FLAGS: + cmd_parts.append(_OUTPUT_MODE_FLAGS[output_mode]) + cmd_parts.append(self._escape_shell_arg(pattern)) + # rg is a native Windows binary (winget/cargo/choco): needs C:/... not MSYS /c/... + cmd_parts.append(self._escape_native_tool_arg(path)) + ml_note = ( + "Pattern contains \\n — multiline mode (-U) was enabled automatically " + "so the regex can match across line boundaries." + ) if multiline else None + return self._run_search_pipeline(cmd_parts, output_mode, limit, offset, context, warning=ml_note) + + def _grep_cmd(self, head: List[str], pattern: str, output_mode: str, context: int, + file_glob: Optional[str] = None) -> List[str]: + """``head`` + context/include/mode flags + quoted pattern (argument order is fixed).""" + parts = list(head) + if context > 0: + parts.extend(["-C", str(context)]) + if file_glob: + parts.extend(["--include", self._escape_shell_arg(file_glob)]) + if output_mode in _OUTPUT_MODE_FLAGS: + parts.append(_OUTPUT_MODE_FLAGS[output_mode]) + parts.append(self._escape_shell_arg(pattern)) + return parts + + def _search_with_grep(self, pattern: str, path: str, file_glob: Optional[str], + limit: int, offset: int, output_mode: str, context: int) -> SearchResult: + """Fallback search using grep.""" + # grep's --exclude-dir matches BASENAMES anywhere, so it can't express "only + # the home-level Downloads"; route pruning through find's path-scoped -prune. + protected_paths = self._protected_prune_paths(path) + if protected_paths: + return self._search_with_grep_pruned( + pattern, path, file_glob, limit, offset, output_mode, context, protected_paths) + # -H forces filenames; -E matches rg regex behavior; --exclude-dir='.*' + # mirrors rg's hidden-dir default (.git/, .hub/index-cache/, ...). + cmd_parts = self._grep_cmd(["grep", "-rnHE", "--exclude-dir='.*'"], pattern, output_mode, context, file_glob) + # --exclude-dir applies to the root too, so "." would be excluded by '.*'; + # anchor relative paths at the shell's live $PWD. + is_absolute = path.startswith(("/", "\\\\")) or bool(re.match(r"^[A-Za-z]:[\\/]", path)) + if is_absolute: + search_root = self._escape_shell_arg(path) + else: + relative_path = path[2:] if path.startswith("./") else path + search_root = '"$PWD"' + if relative_path not in {"", "."}: + search_root += f"/{self._escape_shell_arg(relative_path)}" + cmd_parts.append(search_root) + return self._run_search_pipeline(cmd_parts, output_mode, limit, offset, context, line_cap=True) + + def _search_with_grep_pruned(self, pattern: str, path: str, file_glob: Optional[str], + limit: int, offset: int, output_mode: str, context: int, + protected_paths: List[str]) -> SearchResult: + """grep fallback with PATH-scoped protected-dir pruning: ``find ... -prune`` + enumerates files (traversal never enters protected dirs) and hands them to + grep via ``-exec {} +``; hidden dirs pruned to mirror ``--exclude-dir='.*'``. + Trade-off: find folds grep's exit code, so a hard grep error surfaces as an + empty result — acceptable for this darwin-local-broad-search-only branch.""" + grep_parts = self._grep_cmd(["grep", "-nHE"], pattern, output_mode, context) + find_parts = [ + "find", self._escape_shell_arg(path or "."), + self._prune_expr(protected_paths), "-o", + "\\( -type d -name '.*' \\) -prune", "-o", + "-type f", + ] + if file_glob: + find_parts.extend(["-name", self._escape_shell_arg(file_glob)]) + find_parts.extend(["-exec", *grep_parts, "{}", "+", "2>/dev/null"]) + return self._run_search_pipeline(find_parts, output_mode, limit, offset, context, line_cap=True) diff --git a/tools/file_state.py b/tools/file_state.py new file mode 100644 index 0000000000000000000000000000000000000000..860e12ae4c889fd6c2036c8f4ac19cef53fa0890 --- /dev/null +++ b/tools/file_state.py @@ -0,0 +1,248 @@ +"""Cross-agent file state coordination. + +Prevents mangled edits when concurrent subagents (same process, same +filesystem) touch the same file: B writes a file A already read, so A's next +write would clobber B's changes. Complements the single-agent path-overlap +check in ``agent.tool_dispatch_helpers._should_parallelize_tool_batch``. A process-wide +``FileStateRegistry`` tracks per-agent read stamps, the global last writer and +a per-path lock; every method is a no-op under ``HERMES_DISABLE_FILE_STATE_GUARD=1``. +""" +from __future__ import annotations + +import os +import threading +import time +from collections import defaultdict +from contextlib import contextmanager +from pathlib import Path +from typing import Dict, Iterable, List, Optional, Tuple + +# (mtime, read_ts, partial). partial=True when read_file returned a windowed +# view (offset > 1 or limit < total_lines) — a later write should still warn +# so the model re-reads in full. +ReadStamp = Tuple[float, float, bool] + +# Bounded so long sessions don't accumulate unbounded state. +_MAX_PATHS_PER_AGENT = 4096 +_MAX_GLOBAL_WRITERS = 4096 + + +def _disabled() -> bool: + # Re-read each call so tests can toggle via monkeypatch.setenv. + return os.environ.get("HERMES_DISABLE_FILE_STATE_GUARD", "").strip() == "1" + + +def _mtime_or_none(resolved: str) -> Optional[float]: + try: + return os.path.getmtime(resolved) + except OSError: + return None + + +def _fmt_ts(ts: float) -> str: + # Short wall-clock for warnings; avoids datetime formatting on the hot path. + return time.strftime("%H:%M:%S", time.localtime(ts)) + + +def _evict_oldest(container, cap: int) -> None: + """Pop entries until *container* is within *cap* (sets: arbitrary; dicts: oldest + by insertion order). An eviction only costs one redundant re-send or staleness check.""" + for _ in range(len(container) - cap): + try: + if isinstance(container, set): + container.pop() + else: + container.pop(next(iter(container))) + except (StopIteration, KeyError): + break + + +class FileStateRegistry: + """Process-wide coordinator for cross-agent file edits.""" + + def __init__(self) -> None: + self._reads: Dict[str, Dict[str, ReadStamp]] = defaultdict(dict) + self._last_writer: Dict[str, Tuple[str, float]] = {} + self._path_locks: Dict[str, threading.Lock] = {} + self._path_lock_users: Dict[str, int] = {} + self._meta_lock = threading.Lock() # guards _path_locks + self._state_lock = threading.Lock() # guards _reads + _last_writer + + @contextmanager + def lock_path(self, resolved: str): + """Per-path lock: threads on the same path serialize, different paths proceed. + The lock entry is dropped once the last holder/waiter exits.""" + with self._meta_lock: + lock = self._path_locks.setdefault(resolved, threading.Lock()) + self._path_lock_users[resolved] = self._path_lock_users.get(resolved, 0) + 1 + lock.acquire() + try: + yield + finally: + lock.release() + with self._meta_lock: + users = self._path_lock_users[resolved] - 1 + if users: + self._path_lock_users[resolved] = users + else: + self._path_lock_users.pop(resolved, None) + self._path_locks.pop(resolved, None) + + def _stamp(self, task_id: str, resolved: str, mtime: float, now: float, partial: bool) -> None: + """Caller holds ``_state_lock``.""" + agent_reads = self._reads[task_id] + agent_reads[resolved] = (float(mtime), now, bool(partial)) + _evict_oldest(agent_reads, _MAX_PATHS_PER_AGENT) + + def record_read(self, task_id: str, resolved: str, *, partial: bool = False, + mtime: Optional[float] = None) -> None: + if _disabled(): + return + mtime = _mtime_or_none(resolved) if mtime is None else mtime + if mtime is None: + return + with self._state_lock: + self._stamp(task_id, resolved, mtime, time.time(), partial) + + def note_write(self, task_id: str, resolved: str, *, mtime: Optional[float] = None) -> None: + """Record a successful write: global last-writer AND this agent's own + read stamp (a write is an implicit read of the current content).""" + if _disabled(): + return + mtime = _mtime_or_none(resolved) if mtime is None else mtime + if mtime is None: + return + now = time.time() + with self._state_lock: + self._last_writer[resolved] = (task_id, now) + _evict_oldest(self._last_writer, _MAX_GLOBAL_WRITERS) + self._stamp(task_id, resolved, mtime, now, False) + + def check_stale(self, task_id: str, resolved: str) -> Optional[str]: + """Model-facing warning if this write would be stale, else ``None``. Severity + order: sibling wrote after our read > mtime drift / partial read > never read.""" + if _disabled(): + return None + with self._state_lock: + stamp = self._reads.get(task_id, {}).get(resolved) + last_writer = self._last_writer.get(resolved) + + if stamp is None and last_writer is None: # net-new file / first touch + return None + current_mtime = _mtime_or_none(resolved) + if current_mtime is None: + return None # file doesn't exist — write creates it; not stale + + if last_writer is not None: + writer_tid, writer_ts = last_writer + if writer_tid != task_id: + if stamp is None: + return ( + f"{resolved} was modified by sibling subagent " + f"{writer_tid!r} but this agent never read it. " + "Read the file before writing to avoid overwriting " + "the sibling's changes.") + read_ts = stamp[1] + if writer_ts > read_ts: + return ( + f"{resolved} was modified by sibling subagent " + f"{writer_tid!r} at {_fmt_ts(writer_ts)} — after " + f"this agent's last read at {_fmt_ts(read_ts)}. " + "Re-read the file before writing.") + + if stamp is not None: + read_mtime, _read_ts, partial = stamp + if current_mtime != read_mtime: + return ( + f"{resolved} was modified since you last read it " + "on disk (external edit or unrecorded writer). " + "Re-read the file before writing.") + if partial: + return ( + f"{resolved} was last read with offset/limit pagination " + "(partial view). Re-read the whole file before " + "overwriting it.") + return None + + return ( + f"{resolved} was not read by this agent. " + "Read the file first so you can write an informed edit.") + + def writes_since(self, exclude_task_id: str, since_ts: float, + paths: Iterable[str]) -> Dict[str, List[str]]: + """``{writer_task_id: [paths]}`` for writes after ``since_ts`` by agents + other than ``exclude_task_id`` (delegate_task's "subagent modified files + you previously read" reminder).""" + if _disabled(): + return {} + paths_set = set(paths) + out: Dict[str, List[str]] = defaultdict(list) + with self._state_lock: + for p, (writer_tid, ts) in self._last_writer.items(): + if writer_tid != exclude_task_id and ts >= since_ts and p in paths_set: + out[writer_tid].append(p) + return dict(out) + + def known_reads(self, task_id: str) -> List[str]: + """Resolved paths this agent has read.""" + if _disabled(): + return [] + with self._state_lock: + return list(self._reads.get(task_id, {}).keys()) + + def forget_task(self, task_id: str) -> None: + """Release read stamps owned by a task after its lifecycle ends.""" + with self._state_lock: + self._reads.pop(task_id, None) + + def clear(self) -> None: + """Reset all state. Intended for tests only.""" + with self._state_lock: + self._reads.clear() + self._last_writer.clear() + with self._meta_lock: + self._path_locks.clear() + self._path_lock_users.clear() + + +_registry = FileStateRegistry() + + +def get_registry() -> FileStateRegistry: + return _registry + + +# Convenience wrappers (short names used at call sites). +def record_read(task_id: str, resolved_or_path: str | Path, *, partial: bool = False) -> None: + _registry.record_read(task_id, str(resolved_or_path), partial=partial) + + +def note_write(task_id: str, resolved_or_path: str | Path) -> None: + _registry.note_write(task_id, str(resolved_or_path)) + + +def check_stale(task_id: str, resolved_or_path: str | Path) -> Optional[str]: + return _registry.check_stale(task_id, str(resolved_or_path)) + + +def lock_path(resolved_or_path: str | Path): + return _registry.lock_path(str(resolved_or_path)) + + +def writes_since(exclude_task_id: str, since_ts: float, paths: Iterable[str | Path]) -> Dict[str, List[str]]: + return _registry.writes_since(exclude_task_id, since_ts, [str(p) for p in paths]) + + +def known_reads(task_id: str) -> List[str]: + return _registry.known_reads(task_id) + + +__all__ = [ + "FileStateRegistry", + "get_registry", + "record_read", + "note_write", + "check_stale", + "lock_path", + "writes_since", + "known_reads"] diff --git a/tools/file_tools_read_tracking.py b/tools/file_tools_read_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..46a66e7f1a6723c0321d9e2db864a277319efe60 --- /dev/null +++ b/tools/file_tools_read_tracking.py @@ -0,0 +1,263 @@ +"""Per-task read/search bookkeeping for the file tools. + +Process-lifetime state behind read_file/search_files/write_file/patch. +Per task_id ``_read_tracker`` +stores: ``last_key``/``consecutive`` (loop detection; reset by any OTHER tool +call), ``read_history`` (diagnostics), ``dedup`` (key -> mtime; survives context +compression), ``dedup_generation_reads`` (keys whose full content was served since +the last compaction boundary; cleared on compression so one recovery read returns +full content), ``dedup_hits`` (stub-loop breaker), ``read_timestamps`` +(staleness warnings) and ``not_found`` (short-TTL negative cache). Every +container is hard-capped (``_cap_read_tracker_data``) so long sessions stay small. +""" + +import logging +import os +import threading +import time + +from tools.file_state import _evict_oldest +from tools.file_tools_paths import _authoritative_workspace_root, _resolve_path_for_task + +logger = logging.getLogger("tools.file_tools") + +_read_tracker_lock = threading.Lock() +_read_tracker: dict = {} + +# Consecutive patch failures per (task_id, resolved_path); escalates the hint +# when the model keeps failing the same file. Reset on a successful patch. +_patch_failure_lock = threading.Lock() +_patch_failure_tracker: dict = {} # {task_id: {resolved_path: count}} +_PATCH_FAILURE_PATHS_CAP = 64 + +# Only the most recent reads matter for dedup, loop detection and external-edit +# warnings; caps bound accretion regardless of session length. +_READ_HISTORY_CAP = 500 +_DEDUP_CAP = 1000 +_READ_TIMESTAMPS_CAP = 1000 +_NOT_FOUND_CAP = 500 +_NOT_FOUND_TTL_SECONDS = 60.0 # a path that didn't exist may be created soon + + +def _task_data(task_id: str) -> dict: + """Get-or-create the tracker entry for *task_id*, back-filling missing containers + (search_tool / tests create partial entries). Lock must be held.""" + task_data = _read_tracker.setdefault(task_id, { + "last_key": None, "consecutive": 0, "read_history": set()}) + for key in ("dedup", "dedup_hits", "read_timestamps"): + task_data.setdefault(key, {}) + task_data.setdefault("dedup_generation_reads", set()) + return task_data + + +def _record_patch_failure(task_id: str, resolved_path: str) -> int: + """Increment and return the consecutive-failure count for this path.""" + with _patch_failure_lock: + task_failures = _patch_failure_tracker.setdefault(task_id, {}) + # Evict the oldest entry once a task has failed on many distinct files. + if resolved_path not in task_failures: + _evict_oldest(task_failures, _PATCH_FAILURE_PATHS_CAP - 1) + task_failures[resolved_path] = task_failures.get(resolved_path, 0) + 1 + return task_failures[resolved_path] + + +def _reset_patch_failures(task_id: str, resolved_paths: list) -> None: + """Clear consecutive-failure counts for the given paths.""" + if not resolved_paths: + return + with _patch_failure_lock: + task_failures = _patch_failure_tracker.get(task_id) + for rp in resolved_paths if task_failures else (): + task_failures.pop(rp, None) + + +def _cap_read_tracker_data(task_data: dict) -> None: + """Enforce size caps on the per-task sub-containers. Call with ``_read_tracker_lock`` held.""" + # Caps are read at call time so tests can monkeypatch the module constants. + for key, cap in ( + ("read_history", _READ_HISTORY_CAP), + ("dedup", _DEDUP_CAP), + ("dedup_hits", _DEDUP_CAP), + ("dedup_generation_reads", _DEDUP_CAP), + ("read_timestamps", _READ_TIMESTAMPS_CAP), + ("not_found", _NOT_FOUND_CAP)): + container = task_data.get(key) + if container is not None and len(container) > cap: + _evict_oldest(container, cap) + + +def _resolved_or_none(filepath: str, task_id: str) -> str | None: + try: + return str(_resolve_path_for_task(filepath, task_id)) + except (OSError, ValueError): + return None + + +def _pop_not_found(op: str, resolved_str: str, task_id: str) -> None: + """Drop the negative-cache entry for *(op, resolved_str)*. Lock must be held.""" + task_data = _read_tracker.get(task_id) + nf = task_data.get("not_found") if task_data else None + if nf: + nf.pop((op, resolved_str), None) + + +def _check_not_found_cache(op: str, resolved_str: str, task_id: str) -> str | None: + """Return cached not-found JSON for *(op, resolved_str)* if still fresh. + + *op* is "read" or "search" (different error JSON shapes). Evicted by TTL, + by write_file/patch on the path, or by any other tool call. + """ + with _read_tracker_lock: + task_data = _read_tracker.get(task_id) + entry = (task_data.get("not_found") or {}).get((op, resolved_str)) if task_data else None + if entry is None: + return None + ts, cached_json = entry + if time.monotonic() - ts > _NOT_FOUND_TTL_SECONDS: + _pop_not_found(op, resolved_str, task_id) + return None + # "check → create → read" is common, so never serve a stale miss for a path + # that now exists. The stat runs OUTSIDE the tracker lock: a hung stat on a + # dead network mount must not stall every task. + if os.path.exists(resolved_str): + with _read_tracker_lock: + _pop_not_found(op, resolved_str, task_id) + return None + return cached_json + + +def _record_not_found(op: str, resolved_str: str, task_id: str, error_json: str) -> None: + """Cache a not-found error so the next *op* call for *resolved_str* skips I/O.""" + with _read_tracker_lock: + task_data = _task_data(task_id) + task_data.setdefault("not_found", {})[(op, resolved_str)] = (time.monotonic(), error_json) + _cap_read_tracker_data(task_data) + + +def _bump_consecutive(task_data: dict, key: tuple) -> int: + """Update last_key/consecutive for *key* and return the new count. Lock must be held.""" + if task_data["last_key"] == key: + task_data["consecutive"] += 1 + else: + task_data["last_key"] = key + task_data["consecutive"] = 1 + return task_data["consecutive"] + + +def reset_file_dedup(task_id: str = None): + """Advance the read-dedup generation after context compression (one task, or all + when ``task_id`` is None). The per-key ``dedup`` mtime map is PRESERVED so unchanged + files keep returning stubs instead of re-bloating the reclaimed context; the + generation-read set is cleared so the FIRST unchanged read of each key after + compaction returns full content the summary may have dropped. Stub-hit counters + are cleared so the hard block restarts fresh.""" + with _read_tracker_lock: + if task_id: + targets = [_read_tracker[task_id]] if _read_tracker.get(task_id) else [] + else: + targets = list(_read_tracker.values()) + for task_data in targets: + if "dedup_hits" in task_data: + task_data["dedup_hits"].clear() + task_data.setdefault("dedup_generation_reads", set()).clear() + + +def notify_other_tool_call(task_id: str = "default"): + """Reset the consecutive read/search counter for a task. + + Called by the dispatcher for every tool OTHER than read_file/search_files. + Also clears stub-hit counters and the not-found cache: any other tool may + have created a previously-missing path (or flipped its permissions). + """ + with _read_tracker_lock: + task_data = _read_tracker.get(task_id) + if task_data: + task_data["last_key"] = None + task_data["consecutive"] = 0 + for key in ("dedup_hits", "not_found"): + if task_data.get(key): + task_data[key].clear() + + +def _invalidate_dedup_for_path(filepath: str, task_id: str) -> None: + """Evict every dedup entry (all offset/limit ranges) and not-found entry for *filepath* + after a write, so the next read returns fresh content. Acquires the lock itself.""" + resolved = _resolved_or_none(filepath, task_id) + if resolved is None: + return + with _read_tracker_lock: + task_data = _read_tracker.get(task_id) + if task_data is None: + return + dedup = task_data.get("dedup") + if dedup: + for k in [k for k in dedup if k[0] == resolved]: + del dedup[k] + _pop_not_found("read", resolved, task_id) + _pop_not_found("search", resolved, task_id) + + +def _update_read_timestamp(filepath: str, task_id: str) -> None: + """After a successful write: invalidate dedup and refresh the stored mtime so + consecutive edits by the same task don't trigger false staleness warnings. + + Also invalidates the dedup cache for the written path so that subsequent reads return fresh content + (fixes #13144). + """ + _invalidate_dedup_for_path(filepath, task_id) + resolved = _resolved_or_none(filepath, task_id) + if resolved is None: + return + try: + current_mtime = os.path.getmtime(resolved) + except OSError: + return + with _read_tracker_lock: + task_data = _read_tracker.get(task_id) + if task_data is not None: + task_data.setdefault("read_timestamps", {})[resolved] = current_mtime + _cap_read_tracker_data(task_data) + + +def _check_file_staleness(filepath: str, task_id: str) -> str | None: + """Warn (don't block) when the file's mtime changed since this task last read it. + ``None`` when never read, fresh, or unstattable (a deleted file is the write's problem).""" + resolved = _resolved_or_none(filepath, task_id) + if resolved is None: + return None + with _read_tracker_lock: + task_data = _read_tracker.get(task_id) + read_mtime = task_data.get("read_timestamps", {}).get(resolved) if task_data else None + if read_mtime is None: + return None + try: + current_mtime = os.path.getmtime(resolved) + except OSError: + return None + if current_mtime != read_mtime: + return ( + f"Warning: {filepath} was modified since you last read it " + "(external edit or concurrent agent). The content you read may be " + "stale. Consider re-reading the file to verify before writing.") + return None + + +def _mark_verification_stale(task_id: str, resolved_paths: list[str], + session_id: str | None = None) -> None: + """Best-effort note that successful edits made prior verification stale. cwd: the + first edited path's recognised project root, else the workspace root, else the first parent.""" + from pathlib import Path + + paths = [p for p in resolved_paths if p] + if not paths: + return + try: + from agent.coding_context import project_facts_for + from agent.verification_evidence import mark_workspace_edited + + parents = [str(Path(p).parent) for p in paths] + cwd = (next((c for c in parents if project_facts_for(c)), None) + or _authoritative_workspace_root(task_id) or parents[0]) + mark_workspace_edited(session_id=session_id or task_id, cwd=cwd, paths=paths) + except Exception: + logger.debug("verification stale marker failed", exc_info=True) diff --git a/tools/focus_pane_tool.py b/tools/focus_pane_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..696681afb5902f55023dcb0b7ab5e4dfb68ebde4 --- /dev/null +++ b/tools/focus_pane_tool.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Reveal/focus a pane in the Hermes desktop GUI (``pane.reveal`` via ``desktop_ui``). + +The renderer runs each pane's own reveal path and only acts on the active window, so +a background turn never moves the user's focus. URLs/files go through `desktop_preview`. +""" + +from tools import desktop_ui +from tools.registry import registry, tool_error + +PANES = ("chat", "files", "terminal", "review", "sessions") + + +def focus_pane_tool(pane: str) -> str: + """Ask the desktop GUI to reveal and focus ``pane``.""" + name = (pane or "").strip().lower() + if name not in PANES: + return tool_error(f"pane must be one of: {', '.join(PANES)}.") + return desktop_ui.emit_or_error( + "pane.reveal", {"pane": name}, f"Failed to focus the {name} pane: ", + "Pane focus is only available in the Hermes desktop app.", {"success": True, "pane": name}) + + +registry.register( + name="focus_pane", + toolset="desktop_ui", + schema={ + "name": "focus_pane", + "description": ( + "Reveal and focus a Hermes desktop pane when the user asks to see it: " + "chat, files, terminal, review (git diff), or sessions. For URLs/" + "files use the desktop_preview tool instead." + ), + "parameters": { + "type": "object", + "properties": { + "pane": { + "type": "string", + "enum": list(PANES), + "description": "Which pane to reveal.", + }, + }, + "required": ["pane"], + }, + }, + handler=lambda args, **kw: focus_pane_tool(pane=args.get("pane", "")), + emoji="🪟", +) + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. +import json # noqa: F401,E402 + +FOCUS_PANE_SCHEMA = { + "name": "focus_pane", + "description": ( + "Reveal and focus a Hermes desktop pane when the user asks to see it: " + "chat, files, terminal, review (git diff), or sessions. For URLs/" + "files use the desktop_preview tool instead." + ), + "parameters": { + "type": "object", + "properties": { + "pane": { + "type": "string", + "enum": list(PANES), + "description": "Which pane to reveal.", + }, + }, + "required": ["pane"], + }, +} +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/homeassistant_tool.py b/tools/homeassistant_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..28bd38c0bafe47c90ab918fc5bd4f0b30c26e6a6 --- /dev/null +++ b/tools/homeassistant_tool.py @@ -0,0 +1,335 @@ +"""Home Assistant tool for controlling smart home devices via REST API. + +Registers ``ha_list_entities``, ``ha_get_state``, ``ha_list_services``, ``ha_call_service``. +Auth is a Long-Lived Access Token (``HASS_TOKEN``); the instance URL comes from +``HASS_URL`` (default http://homeassistant.local:8123). +""" + +import asyncio +import json +import logging +import re +from typing import Any, Dict, Optional + +from agent.secret_scope import get_secret +from tools.registry import registry, tool_error + +logger = logging.getLogger(__name__) + + +def _get_config(): + """Return the active profile's Home Assistant URL and token.""" + return ( + (get_secret("HASS_URL", "http://homeassistant.local:8123") or "").rstrip("/"), + get_secret("HASS_TOKEN", "") or "") + + +# Valid HA entity_id (e.g. "light.living_room", "sensor.temperature_1"). +_ENTITY_ID_RE = re.compile(r"^[a-z_][a-z0-9_]*\.[a-z0-9_]+$") + +# Domain/service names are interpolated into /api/services/{domain}/{service}, so only +# [a-z0-9_] is allowed: anything else enables SSRF via path traversal +# (domain="../../api/config") or blocklist bypass (domain="shell_command/../light"). +_SERVICE_NAME_RE = re.compile(r"^[a-z][a-z0-9_]*$") + +# Domains that allow arbitrary code/command execution on the HA host or SSRF on the +# local network. HA has zero service-level access control; all safety lives here. +_BLOCKED_DOMAINS = frozenset({ + "shell_command", # arbitrary shell commands as root in HA container + "command_line", # sensors/switches that execute shell commands + "python_script", # sandboxed but can escalate via hass.services.call() + "pyscript", # scripting integration with broader access + "hassio", # addon control, host shutdown/reboot, stdin to containers + "rest_command", # HTTP requests from HA server (SSRF vector) +}) + + +def _get_headers(token: str = "") -> Dict[str, str]: + """Return authorization headers for HA REST API.""" + if not token: + _, token = _get_config() + return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} + + +async def _api_json(method: str, path: str, timeout: float, payload: Any = None) -> Any: + """One HA REST call (GET or POST JSON) that raises on HTTP errors and returns the JSON body.""" + import aiohttp + hass_url, hass_token = _get_config() + kwargs: Dict[str, Any] = {"headers": _get_headers(hass_token), "timeout": aiohttp.ClientTimeout(total=timeout)} + if method == "POST": + kwargs["json"] = payload + async with aiohttp.ClientSession() as session: + async with session.request(method, f"{hass_url}{path}", **kwargs) as resp: + resp.raise_for_status() + return await resp.json() + + +# ── async helpers (called from sync handlers via _run_async) ───────────────── +def _filter_and_summarize(states: list, domain: Optional[str] = None, area: Optional[str] = None) -> Dict: + """Filter raw HA states by domain/area (area matches friendly_name or area attr) and compact them.""" + if domain: + states = [s for s in states if s.get("entity_id", "").startswith(f"{domain}.")] + if area: + area_lower = area.lower() + states = [ + s for s in states + if area_lower in (s.get("attributes", {}).get("friendly_name", "") or "").lower() + or area_lower in (s.get("attributes", {}).get("area", "") or "").lower()] + entities = [ + { + "entity_id": s["entity_id"], "state": s["state"], + "friendly_name": s.get("attributes", {}).get("friendly_name", "")} + for s in states] + return {"count": len(entities), "entities": entities} + + +async def _async_list_entities(domain: Optional[str] = None, area: Optional[str] = None) -> Dict[str, Any]: + return _filter_and_summarize(await _api_json("GET", "/api/states", 15), domain, area) + + +async def _async_get_state(entity_id: str) -> Dict[str, Any]: + data = await _api_json("GET", f"/api/states/{entity_id}", 10) + return { + "entity_id": data["entity_id"], "state": data["state"], "attributes": data.get("attributes", {}), + "last_changed": data.get("last_changed"), "last_updated": data.get("last_updated")} + + +def _build_service_payload(entity_id: Optional[str] = None, data: Optional[Dict[str, Any]] = None) -> Dict: + """JSON payload for a HA service call; ``entity_id`` overrides data["entity_id"].""" + payload: Dict[str, Any] = dict(data or {}) + if entity_id: + payload["entity_id"] = entity_id + return payload + + +def _parse_service_response(domain: str, service: str, result: Any) -> Dict[str, Any]: + affected = [] + if isinstance(result, list): + affected = [{"entity_id": s.get("entity_id", ""), "state": s.get("state", "")} for s in result] + return {"success": True, "service": f"{domain}.{service}", "affected_entities": affected} + + +async def _async_call_service( + domain: str, service: str, entity_id: Optional[str] = None, data: Optional[Dict[str, Any]] = None, +) -> Dict[str, Any]: + result = await _api_json( + "POST", f"/api/services/{domain}/{service}", 15, _build_service_payload(entity_id, data)) + return _parse_service_response(domain, service, result) + + +async def _async_list_services(domain: Optional[str] = None) -> Dict[str, Any]: + """Available services, optionally filtered by domain, compacted for context.""" + services = await _api_json("GET", "/api/services", 15) + if domain: + services = [s for s in services if s.get("domain") == domain] + result = [] + for svc_domain in services: + domain_services = {} + for svc_name, svc_info in svc_domain.get("services", {}).items(): + svc_entry: Dict[str, Any] = {"description": svc_info.get("description", "")} + fields = svc_info.get("fields", {}) + if fields: + svc_entry["fields"] = { + k: v.get("description", "") for k, v in fields.items() if isinstance(v, dict)} + domain_services[svc_name] = svc_entry + result.append({"domain": svc_domain.get("domain", ""), "services": domain_services}) + return {"count": len(result), "domains": result} + + +# ── sync wrappers (handler signature: (args, **kw) -> str) ─────────────────── +def _run_async(coro): + """Run a coroutine from a sync handler; hops to a thread if a loop is already running.""" + try: + loop = asyncio.get_running_loop() + except RuntimeError: + loop = None + if loop and loop.is_running(): # already inside a loop: asyncio.run() needs its own thread + import concurrent.futures + with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool: + return pool.submit(asyncio.run, coro).result(timeout=30) + return asyncio.run(coro) + + +def _dispatch(coro, log_name: str, fail_msg: str) -> str: + """Run ``coro`` and wrap as ``{"result": ...}``; on error log and return tool_error.""" + try: + return json.dumps({"result": _run_async(coro)}) + except Exception as e: + logger.error("%s error: %s", log_name, e) + return tool_error(f"{fail_msg}: {e}") + + +def _handle_get_state(args: dict, **kw) -> str: + entity_id = args.get("entity_id", "") + if not entity_id: + return tool_error("Missing required parameter: entity_id") + if not _ENTITY_ID_RE.match(entity_id): + return tool_error(f"Invalid entity_id format: {entity_id}") + return _dispatch(_async_get_state(entity_id), "ha_get_state", f"Failed to get state for {entity_id}") + + +def _handle_call_service(args: dict, **kw) -> str: + domain = args.get("domain", "") + service = args.get("service", "") + if not domain or not service: + return tool_error("Missing required parameters: domain and service") + # Format check BEFORE the blocklist: rejects "shell_command/../light" style bypasses. + if not _SERVICE_NAME_RE.match(domain): + return tool_error(f"Invalid domain format: {domain!r}") + if not _SERVICE_NAME_RE.match(service): + return tool_error(f"Invalid service format: {service!r}") + if domain in _BLOCKED_DOMAINS: + return tool_error( + f"Service domain '{domain}' is blocked for security. " + f"Blocked domains: {', '.join(sorted(_BLOCKED_DOMAINS))}") + entity_id = args.get("entity_id") + if entity_id and not _ENTITY_ID_RE.match(entity_id): + return tool_error(f"Invalid entity_id format: {entity_id}") + data = args.get("data") + if isinstance(data, str): # XML tool-calling mode delivers data as a JSON string + try: + data = json.loads(data) if data.strip() else None + except json.JSONDecodeError as e: + return tool_error(f"Invalid JSON string in 'data' parameter: {e}") + return _dispatch( + _async_call_service(domain, service, entity_id, data), + "ha_call_service", f"Failed to call {domain}.{service}") + + +def _check_ha_available() -> bool: + """Tool is only available when HASS_TOKEN is set.""" + return bool(get_secret("HASS_TOKEN")) + + +# ── tool schemas ───────────────────────────────────────────────────────────── +HA_LIST_ENTITIES_SCHEMA = { + "name": "ha_list_entities", + "description": ( + "List Home Assistant entities. Optionally filter by domain " + "(light, switch, climate, sensor, binary_sensor, cover, fan, etc.) " + "or by area name (living room, kitchen, bedroom, etc.)." + ), + "parameters": { + "type": "object", + "properties": { + "domain": { + "type": "string", + "description": ( + "Entity domain to filter by (e.g. 'light', 'switch', 'climate', " + "'sensor', 'binary_sensor', 'cover', 'fan', 'media_player'). " + "Omit to list all entities." + ), + }, + "area": { + "type": "string", + "description": ( + "Area/room name to filter by (e.g. 'living room', 'kitchen'). " + "Matches against entity friendly names. Omit to list all." + ), + }, + }, + "required": [], + }, +} + +HA_GET_STATE_SCHEMA = { + "name": "ha_get_state", + "description": ( + "Get the detailed state of a single Home Assistant entity, including all " + "attributes (brightness, color, temperature setpoint, sensor readings, etc.)." + ), + "parameters": { + "type": "object", + "properties": { + "entity_id": { + "type": "string", + "description": ( + "The entity ID to query (e.g. 'light.living_room', " + "'climate.thermostat', 'sensor.temperature')." + ), + }, + }, + "required": ["entity_id"], + }, +} + +HA_LIST_SERVICES_SCHEMA = { + "name": "ha_list_services", + "description": ( + "List available Home Assistant services (actions) for device control. " + "Shows what actions can be performed on each device type and what " + "parameters they accept. Use this to discover how to control devices " + "found via ha_list_entities." + ), + "parameters": { + "type": "object", + "properties": { + "domain": { + "type": "string", + "description": ( + "Filter by domain (e.g. 'light', 'climate', 'switch'). " + "Omit to list services for all domains." + ), + }, + }, + "required": [], + }, +} + +HA_CALL_SERVICE_SCHEMA = { + "name": "ha_call_service", + "description": ( + "Call a Home Assistant service to control a device. Use ha_list_services " + "to discover available services and their parameters for each domain." + ), + "parameters": { + "type": "object", + "properties": { + "domain": { + "type": "string", + "description": ( + "Service domain (e.g. 'light', 'switch', 'climate', " + "'cover', 'media_player', 'fan', 'scene', 'script')." + ), + }, + "service": { + "type": "string", + "description": ( + "Service name (e.g. 'turn_on', 'turn_off', 'toggle', " + "'set_temperature', 'set_hvac_mode', 'open_cover', " + "'close_cover', 'set_volume_level')." + ), + }, + "entity_id": { + "type": "string", + "description": ( + "Target entity ID (e.g. 'light.living_room'). " + "Some services (like scene.turn_on) may not need this." + ), + }, + "data": { + "type": "string", + "description": ( + "Additional service data as a JSON string. Examples: " + '{"brightness": 255, "color_name": "blue"} for lights, ' + '{"temperature": 22, "hvac_mode": "heat"} for climate, ' + '{"volume_level": 0.5} for media players.' + ), + }, + }, + "required": ["domain", "service"], + }, +} + + +for _schema, _handler in ( + (HA_LIST_ENTITIES_SCHEMA, lambda args, **kw: _dispatch( + _async_list_entities(domain=args.get("domain"), area=args.get("area")), + "ha_list_entities", "Failed to list entities")), + (HA_GET_STATE_SCHEMA, _handle_get_state), + (HA_LIST_SERVICES_SCHEMA, lambda args, **kw: _dispatch( + _async_list_services(domain=args.get("domain")), "ha_list_services", "Failed to list services")), + (HA_CALL_SERVICE_SCHEMA, _handle_call_service)): + registry.register( + name=_schema["name"], toolset="homeassistant", schema=_schema, handler=_handler, + check_fn=_check_ha_available, emoji="🏠") diff --git a/tools/hook_output_spill.py b/tools/hook_output_spill.py new file mode 100644 index 0000000000000000000000000000000000000000..53b55f3f73619234436b0458115d41ea489391b9 --- /dev/null +++ b/tools/hook_output_spill.py @@ -0,0 +1,117 @@ +"""Spill oversized hook-injected context to disk with a preview placeholder. + +Hook ``{"context": ...}`` output rides EVERY subsequent API call, so a large blob +inflates every turn and breaks the prompt-cache prefix. Above +``hooks.output_spill.max_chars`` (default 10000) the text is written under +``hooks.output_spill.directory`` (default ``/hook_outputs/``) +and the payload becomes a ``preview_head``/``preview_tail`` excerpt plus the path. +``enabled: false`` disables. Never raises: an I/O failure still returns a preview. +""" + +from __future__ import annotations + +import logging +import os +import uuid +from pathlib import Path +from typing import Any, Dict, Optional + +from tools.tool_output_limits import _coerce_int, _coerce_positive_int + +logger = logging.getLogger(__name__) + + +DEFAULT_MAX_CHARS = 10_000 +DEFAULT_PREVIEW_HEAD = 500 +DEFAULT_PREVIEW_TAIL = 500 +DEFAULT_ENABLED = True + + +def get_spill_config() -> Dict[str, Any]: + """Return resolved hook output-spill config. Never raises.""" + section: Dict[str, Any] = {} + try: + from hermes_cli.config import load_config + cfg = load_config() or {} + hooks = cfg.get("hooks") if isinstance(cfg, dict) else None + if isinstance(hooks, dict) and isinstance(hooks.get("output_spill"), dict): + section = hooks["output_spill"] + except Exception: + section = {} + enabled_raw = section.get("enabled", DEFAULT_ENABLED) + directory = section.get("directory") + return { + "enabled": bool(enabled_raw) if enabled_raw is not None else DEFAULT_ENABLED, + "max_chars": _coerce_positive_int(section.get("max_chars"), DEFAULT_MAX_CHARS), + # head/tail allow zero (empty tail), max_chars must be positive. + "preview_head": _coerce_int(section.get("preview_head"), DEFAULT_PREVIEW_HEAD, 0), + "preview_tail": _coerce_int(section.get("preview_tail"), DEFAULT_PREVIEW_TAIL, 0), + "directory": directory if isinstance(directory, str) else None, + } + + +def _resolve_spill_dir(directory_override: Optional[str], session_id: Optional[str]) -> Path: + """Per-session spill directory; session id is sanitised so it can't escape ``base``.""" + if directory_override: + base = Path(os.path.expanduser(directory_override)) + else: + from hermes_constants import get_hermes_home + base = Path(get_hermes_home()) / "hook_outputs" + session_segment = (session_id or "no-session").replace("/", "_").replace("\\", "_").replace("..", "_") + return base / session_segment + + +def spill_if_oversized( + text: str, *, session_id: Optional[str] = None, source: str = "hook", config: Optional[Dict[str, Any]] = None, +) -> str: + """Spill ``text`` to disk if it exceeds the configured cap. + + Returns ``text`` unchanged (under cap, disabled, or empty) or a preview + string pointing at the full content. Non-string input is ``str()``-coerced; + ``source`` labels the preview header; ``config`` overrides config.yaml. + """ + if text is None: + return "" + if not isinstance(text, str): + try: + text = str(text) + except Exception: + return "" + cfg = config if config is not None else get_spill_config() + if not cfg.get("enabled", True): + return text + if len(text) <= int(cfg.get("max_chars") or DEFAULT_MAX_CHARS): + return text + head = int(cfg.get("preview_head") or 0) + tail = int(cfg.get("preview_tail") or 0) + + # A disk failure must never blow up the turn — fall through to a preview + # without a saved path. + saved_path: Optional[str] = None + try: + spill_dir = _resolve_spill_dir(cfg.get("directory"), session_id) + from tools.spill_safety import ensure_spill_dir, write_text_exclusive + # Hook context may embed raw secrets: private perms + exclusive, + # symlink-refusing create (the per-session dir is predictable). + ensure_spill_dir(spill_dir, private=True) + spill_path = spill_dir / f"{uuid.uuid4().hex}.txt" + # Trailing newline so tail readers don't report "missing newline". + write_text_exclusive(spill_path, text if text.endswith("\n") else text + "\n", private=True) + saved_path = str(spill_path) + except Exception as exc: + logger.warning("hook output spill failed: %s", exc) + + total = len(text) + parts = [ + f"[{source} output truncated — {total:,} chars; full content " + + (f"saved to {saved_path}]" if saved_path else "unavailable — spill write failed]"), + ] + if head > 0 and text[:head]: + parts.extend(["--- head ---", text[:head]]) + if tail > 0 and total > head: + parts.extend(["--- tail ---", text[-tail:]]) + return "\n".join(parts) + + +__all__ = ["DEFAULT_MAX_CHARS", "DEFAULT_PREVIEW_HEAD", "DEFAULT_PREVIEW_TAIL", "DEFAULT_ENABLED", + "get_spill_config", "spill_if_oversized"] diff --git a/tools/image_generation_tool.py b/tools/image_generation_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..9a1ec2de01960d3f8617c51166d029dd3bf360c7 --- /dev/null +++ b/tools/image_generation_tool.py @@ -0,0 +1,877 @@ +#!/usr/bin/env python3 +"""Image generation via FAL.ai (model picked in ``hermes tools``, persisted to ``image_gen.model``). + +``_build_fal_payload()`` / ``_build_fal_edit_payload()`` translate unified inputs into the +``FAL_MODELS`` payload filtered to its ``supports`` whitelist so models never receive rejected +keys. Clarity upscaling is strictly per-call opt-in: default-on degraded text/CJK/faces. +""" + +import json +import logging +import os +import datetime +import threading +import uuid +from typing import Any, Dict, Optional + +# Imported lazily by _load_fal_client() (~64 ms on every CLI cold start); a test-monkeypatched +# value short-circuits the loader. +fal_client: Any = None + + +def _load_fal_client() -> Any: + """Lazily import fal_client into the module global (idempotent; keeps a test-installed mock).""" + global fal_client + if fal_client is None: + from tools.fal_common import import_fal_client + fal_client = import_fal_client() + return fal_client + + +from tools.debug_helpers import DebugSession +from tools.fal_common import ( + _ManagedFalSyncClient, _extract_http_status, _managed_fal_billing_error, + _normalize_fal_queue_url_format, +) +from tools.image_generation_catalog import ( + DEFAULT_ASPECT_RATIO, DEFAULT_MODEL, FAL_MODELS, UPSCALER_CREATIVITY, UPSCALER_DEFAULT_PROMPT, + UPSCALER_FACTOR, UPSCALER_GUIDANCE_SCALE, UPSCALER_MODEL, UPSCALER_NEGATIVE_PROMPT, + UPSCALER_NUM_INFERENCE_STEPS, UPSCALER_RESEMBLANCE, UPSCALER_SAFETY_CHECKER, VALID_ASPECT_RATIOS, +) +from tools.managed_tool_gateway import resolve_managed_tool_gateway +from tools.tool_backend_helpers import ( + NOUS_MANAGED_PROVIDER, fal_key_is_configured, managed_nous_tools_enabled, + nous_tool_gateway_unavailable_message, read_selection, selection_error) + +logger = logging.getLogger(__name__) + +_debug = DebugSession("image_tools", env_var="IMAGE_TOOLS_DEBUG") +_managed_fal_client = None +_managed_fal_client_config = None +_managed_fal_client_lock = threading.Lock() + + +# --- Managed FAL gateway (Nous Subscription) --- +def _resolve_managed_fal_gateway(): + """Managed gateway config for the stored `hermes tools` selection, or ``None`` for direct FAL. + + ``"nous"`` (or legacy ``use_gateway: true``) → managed ONLY (unreachable = selection-naming + error, never a silent FAL_KEY fallback). Other stored provider → direct ONLY (missing FAL_KEY + = error naming the selection). Never configured → autodetect: direct if FAL_KEY, else managed. + """ + selected = read_selection("image_gen") + if selected == NOUS_MANAGED_PROVIDER: + gateway = resolve_managed_tool_gateway("fal-queue") + if gateway is None: + raise ValueError(selection_error( + "image_gen", NOUS_MANAGED_PROVIDER, + "the Nous Tool Gateway is not available (not entitled or unreachable)")) + return gateway + if selected is not None: + if fal_key_is_configured(): + return None + raise ValueError(selection_error("image_gen", selected, "FAL_KEY is not set")) + # Never-configured category: legacy credential autodetect (do NOT persist). + return None if fal_key_is_configured() else resolve_managed_tool_gateway("fal-queue") + + +def _get_managed_fal_client(managed_gateway): + """Reuse the managed FAL client so its internal httpx.Client is not leaked per call.""" + global _managed_fal_client, _managed_fal_client_config + client_config = (managed_gateway.gateway_origin.rstrip("/"), managed_gateway.nous_user_token) + with _managed_fal_client_lock: + if _managed_fal_client is None or _managed_fal_client_config != client_config: + # Resolved on this module so monkeypatching ``image_generation_tool.fal_client`` still applies. + _managed_fal_client = _ManagedFalSyncClient( + _load_fal_client(), key=managed_gateway.nous_user_token, + queue_run_origin=managed_gateway.gateway_origin) + _managed_fal_client_config = client_config + return _managed_fal_client + + +class ImageGenerationInterrupted(Exception): + """Raised when the user interrupts while a FAL job is in flight.""" + + +def _wait_fal_result(handler, *, poll_seconds: float = 0.5): + """Interrupt-aware ``handler.get()``: the SDK blocks 30-60s, hiding user interrupts. + + The get runs on a daemon worker; the interrupt bit is polled between join slices and on + interrupt the worker is abandoned (remote job keeps running). + """ + from tools.interrupt import is_interrupted + result_box: list = [] + error_box: list = [] + def _get(): + try: + result_box.append(handler.get()) + except BaseException as exc: # noqa: BLE001 — re-raised on the caller thread + error_box.append(exc) + worker = threading.Thread(target=_get, daemon=True, name="fal-result-wait") + worker.start() + while worker.is_alive(): + if is_interrupted(): + raise ImageGenerationInterrupted( + "Image generation interrupted by user — abandoned the in-flight FAL job.") + worker.join(timeout=poll_seconds) + if error_box: + raise error_box[0] + return result_box[0] if result_box else None + + +def _submit_fal_request(model: str, arguments: Dict[str, Any]): + """Submit a FAL request using direct credentials or the managed queue gateway.""" + _load_fal_client() + request_headers = {"x-idempotency-key": str(uuid.uuid4())} + managed_gateway = _resolve_managed_fal_gateway() + if managed_gateway is None: + return fal_client.submit(model, arguments=arguments, headers=request_headers) + try: + return _get_managed_fal_client(managed_gateway).submit( + model, arguments=arguments, headers=request_headers) + except Exception as exc: + # A managed-gateway 4xx usually means the portal doesn't proxy this model + # (allowlist miss, billing gate): give remediation instead of a raw httpx error. + status = _extract_http_status(exc) + if status is not None and 400 <= status < 500: + billing = _managed_fal_billing_error(exc, "model") + if billing is not None: + raise ValueError( + f"Nous Subscription gateway rejected model '{model}' (HTTP {status}): {billing}") from exc + gateway_message = "" + if status in {401, 402, 403}: + gateway_message = "\n\n" + nous_tool_gateway_unavailable_message( + "managed FAL image generation", force_fresh=True) + raise ValueError( + f"Nous Subscription gateway rejected model '{model}' (HTTP {status}). This model " + f"may not yet be enabled on the Nous Portal's FAL proxy. Either:\n" + f" • Set FAL_KEY in your environment to use FAL.ai directly, or\n" + f" • Pick a different model via `hermes tools` → Image Generation." + f"{gateway_message}") from exc + raise + + +# --- Config readers, model resolution + payload construction --- +def _read_image_gen_key(key: str) -> Optional[str]: + """Return the stripped ``image_gen.`` string from config.yaml, or None.""" + try: + from hermes_cli.config import load_config + cfg = load_config() + section = cfg.get("image_gen") if isinstance(cfg, dict) else None + value = section.get(key) if isinstance(section, dict) else None + if isinstance(value, str) and value.strip(): + return value.strip() + except Exception as exc: + logger.debug("Could not read image_gen.%s: %s", key, exc) + return None + + +def _read_configured_image_model(): + """``image_gen.model`` from config.yaml, or None.""" + return _read_image_gen_key("model") + + +def _read_configured_image_provider(): + """``image_gen.provider`` from config.yaml, or None (unset keeps the in-tree FAL fallback even + when other providers are registered; ``"fal"`` routes via ``plugins/image_gen/fal/``). + + We only consult the plugin registry when this is explicitly set — an unset value keeps users on the + in-tree FAL fallback even when other providers happen to be registered (e.g. a user has OPENAI_API_KEY + set for other features but never asked for OpenAI image gen). ``"fal"`` explicitly routes through + ``plugins/image_gen/fal/`` (which delegates back into this module's pipeline via call-time indirection — + see issue #26241). + """ + return _read_image_gen_key("provider") + + +def _plugin_provider_name() -> Optional[str]: + """Configured provider that must go through the plugin registry; None for unset/fal/nous.""" + configured = _read_configured_image_provider() + if not configured or configured in ("fal", NOUS_MANAGED_PROVIDER): + return None + return configured + + +def _resolve_fal_model() -> tuple: + """Return ``(model_id, meta)`` for the configured FAL model, falling back to DEFAULT_MODEL (warned) when unknown.""" + # FAL_IMAGE_MODEL is an undocumented escape hatch (backward-compat for tests/scripts). + model_id = _read_image_gen_key("model") or os.getenv("FAL_IMAGE_MODEL", "").strip() + if model_id and model_id not in FAL_MODELS: + logger.warning("Unknown FAL model '%s' in config; falling back to %s", model_id, DEFAULT_MODEL) + model_id = None + model_id = model_id or DEFAULT_MODEL + return model_id, FAL_MODELS[model_id] + + +_SIZE_KEY_BY_STYLE = {"image_size_preset": "image_size", "gpt_literal": "image_size", + "aspect_ratio": "aspect_ratio"} + + +def _build_payload(model_id, prompt, aspect_ratio, seed, overrides, image_urls=None) -> Dict[str, Any]: + """Text-to-image / edit payload (``image_urls`` selects edit mode): defaults + native size + spec + overrides, filtered to the model whitelist. + + Edit endpoints mostly auto-infer size, so the size key is sent only when ``edit_supports`` + lists it. ``prompt`` (and the source-image key on edits) survive a whitelist gap: every FAL + endpoint requires them, so a catalog mistake can't send a broken request. + """ + meta = FAL_MODELS[model_id] + edit = image_urls is not None + supports = (meta.get("edit_supports") or set()) if edit else meta["supports"] + sizes = meta["sizes"] + aspect = (aspect_ratio or DEFAULT_ASPECT_RATIO).lower().strip() + if aspect not in sizes: + aspect = DEFAULT_ASPECT_RATIO + payload: Dict[str, Any] = dict(meta.get("defaults", {})) + payload["prompt"] = (prompt or "").strip() + required = {"prompt"} + if edit: # a few edit endpoints (Kling Image v3) take a singular `image_url` string instead of the list + image_param = meta.get("edit_image_param") or "image_urls" + payload[image_param] = list(image_urls)[0] if image_param != "image_urls" else list(image_urls) + required.add(image_param) + size_key = _SIZE_KEY_BY_STYLE.get(meta["size_style"]) + if size_key is None and not edit: + raise ValueError(f"Unknown size_style: {meta['size_style']!r}") + if size_key is not None and (not edit or size_key in supports): + payload[size_key] = sizes[aspect] + if isinstance(seed, int): + payload["seed"] = seed + payload.update({k: v for k, v in (overrides or {}).items() if v is not None}) + return {k: v for k, v in payload.items() if k in supports or k in required} + + +def _build_fal_payload(model_id, prompt, aspect_ratio=DEFAULT_ASPECT_RATIO, seed=None, overrides=None): + """FAL text-to-image payload for ``model_id`` from unified inputs.""" + return _build_payload(model_id, prompt, aspect_ratio, seed, overrides) + + +def _build_fal_edit_payload(model_id, prompt, image_urls, aspect_ratio=DEFAULT_ASPECT_RATIO, + seed=None, overrides=None): + """FAL *edit* (image-to-image) payload: ``image_urls`` + prompt, filtered to ``edit_supports``.""" + return _build_payload(model_id, prompt, aspect_ratio, seed, overrides, image_urls=image_urls) + + +# --- Upscaler --- +def _upscale_image(image_url: str, original_prompt: str) -> Optional[Dict[str, Any]]: + """Upscale via FAL's Clarity Upscaler; None on failure (caller keeps the original).""" + try: + logger.info("Upscaling image with Clarity Upscaler...") + handler = _submit_fal_request(UPSCALER_MODEL, arguments={ + "image_url": image_url, "prompt": f"{UPSCALER_DEFAULT_PROMPT}, {original_prompt}", + "upscale_factor": UPSCALER_FACTOR, "negative_prompt": UPSCALER_NEGATIVE_PROMPT, + "creativity": UPSCALER_CREATIVITY, "resemblance": UPSCALER_RESEMBLANCE, + "guidance_scale": UPSCALER_GUIDANCE_SCALE, + "num_inference_steps": UPSCALER_NUM_INFERENCE_STEPS, + "enable_safety_checker": UPSCALER_SAFETY_CHECKER}) + result = _wait_fal_result(handler) + if result and "image" in result: + up = result["image"] + logger.info("Image upscaled successfully to %sx%s", + up.get("width", "unknown"), up.get("height", "unknown")) + return { + "url": up["url"], "width": up.get("width", 0), "height": up.get("height", 0), + "upscaled": True, "upscale_factor": UPSCALER_FACTOR} + logger.error("Upscaler returned invalid response") + return None + except ImageGenerationInterrupted: + # A user interrupt must not degrade into a silent "use original" fallback. + raise + except Exception as e: + logger.error("Error upscaling image: %s", e, exc_info=True) + return None + + +# --- Artifact path hinting for non-local terminal backends --- +_CONTAINER_HOME_ENVS = {"DockerEnvironment", "SingularityEnvironment", "ModalEnvironment"} +# No env yet: only deterministic cache roots translate side-effect free (SSH: tilde path; its +# first sync uploads the cache file). +_CACHE_BASE_BY_BACKEND = {"docker": "/root/.hermes", "singularity": "/root/.hermes", + "modal": "/root/.hermes", "ssh": "~/.hermes"} + + +def _looks_like_absolute_file_path(value: str) -> bool: + if not value or not isinstance(value, str) or value.lower().startswith(("http://", "https://", "data:")): + return False + return os.path.isabs(value) or (len(value) >= 3 and value[1] == ":" and value[2] in {"/", "\\"}) + + +def _active_terminal_env(task_id: str | None): + try: + from tools.terminal_tool_lifecycle import get_active_env + return get_active_env(task_id or "default") + except Exception as exc: # noqa: BLE001 - artifact hinting must not break generation + logger.debug("Could not inspect active terminal environment: %s", exc) + return None + + +def _agent_cache_base_for_env(env: Any) -> str | None: + if env is not None: + # Optional extension hook: an environment may expose its own agent-visible cache root. + explicit = getattr(env, "agent_visible_cache_base", None) + if callable(explicit): + try: + value = explicit() + if value: + return str(value).rstrip("/") + except Exception as exc: # noqa: BLE001 + logger.debug("active env agent_visible_cache_base failed: %s", exc) + remote_home = getattr(env, "_remote_home", None) + if remote_home: + return f"{str(remote_home).rstrip('/')}/.hermes" + if env.__class__.__name__ in _CONTAINER_HOME_ENVS: + return "/root/.hermes" + from tools.terminal_scope import terminal_env + backend = (terminal_env("TERMINAL_ENV") or "local").strip().lower() + return _CACHE_BASE_BY_BACKEND.get(backend) + + +def _postprocess_image_generate_result(raw: str, task_id: str | None = None) -> str: + """Annotate successful local results: ``image`` stays the host/gateway-deliverable path; + ``agent_visible_image`` is the same file as seen by a non-local terminal backend.""" + try: + payload = json.loads(raw) if isinstance(raw, str) else raw + except Exception: + return raw + if not isinstance(payload, dict) or not payload.get("success"): + return raw + image = payload.get("image") + if not isinstance(image, str) or not _looks_like_absolute_file_path(image): + return raw + env = _active_terminal_env(task_id) + cache_base = _agent_cache_base_for_env(env) + if not cache_base: + return raw + try: + from tools.credential_files import map_cache_path_to_container + agent_path = map_cache_path_to_container(image, container_base=cache_base) + except Exception as exc: # noqa: BLE001 + logger.debug("Could not translate image cache path for backend: %s", exc) + return raw + if not agent_path or agent_path == image: + return raw + sync_manager = getattr(env, "_sync_manager", None) + if sync_manager is not None: + try: + sync_manager.sync(force=True) + except Exception as exc: # noqa: BLE001 - keep generation success; log for operators + logger.warning("Could not force-sync generated image artifact: %s", exc) + payload.setdefault("host_image", image) + payload.setdefault("agent_visible_image", agent_path) + return json.dumps(payload, ensure_ascii=False) + + +# --- Tool entry point --- +def _format_images(images: list, should_upscale: bool, prompt: str) -> list: + """Normalize FAL result images, optionally chaining the upscaler (falls back to the original on failure).""" + formatted = [] + for img in images: + if not (isinstance(img, dict) and "url" in img): + continue + if should_upscale: + upscaled = _upscale_image(img["url"], prompt.strip()) + if upscaled: + formatted.append(upscaled) + continue + logger.warning("Using original image as fallback (upscale failed)") + formatted.append({ + "url": img["url"], "width": img.get("width", 0), "height": img.get("height", 0), + "upscaled": False}) + return formatted + + +def _prepare_fal_request(model_id, meta, prompt, aspect_ratio, seed, overrides, source_images): + """Validate inputs and return ``(endpoint, arguments)``; raises ValueError with the user-facing message.""" + if not isinstance(prompt, str) or not prompt.strip(): + raise ValueError("Prompt is required and must be a non-empty string") + # A stored-but-broken selection raises the selection-naming error from + # _resolve_managed_fal_gateway(); only never-configured reports "no backend at all". + if not (fal_key_is_configured() or _resolve_managed_fal_gateway()): + raise ValueError(_build_no_backend_setup_message()) + edit_endpoint, display = meta.get("edit_endpoint"), meta.get("display", model_id) + # Fail clearly rather than silently dropping sources and producing an unrelated picture. + if source_images and not edit_endpoint: + raise ValueError( + f"Model '{display}' ({model_id}) is not capable of image-to-image / editing. " + f"Provide a text-only prompt (omit image_url), or switch to an edit-capable model " + f"via `hermes tools` → Image Generation.") + aspect_lc = (aspect_ratio or DEFAULT_ASPECT_RATIO).lower().strip() + if aspect_lc not in VALID_ASPECT_RATIOS: + logger.warning("Invalid aspect_ratio '%s', defaulting to '%s'", aspect_ratio, DEFAULT_ASPECT_RATIO) + aspect_lc = DEFAULT_ASPECT_RATIO + if source_images: + # Clamp reference count to the model's declared cap. + max_refs = int(meta.get("max_reference_images") or 1) + clamped_sources = source_images[:max_refs] if max_refs > 0 else source_images + arguments = _build_fal_edit_payload( + model_id, prompt, clamped_sources, aspect_lc, seed=seed, overrides=overrides) + logger.info("Editing image with %s (%s) — %d source image(s), prompt: %s", + display, edit_endpoint, len(clamped_sources), prompt[:80]) + return edit_endpoint, arguments + arguments = _build_fal_payload(model_id, prompt, aspect_lc, seed=seed, overrides=overrides) + logger.info("Generating image with %s (%s) — prompt: %s", display, model_id, prompt[:80]) + return model_id, arguments + + +def image_generate_tool( + prompt: str, aspect_ratio: str = DEFAULT_ASPECT_RATIO, + num_inference_steps: Optional[int] = None, guidance_scale: Optional[float] = None, + num_images: Optional[int] = None, output_format: Optional[str] = None, + seed: Optional[int] = None, image_url: Optional[str] = None, + reference_image_urls: Optional[list] = None, upscale: Optional[bool] = None) -> str: + """Generate (or, with source images + an ``edit_endpoint`` model, edit) an image via FAL. + + Extra kwargs are overrides filtered per-model via ``supports`` / ``edit_supports`` (dropped + silently so callers survive model switches). Returns JSON ``{"success", "image", "modality", + "error", "error_type"}``. + """ + model_id, meta = _resolve_fal_model() + refs = reference_image_urls if isinstance(reference_image_urls, (list, tuple)) else [] + source_images = [c.strip() for c in (image_url, *refs) if isinstance(c, str) and c.strip()] + use_edit = bool(source_images) and bool(meta.get("edit_endpoint")) + modality = "image" if use_edit else "text" + overrides: Dict[str, Any] = { + "num_inference_steps": num_inference_steps, "guidance_scale": guidance_scale, + "num_images": num_images, "output_format": output_format} + debug_call_data = { + "model": model_id, + "parameters": {"prompt": prompt, "aspect_ratio": aspect_ratio, **overrides, "seed": seed, + "modality": modality, "source_images": len(source_images)}, + "error": None, "success": False, "images_generated": 0, "generation_time": 0} + start_time = datetime.datetime.now() + + def finish(generation_time: float, response: Dict[str, Any]) -> str: + debug_call_data["generation_time"] = generation_time + _debug.log_call("image_generate_tool", debug_call_data) + _debug.save() + return json.dumps(response, indent=2, ensure_ascii=False) + try: + endpoint, arguments = _prepare_fal_request( + model_id, meta, prompt, aspect_ratio, seed, + {k: v for k, v in overrides.items() if v is not None}, source_images) + result = _wait_fal_result(_submit_fal_request(endpoint, arguments=arguments)) + generation_time = (datetime.datetime.now() - start_time).total_seconds() + if not result or "images" not in result: + raise ValueError("Invalid response from FAL.ai API — no images returned") + images = result.get("images", []) + if not images: + raise ValueError("No images were generated") + # Explicit ``upscale`` wins, including for edits; the catalog default never upscales + # edits (Clarity is a text-to-image pass and must not silently alter compositions). + if upscale is not None: + should_upscale = bool(upscale) + else: + should_upscale = bool(meta.get("upscale", False)) and not use_edit + formatted_images = _format_images(images, should_upscale, prompt) + if not formatted_images: + raise ValueError("No valid image URLs returned from API") + upscaled_count = sum(1 for img in formatted_images if img.get("upscaled")) + logger.info("Generated %s image(s) in %.1fs (%s upscaled) via %s [%s]", + len(formatted_images), generation_time, upscaled_count, endpoint, modality) + debug_call_data["success"] = True + debug_call_data["images_generated"] = len(formatted_images) + return finish(generation_time, { + "success": True, + "image": formatted_images[0]["url"], + "modality": modality, + "upscaled": bool(formatted_images[0].get("upscaled"))}) + except Exception as e: + error_msg = f"Error generating image: {str(e)}" + logger.error("%s", error_msg, exc_info=True) + debug_call_data["error"] = error_msg + generation_time = (datetime.datetime.now() - start_time).total_seconds() + return finish(generation_time, + {"success": False, "image": None, "error": str(e), "error_type": type(e).__name__}) + + +def check_fal_api_key() -> bool: + """True if the selected FAL backend (never configured: any FAL backend) is available. + + A stored-but-broken selection reports False here (registry gating); the naming error + surfaces at call time from ``_resolve_managed_fal_gateway``. + """ + try: + gateway = _resolve_managed_fal_gateway() + except ValueError: + return False + return bool(gateway) or fal_key_is_configured() + + +def _build_no_backend_setup_message() -> str: + """Actionable no-backend error: FAL_KEY signup, managed-gateway status, plugin alternative.""" + managed = managed_nous_tools_enabled() + lines = ["Image generation is unavailable in this environment.", "", "Missing requirements:"] + if managed: + lines.append(" - FAL_KEY is not set and the managed FAL gateway is unreachable") + else: + lines.append(" - FAL_KEY environment variable is not set") + if gateway_message := nous_tool_gateway_unavailable_message("managed FAL image generation"): + lines.append(f" - {gateway_message}") + lines += ["", "To enable image generation, do one of:", + " 1. Get a free API key at https://fal.ai and set FAL_KEY= " + "(then restart the session)"] + if managed: + lines.append(" 2. Sign in to a Nous account that has the managed FAL gateway enabled " + "(`hermes setup`)") + lines.append(" 3. Configure a different image_gen provider via `hermes tools` → Image Generation " + "(run `hermes plugins list` to see installed backends)") + return "\n".join(lines) + + +def _get_plugin_provider(name: str, *, force: bool = False): + """Discover plugins (local import: importing this module must not trigger discovery) and return the named provider.""" + from agent.image_gen_registry import get_provider + from hermes_cli.plugins import _ensure_plugins_discovered + if force: + _ensure_plugins_discovered(force=True) + else: + _ensure_plugins_discovered() + return get_provider(name) + + +def check_image_generation_requirements() -> bool: + """True if FAL or the explicitly configured image backend is available.""" + try: + if check_fal_api_key(): + # Lazy import doubles as the SDK presence check: ImportError falls through to plugins. + _load_fal_client() + return True + except ImportError: + pass + configured = _plugin_provider_name() + if configured is None: + return False + # Probe only the selected plugin: a cloud key alone must not opt a user into a paid backend. + provider = _get_plugin_provider(configured) + return bool(provider and provider.is_available()) + + +# --- Registry --- +from tools.registry import registry, tool_error + +IMAGE_GENERATE_SCHEMA = { + "name": "image_generate", + # Placeholder: description AND params are rebuilt at get_tool_definitions() time by + # _build_dynamic_image_schema() from the active backend's capabilities. Edit-only args + # and upscale are advertised ONLY when supported; the handler accepts them regardless + # (replay compat + teaching errors). + "description": ( + "Generate images from text prompts. The active model's edit/reference " + "capabilities are rendered at serving time." + ), + "parameters": { + "type": "object", + "properties": { + "prompt": { + "type": "string", + "description": ( + "The text prompt describing the desired image (text-to-" + "image) or the edit to apply (image-to-image). Be detailed " + "and descriptive." + ), + }, + "aspect_ratio": { + "type": "string", + "enum": list(VALID_ASPECT_RATIOS), + "description": "The aspect ratio of the generated image. 'landscape' is 16:9 wide, 'portrait' is 16:9 tall, 'square' is 1:1.", + "default": DEFAULT_ASPECT_RATIO, + }, + # image_url / reference_image_urls / upscale are added per-capability; never statically. + }, + # See #95681. + "required": ["prompt"], + }, +} + + +# --- Plugin provider dispatch + managed-mode Krea routing --- +def _provider_error(error: str, error_type: str) -> str: + """JSON error envelope shared by every provider-dispatch failure path.""" + return json.dumps({"success": False, "image": None, "error": error, "error_type": error_type}) + + +def _provider_result(result, contract_error: str) -> str: + """JSON-encode a provider's dict result; anything else is a contract violation.""" + if not isinstance(result, dict): + return _provider_error(contract_error, "provider_contract") + return json.dumps(result) + + +def _add_provider_kwargs(kwargs, image_url, reference_image_urls, upscale, model=None) -> Dict[str, Any]: + """Add the optional ``provider.generate(**kwargs)`` args in place (edit args only when supplied).""" + if model: + kwargs["model"] = model + if isinstance(image_url, str) and image_url.strip(): + kwargs["image_url"] = image_url.strip() + if reference_image_urls is not None: + from agent.image_gen_provider import normalize_reference_images + norm_refs = normalize_reference_images(reference_image_urls) + if norm_refs: + kwargs["reference_image_urls"] = norm_refs + if upscale is not None: + kwargs["upscale"] = bool(upscale) + return kwargs + + +def _dispatch_to_plugin_provider( + prompt: str, aspect_ratio: str, image_url: Optional[str] = None, + reference_image_urls: Optional[list] = None, upscale: Optional[bool] = None): + """JSON result from the selected plugin provider, or ``None`` to fall through to in-tree FAL + (provider unset / ``"fal"`` / ``"nous"``). Providers without ``upscale`` ignore it via ``**kwargs``.""" + configured = _plugin_provider_name() + if configured is None: + return None + try: + provider = _get_plugin_provider(configured) + except Exception as exc: + logger.debug("image_gen plugin dispatch skipped: %s", exc) + return None + if provider is None: + # Long-lived sessions may have discovered plugins before a bundled backend + # was patched in or config changed: retry once with a forced refresh. + try: + provider = _get_plugin_provider(configured, force=True) + except Exception as exc: + logger.debug("image_gen plugin force-refresh skipped: %s", exc) + if provider is None: + return _provider_error( + f"image_gen.provider='{configured}' is set but no plugin registered that name. " + f"Run `hermes plugins list` to see available image gen backends.", "provider_not_registered") + pname = getattr(provider, "name", "?") + kwargs: Dict[str, Any] = {"prompt": prompt, "aspect_ratio": aspect_ratio} + try: + _add_provider_kwargs(kwargs, image_url, reference_image_urls, upscale, + model=_read_configured_image_model()) + result = provider.generate(**kwargs) + except Exception as exc: + # A TypeError from generate() predating image_url support (third-party plugin not yet + # updated): text-to-image keeps working; surface a clear note when an edit was requested. + is_type_error = isinstance(exc, TypeError) + if is_type_error and ("image_url" in kwargs or "reference_image_urls" in kwargs): + logger.warning("image_gen provider '%s' rejected image-to-image kwargs " + "(signature too narrow): %s", pname, exc) + return _provider_error( + f"Provider '{pname}' does not support image-to-image / editing (its generate() " + f"signature is out of date with the image_generate schema). Omit image_url for " + f"text-to-image, or pick a backend that supports editing via `hermes tools` → " + f"Image Generation.", "modality_unsupported") + logger.warning("Image gen provider '%s' raised%s: %s", pname, + " TypeError" if is_type_error else "", exc) + return _provider_error(f"Provider '{pname}' error: {exc}", "provider_exception") + return _provider_result(result, "Provider returned a non-dict result") + + +# Native ``krea-2-*`` ids are served by the Krea managed gateway (managed mode only — +# direct/BYO users keep their pipeline); ``fal-ai/krea/v2/*`` catalog ids stay on FAL. +_KREA_NATIVE_MODELS = {"krea-2-medium", "krea-2-large", "krea-2-medium-turbo"} + + +def _normalize_krea_model(model_id: Optional[str]) -> Optional[str]: + """Return the native Krea plugin model id when ``model_id`` is ``krea-2-*``.""" + candidate = model_id.strip() if isinstance(model_id, str) else None + return candidate if candidate in _KREA_NATIVE_MODELS else None + + +def _maybe_route_managed_krea( + prompt: str, aspect_ratio: str, image_url: Optional[str] = None, + reference_image_urls: Optional[list] = None, upscale: Optional[bool] = None) -> Optional[str]: + """JSON result from the managed Krea gateway, or ``None`` to fall through. + + Fires only for a native ``krea-2-*`` model with no ``image_gen.provider`` other than + ``"nous"`` stored (a picker choice dispatches normally) and a resolvable Krea gateway. + """ + configured_provider = _read_configured_image_provider() + if configured_provider is not None and configured_provider != NOUS_MANAGED_PROVIDER: + return None + normalized = _normalize_krea_model(_read_configured_image_model()) + if normalized is None: + return None + try: + from plugins.image_gen.krea import _resolve_managed_krea_gateway + if _resolve_managed_krea_gateway() is None: + return None + provider = _get_plugin_provider("krea") + except Exception as exc: # noqa: BLE001 + logger.debug("Managed Krea routing unavailable: %s", exc) + return None + if provider is None: + return None + kwargs: Dict[str, Any] = {"prompt": prompt, "aspect_ratio": aspect_ratio, "model": normalized} + try: + _add_provider_kwargs(kwargs, image_url, reference_image_urls, upscale) + result = provider.generate(**kwargs) + except Exception as exc: # noqa: BLE001 + logger.warning("Managed Krea routing failed: %s", exc) + return _provider_error(f"Managed Krea generation error: {exc}", "provider_exception") + return _provider_result(result, "Krea provider returned a non-dict result") + + +def _confine_source_images(image_url, reference_image_urls, task_id, *, permitted: tuple = ("image",)): + """Resolve path-like sources to ``data:`` URLs under a non-local terminal backend. + + Routes through ``tools.image_source`` (in-sandbox exec-read, media-cache host reads, + credential guard) so generation obeys the same confinement as vision. URLs/data: pass + through; local backend is a no-op. Returns ``(image_url, reference_image_urls, error_json_or_None)``. + """ + from tools.terminal_scope import terminal_env + if (terminal_env("TERMINAL_ENV") or "local").strip().lower() in ("", "local"): + return image_url, reference_image_urls, None + from model_tools import _run_async + from tools.image_source import ImageResolutionError, resolve_local_source_to_data_url + + def resolve(ref): + return _run_async(resolve_local_source_to_data_url(ref, task_id, permitted=permitted)) + try: + if isinstance(image_url, str) and image_url.strip(): + image_url = resolve(image_url) + if isinstance(reference_image_urls, (list, tuple)): + reference_image_urls = [resolve(r) if isinstance(r, str) else r for r in reference_image_urls] + except ImageResolutionError as exc: + return image_url, reference_image_urls, _provider_error( + f"Could not read source image: {exc}", type(exc).__name__) + return image_url, reference_image_urls, None + + +def _handle_image_generate(args, **kw): + prompt = args.get("prompt", "") + if not prompt: + return tool_error("prompt is required for image generation") + aspect_ratio = args.get("aspect_ratio", DEFAULT_ASPECT_RATIO) + upscale = args.get("upscale") + task_id = kw.get("task_id") + # Confinement chokepoint BEFORE any dispatch: every route receives sandbox-confined bytes. + image_url, reference_image_urls, confine_error = _confine_source_images( + args.get("image_url"), args.get("reference_image_urls"), task_id) + if confine_error is not None: + return confine_error + # Order matters: explicit plugin provider (incl. "krea"), then model-driven managed Krea + # interception (only when no provider is set, so BYO/direct FAL stays untouched), then FAL. + sources = dict(image_url=image_url, reference_image_urls=reference_image_urls, + upscale=upscale if isinstance(upscale, bool) else None) + raw = None + for route in (_dispatch_to_plugin_provider, _maybe_route_managed_krea, image_generate_tool): + raw = route(prompt, aspect_ratio, **sources) + if raw is not None: + break + return _postprocess_image_generate_result(raw, task_id=task_id) + + +# --- Dynamic schema — reflect the active backend's image-to-image capability --- +# Advertising edit capability up front saves a wasted turn. Memoized by config.yaml mtime in +# model_tools.get_tool_definitions(), so it rebuilds on switch. +_NO_CAPABILITIES = {"modalities": ["text"], "max_reference_images": 0, "supports_upscale": False} + + +def _active_image_capabilities() -> Dict[str, Any]: + """Best-effort capabilities of the active backend/model; never raises. + + Mirrors runtime dispatch: a set ``image_gen.provider`` asks that plugin, else the FAL + catalog. Fail-closed: an undeclared capability is advertised as absent. + """ + info: Dict[str, Any] = dict(_NO_CAPABILITIES) + configured_provider = _read_configured_image_provider() + if configured_provider and configured_provider != "fal": + try: + provider = _get_plugin_provider(configured_provider) + if provider is not None: + try: + caps = provider.capabilities() or {} + except Exception: # noqa: BLE001 + caps = {} + info["provider"] = provider.display_name + info["model"] = _read_configured_image_model() or (provider.default_model() or "") + if caps.get("modalities"): + info["modalities"] = list(caps["modalities"]) + if caps.get("max_reference_images"): + info["max_reference_images"] = int(caps["max_reference_images"]) + # Plugins opt in explicitly; absent = no upscale param. + info["supports_upscale"] = bool(caps.get("supports_upscale")) + return info + except Exception: # noqa: BLE001 + pass + # In-tree FAL path (provider unset or == "fal"); _resolve_fal_model() never raises. + model_id, meta = _resolve_fal_model() + can_edit = bool(meta.get("edit_endpoint")) + info["provider"] = "FAL.ai" + info["model"] = meta.get("display", model_id) + info["modalities"] = ["text", "image"] if can_edit else ["text"] + info["max_reference_images"] = int(meta.get("max_reference_images") or 1) if can_edit else 0 + # Clarity is available on request for ANY catalog model (``upscale`` is only the default). + info["supports_upscale"] = True + return info + + +# Param snippets assembled per-capability by _build_dynamic_image_schema. +_IMAGE_URL_PARAM = { + "type": "string", + "description": ( + "Source image to edit/transform (image-to-image). A public URL or " + "an absolute local file path from the conversation. Omit for " + "text-to-image." + ), +} + +_UPSCALE_PARAM = { + "type": "boolean", + "description": ( + "Post-generation high-resolution pass (~2x, extra cost/latency), " + "off by default. A creative enhancer that can alter fine detail " + "(rendered text, faces) — use only when resolution matters more " + "than fidelity." + ), +} + + +def _build_dynamic_image_schema() -> Dict[str, Any]: + """Render description AND params from the active model's capabilities; args it cannot + honor are NOT advertised (the handler still accepts them for replay compat).""" + base_desc = ( + "Generate high-quality images from text prompts{edit_clause}. " + "Returns the result in the `image` field — a URL or an absolute " + "file path; reference it in your response using the current " + "platform's file-delivery convention." + ) + info = _active_image_capabilities() + max_refs = int(info.get("max_reference_images") or 0) + can_edit = "image" in set(info.get("modalities") or ["text"]) + static_props = IMAGE_GENERATE_SCHEMA["parameters"]["properties"] + properties: Dict[str, Any] = { + "prompt": static_props["prompt"], "aspect_ratio": static_props["aspect_ratio"]} + if can_edit: + edit_clause = ", or edit / transform an existing image by passing image_url" + properties["image_url"] = _IMAGE_URL_PARAM + if max_refs > 1: + properties["reference_image_urls"] = { + "type": "array", + "items": {"type": "string"}, + "maxItems": max_refs, + "description": ( + f"Up to {max_refs} additional reference images (style, " + "character, or composition) guiding an edit. URLs or " + "absolute local paths." + ), + } + else: + edit_clause = " (text-to-image only — the active model cannot edit existing images)" + if info.get("supports_upscale"): + properties["upscale"] = _UPSCALE_PARAM + return {"description": base_desc.format(edit_clause=edit_clause), + "parameters": {"type": "object", "properties": properties, "required": ["prompt"]}} + + +registry.register( + name="image_generate", toolset="image_gen", schema=IMAGE_GENERATE_SCHEMA, + handler=_handle_image_generate, check_fn=check_image_generation_requirements, requires_env=[], + is_async=False, # sync fal_client API to avoid "Event loop is closed" in gateway + emoji="🎨", dynamic_schema_overrides=_build_dynamic_image_schema, +) + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. + +def is_krea_model(model_id: Optional[str]) -> bool: + """True when ``model_id`` is a native Krea plugin id (``krea-2-*``).""" + return _normalize_krea_model(model_id) is not None +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/image_source.py b/tools/image_source.py new file mode 100644 index 0000000000000000000000000000000000000000..c780cf7ef7430b95c9b01be86e36c2571eb6de51 --- /dev/null +++ b/tools/image_source.py @@ -0,0 +1,314 @@ +"""Single resolver for every media source (data:/http(s)/file/local/container) -> bytes + mime. + +Everything funnels through :func:`resolve_image_source` so size and magic-byte checks run +exactly once. Images are the default; video callers opt in via ``permitted=("video",)``. +Security (GHSA-gpxw-6wxv-w3qq): under a non-local backend vision is confined like the file +tools — host-read only inside a media cache (bind-mounted into the sandbox), anything else is +exec-read *inside the sandbox*, so ``vision_analyze('/etc/passwd')`` never reads the host. +""" +from __future__ import annotations + +import asyncio +import base64 +import os +import re +from dataclasses import dataclass +from pathlib import Path +from typing import Optional + +# Raw-bytes INGEST budget: deliberately the 50MB download cap, NOT the 20MB provider +# payload cap — that one is enforced post-resize at the call sites. +_MAX_INGEST_BYTES = 50 * 1024 * 1024 + + +class ImageResolutionError(Exception): + def __init__(self, message: str, *, src: str = "", origin: str = ""): + super().__init__(message) + self.src, self.origin = src, origin + + +class UnsupportedScheme(ImageResolutionError): ... +class SourceUnsafe(ImageResolutionError): ... # SSRF / path-allowlist +class SourceTooLarge(ImageResolutionError): ... +class SourceNotFound(ImageResolutionError): ... +class NotAnImage(ImageResolutionError): ... + + +@dataclass +class ResolveContext: + task_id: Optional[str] = None + + +@dataclass +class ResolvedImage: + data: bytes + mime: str + origin: str # one of: data | http | file | local | container + + +# Explicit URL scheme ("ftp://", "s3://"). Bare Windows drive paths lack the "//". +_SCHEME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.\-]*://") + + +async def resolve_image_source( + src: str, ctx: ResolveContext, *, permitted: tuple = ("image",)) -> ResolvedImage: + if not isinstance(src, str) or not src.strip(): + raise SourceNotFound("image_url is required", src=str(src)) + s = src.strip() + if s.startswith("data:"): + data, mime = _resolve_data_url(s) + return _finalize(data, mime, "data", s, permitted) + if s.startswith(("http://", "https://")): + reason = _http_block_reason(s) + if reason: + raise SourceUnsafe(reason, src=s) + return _finalize(await _download_to_bytes(s), "", "http", s, permitted) + if _SCHEME_RE.match(s) and not s.lower().startswith("file://"): + raise UnsupportedScheme( + "Unrecognized image source scheme. Use an http(s) URL, a local " + "file path, a file:// URI, or a data: URL.", + src=s) + # Everything else is a filesystem path — including bare relative names like "pic.png" + # (a path-shape gate here regressed them once). + candidate = s[len("file://"):] if s.lower().startswith("file://") else s + p = Path(os.path.expanduser(candidate)) + host_target = _permitted_host_read_target(p, ctx) + if host_target is not None and host_target.is_file(): + _guard_credential_read(host_target, s) + data = await asyncio.to_thread(host_target.read_bytes) + return _finalize(data, "", "file", s, permitted) + if _is_local_terminal_backend(): + # Any path was host-readable, so a miss means the file doesn't exist. + raise SourceNotFound(f"media file not found: '{p}'", src=s, origin="file") + return await _resolve_container_fallback(p, ctx, s, permitted) + + +def _guard_credential_read(host_target: Path, src: str) -> None: + """Shared credential-read guard: refuse secret-bearing files (.env, auth.json) with a specific + error. Guard import is best-effort; a real block always propagates.""" + try: + # Shared credential-read guard (agent.file_safety, #57698): refuse secret-bearing files (.env, + # auth.json, ...) with an intentional, specific error instead of relying on the magic-byte sniff to + # reject them incidentally. Same chokepoint the image-gen/video-gen provider plugins enforce on + # model-supplied local paths. Import is best-effort (guard unavailability must not break image + # loading); a real block always propagates. + from agent.file_safety import raise_if_read_blocked + except Exception: # noqa: BLE001 — guard unavailable: proceed + return + try: + raise_if_read_blocked(str(host_target)) + except ValueError as exc: + raise SourceUnsafe(str(exc), src=src, origin="file") + + +def _resolve_data_url(s: str) -> tuple[bytes, str]: + header, _, payload = s.partition(",") + if ";base64" not in header: + raise NotAnImage("data: URL must be base64-encoded", src=s[:64]) + declared = header[len("data:"):].split(";", 1)[0].strip() or "application/octet-stream" + # Cheap pre-decode size gate on the encoded length (~4/3 expansion). + if (len(payload) * 3) // 4 > _MAX_INGEST_BYTES: + raise SourceTooLarge("data: URL exceeds size limit", src=s[:64]) + try: + data = base64.b64decode(payload, validate=True) + except Exception as exc: + raise NotAnImage(f"invalid base64 in data: URL: {exc}", src=s[:64]) + return data, declared # real mime verified in _finalize via magic bytes + + +def _http_block_reason(url: str) -> Optional[str]: + """Block reason, or None when allowed. Refuses policy-blocked URLs BEFORE any network I/O; + ``_download_image`` re-checks per attempt and against the final redirect target (intentional).""" + from tools.url_safety import is_safe_url + from tools.website_policy import check_website_access + if not is_safe_url(url): + return "blocked: unsafe or private URL" + if blocked := check_website_access(url): + return blocked.get("message") or "blocked by website policy" + return None + + +async def _download_to_bytes(url: str) -> bytes: + import tempfile + from tools.vision_tools import _download_image + with tempfile.NamedTemporaryFile(suffix=".img", delete=False) as tf: + tmp = Path(tf.name) + try: + # Enforces the 50MB stream cap, redirect SSRF guard, and website policy. + await _download_image(url, tmp) + return await asyncio.to_thread(tmp.read_bytes) + except PermissionError as exc: # website policy block + raise SourceUnsafe(str(exc), src=url, origin="http") + finally: + tmp.unlink(missing_ok=True) + + +def _is_local_terminal_backend() -> bool: + """True when the terminal backend runs directly on the host (keys off ``TERMINAL_ENV``, read + through the per-turn terminal scope so a routed multiplex profile sees ITS backend).""" + from tools.terminal_scope import terminal_env + return terminal_env("TERMINAL_ENV", "local").strip().lower() in ("local", "") + + +# Host-side media caches: the only host paths vision may read under a non-local backend +# (gateway inbound media + the tools' own download temp dirs). +_MEDIA_CACHE_SUBDIRS = ( + "cache", # cache/images, cache/vision, cache/video(s), cache/audio + "images", # desktop/clipboard/PDF uploads (tui_gateway) + "image_cache", "audio_cache", "video_cache", "temp_vision_images", "temp_video_files") + + +def _media_cache_roots() -> list: + from hermes_constants import get_hermes_home + home = get_hermes_home() + return [home / sub for sub in _MEDIA_CACHE_SUBDIRS] + + +def _permitted_host_read_target(p: Path, ctx: ResolveContext) -> Optional[Path]: + """Host path to read, or ``None`` (caller exec-reads inside the sandbox instead). + + Local backend: any path. Non-local: only paths inside a media cache root (a + container-visible cache path is first translated back to its host mount). + """ + if _is_local_terminal_backend(): + try: + return p.resolve() + except Exception: # noqa: BLE001 — unresolved path: let is_file() fail downstream + return p + from tools.credential_files import from_agent_visible_cache_path + try: + real = Path(from_agent_visible_cache_path(str(p))).resolve() + except Exception: # noqa: BLE001 — cannot resolve -> not a safe host read + return None + if any(real.is_relative_to(root.resolve()) for root in _media_cache_roots()): + return real + return None + + +def _get_active_env(task_id: Optional[str]): + if not task_id: + return None + try: + from tools.terminal_tool_lifecycle import get_active_env + return get_active_env(task_id) + except Exception: + return None + + +def _ensure_container_env(task_id: Optional[str]) -> None: + """Lazily bring up the sandbox before an in-sandbox read (vision may be a session's first + action). Best-effort: failure leaves the env absent and the caller hits the fail-closed error. + + Unlike the terminal tool, vision never triggered environment creation, so a session whose first action + is ``vision_analyze`` on a container-only path under a non-local backend found no active env and failed + — until a terminal command happened to create one (issue #62825). + """ + if not task_id: + return + try: + from tools.terminal_tool import ensure_task_env + ensure_task_env(task_id) + except Exception: + pass + + +async def _resolve_container_fallback( + p: Path, ctx: ResolveContext, src: str, permitted: tuple = ("image",)) -> ResolvedImage: + """Read the bytes inside the sandbox; fail-closed when no env exists (a non-cache host + path under a sandbox must never leak via a host fallback). + + Cold-start retry: under Docker the first exec against a fresh container can fail (empty + pipe) while a second succeeds. On final failure the container's output is folded into the + error so "no such file" / "permission denied" / "never came up" are distinguishable. + + We retry once with a short delay before giving up, so callers don't see "could not read inside the + sandbox" on a file that is verifiably readable on the immediate retry. See #76566. + """ + import shlex + # Bring the sandbox up on demand: without this, the first vision_analyze of a session (before any + # terminal command) has no active env to read from under a non-local backend (issue #62825). + _ensure_container_env(ctx.task_id) + env = _get_active_env(ctx.task_id) + if env is None: + raise SourceNotFound( + f"'{p}' is not reachable inside the sandbox and no active sandbox " + f"session is available to read it", + src=src, origin="container") + # Bound the read INSIDE the sandbox: head -c caps at ingest-limit+1 (+1 distinguishes "at the + # cap" from "over") so /dev/zero can't stream unbounded base64 into host memory. The input + # redirect avoids argv (leading-dash paths); tr -d instead of GNU-only base64 -w0 (BusyBox). + cmd = f"head -c {_MAX_INGEST_BYTES + 1} < {shlex.quote(str(p))} | base64 | tr -d '\\n'" + last_res: dict = {"returncode": 1, "output": ""} + for attempt in range(2): + last_res = await asyncio.to_thread(env.execute, cmd) + if last_res.get("returncode", 1) == 0: + break + if attempt == 0: + await asyncio.sleep(0.15) # covers Docker exec warm-up in practice + if last_res.get("returncode", 1) != 0: + diag = (last_res.get("output") or "").strip().splitlines() + first = next((ln.strip() for ln in diag if ln.strip()), "") + suffix = f" ({first[:200]})" if first else "" + raise SourceNotFound(f"could not read '{p}' inside the sandbox{suffix}", src=src, origin="container") + try: + data = base64.b64decode(last_res.get("output", ""), validate=True) + except Exception as exc: + raise NotAnImage(f"sandbox returned non-image data for '{p}': {exc}", src=src) + if len(data) > _MAX_INGEST_BYTES: + raise SourceTooLarge("media exceeds size limit", src=src, origin="container") + return _finalize(data, "", "container", src, permitted) + + +def _finalize( + data: bytes, declared_mime: str, origin: str, src: str, permitted: tuple = ("image",) +) -> ResolvedImage: + """Chokepoint: 50MB ingest cap + type check. Images by magic bytes; video (opt-in) by + extension + mp4 sniff — enough because every downstream consumer re-validates.""" + from tools.vision_tools_image_prep import _detect_image_mime_type_from_bytes + if len(data) > _MAX_INGEST_BYTES: + raise SourceTooLarge("media exceeds size limit", src=src, origin=origin) + sniffed = _detect_image_mime_type_from_bytes(data) + if sniffed is not None: + if "image" not in permitted: + raise NotAnImage("source is an image, but this argument takes a video", src=src, origin=origin) + return ResolvedImage(data=data, mime=sniffed, origin=origin) + if "image" in permitted and b" Optional[str]: + """Video MIME from the extension table, else the ISO base-media ``ftyp`` magic at + offset 4 (covers extensionless data: URLs / query-string URLs).""" + from urllib.parse import urlsplit + from tools.vision_tools import _detect_video_mime_type + path_part = urlsplit(src).path if _SCHEME_RE.match(src) else src + by_extension = _detect_video_mime_type(Path(path_part)) + if by_extension is not None: + return by_extension + if len(data) > 12 and data[4:8] == b"ftyp": + return "video/mp4" + return None + + +async def resolve_local_source_to_data_url( + src: str, task_id: Optional[str], *, permitted: tuple = ("image",)) -> str: + """Convert a path-like media source into a ``data:`` URL via the resolver. + + Dispatch-layer chokepoint for generation tools so providers never read model-supplied paths + off the HOST under a sandbox. URL-shaped sources pass through; callers apply this only under + a non-local backend. + """ + s = (src or "").strip() + if not s or s.lower().startswith(("http://", "https://", "data:")): + return src + resolved = await resolve_image_source(s, ResolveContext(task_id=task_id), permitted=permitted) + encoded = base64.b64encode(resolved.data).decode("ascii") + mime = resolved.mime or "application/octet-stream" + return f"data:{mime};base64,{encoded}" diff --git a/tools/interpreter_shutdown.py b/tools/interpreter_shutdown.py new file mode 100644 index 0000000000000000000000000000000000000000..770010fad18d3b04c03a048b7fa39ac1d439b252 --- /dev/null +++ b/tools/interpreter_shutdown.py @@ -0,0 +1,25 @@ +"""Shared interpreter-shutdown predicate for background threads that can outlive +process teardown (cron delivery, concurrent tool submission, retry paths). + +Once finalization starts, ``concurrent.futures`` refuses new work and asyncio's +default executor is gone, so any further scheduling only produces noise (stray +prints after the TUI exited, tracebacks in ``errors.log``, futile retries). +CPython raises ``cannot schedule new futures after interpreter shutdown`` +(module-global flag) or ``... after shutdown`` (a pool whose ``shutdown()`` ran); +the short prefix catches both — safe here because every pool involved is a +module-global daemon or a ``with``-scoped local only finalization can shut down. +""" + +from __future__ import annotations + +import sys +from typing import Optional + + +def interpreter_shutting_down(exc: Optional[BaseException] = None) -> bool: + """True when the interpreter is finalizing. ``exc`` lets a caller treat an + already-raised scheduling error as a shutdown signal: the ``concurrent.futures`` + flag can be set a hair before ``sys.is_finalizing()`` flips.""" + if sys.is_finalizing(): + return True + return exc is not None and "cannot schedule new futures" in str(exc).lower() diff --git a/tools/interrupt.py b/tools/interrupt.py new file mode 100644 index 0000000000000000000000000000000000000000..e9ca0b994e9f8c84a80f6df7f32e295fb305b9af --- /dev/null +++ b/tools/interrupt.py @@ -0,0 +1,121 @@ +"""Per-thread interrupt signaling for all tools: thread-scoped so interrupting one +agent session does not kill tools in other sessions (the gateway runs many agents in one +process). The agent passes its execution thread id to set_interrupt(); tools call +is_interrupted(), which checks the CURRENT thread.""" + +import logging +import os +import threading +from collections.abc import Callable + +logger = logging.getLogger(__name__) + +# Opt-in debug tracing — pairs with HERMES_DEBUG_INTERRUPT in tools/environments/base.py. +_DEBUG_INTERRUPT = bool(os.getenv("HERMES_DEBUG_INTERRUPT")) +if _DEBUG_INTERRUPT: + # AIAgent's quiet_mode forces the `tools` logger to ERROR on CLI startup; + # force ours back to INFO so the trace is visible in agent.log. + logger.setLevel(logging.INFO) + +# Interrupted thread idents + optional user-safe cause (never the user's message text). +_interrupted_threads: set[int] = set() +_interrupt_reasons: dict[int, str] = {} +# Threads asked to YIELD: hand a long-running foreground command to the background +# instead of killing it, so a mid-turn user message is not parked behind it. +_yield_threads: set[int] = set() +_lock = threading.Lock() + + +def set_interrupt(active: bool, thread_id: int | None = None, *, reason: str | None = None) -> None: + """Set or clear the interrupt for *thread_id* (default: current thread); ``reason`` is + an optional user-safe cause. Clearing also drops a pending yield request.""" + tid = thread_id if thread_id is not None else threading.current_thread().ident + with _lock: + (_interrupted_threads.add if active else _interrupted_threads.discard)(tid) + if active and reason: + _interrupt_reasons[tid] = reason + else: + _interrupt_reasons.pop(tid, None) + if not active: + _yield_threads.discard(tid) + _snapshot = set(_interrupted_threads) if _DEBUG_INTERRUPT else None + if _DEBUG_INTERRUPT: + logger.info( + "[interrupt-debug] set_interrupt(active=%s, target_tid=%s) " + "called_from_tid=%s current_set=%s", + active, tid, threading.current_thread().ident, _snapshot) + + +def is_interrupted() -> bool: + return is_thread_interrupted(threading.current_thread().ident) + + +def is_thread_interrupted(thread_id: int | None) -> bool: + """Whether *thread_id* has an interrupt bit set (``None`` never is). Used when + a wait moves onto a deadline worker (``run_bounded_sync``) so ``/stop`` + targeting the original tool-worker tid still kills the subprocess. + + See #94285. + """ + if thread_id is None: + return False + with _lock: + return thread_id in _interrupted_threads + + +def request_yield(thread_id: int) -> None: + """Ask the tool running on *thread_id* to yield: a foreground terminal command hands + its live process to the background registry and returns at once, so a user's mid-turn + message (``redirect()`` during tool execution) is delivered instead of parked behind it. + The command itself is never killed; that is what ``set_interrupt`` is for.""" + with _lock: + _yield_threads.add(thread_id) + + +def is_thread_yield_requested(thread_id: int | None) -> bool: + """Whether a yield is pending for *thread_id* (``None`` never is).""" + if thread_id is None: + return False + with _lock: + return thread_id in _yield_threads + + +def consume_yield(thread_id: int | None) -> bool: + """Atomically take the pending yield for *thread_id*; True if one was pending.""" + if thread_id is None: + return False + with _lock: + if thread_id in _yield_threads: + _yield_threads.discard(thread_id) + return True + return False + + +def run_if_not_interrupted(callback: Callable[[], None]) -> bool: + """Run a state transition atomically with current-thread interruption. + + Returns ``False`` without calling ``callback`` when the current thread is + already interrupted. The callback runs under the interrupt lock and must + not block or re-enter any interrupt API. + """ + tid = threading.current_thread().ident + with _lock: + if tid in _interrupted_threads: + return False + callback() + return True + + +def get_interrupt_reason() -> str | None: + """User-safe interrupt cause for the current thread, if known.""" + with _lock: + return _interrupt_reasons.get(threading.current_thread().ident) + + +def clear_current_thread_interrupt() -> None: + """Clear any interrupt bit on the CURRENT thread: gives a user-approved command a clean + slate right before it spawns its child, so a stale bit that landed during the blocking + approval-wait cannot SIGINT the just-approved run. A *genuine* interrupt arriving after + this call re-sets the bit and is still observed by the executor's poll loop. Call + directly on the executing thread.""" + set_interrupt(False) diff --git a/tools/kanban_tools_schemas.py b/tools/kanban_tools_schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..b6f4be7fb6dd2b3aea714e36997daf0ffff40c09 --- /dev/null +++ b/tools/kanban_tools_schemas.py @@ -0,0 +1,533 @@ +"""Tool schemas for tools.kanban_tools (model-facing; strings are byte-frozen).""" +from __future__ import annotations + +from typing import Any + +_DESC_TASK_ID_DEFAULT = ( + "Task id. If omitted, defaults to HERMES_KANBAN_TASK from the env " + "(the task the dispatcher spawned you to work on)." +) + +_DESC_BOARD = ( + "Kanban board slug to target. When omitted, the call resolves the " + "active board the usual way: HERMES_KANBAN_DB env → " + "HERMES_KANBAN_BOARD env → the 'current' symlink under the kanban " + "home → 'default'. Pass an explicit slug only when the caller (e.g. " + "a Telegram routing layer) needs to override the env-pinned active " + "board for this one call." +) + + +def _prop(type_: str, description: str) -> dict[str, str]: + return {"type": type_, "description": description} + + +def _board_schema_prop() -> dict[str, str]: + """Schema fragment for the optional ``board`` parameter (one place to tweak).""" + return _prop("string", _DESC_BOARD) + + +def _schema(name: str, description: str, properties: dict[str, Any], required: list[str]) -> dict[str, Any]: + """Build a tool schema; every kanban tool takes an optional trailing ``board``.""" + return { + "name": name, + "description": description, + "parameters": { + "type": "object", + "properties": {**properties, "board": _board_schema_prop()}, + "required": required, + }, + } + + +KANBAN_SHOW_SCHEMA = _schema( + "kanban_show", + ( + "Read a task's full state — title, body, assignee, parent task " + "handoffs, your prior attempts on this task if any, comments, " + "and recent events. Use this to (re)orient yourself before " + "starting work, especially on retries. The response includes a " + "pre-formatted ``worker_context`` string suitable for inclusion " + "verbatim in your reasoning." + ), + { + "task_id": _prop("string", _DESC_TASK_ID_DEFAULT), + }, + [], +) + +KANBAN_LIST_SCHEMA = _schema( + "kanban_list", + ( + "List Kanban task summaries so an orchestrator profile can discover " + "work to route. Supports the same core filters as the CLI: assignee, " + "status, tenant, include_archived, and limit. Returns compact rows " + "with ids, title, status, assignee, priority, parent/child ids, and " + "counts. Bounded to 50 rows by default, 200 max, with truncation " + "metadata. Also recomputes ready tasks before listing, matching the " + "CLI. Orchestrator-only — dispatcher-spawned task workers never see " + "this tool." + ), + { + "assignee": _prop("string", "Optional assignee/profile filter."), + "status": { + "type": "string", + "enum": [ + "triage", "todo", "ready", "running", + "blocked", "done", "archived", + ], + "description": "Optional task status filter.", + }, + "tenant": _prop("string", "Optional tenant/project namespace filter."), + "include_archived": _prop("boolean", "Include archived tasks. Defaults to false."), + "limit": _prop("integer", "Optional maximum rows to return (default 50, max 200)."), + }, + [], +) + +KANBAN_COMPLETE_SCHEMA = _schema( + "kanban_complete", + ( + "Mark your current task done with a structured handoff for " + "downstream workers and humans. Prefer ``summary`` for a " + "human-readable 1-3 sentence description of what you did; put " + "machine-readable facts in ``metadata`` (changed_files, " + "tests_run, decisions, findings, etc). At least one of " + "``summary`` or ``result`` is required. If you created new " + "tasks via ``kanban_create`` during this run, list their ids " + "in ``created_cards`` — the kernel verifies them so phantom " + "references are caught before they leak into downstream " + "automation. If you produced deliverable files (charts, PDFs, " + "spreadsheets, generated images), list their absolute paths " + "in ``artifacts`` — the gateway notifier will upload them as " + "native attachments to the human who subscribed to the task, " + "so the deliverable lands in their chat alongside the summary " + "instead of being a path they have to fetch by hand." + ), + { + "task_id": _prop("string", _DESC_TASK_ID_DEFAULT), + "summary": _prop("string", ( + "Human-readable handoff, 1-3 sentences. Appears in " + "Run History on the dashboard and in downstream " + "workers' context." + )), + "metadata": _prop("object", ( + "Free-form dict of structured facts about this " + "attempt — {\"changed_files\": [...], \"tests_run\": 12, " + "\"findings\": [...]}. Surfaced to downstream " + "workers alongside ``summary``." + )), + "result": _prop("string", ( + "Short result log line (legacy field, maps to " + "task.result). Use ``summary`` instead when " + "possible; this exists for compatibility with " + "callers that still set --result on the CLI." + )), + "created_cards": { + "type": "array", + "items": {"type": "string"}, + "description": ( + "Optional structured manifest of task ids you " + "created via ``kanban_create`` during this run. " + "The kernel verifies each id exists and was " + "created by this worker's profile; any phantom " + "id blocks the completion with an error listing " + "what went wrong (auditable in the task's events). " + "Only list ids you got back from a successful " + "``kanban_create`` call — do not invent or " + "remember ids from prose. Omit the field if you " + "did not create any cards." + ), + }, + "artifacts": { + "type": "array", + "items": {"type": "string"}, + "description": ( + "Optional list of absolute paths to deliverable " + "files you produced during this run — generated " + "charts, PDFs, spreadsheets, images, archives. " + "Examples: [\"/tmp/q3-revenue.png\", " + "\"/tmp/report.pdf\"]. The gateway notifier " + "uploads each path as a native attachment to the " + "subscribed chat (images embed inline, everything " + "else uploads as a file) so the deliverable " + "lands with the completion notification. Skip " + "intermediate scratch files and references that " + "are not the deliverable. The path must exist " + "on disk at completion. Files inside a managed scratch " + "workspace are copied to durable task attachments before " + "cleanup; a missing declared scratch artifact keeps the " + "task in-flight so you can fix the path and retry." + ), + }, + }, + [], +) + +KANBAN_BLOCK_SCHEMA = _schema( + "kanban_block", + ( + "Stop work on this task and route it according to WHY you're stuck. " + "Set ``kind`` to say which: 'dependency' (waiting on another task — " + "goes to todo and auto-resumes when that task finishes, no human " + "needed), 'needs_input' (you need a human decision/answer), " + "'capability' (a hard wall: no access, missing credentials, an action " + "no agent can do), or 'transient' (a flaky failure that may clear). " + "``reason`` is shown to the human on the board. If a task keeps " + "getting unblocked and re-blocked for the same reason, it is " + "auto-escalated to triage. Use for genuine blockers only — don't " + "block on things you can resolve yourself." + ), + { + "task_id": _prop("string", _DESC_TASK_ID_DEFAULT), + "reason": _prop("string", ( + "What you need answered or what stopped you, in one or " + "two sentences. Don't paste the whole conversation; the " + "human has the board and can ask follow-ups via comments." + )), + "kind": { + "type": "string", + "enum": ["dependency", "needs_input", "capability", "transient"], + "description": ( + "Why you're blocked. 'dependency' waits in todo and " + "resumes automatically; the others surface to a human. " + "Omit only if none apply." + ), + }, + }, + ["reason"], +) + +KANBAN_REQUEST_REVIEW_SCHEMA = _schema( + "kanban_request_review", + ( + "Hand the task off for review: implementation, self-review, and " + "verification are complete and you want a human (or reviewer) to " + "look before it is marked done. Moves the task to the 'review' " + "column and notifies the subscriber. Unlike ``kanban_block`` this is " + "NOT a blocker — it never counts toward unblock-loop detection, so a " + "task can cycle through review across follow-ups without ever being " + "falsely escalated to triage. Use this instead of blocking with a " + "free-form 'review-required:' reason." + ), + { + "task_id": _prop("string", _DESC_TASK_ID_DEFAULT), + "summary": _prop("string", ( + "What was implemented and how it was verified, in one or " + "two sentences — shown to the reviewer. Don't paste " + "the whole diff; the reviewer has the board and the PR." + )), + "reviewer": _prop("string", ( + "Optional reviewer profile. When provided, the task is " + "reassigned to that profile before review dispatch." + )), + "metadata": { + "type": "object", + "description": ( + "Optional structured handoff facts for the reviewer, such " + "as changed_files, tests_run, commit, or decisions." + ), + "additionalProperties": True, + }, + "artifacts": { + "type": "array", + "items": {"type": "string"}, + "description": ( + "Optional list of absolute paths to deliverable " + "files this handoff names — generated charts, " + "PDFs, spreadsheets, images, archives. Examples: " + "['/tmp/q3-revenue.png', '/tmp/report.pdf']. " + "A review handoff is the last implementer " + "transition, so the kernel copies these into the " + "task's durable attachments before the reviewer's " + "completion cleans the scratch workspace up, and " + "the gateway notifier uploads them as native " + "attachments to the subscribed chat. A missing " + "declared scratch artifact keeps the task in place " + "so you can fix the path and retry." + ), + }, + }, + ["summary"], +) + +KANBAN_REQUEST_CHANGES_SCHEMA = _schema( + "kanban_request_changes", + ( + "Reviewer verdict: return the current review run to the original " + "implementer with concrete required changes. This closes the review " + "run, reapplies parent dependency gating, and requeues the task without " + "using block-loop accounting. Only use from a task claimed from the " + "review column; use kanban_block only for a genuine external blocker." + ), + { + "task_id": _prop("string", _DESC_TASK_ID_DEFAULT), + "reason": _prop("string", ( + "Specific, actionable changes the implementer must make " + "before requesting another review." + )), + }, + ["reason"], +) + +KANBAN_HEARTBEAT_SCHEMA = _schema( + "kanban_heartbeat", + ( + "Signal that you're still alive during a long operation " + "(training, encoding, large crawls). Call every few minutes so " + "humans see liveness separately from PID checks. Pure side " + "effect — no work changes." + ), + { + "task_id": _prop("string", _DESC_TASK_ID_DEFAULT), + "note": _prop("string", ( + "Optional short note describing current progress. " + "Shown in the event log." + )), + }, + [], +) + +KANBAN_COMMENT_SCHEMA = _schema( + "kanban_comment", + ( + "Append a comment to a task's thread. Use for durable notes " + "that should outlive this run (questions for the next worker, " + "partial findings, rationale). Ephemeral reasoning doesn't " + "belong here — use your normal response instead." + ), + { + "task_id": _prop("string", ( + "Task id. Required (may be your own task or " + "another's — comment threads are per-task)." + )), + "body": _prop("string", "Markdown-supported comment body."), + }, + ["task_id", "body"], +) + +KANBAN_ATTACH_SCHEMA = _schema( + "kanban_attach", + ( + "Attach a file to a task by passing its bytes inline (base64). " + "Use for genuine file artifacts the next worker or a human should " + "be able to download — generated reports, images, exports. The " + "file is stored as a real attachment (not a comment link) under " + "the task's attachments dir, capped at 25 MB. Prefer " + "kanban_attach_url when you only have a URL." + ), + { + "task_id": _prop("string", _DESC_TASK_ID_DEFAULT), + "filename": _prop("string", ( + "File name to store it under (e.g. 'report.pdf'). " + "Directory components are stripped; only the leaf is kept." + )), + "content_base64": { + "type": "string", + "description": "The file contents, base64-encoded. Max 25 MB decoded.", + }, + "content_type": _prop("string", "Optional MIME type (e.g. 'application/pdf')."), + }, + ["filename", "content_base64"], +) + +KANBAN_ATTACH_URL_SCHEMA = _schema( + "kanban_attach_url", + ( + "Attach a file to a task by URL — Hermes downloads it server-side " + "and stores it as a real attachment (capped at 25 MB). Use when " + "you have a link rather than the bytes. Only http/https URLs are " + "accepted." + ), + { + "task_id": _prop("string", _DESC_TASK_ID_DEFAULT), + "url": _prop("string", "http(s) URL to fetch and store."), + "filename": _prop("string", ( + "Optional name to store it under. Defaults to the URL " + "path's leaf component." + )), + "content_type": _prop("string", ( + "Optional MIME type override. Defaults to the " + "Content-Type the server returns." + )), + }, + ["url"], +) + +KANBAN_ATTACHMENTS_SCHEMA = _schema( + "kanban_attachments", + ( + "List the files attached to a task: id, filename, content_type, " + "size, who uploaded it, and the absolute on-disk path you can read." + ), + { + "task_id": _prop("string", _DESC_TASK_ID_DEFAULT), + }, + [], +) + +KANBAN_CREATE_SCHEMA = _schema( + "kanban_create", + ( + "Create a new kanban task, optionally as a child of the current " + "one (pass the current task id in ``parents``). Used by " + "orchestrator workers to fan out — decompose work into child " + "tasks with specific assignees, link them into a pipeline, " + "then complete your own task. The dispatcher picks up the new " + "tasks on its next tick and spawns the assigned profiles." + ), + { + "title": _prop("string", "Short task title (required)."), + "assignee": _prop("string", ( + "Profile name that should execute this task " + "(e.g. 'researcher-a', 'reviewer', 'writer'). " + "Required — tasks without an assignee are never " + "dispatched." + )), + "body": _prop("string", ( + "Opening post: full spec, acceptance criteria, " + "links. The assigned worker reads this as part of " + "its context." + )), + "parents": { + "type": "array", + "items": {"type": "string"}, + "description": ( + "Parent task ids. The new task stays in 'todo' " + "until every parent reaches 'done'; then it " + "auto-promotes to 'ready'. Typical fan-in: list " + "all the researcher task ids when creating a " + "synthesizer task." + ), + }, + "tenant": _prop("string", ( + "Optional namespace for multi-project isolation. " + "Defaults to HERMES_TENANT env if set." + )), + "priority": _prop("integer", ( + "Dispatcher tiebreaker. Higher = picked sooner " + "when multiple ready tasks share an assignee." + )), + "workspace_kind": { + "type": "string", + "enum": ["scratch", "dir", "worktree"], + "description": ( + "Workspace flavor: 'scratch' (fresh tmp dir, " + "default), 'dir' (shared directory, requires " + "absolute workspace_path), 'worktree' (git worktree)." + ), + }, + "workspace_path": _prop("string", ( + "Absolute path for 'dir' or 'worktree' workspace. " + "Relative paths are rejected at dispatch." + )), + "project": _prop("string", ( + "Optional project id or slug to link the task to. When " + "set, the task becomes a git worktree under the project's " + "primary repo with a deterministic branch (project slug + " + "task id), instead of a random branch." + )), + "triage": _prop("boolean", ( + "If true, task lands in 'triage' instead of 'todo' " + "— a specifier profile is expected to flesh out " + "the body before work starts." + )), + "idempotency_key": _prop("string", ( + "If a non-archived task with this key already " + "exists, return that task's id instead of creating " + "a duplicate. Useful for retry-safe automation." + )), + "max_runtime_seconds": _prop("integer", ( + "Per-task runtime cap. When exceeded, the " + "dispatcher SIGTERMs the worker and re-queues the " + "task with outcome='timed_out'." + )), + "initial_status": { + "type": "string", + "enum": ["running", "blocked"], + "description": ( + "Initial card status. Use 'blocked' for tasks that " + "require immediate human ops (R3 gate) to skip the " + "brief running-to-blocked transition. Defaults to " + "'running', which preserves the usual dispatch path." + ), + }, + "skills": { + "type": "array", + "items": {"type": "string"}, + "description": ( + "Skill names to force-load into the dispatched " + "worker. The kanban lifecycle is already injected " + "automatically; use this to pin a task to a specialist " + "context — e.g. ['translation'] for a translation " + "task, ['github-code-review'] for a reviewer task. " + "The names must match skills installed on the " + "assignee's profile." + ), + }, + "goal_mode": _prop("boolean", ( + "Run the dispatched worker in a goal loop. When true, " + "after each turn an auxiliary judge checks the worker's " + "response against this card's title/body; if the work " + "isn't done and budget remains, the worker keeps going " + "in the same session until the judge agrees it's " + "complete (or the goal-turn budget is exhausted, which " + "blocks the task for human review). Use this for " + "open-ended cards where one shot rarely finishes the " + "work. Defaults to false (classic single-shot worker)." + )), + "completion_contract": _prop("string", ( + "Declare at creation: local-only (default), OWNER/REPO for PR publication, or an exact GitHub PR URL. " + "PR tasks cannot complete until repository-required exact-head CI passes. On publication pass metadata.published_pr." + )), + "goal_max_turns": _prop("integer", ( + "Turn budget for goal_mode workers. Caps how many " + "continuation turns the worker may take before the task " + "is blocked for review. Ignored unless goal_mode is " + "true. Defaults to the goal-engine default (20)." + )), + "model": _prop("string", ( + "Pin the dispatched worker to this model instead of " + "the assignee profile's configured model. Use the " + "exact model name the target provider expects. Omit " + "to use the profile default." + )), + "provider": _prop("string", ( + "Provider the 'model' belongs to (e.g. 'openrouter', " + "'anthropic', 'nous'). Set this whenever the model " + "is not from the assignee profile's configured " + "provider — a model name alone is resolved against " + "the profile's provider and will fail if it belongs " + "to a different one. Requires 'model'." + )), + }, + ["title", "assignee"], +) + +KANBAN_UNBLOCK_SCHEMA = _schema( + "kanban_unblock", + ( + "Unblock a Kanban task. It moves to ready when all parents are done, " + "or todo while any parent remains open. Orchestrator-only — only " + "profiles with the kanban toolset can unblock routed work; " + "dispatcher-spawned task workers never see this tool." + ), + { + "task_id": _prop("string", "Blocked task id to move to ready or parent-gated todo."), + }, + ["task_id"], +) + +KANBAN_LINK_SCHEMA = _schema( + "kanban_link", + ( + "Add a parent→child dependency edge after both tasks already " + "exist. The child won't promote to 'ready' until all parents " + "are 'done'. Cycles and self-links are rejected." + ), + { + "parent_id": {"type": "string", "description": "Parent task id."}, + "child_id": {"type": "string", "description": "Child task id."}, + }, + ["parent_id", "child_id"], +) diff --git a/tools/kanban_toolset_context.py b/tools/kanban_toolset_context.py new file mode 100644 index 0000000000000000000000000000000000000000..da932744911af390bfc490172dade3af5204dc8b --- /dev/null +++ b/tools/kanban_toolset_context.py @@ -0,0 +1,28 @@ +"""Explicit Kanban selection during one model-schema build. + +The registry's ordinary availability cache is profile-wide, while a gateway +can build schemas for several platforms in the same profile concurrently. +Carry only the explicit selection through a ContextVar, never process env. +""" +from __future__ import annotations + +from contextlib import contextmanager +from contextvars import ContextVar +from typing import Iterable, Iterator, Optional + +_requested: ContextVar[Optional[bool]] = ContextVar("kanban_toolset_requested", default=None) + + +def kanban_toolset_requested() -> Optional[bool]: + """None outside schema assembly; otherwise whether Kanban was named explicitly.""" + return _requested.get() + + +@contextmanager +def scoped_kanban_toolset_selection(toolsets: Optional[Iterable[str]]) -> Iterator[None]: + """An all/default selection is not an explicit workflow opt-in.""" + token = _requested.set("kanban" in (toolsets or ())) + try: + yield + finally: + _requested.reset(token) diff --git a/tools/lazy_deps.py b/tools/lazy_deps.py new file mode 100644 index 0000000000000000000000000000000000000000..bf057619bc0eecf5f9eac099acfcc919a28a6525 --- /dev/null +++ b/tools/lazy_deps.py @@ -0,0 +1,752 @@ +"""Lazy dependency installer for opt-in Hermes backends. + +Backends call :func:`ensure(feature)` on first import; missing packages are installed into the +active venv (or the durable target) unless ``security.allow_lazy_installs: false``, in which +case :class:`FeatureUnavailable` carries a remediation hint. Security model: venv-scoped +(never system Python); durable-target mode (``HERMES_LAZY_INSTALL_TARGET``, sealed images) +APPENDS the target to ``sys.path`` so core site-packages wins every collision and a lazy +package can only add modules, never shadow core; PyPI-by-name specs only (``_spec_is_safe``); +``ensure`` accepts only the :data:`LAZY_DEPS` allowlist; failures surface pip's stderr, no retry. +""" + +from __future__ import annotations + +import contextlib +import logging +import os +import re +import shutil +import site +import subprocess +import sys +import sysconfig +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Callable, Optional + +from hermes_cli._subprocess_compat import windows_hide_flags + +logger = logging.getLogger(__name__) + + +# Allowlist: "namespace.backend" -> pip specs matching the pyproject extra. Pins are exact +# (security posture); bump here AND in pyproject. Shared patched floors (aiohttp==3.14.3, +# starlette==1.3.1) are literals in every feature: tests/test_packaging_metadata.py checks by AST. +LAZY_DEPS: dict[str, tuple[str, ...]] = { + # ─── Inference providers ─────────────────────────────────────────────── + # Native Anthropic SDK (provider=anthropic; aggregators use the openai SDK). + "provider.anthropic": ("anthropic==0.87.0",), # CVE-2026-34450, CVE-2026-34452 + "provider.bedrock": ("boto3==1.42.89",), + # Vertex OAuth2 token minting; google-auth is NOT in [all] on purpose. + "provider.vertex": ( + "google-auth==2.55.1", + "pyasn1==0.6.4", + ), + # Foundry Entra ID auth; only when model.auth_mode=entra_id. + "provider.azure_identity": ("azure-identity==1.25.3",), + + # ─── Web search backends ─────────────────────────────────────────────── + "search.exa": ("exa-py==2.10.2",), + "search.firecrawl": ("firecrawl-py==4.17.0",), + "search.parallel": ("parallel-web==0.4.2",), + + # ─── Monitoring ───────────────────────────────────────────────────────── + # OTLP export; tracks the `otlp` extra. + "export.otlp": ( + "opentelemetry-sdk==1.39.1", + "opentelemetry-exporter-otlp-proto-http==1.39.1", + ), + + # ─── TTS providers ───────────────────────────────────────────────────── + # mistralai: 2.4.6 was a malicious quarantined release — never pin below 2.4.7. + # Voxtral STT + TTS share the SDK. + "tts.mistral": ("mistralai==2.4.8",), + "tts.edge": ("edge-tts==7.2.7",), + "tts.elevenlabs": ("elevenlabs==1.59.0",), + + # ─── Speech-to-text providers ────────────────────────────────────────── + "stt.mistral": ("mistralai==2.4.8",), + "stt.faster_whisper": ( + "faster-whisper==1.2.1", + "sounddevice==0.5.5", + "numpy==2.4.3", + ), + # SILK voice-note decoding (WeChat/QQ); silk-v3 codec binding. + "stt.silk": ("pilk==0.2.4",), + + # ─── Wake word ("Hey Hermes") engines (sync with the `wake` extra) ────── + # openWakeWord's ONNX model scores ~0 on macOS ARM64, so macOS uses the tflite backend + # (ai-edge-litert, bridged in tools/wake_word.py). Separate feature because specs cannot + # carry PEP 508 markers (";" is rejected) — the caller applies the platform gate. + "wake.openwakeword.tflite": ( + "ai-edge-litert==2.1.6", + ), + "wake.openwakeword": ( + "openwakeword==0.6.0", + "onnxruntime==1.27.0", + "sounddevice==0.5.5", + "numpy==2.4.3", + ), + # Open-vocabulary keyword spotting. sentencepiece is needed by + # sherpa_onnx.text2token but undeclared by sherpa-onnx. + "wake.sherpa": ( + "sherpa-onnx==1.13.4", + "sentencepiece==0.2.2", + "sounddevice==0.5.5", + "numpy==2.4.3", + ), + "wake.porcupine": ( + "pvporcupine==4.0.3", + "sounddevice==0.5.5", + "numpy==2.4.3", + ), + + # ─── Image generation backends ───────────────────────────────────────── + "image.fal": ("fal-client==0.13.1",), + + # ─── Memory providers ────────────────────────────────────────────────── + "memory.honcho": ("honcho-ai==2.2.0",), + "memory.hindsight": ("hindsight-client==0.6.1",), + # Cloud memory SDKs MUST be allowlisted + ensure()'d at the import site, or they never + # install on the sealed Docker image (durable-target only). + "memory.supermemory": ("supermemory==3.50.0",), + "memory.mem0": ("mem0ai==2.0.10",), + + # ─── Messaging platforms (lazy-installable on demand) ────────────────── + "platform.telegram": ("python-telegram-bot[webhooks]==22.8",), + # brotlicffi: aiohttp needs its 2-arg Decompressor for Discord CDN Brotli attachments + # (google's 1-arg `Brotli` fails "Can not decode br"). aiohttp is only capped transitively + # by these adapters, so pin the patched floor explicitly. + # Without it, aiohttp falls back to google's `Brotli` package (1-arg API), and any .txt/.md/.doc + # uploaded to the Discord gateway fails to decode at att.read() with "Can not decode content-encoding: + # br" — see #12511 / #15744. + "platform.discord": ( + "discord.py[voice]==2.7.1", + "brotlicffi==1.2.0.2", + "aiohttp==3.14.3", + ), + "platform.slack": ( + "slack-bolt==1.30.0", + "slack-sdk==3.44.1", + "aiohttp==3.14.3", + ), + "platform.matrix": ( + "mautrix[encryption]==0.21.1", + "aiosqlite==0.22.1", + "asyncpg==0.31.0", + "aiohttp-socks==0.11.0", + "aiohttp==3.14.3", + ), + "platform.dingtalk": ( + "dingtalk-stream==0.24.3", + "alibabacloud-dingtalk==2.2.42", + "qrcode==7.4.2", + ), + "platform.feishu": ( + "lark-oapi==1.6.8", + "qrcode==7.4.2", + ), + # WeCom callback adapter parses untrusted XML POST bodies -> defusedxml. + "platform.wecom_callback": ("defusedxml==0.7.1",), + # Teams pulls a heavy tree (msal, dependency-injector); also the `teams` extra. + "platform.teams": ("microsoft-teams-apps==2.0.13.4", "aiohttp==3.14.3"), + # Google Chat — Pub/Sub + Chat API. Not in [all]; Docker bakes `--extra google-chat` + # so hosted/immutable images do not have to write the sealed venv. + "platform.google_chat": ( + "google-cloud-pubsub==2.39.0", + "google-api-python-client==2.194.0", + "google-auth==2.55.1", + "google-auth-oauthlib==1.3.1", + "google-auth-httplib2==0.3.1", + "httplib2==0.32.0", + "pyasn1==0.6.4", + ), + + # ─── Terminal backends ───────────────────────────────────────────────── + "terminal.modal": ("modal==1.3.4",), + "terminal.daytona": ("daytona==0.155.0",), + "terminal.vercel": ("vercel==0.7.2",), + + # ─── Skills ──────────────────────────────────────────────────────────── + "skill.google_workspace": ( + "google-api-python-client==2.194.0", + "google-auth==2.55.1", + "google-auth-oauthlib==1.3.1", + "google-auth-httplib2==0.3.1", + # Explicit transitive pins: httplib2 <0.32 has a decompression-bomb DoS. + "httplib2==0.32.0", + "pyasn1==0.6.4", + ), + "skill.youtube": ("youtube-transcript-api==1.2.4",), + + # ─── Tools ───────────────────────────────────────────────────────────── + # ACP adapter (VS Code / Zed / JetBrains) + "tool.acp": ("agent-client-protocol==0.9.0",), + "tool.dashboard": ( + "fastapi==0.133.1", + "uvicorn[standard]==0.41.0", + "starlette==1.3.1", + "python-multipart==0.0.32", # FastAPI UploadFile/Form streaming uploads + ), + # Pillow and firecrawl-anydoc are CORE deps; these entries self-heal lean/partial installs. + # Call sites use prompt=False so read_file / vision never block on input() mid-session. + # Vision image-resize recovery (Pillow). Pillow is now a CORE dependency (pyproject `dependencies`), so + # this entry is a belt-and-suspenders fallback for stripped/source-build installs that somehow dropped + # it. See #40490. + "tool.vision": ("Pillow==12.3.0",), + "tool.doc_extract": ("firecrawl-anydoc==0.2.4",), # imports as `anydoc`; lockstep with pyproject + # MCP client SDK for the cua-driver, so computer_use never dead-ends on `No module named 'mcp'`. + "tool.computer_use": ( + "mcp==2.0.0", + "httpx2==2.7.0", # mcp 2.x HTTP stack — sync with pyproject [computer-use] + "starlette==1.3.1", + ), + # huggingface-hub is SHARED with transformers (>=1.5.0,<2 via Hindsight) and marked active + # on mere presence, so `hermes update` re-asserts this pin everywhere hub exists. MUST stay + # inside transformers' window and match uv.lock (tests/test_project_metadata.py enforces). + # HF Agent Trace Viewer upload (hermes trace upload / /upload-trace). huggingface-hub is a SHARED + # dependency: transformers (pulled by sentence-transformers for local Hindsight embeddings) requires + # >=1.5.0,<2, and faster-whisper/tokenizers depend on it transitively. Because active_features() marks a + # feature active from mere package presence, the `hermes update` lazy-refresh pass re-asserts THIS pin + # on every install where hub is present — so an exact pin below 1.5.0 force-downgrades the shared + # package and breaks Hindsight startup (#60783). Policy: keep the exact pin (no ranges — security + # posture), but it MUST stay inside transformers' accepted window and MUST match uv.lock so the whole + # tree converges on ONE hub version (tests/test_project_metadata.py enforces both). When bumping: update + # here AND `uv lock --upgrade-package huggingface-hub` in lockstep. + "tool.trace_upload": ("huggingface-hub==1.24.0",), +} + + +# Spec validation: name[extras]specifier only — no URLs, paths, or shell metachars. +_NAME_RE = r"[A-Za-z0-9_][A-Za-z0-9_.\-]*" +_NAME_EXTRAS_RE = re.compile(rf"^{_NAME_RE}(?:\[[A-Za-z0-9_,\-]+\])?") +_SAFE_SPEC = re.compile(rf"^{_NAME_RE}(?:\[[A-Za-z0-9_,\-]+\])?(?:[<>=!~]=?[A-Za-z0-9_.\-+,*<>=!~]+)?$") + + +class FeatureUnavailable(RuntimeError): + """A lazily-installable feature is missing and cannot be made available (installs disabled or failed).""" + + def __init__(self, feature: str, missing: tuple[str, ...], reason: str): + self.feature, self.missing, self.reason = feature, missing, reason + spec_list = " ".join(repr(s) for s in missing) + super().__init__( + f"Feature {feature!r} unavailable: {reason}. " + f"To enable manually: uv pip install {spec_list} (or: pip install {spec_list}).") + + +@dataclass(frozen=True) +class _InstallResult: + success: bool + stdout: str + stderr: str + + +# Internal bridge var (set by the Docker image, not user config) redirecting lazy installs from the +# sealed venv to a writable durable volume. +_LAZY_TARGET_ENV = "HERMES_LAZY_INSTALL_TARGET" +# Stamp of the Python X.Y + ABI the target was populated for; a mismatch after an image rebuild +# wipes the store so stale .so files are never imported. +_TARGET_STAMP_NAME = ".python-abi" + +_SUBPROCESS_KW = dict(capture_output=True, text=True, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL) + + +def _python_abi_tag() -> str: + """X.Y + EXT_SUFFIX (ABI tag + platform); interpreters sharing compiled wheels match.""" + return f"{sys.version_info.major}.{sys.version_info.minor}:{sysconfig.get_config_var('EXT_SUFFIX') or ''}" + + +def _lazy_install_target() -> Optional[Path]: + """Durable install-target dir (:data:`_LAZY_TARGET_ENV`), or None for venv-scoped mode.""" + raw = os.environ.get(_LAZY_TARGET_ENV, "").strip() + return Path(raw) if raw else None + + +def _ensure_target_ready(target: Path) -> Optional[str]: + """Create the target dir and validate its ABI stamp; a different-ABI stamp wipes the contents + first (stale .so must never import). None on success, else an error string.""" + want = _python_abi_tag() + stamp = target / _TARGET_STAMP_NAME + try: + if target.exists(): + have = "" + with contextlib.suppress(OSError): + have = stamp.read_text(encoding="utf-8").strip() + if have and have != want: + logger.info("Lazy install target %s was built for ABI %r but running ABI is %r; wiping stale packages.", target, have, want) + for child in target.iterdir(): + if child.is_dir() and not child.is_symlink(): + shutil.rmtree(child, ignore_errors=True) + else: + with contextlib.suppress(OSError): + child.unlink() + target.mkdir(parents=True, exist_ok=True) + stamp.write_text(want, encoding="utf-8") + except OSError as e: + return f"lazy install target {target} is not writable: {e}" + return None + + +def _activate_target_on_syspath(target: Path) -> None: + """Append the durable target to ``sys.path`` (idempotent). ``site.addsitedir`` honours ``.pth`` + files but inserts near the front, so new entries are moved to the END — core venv site-packages must win collisions.""" + target_str = str(target) + before = list(sys.path) + if target_str not in before: + site.addsitedir(target_str) + new_entries = [p for p in sys.path if p not in before] + if new_entries: + sys.path[:] = [p for p in sys.path if p not in new_entries] + new_entries + _invalidate_import_caches() + + +def _invalidate_import_caches() -> None: + """Make just-installed dists visible to importers and importlib.metadata in this process.""" + with contextlib.suppress(Exception): + import importlib + importlib.invalidate_caches() + import importlib.metadata as _md + if hasattr(_md, "_cache_clear"): + _md._cache_clear() # type: ignore[attr-defined] + + +def activate_durable_lazy_target() -> None: + """Wire the durable target onto ``sys.path`` at startup so packages installed on a previous run + import on this one. No-op when unset or absent. Never raises.""" + target = _lazy_install_target() + try: + if target is not None and target.exists(): + _activate_target_on_syspath(target) + except Exception as e: # pragma: no cover - defensive + logger.debug("Failed to activate durable lazy target %s: %s", target, e) + + +def _allow_lazy_installs() -> bool: + """Whether lazy installs are permitted: (1) ``security.allow_lazy_installs: false`` blocks in BOTH + modes; (2) the sealed venv (``HERMES_DISABLE_LAZY_INSTALLS=1``) blocks only without a durable + target to redirect into. Unreadable config fails OPEN — blocking is an explicit opt-in.""" + cfg = None + with contextlib.suppress(Exception): + from hermes_cli.config import load_config + cfg = load_config() + if cfg is not None and not bool((cfg.get("security") or {}).get("allow_lazy_installs", True)): + return False + if os.environ.get("HERMES_DISABLE_LAZY_INSTALLS") == "1": + return _lazy_install_target() is not None + return True + + +def _unsupported_feature_reason(feature: str) -> Optional[str]: + """Platform capability gate (not policy): why a feature cannot work on this host, or None.""" + if sys.platform == "win32" and feature == "platform.matrix": + return ("unsupported on Windows: Matrix E2EE depends on python-olm, which has no Windows wheel and " + "requires make + libolm to build from sdist. Run Hermes under WSL to use Matrix on Windows.") + return None + + +def _spec_is_safe(spec: str) -> bool: + """Reject pip specs that contain URLs, paths, or shell metacharacters.""" + return bool(spec and len(spec) <= 200 + and not any(ch in spec for ch in (";", "|", "&", "`", "$", "\n", "\r", "\t", "\\")) + and not spec.startswith(("-", "/", ".")) and "://" not in spec and "@" not in spec + and _SAFE_SPEC.match(spec)) + + +def _pkg_name_from_spec(spec: str) -> str: + """``"mautrix[encryption]>=0.20"`` -> ``"mautrix"``.""" + m = re.match(rf"^({_NAME_RE})", spec) + return m.group(1) if m else spec + + +def _specifier_from_spec(spec: str) -> str: + """``"mautrix[encryption]>=0.20,<1"`` -> ``">=0.20,<1"``; ``""`` if unconstrained.""" + m = _NAME_EXTRAS_RE.match(spec) + return spec[m.end():] if m else "" + + +def _installed_version(spec: str) -> Optional[str]: + """Installed version of the spec's package, or None when absent.""" + try: + from importlib.metadata import version + + return version(_pkg_name_from_spec(spec)) + except Exception: + return None + + +def _is_satisfied(spec: str) -> bool: + """Present AND inside the spec's version range, so ``hermes update`` propagates pin bumps to + installed backends. Unparseable specs/versions or a missing ``packaging`` count as satisfied — err + toward "don't churn".""" + installed = _installed_version(spec) + if installed is None: + return False + if not (spec_tail := _specifier_from_spec(spec)): + return True + try: + from packaging.specifiers import SpecifierSet + from packaging.version import Version + + return Version(installed) in SpecifierSet(spec_tail) + except Exception: + return True + + +def _is_present(spec: str) -> bool: + """Presence-only check (any version) — how :func:`active_features` detects activated backends.""" + return _installed_version(spec) is not None + + +def _core_constraints_file() -> Optional[Path]: + """Temp ``--constraint`` file pinning every core-venv package to its installed version for + durable-target installs: shared deps resolve as satisfied (store stays minimal) and a conflicting + backend fails loudly instead of installing a shadowed copy that can never win on sys.path. None if + enumeration failed (install unconstrained).""" + try: + import tempfile + from importlib.metadata import distributions + + pins: dict[str, str] = {} + for dist in distributions(): + name = dist.metadata["Name"] if dist.metadata else None + if name and dist.version and name.lower() not in pins: + pins[name.lower()] = f"{name}=={dist.version}" + if not pins: + return None + fd, path = tempfile.mkstemp(prefix="hermes-core-constraints-", suffix=".txt") + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write("\n".join(sorted(pins.values())) + "\n") + return Path(path) + except Exception as e: + logger.debug("Could not build core constraints file: %s", e) + return None + + +def _installed_dist_roots(spec: str, target: Optional[Path]) -> set[Path]: + """Package dirs a freshly installed *spec* owns, from the dist's file list (``python-telegram-bot`` + ships ``telegram``; some ship several).""" + name = _pkg_name_from_spec(spec) + roots: set[Path] = set() + try: + import importlib.metadata as _md + + dist = next(iter(_md.distributions(name=name, path=[str(target)])), None) if target is not None else _md.distribution(name) + for entry in dist.files or () if dist is not None else (): + top = entry.parts[0] if entry.parts else "" + # Skip hidden entries, __pycache__ and metadata dirs (no importable code). + if not top or top.startswith(".") or top == "__pycache__" or top.endswith((".dist-info", ".egg-info")): + continue + root = Path(dist.locate_file(top)) + if root.is_dir(): + roots.add(root) + except Exception: + return set() + return roots + + +def _warm_installed_bytecode(specs: tuple[str, ...], target: Optional[Path]) -> None: + """Byte-compile what was just installed: a fresh install writes no ``__pycache__``, so the next + import (often a user request, ~2-10s for a big SDK, reading as a hang) would pay the compile. Pay + it here while the caller already waits. Best-effort; never fails the install. + + A pip/uv install writes ``.py`` sources and no ``__pycache__`` — and an install of the *same* version + still deletes the cache the old copy had. Whoever imports the package next pays the whole compile: for + ``anthropic==0.87.0`` (541 modules) on cpython-3.12.13 that measured 2.2-2.7s cold against 0.7-1.0s + warm, and 10.5s cold under concurrent load. That bill lands wherever the first import happens, and for a + lazily-installed backend that is the foreground of a user request (#100461) — with nothing printed while + it runs, so it reads as a hang. Worse, N per-profile daemons cold-starting together each pay it in full + before any of them has written the cache. + """ + if sys.dont_write_bytecode: + return + try: + import compileall + except Exception: # pragma: no cover — stdlib, but never break an install + return + for spec in specs: + try: + for root in _installed_dist_roots(spec, target): + try: + compileall.compile_dir(str(root), quiet=2, force=False, workers=1) + except Exception as exc: + logger.debug("Bytecode warm skipped for %s: %s", root, exc) + except Exception as exc: + logger.debug("Bytecode warm skipped for %s: %s", spec, exc) + + +def _run_installer(cmd: list[str], **kw) -> subprocess.CompletedProcess: + # _SUBPROCESS_KW carries stdin=DEVNULL # noqa: subprocess-stdin + return subprocess.run(cmd, **_SUBPROCESS_KW, creationflags=windows_hide_flags(), **kw) + + +def _uv_binary() -> Optional[str]: + """Managed uv first ($HERMES_HOME/bin is never on PATH), then PATH. A lookup, not ensure_uv(): + downloading uv mid-turn is more than the caller asked for; pip covers no-uv.""" + try: + from hermes_cli.managed_uv import resolve_uv + + return resolve_uv() or shutil.which("uv") + except Exception: + return shutil.which("uv") + + +def _venv_pip_install(specs: tuple[str, ...], *, timeout: int = 300) -> _InstallResult: + """Install ``specs`` via the uv -> pip -> ensurepip ladder, venv-scoped or into the durable + ``--target`` (constrained to core versions) when :data:`_LAZY_TARGET_ENV` is set. Independent of + ``hermes_cli.tools_config._pip_install`` (no CLI dependency).""" + if not specs: + return _InstallResult(True, "", "") + target = _lazy_install_target() + constraints: Optional[Path] = None + extra_args: list[str] = [] + if target is not None: + if err := _ensure_target_ready(target): + return _InstallResult(False, "", err) + constraints = _core_constraints_file() + extra_args += ["--target", str(target)] + if constraints is not None: + extra_args += ["--constraint", str(constraints)] + + def _finish(r: subprocess.CompletedProcess) -> _InstallResult: + if r.returncode == 0: + if target is not None: + _activate_target_on_syspath(target) + _warm_installed_bytecode(specs, target) + return _InstallResult(r.returncode == 0, r.stdout or "", r.stderr or "") + + try: + from tools.environments.local import hermes_subprocess_env + uv_env = hermes_subprocess_env(inherit_credentials=False) + uv_env["VIRTUAL_ENV"] = str(Path(sys.executable).parent.parent) + # Tier 1: uv. --compile-bytecode because uv writes no __pycache__ by default, so the first + # import would recompile the backend AND its transitives (_warm_installed_bytecode is the + # belt-and-braces pass for the spec's own roots on any tier). + if uv_bin := _uv_binary(): + try: + r = _run_installer([uv_bin, "pip", "install", "--compile-bytecode", *extra_args, *specs], timeout=timeout, env=uv_env) + if r.returncode != 0: + logger.debug("uv pip install failed: %s", r.stderr) + # A uv resolver failure is authoritative: falling through to pip would discard uv + # policy (exclude-newer) and could install a quarantined release. + return _finish(r) + except subprocess.TimeoutExpired as e: + logger.debug("uv invocation failed: %s", e) + return _InstallResult(False, "", f"uv pip install timed out: {e}") + except FileNotFoundError as e: # uv vanished between lookup and spawn; it never evaluated the requirements + logger.debug("uv invocation failed: %s", e) + # Tier 2: python -m pip (ensurepip bootstrap if needed) + pip_cmd = [sys.executable, "-m", "pip"] + try: + if _run_installer(pip_cmd + ["--version"], timeout=15).returncode != 0: + raise FileNotFoundError("pip not in venv") + except (subprocess.TimeoutExpired, FileNotFoundError): + try: + _run_installer([sys.executable, "-m", "ensurepip", "--upgrade", "--default-pip"], timeout=120, check=True) + except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e: + return _InstallResult(False, "", f"pip not available and ensurepip failed: {e}") + try: + return _finish(_run_installer(pip_cmd + ["install", *extra_args, *specs], timeout=timeout)) + except subprocess.TimeoutExpired as e: + return _InstallResult(False, "", f"pip install timed out: {e}") + except Exception as e: + return _InstallResult(False, "", f"pip install failed: {e}") + finally: + if constraints is not None: + with contextlib.suppress(OSError): + constraints.unlink() + + +def feature_missing(feature: str) -> tuple[str, ...]: + """Return the subset of specs for ``feature`` not currently installed.""" + if feature not in LAZY_DEPS: + raise KeyError(f"Unknown lazy feature: {feature!r}") + return tuple(s for s in LAZY_DEPS[feature] if not _is_satisfied(s)) + + +def _prompt_toolkit_active() -> bool: + """A bare input() deadlocks while a prompt_toolkit app owns the terminal, so ensure() skips the + confirmation under the TUI — reaching it is already gated by security.allow_lazy_installs.""" + if "prompt_toolkit.application.current" not in sys.modules: + return False + try: + from prompt_toolkit.application.current import get_app_or_none + return bool(getattr(get_app_or_none(), "is_running", False)) + except Exception: + return False + + +def ensure(feature: str, *, prompt: bool = True) -> None: + """Make every package for ``feature`` importable, installing if needed; raises + :class:`FeatureUnavailable` when installs are disabled or fail. ``prompt``: confirm on a TTY first + (non-interactive callers pass False and rely on the config gate).""" + if feature not in LAZY_DEPS: + raise FeatureUnavailable(feature, (), f"feature {feature!r} not in LAZY_DEPS allowlist") + missing = feature_missing(feature) + if not missing: + return + if unsupported := _unsupported_feature_reason(feature): + raise FeatureUnavailable(feature, missing, unsupported) + # Package-manager installs (NixOS etc.) have read-only site-packages: fail fast instead of burning + # ~15s on ensurepip — unless a durable target is configured. The reason MUST start with + # "unsupported ": _refresh_features classifies skips by that prefix. + if _lazy_install_target() is None: + managed_by = "" # config unreadable — proceed with the install + with contextlib.suppress(Exception): + from hermes_cli.config import get_managed_system + managed_by = get_managed_system() + if managed_by: + raise FeatureUnavailable( + feature, missing, + f"unsupported on {managed_by}-managed installs: this build's packages come from {managed_by}, " + f"so Hermes cannot install them at runtime. Add the dependencies for {feature!r} via " + f"{managed_by} (or run a pip/uv install of Hermes instead).") + for spec in missing: # belt and braces on top of the allowlist + if not _spec_is_safe(spec): + raise FeatureUnavailable(feature, missing, f"refusing to install unsafe spec {spec!r}") + if not _allow_lazy_installs(): + raise FeatureUnavailable(feature, missing, "lazy installs disabled (security.allow_lazy_installs=false)") + if prompt and not _prompt_toolkit_active() and sys.stdin.isatty() and sys.stdout.isatty(): + try: + answer = input(f"\nFeature {feature!r} requires: {', '.join(missing)}\nInstall into the active venv now? [Y/n] ").strip().lower() + except (EOFError, KeyboardInterrupt): + answer = "n" + if answer and answer not in {"y", "yes"}: + raise FeatureUnavailable(feature, missing, "user declined install at prompt") + logger.info("Lazy-installing %s for feature %r", " ".join(missing), feature) + result = _venv_pip_install(missing) + if not result.success: # surface pip's own error (quarantine 404, network), tail-clipped + snippet = (result.stderr or result.stdout or "").strip()[-2000:] + raise FeatureUnavailable(feature, missing, f"pip install failed: {snippet or 'no error output'}") + _invalidate_import_caches() + if still_missing := feature_missing(feature): + raise FeatureUnavailable(feature, still_missing, "install reported success but packages still not importable (may require Python restart)") + logger.info("Lazy install complete for feature %r", feature) + + +def is_available(feature: str) -> bool: + """Return True if the feature's deps are already satisfied.""" + return feature in LAZY_DEPS and not feature_missing(feature) + + +def feature_install_command(feature: str, *, venv_pip: bool = False) -> Optional[str]: + """Manual install command for a feature, or None. ``venv_pip=True`` uses ``{sys.executable} -m pip`` + — immune to PEP 668 failures a bare ``pip install`` invites.""" + if feature not in LAZY_DEPS: + return None + joined = " ".join(repr(s) for s in LAZY_DEPS[feature]) + return f"{sys.executable} -m pip install {joined}" if venv_pip else "uv pip install " + joined + + +@dataclass +class InstallSpecsResult: + """Outcome of :func:`install_specs` for one batch of pip specs. ``blocked`` means installs are gated + off (config kill switch, sealed venv without a durable target) or a spec failed validation — nothing + was executed, ``reason`` says why. ``command`` is the human-readable description of what ran.""" + ok: bool + blocked: bool = False + reason: str = "" + command: str = "" + stdout: str = "" + stderr: str = "" + + +def install_specs(specs: list[str] | tuple[str, ...], *, timeout: int = 300) -> InstallSpecsResult: + """Install data-driven pip specs (plugin manifest ``pip_dependencies``) with the same routing and + gating as :func:`ensure`, but unknown packages are allowed — the caller owns manifest trust, this + owns spec hygiene. Never raises; inspect the :class:`InstallSpecsResult`.""" + cleaned = tuple(str(s).strip() for s in specs if str(s).strip()) + if not cleaned: + return InstallSpecsResult(ok=True, command="") + for spec in cleaned: + if not _spec_is_safe(spec): + return InstallSpecsResult(ok=False, blocked=True, reason=f"refusing to install unsafe spec {spec!r}") + target = _lazy_install_target() + if not _allow_lazy_installs(): + sealed = os.environ.get("HERMES_DISABLE_LAZY_INSTALLS") == "1" and target is None + reason = ("runtime installs are disabled on this deployment: the agent environment is immutable " + "and no writable install target is configured (HERMES_LAZY_INSTALL_TARGET)" + ) if sealed else "runtime installs disabled (security.allow_lazy_installs=false)" + return InstallSpecsResult(ok=False, blocked=True, reason=reason) + display = "uv pip install " + (f"--target {target} " if target is not None else "") + " ".join(cleaned) + logger.info("Installing pip specs %s (target=%s)", " ".join(cleaned), target or "venv") + try: + result = _venv_pip_install(cleaned, timeout=timeout) + except Exception as exc: + logger.warning("install_specs failed unexpectedly: %s", exc) + return InstallSpecsResult(ok=False, command=display, stderr=f"install failed: {exc}") + + _invalidate_import_caches() # dashboard rechecks availability inline + return InstallSpecsResult(ok=result.success, command=display, stdout=result.stdout, stderr=result.stderr) + + +def active_features() -> list[str]: + """Features whose ANCHOR package (first spec) is present at any version — shared helpers like + asyncpg are deliberately not proof a backend was enabled. Drives ``hermes update``.""" + return [f for f, specs in LAZY_DEPS.items() if specs and _is_present(specs[0])] + + +def refresh_active_features(*, prompt: bool = False) -> dict[str, str]: + """Re-run ``ensure`` for every active feature (``hermes update``); returns + ``{feature: "current" | "refreshed" | "failed: " | "skipped: "}``. Never raises.""" + return _refresh_features(active_features(), prompt=prompt, restoring=False) + + +def restore_features(features: list[str]) -> dict[str, str]: + """Restore features captured before a managed-runtime rebuild; opt-out -> "skipped".""" + return _refresh_features(features, prompt=False, restoring=True) + + +def _refresh_features(features: list[str], *, prompt: bool, restoring: bool) -> dict[str, str]: + """Refresh or restore a known set of allowlisted lazy features.""" + results: dict[str, str] = {} + for feature in features: + if feature not in LAZY_DEPS: + continue + if not feature_missing(feature): + results[feature] = "current" + continue + if unsupported := _unsupported_feature_reason(feature): + results[feature] = f"skipped: {unsupported}" + continue + try: + ensure(feature, prompt=False if restoring else prompt) + results[feature] = "restored" if restoring else "refreshed" + except FeatureUnavailable as e: # opt-outs and platform-incompatible features are skips, not failures + skip = "lazy installs disabled" in str(e) or "declined" in str(e) or e.reason.startswith("unsupported ") + results[feature] = f"skipped: {e.reason}" if skip else f"failed: {e.reason}" + except Exception as e: + results[feature] = f"failed: {e}" + return results + + +def ensure_and_bind(feature: str, importer: Callable[[], dict[str, Any]], target_globals: dict, *, prompt: bool = False) -> bool: + """:func:`ensure` the feature, then ``target_globals.update(importer())`` so module-level names are + rebound after a lazy install (``importer`` returns ``{name: obj}`` and runs only after ensure + succeeds). Returns False (and logs) if deps could not be installed or imported.""" + try: + ensure(feature, prompt=prompt) + except FeatureUnavailable as exc: + logger.warning("%s", exc) + return False + except Exception as exc: + logger.warning("Failed to ensure feature %r: %s", feature, exc) + return False + try: + target_globals.update(importer()) + except ImportError as exc: + logger.warning("Failed to import feature %r after install: %s", feature, exc) + return False + return True + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. + +def feature_specs(feature: str) -> tuple[str, ...]: + """Return the registered specs for a feature, or raise KeyError.""" + if feature not in LAZY_DEPS: + raise KeyError(f"Unknown lazy feature: {feature!r}") + return LAZY_DEPS[feature] +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/mcp_oauth.py b/tools/mcp_oauth.py new file mode 100644 index 0000000000000000000000000000000000000000..6e17a8e821d561dbd2f0b30d045ff46e3cb43f16 --- /dev/null +++ b/tools/mcp_oauth.py @@ -0,0 +1,1194 @@ +#!/usr/bin/env python3 +"""MCP OAuth 2.1 client support: browser authorization-code flow with PKCE. + +The SDK's ``OAuthClientProvider`` does discovery, client identification, PKCE, exchange and +refresh; this module supplies ``HermesTokenStorage`` (on-disk persistence), the localhost callback +listener and ``build_oauth_auth()`` (legacy entry point). client_id is Hermes' Client ID Metadata +Document URL (CIMD) when the server supports it, else RFC 7591 DCR. ``mcp_servers..oauth`` keys +(all optional): client_id, client_secret, scope, redirect_port, redirect_uri (proxy callback), +redirect_host, client_name, client_metadata_url, cimd, user_agent, timeout.""" + +import asyncio +import contextlib +import contextvars +import errno +import html +import importlib.util as _importlib_util +import json +import logging +import os +import re +import socket +import stat +import sys +import threading +import time +import webbrowser +from functools import partialmethod + +# Cross-process advisory file locking for the refresh fence. Mirrors +# cron/jobs.py: fcntl is Unix-only, msvcrt is the Windows fallback. +try: + import fcntl +except ImportError: # pragma: no cover - non-Unix + fcntl = None +try: + import msvcrt +except ImportError: # pragma: no cover - non-Windows + msvcrt = None +from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path +from typing import TYPE_CHECKING, Any +from urllib.parse import parse_qs, urlparse + +from hermes_constants import secure_parent_dir +from utils import atomic_json_write +from tools.mcp_dashboard_oauth import contextvar_set as _contextvar_set, get_dashboard_oauth_flow + +if TYPE_CHECKING: # annotations only; the SDK is imported lazily at runtime + from mcp.client.auth import OAuthClientProvider + from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata, OAuthMetadata, OAuthToken + +logger = logging.getLogger(__name__) + +# The refresh fence's critical section spans the token-endpoint POST, so it must +# outlast a slow network round trip. Bounded anyway -- a wedged peer must not +# strand us forever -- but generous enough that a healthy refresh never trips it. +_REFRESH_FENCE_TIMEOUT_SECONDS = 60.0 + +class RefreshFenceTimeout(RuntimeError): + """The refresh fence could not be acquired within its bound. + + Raised so the caller FAILS CLOSED. Submitting a refresh token we are not + certain we own is the whole defect class this fence exists to close: on a + provider with single-use refresh tokens it burns the credential and logs + the user out of a working session. Aborting this one refresh attempt is + strictly cheaper -- the next request retries, and by then the peer that + held the fence has published its replacement. + """ + + +# POSIX flock: EWOULDBLOCK/EAGAIN, EACCES on some NFS; msvcrt.locking: EACCES/EDEADLK. +# Same set as cron.scheduler._is_lock_contention_errno (not imported: that module is heavy). +_FENCE_CONTENTION_ERRNOS = frozenset({errno.EWOULDBLOCK, errno.EAGAIN, errno.EACCES, errno.EDEADLK}) + + +def _refresh_lock_path(path: "Path") -> "Path": + return path.with_suffix(path.suffix + ".refresh.lock") + + +async def acquire_refresh_fence(path: "Path", *, timeout: float = _REFRESH_FENCE_TIMEOUT_SECONDS) -> int: + """Take the fence that owns one refresh generation across read -> POST -> persist. + + Token files are written atomically (``_write_json``), so a reader never + sees a torn file; the only cross-process hazard is the read-modify-write + of a single-use refresh token. The damaging interleaving is: + + A: get_tokens() -> R1 + B: get_tokens() -> R1 + A: POST R1 -> 200, receives R2 + B: POST R1 -> 400, credential already burned + B: clear_tokens() -> user is logged out of a live session + + No lock scoped to one file read or write can prevent it: the fence must + be held across the POST. It lives in a ``.refresh.lock`` sibling of the + token file so the holder can still read/write the tokens normally. + + Entered from the SDK's coroutine-driven auth flow, so the wait is an + ``asyncio.sleep`` poll on a non-blocking lock: a peer's slow network + round trip must not freeze every other task on this event loop. No + in-process lock layer is needed: an advisory lock on a fresh descriptor + already excludes sibling tasks and threads of the same process. + + Acquisition failure RAISES. Degrading to "proceed unlocked" would + reintroduce the exact race. Returns the locked descriptor; the caller + hands it back to ``release_refresh_fence`` from its own exit path (the + SDK drives the refresh as a generator, so no single ``with`` block can + span the critical section). + """ + lock_path = _refresh_lock_path(path) + try: + lock_path.parent.mkdir(parents=True, exist_ok=True) + secure_parent_dir(lock_path) + fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o600) + except OSError as exc: + # No lock file means no ownership proof. Fail closed: see the + # class docstring for why proceeding is worse than aborting. + raise RefreshFenceTimeout( + f"refresh fence unavailable ({lock_path.name}): {exc}" + ) from exc + + deadline = time.monotonic() + timeout + try: + while True: + try: + if fcntl is not None: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + elif msvcrt is not None: + getattr(msvcrt, "locking")(fd, getattr(msvcrt, "LK_NBLCK"), 1) + else: # pragma: no cover - no advisory locking primitive + raise RefreshFenceTimeout( + "refresh fence unsupported: no flock/msvcrt on this platform" + ) + return fd + except OSError as exc: + if exc.errno not in _FENCE_CONTENTION_ERRNOS: + # Not "a peer holds it" but "this filesystem cannot lock" + # (e.g. some network mounts). Still fail closed, but say so + # now instead of spinning to the deadline and blaming a peer. + raise RefreshFenceTimeout( + f"refresh fence unavailable on this filesystem: {exc}" + ) from exc + if time.monotonic() >= deadline: + raise RefreshFenceTimeout( + f"refresh fence held by a peer for {timeout:.0f}s ({lock_path.name})" + ) from None + await asyncio.sleep(0.05) + except BaseException: + os.close(fd) + raise + + +def release_refresh_fence(fd: int) -> None: + """Unlock and close a descriptor returned by ``acquire_refresh_fence``. Never raises.""" + try: + if fcntl is not None: + fcntl.flock(fd, fcntl.LOCK_UN) + elif msvcrt is not None: + getattr(msvcrt, "locking")(fd, getattr(msvcrt, "LK_UNLCK"), 1) + except OSError: + pass + finally: + with contextlib.suppress(OSError): + os.close(fd) + + +# --------------------------------------------------------------------------- +# Lazy imports -- MCP SDK with OAuth support is optional +# --------------------------------------------------------------------------- + +# SDK availability is detected WITHOUT importing mcp (~170 ms); classes bind lazily via _sdk_class(). +_OAUTH_AVAILABLE = _importlib_util.find_spec("mcp") is not None +if not _OAUTH_AVAILABLE: + logger.debug("MCP OAuth types not available -- OAuth MCP auth disabled") + +_SDK_CLASS_NAMES = ("OAuthClientProvider", "OAuthClientInformationFull", "OAuthClientMetadata", "OAuthMetadata", "OAuthToken") +_SDK_CLASSES: dict[str, Any] = {} + + +def _sdk_class(name: str) -> Any: + """SDK OAuth class *name*, importing the SDK on first call; None when unavailable (a broken SDK is probed once).""" + global _OAUTH_AVAILABLE + if not _SDK_CLASSES: + try: + from mcp.client import auth as _client_auth + from mcp.shared import auth as _shared_auth + + _SDK_CLASSES["OAuthClientProvider"] = _client_auth.OAuthClientProvider + for _name in _SDK_CLASS_NAMES[1:]: + _SDK_CLASSES[_name] = getattr(_shared_auth, _name) + except (ImportError, AttributeError): + _SDK_CLASSES.update(dict.fromkeys(_SDK_CLASS_NAMES)) + _OAUTH_AVAILABLE = False + logger.debug("MCP OAuth types not available -- OAuth MCP auth disabled") + return _SDK_CLASSES.get(name) + + +try: + from pydantic import AnyUrl +except ImportError: + AnyUrl = None # type: ignore[assignment, misc] + + +class OAuthNonInteractiveError(RuntimeError): + """Raised when OAuth requires browser interaction in a non-interactive env.""" + + +# Port of the most recent callback-port resolution. Legacy global; per-flow closures are the +# real mechanism (concurrent flows must not share it). +_oauth_port: int | None = None + +# Interactivity gates for OAuth stdin prompts. ContextVars, NOT threading.local: background +# discovery sets them on its own thread while connect+OAuth runs on the `mcp-event-loop` thread +# via run_coroutine_threadsafe, which copies the calling context into the coroutine. `forced` +# pushes _is_interactive() past the TTY check for GUI-driven flows (dashboard/desktop REST; the +# paste fallback degrades harmlessly to EOF). Suppression wins — background discovery must never +# start a browser flow. +_oauth_interactive_enabled = contextvars.ContextVar("_oauth_interactive_enabled", default=True) +_oauth_interactive_forced = contextvars.ContextVar("_oauth_interactive_forced", default=False) + +# Paste-prompt tokens that exit OAuth without auth; the waiter maps the sentinel to +# OAuthNonInteractiveError("user_skipped") so MCP setup continues without this server. +_SKIP_TOKENS = frozenset({"skip", "cancel", "s", "n", "no", "q", "quit"}) +_USER_SKIPPED_SENTINEL = "__hermes_user_skipped__" + + +def _get_token_dir(hermes_home: str | Path | None = None) -> Path: + """``HERMES_HOME/mcp-tokens/`` — per-profile token directory.""" + from hermes_constants import get_hermes_home + + return Path(hermes_home if hermes_home is not None else get_hermes_home()) / "mcp-tokens" + + +def _safe_filename(name: str) -> str: + """Sanitize a server name for use as a filename (no path separators).""" + return re.sub(r"[^\w\-]", "_", name).strip("_")[:128] or "default" + + +# Callback-port reservation: bound-but-not-listening sockets keyed by port, held from selection +# until the waiter adopts them (closes the select→bind TOCTOU window). Bounded so reconnect loops cannot leak fds. +# Holding the socket from port-selection time until _wait_for_callback adopts it closes the TOCTOU window +# where another process could grab the port between _find_free_port() closing its probe socket and +# HTTPServer binding minutes later (#22161). +_reserved_sockets: "dict[int, socket.socket]" = {} +_MAX_RESERVED_SOCKETS = 8 + + +def _bind_reserved(port: int) -> int | None: + """Bind ``127.0.0.1:port`` (0 = ephemeral) and park it until the waiter adopts it; None if taken. + The cap evicts ephemeral parks only: losing a pinned CIMD port (the only ones the published + document declares) mid-flow would reopen the race.""" + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + sock.bind(("127.0.0.1", port)) + except OSError: + sock.close() + if port: + return None + raise + bound = sock.getsockname()[1] + while len(_reserved_sockets) >= _MAX_RESERVED_SOCKETS: + stale_port = next((p for p in _reserved_sockets if p not in _CIMD_PORTS), None) + if stale_port is None: + break # only pinned sockets remain — never evict those + with contextlib.suppress(OSError): + _reserved_sockets.pop(stale_port).close() + _reserved_sockets[bound] = sock + return bound + + +def _reserve_callback_port() -> int: + """Pick an ephemeral callback port and keep its socket bound (parked).""" + return _bind_reserved(0) # type: ignore[return-value] # port 0 never returns None + + +def _cached_client_info(storage: "HermesTokenStorage | None") -> dict | None: + """The on-disk client registration for *storage*, or None.""" + try: + return _read_json(storage._client_info_path()) if storage is not None else None + except (AttributeError, TypeError, ValueError): + return None + + +def _cached_redirect(storage: "HermesTokenStorage | None") -> "tuple[str | None, int | None]": + """``(https proxy URI, loopback callback port)`` from the cached client registration (None when + absent): a DCR ``client_id`` is bound to its registered redirect URI, so a new random port under + it gets ``redirect_uri does not match any registered URIs``.""" + uri = port = None + for raw in (_cached_client_info(storage) or {}).get("redirect_uris") or []: + try: + parsed = urlparse(str(raw)) + except (TypeError, ValueError): + continue + if uri is None and parsed.scheme == "https" and parsed.netloc: + uri = str(raw) + is_loopback_callback = parsed.scheme == "http" and parsed.path == "/callback" and parsed.hostname in {"127.0.0.1", "localhost"} + if port is None and is_loopback_callback and parsed.port is not None: + port = int(parsed.port) + return uri, port + + +def _stdin_is_console() -> bool: + """A human can type on stdin. ``isatty()`` alone is wrong on Windows: the CRT reports True for + a DEVNULL / detached / CREATE_NO_WINDOW stdin (the gateway's), so a background process looked + interactive and launched browser OAuth flows nobody could finish. Confirm with the console API + there: ``GetConsoleMode`` fails on anything that is not a real console handle.""" + try: + if not sys.stdin.isatty(): + return False + except (AttributeError, ValueError): + return False + if os.name != "nt": + return True + try: + import ctypes + import msvcrt + handle = msvcrt.get_osfhandle(sys.stdin.fileno()) + mode = ctypes.c_ulong() + return bool(ctypes.windll.kernel32.GetConsoleMode(ctypes.c_void_p(handle), ctypes.byref(mode))) + except Exception: + return False + + +def _is_interactive() -> bool: + """True if we can reasonably expect to interact with a user.""" + if not _oauth_interactive_enabled.get(): + return False + if _oauth_interactive_forced.get(): + return True + return _stdin_is_console() + + +def _raise_if_non_interactive(lead: str) -> None: + """Raise ``OAuthNonInteractiveError`` unless interactive; *lead* is the boundary-specific first sentence. + + ``lead`` is the boundary-specific first sentence; this helper appends the shared, actionable ``hermes + mcp login`` next-step so the guidance wording lives in one place across every non-interactive OAuth + boundary (#57836). + """ + if not _is_interactive(): + raise OAuthNonInteractiveError( + f"{lead} Run `hermes mcp login ` interactively to (re)authorize, then restart or reload the gateway." + ) + + +def force_interactive_oauth(): + """Treat the context as interactive despite no TTY (GUI-driven auth: the user IS present, just not + on stdin). Crosses the MCP event-loop thread like ``suppress_interactive_oauth``. + + Opens the browser + localhost callback flow that the TTY heuristic would otherwise refuse. Same + ContextVar propagation story as suppress_interactive_oauth() (#35927). + """ + return _contextvar_set(_oauth_interactive_forced, True) + + +def suppress_interactive_oauth(): + """Disable stdin-based OAuth prompts for the current context; ContextVar-based so a + background-discovery thread's suppression reaches the coroutine on the MCP event-loop thread. + + Uses a ContextVar so the suppression propagates from a background-discovery thread onto the coroutine + scheduled (via run_coroutine_threadsafe) on the dedicated MCP event-loop thread — where the OAuth + callback actually runs (#35927). A threading.local would not cross that thread boundary. + """ + return _contextvar_set(_oauth_interactive_enabled, False) + + +def _can_open_browser() -> bool: + """True if opening a browser is likely to work.""" + if os.environ.get("SSH_CLIENT") or os.environ.get("SSH_TTY"): + return False # explicit SSH session → no local display + if os.name == "nt" or (hasattr(os, "uname") and os.uname().sysname == "Darwin"): + return True + return bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")) + + +def _read_json(path: Path) -> dict | None: + """Read a JSON file, returning None if it doesn't exist or is invalid.""" + if not path.exists(): + return None + try: + return json.loads(path.read_text(encoding="utf-8")) + except (json.JSONDecodeError, OSError) as exc: + logger.warning("Failed to read %s: %s", path, exc) + return None + + +def _write_json(path: Path, data: dict) -> None: + """OAuth tokens/client info at 0600 from creation, parent tightened to 0700 (``secure_parent_dir`` + refuses ``/``, top-level dirs and the install tree — #25821, #93050).""" + path.parent.mkdir(parents=True, exist_ok=True) + secure_parent_dir(path) + atomic_json_write(path, data, mode=0o600, default=str) + + +def _model_json(model: Any) -> dict: + """The on-disk JSON shape of an SDK pydantic model.""" + return model.model_dump(mode="json", exclude_none=True) + + +class HermesTokenStorage: + """Persist OAuth state as ``HERMES_HOME/mcp-tokens/`` + ``.json`` (tokens), + ``.client.json`` (client info), ``.meta.json`` (server metadata), ``.cimd-off`` (CIMD refused).""" + + def __init__(self, server_name: str, *, hermes_home: str | Path | None = None): + self._server_name = _safe_filename(server_name) + self._hermes_home = Path(hermes_home) if hermes_home is not None else None + # Issuer binding: ``loaded_issuer`` is what the token file on disk recorded (the authorization + # server that granted the stored refresh token); ``_bound_issuer`` is stamped onto the next + # ``set_tokens`` write. See ``tools.mcp_oauth_provider.enforce_refresh_token_issuer``. + self.loaded_issuer: str | None = None + self._bound_issuer: str | None = None + + def _path(self, suffix: str) -> Path: + return _get_token_dir(self._hermes_home) / f"{self._server_name}{suffix}" + + _tokens_path = partialmethod(_path, ".json") + _client_info_path = partialmethod(_path, ".client.json") + _meta_path = partialmethod(_path, ".meta.json") + _cimd_rejected_path = partialmethod(_path, ".cimd-off") + + def _state_paths(self) -> tuple[Path, Path, Path]: + return self._tokens_path(), self._client_info_path(), self._meta_path() + + @staticmethod + def _load_model(path: Path, sdk_name: str, label: str, fixup=None): + """Read *path* into SDK model *sdk_name*; None if absent, no SDK, or corrupt. + ``fixup(data)`` may rewrite the raw dict before validation.""" + data = _read_json(path) + cls = _sdk_class(sdk_name) if data is not None else None + if (cls is not None and sdk_name == "OAuthMetadata" and isinstance(data, dict) + and data.get("device_authorization_endpoint")): + from tools.mcp_oauth_device import DeviceOAuthMetadata + cls = DeviceOAuthMetadata + if cls is None: + return None + if fixup is not None: + fixup(data) + try: + return cls.model_validate(data) + except (ValueError, TypeError, KeyError) as exc: + # A pydantic ValidationError's str() echoes the raw input (the token material); log + # only which fields failed. + detail = exc + if hasattr(exc, "errors"): # pydantic ValidationError + detail = "validation failed for " + ", ".join( + ".".join(map(str, e.get("loc", ()))) for e in exc.errors(include_input=False)) + logger.warning("Corrupt %s at %s -- ignoring: %s", label, path, detail) + return None + + def _rebase_expires_in(self, data: dict) -> None: + """Rewrite ``expires_in`` to seconds remaining from the stored absolute ``expires_at`` (not an + SDK field, so stripped): a relative value reloaded after restart would make ``is_token_valid()`` + True for tokens that expired while down. Legacy files without it use the file mtime, clamped + to zero (self-heals on the next ``set_tokens``).""" + absolute_expiry = data.pop("expires_at", None) + if absolute_expiry is not None: + data["expires_in"] = int(max(absolute_expiry - time.time(), 0)) + elif data.get("expires_in") is not None: + with contextlib.suppress(OSError, TypeError, ValueError): + implied_expiry = self._tokens_path().stat().st_mtime + int(data["expires_in"]) + data["expires_in"] = int(max(implied_expiry - time.time(), 0)) + + def _fixup_loaded_tokens(self, data: dict) -> None: + # ``hermes_issuer`` is Hermes bookkeeping, not an SDK OAuthToken field: pop before validation. + self.loaded_issuer = data.pop("hermes_issuer", None) + self._rebase_expires_in(data) + + async def get_tokens(self) -> "OAuthToken | None": + self.loaded_issuer = None + return self._load_model(self._tokens_path(), "OAuthToken", "tokens", self._fixup_loaded_tokens) + + async def set_tokens(self, tokens: "OAuthToken") -> None: + payload = _model_json(tokens) + # Absolute ``expires_at``: see _rebase_expires_in. + if payload.get("expires_in") is not None: + with contextlib.suppress(TypeError, ValueError): # mock tokens / odd shapes: skip, don't fail persistence + payload["expires_at"] = time.time() + int(payload["expires_in"]) + if self._bound_issuer: # which authorization server granted these tokens (never sent on the wire) + payload["hermes_issuer"] = self._bound_issuer + self.loaded_issuer = self._bound_issuer + _write_json(self._tokens_path(), payload) + logger.debug("OAuth tokens saved for %s", self._server_name) + + def bind_issuer(self, issuer: str | None) -> None: + """Set the authorization-server issuer stamped on future token writes.""" + self._bound_issuer = str(issuer) if issuer else None + + def stamp_issuer(self, issuer: str) -> None: + """Backfill ``hermes_issuer`` onto a pre-binding token file: adopt the currently discovered + issuer once instead of forcing a re-login, so the *next* read is protected.""" + data = _read_json(self._tokens_path()) + if data is None or data.get("hermes_issuer"): + return + data["hermes_issuer"] = str(issuer) + try: + _write_json(self._tokens_path(), data) + except OSError as exc: # non-fatal — worst case we stamp next time + logger.debug("Could not stamp issuer on tokens for %s: %s", self._server_name, exc) + return + self.loaded_issuer = str(issuer) + + def strip_refresh_token(self) -> None: + """Drop the refresh token (and its issuer record) from disk, keeping the access token: the + unexpired access token may still be used, but a refresh token must never go to a different + issuer than the one that granted it.""" + data = _read_json(self._tokens_path()) + if data is None or not data.get("refresh_token"): + return + data.pop("refresh_token", None) + data.pop("hermes_issuer", None) + self.loaded_issuer = None + try: + _write_json(self._tokens_path(), data) + except OSError as exc: + logger.warning("Could not strip refresh token for %s: %s", self._server_name, exc) + return + logger.info("Removed issuer-mismatched refresh token for %s (re-authorization will be required " + "when the access token expires)", self._server_name) + + @staticmethod + def _coerce_secret_auth_method(data: dict) -> bool: + """Set ``client_secret_post`` when a secret is present but no method is: some DCR providers + (Supabase) omit ``token_endpoint_auth_method``, the SDK defaults it to ``none`` and the + exchange fails without the secret.""" + if data.get("client_secret") and data.get("token_endpoint_auth_method") in (None, "none", ""): + data["token_endpoint_auth_method"] = "client_secret_post" + return True + return False + + async def get_client_info(self) -> "OAuthClientInformationFull | None": + coerced: list[bool] = [] + info = self._load_model( + self._client_info_path(), "OAuthClientInformationFull", "client info", + lambda data: coerced.append(self._coerce_secret_auth_method(data))) + if info is not None and coerced[0]: + _write_json(self._client_info_path(), _model_json(info)) # persist so later flows skip the coercion + return info + + async def set_client_info(self, client_info: "OAuthClientInformationFull") -> None: + data = _model_json(client_info) + self._coerce_secret_auth_method(data) + _write_json(self._client_info_path(), data) + logger.debug("OAuth client info saved for %s", self._server_name) + + def save_oauth_metadata(self, metadata: "OAuthMetadata") -> None: + """Persist server metadata so a restarted process can refresh without re-discovery; + otherwise the SDK guesses ``{server_url}/token`` (404) and forces re-auth.""" + _write_json(self._meta_path(), _model_json(metadata)) + logger.debug("OAuth metadata saved for %s", self._server_name) + + def load_oauth_metadata(self) -> "OAuthMetadata | None": + return self._load_model(self._meta_path(), "OAuthMetadata", "OAuth metadata") + + def mark_cimd_rejected(self) -> None: + """Durably record that this server refused our CIMD document so a restart does not re-present + the refused client_id. Cleared by ``remove()`` so a fixed document gets a retry.""" + path = self._cimd_rejected_path() + try: + path.parent.mkdir(parents=True, exist_ok=True) + path.touch() + except OSError as exc: # non-fatal — worst case we retry CIMD later + logger.debug("Could not record CIMD rejection at %s: %s", path, exc) + + def cimd_rejected(self) -> bool: + """True when this server has refused our metadata document before.""" + return self._cimd_rejected_path().exists() + + def remove(self) -> None: + """Delete all stored OAuth state for this server.""" + # The ``.refresh.lock`` sidecar is deliberately kept: flock is inode-bound, so unlinking it + # while a peer holds the fence would let the next acquirer lock a fresh inode (two holders). + for p in (*self._state_paths(), self._cimd_rejected_path()): + p.unlink(missing_ok=True) + + def snapshot(self) -> dict[str, bytes]: + """filename -> bytes of the existing state files; ``restore()`` it to undo a ``remove()`` after + a failed re-auth so a valid token survives.""" + snap: dict[str, bytes] = {} + for p in self._state_paths(): + with contextlib.suppress(OSError): + snap[p.name] = p.read_bytes() + return snap + + def restore(self, snapshot: dict[str, bytes], *, only_if_absent: bool = False) -> None: + """Revert to a snapshot without overwriting a concurrent successful write.""" + if only_if_absent and any(path.exists() for path in self._state_paths()): + logger.info("Skipping OAuth rollback for %s because newer state exists", self._server_name) + return + self.remove() + if not snapshot: + return + token_dir = _get_token_dir(self._hermes_home) + token_dir.mkdir(parents=True, exist_ok=True) + for fname, data in snapshot.items(): + try: + fd = os.open(str(token_dir / fname), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, stat.S_IRUSR | stat.S_IWUSR) + with os.fdopen(fd, "wb") as fh: + fh.write(data) + except OSError as exc: + logger.warning("Failed to restore OAuth state %s: %s", fname, exc) + + def poison_client_registration(self) -> bool: + """Discard a dead DCR client (``invalid_client`` at the token endpoint) plus stale ``meta.json`` + so the SDK re-registers next flow; tokens are kept (a valid refresh token survives if + re-registration never completes). Keeps one ``.bak``. True if a client file was removed.""" + client_path = self._client_info_path() + if not client_path.exists(): + return False + backup = client_path.with_name(client_path.name + ".bak") + try: + backup.write_bytes(client_path.read_bytes()) + except OSError as exc: # non-fatal — proceed with the removal anyway + logger.warning("Could not back up client info at %s: %s", client_path, exc) + client_path.unlink(missing_ok=True) + self._meta_path().unlink(missing_ok=True) + logger.warning( + "MCP OAuth '%s': cached client registration rejected as invalid_client; " + "removed client.json + meta.json (backup at %s) to force re-registration", + self._server_name, backup.name) + return True + + def has_cached_tokens(self) -> bool: + """True if we have tokens on disk (may be expired).""" + return self._tokens_path().exists() + + +# Callback capture: the HTTP listener and the stdin paste reader share one result dict. +def _authorization_code_result(code: str, state: "str | None", iss: "str | None" = None): + """Redirect parameters in the shape the installed SDK expects: mcp 2.0's ``callback_handler`` + returns an ``AuthorizationCodeResult`` (the SDK reads ``.state``/``.iss`` off it); older SDKs take a tuple.""" + try: + from mcp.shared.auth import AuthorizationCodeResult + except ImportError: # mcp < 2.0 + return code, state + return AuthorizationCodeResult(code=code, state=state, iss=iss) + + +def _parse_redirect_query(query: str) -> dict[str, Any]: + """code/state/error/iss from a redirect query string. ``iss`` (RFC 9207 issuer) is kept: mcp 2.0 + rejects a response omitting it when the server advertised ``authorization_response_iss_parameter_supported``.""" + params = parse_qs(query) + return {k: params.get(k, [None])[0] for k in ("code", "state", "error", "iss")} + + +def _result_taken(result: dict) -> bool: + return result.get("auth_code") is not None or result.get("error") is not None + + +def _make_callback_handler() -> tuple[type, dict]: + """Fresh ``(HandlerClass, result_dict)`` per flow so concurrent flows don't stomp on each other.""" + result: dict[str, Any] = {"auth_code": None, "state": None, "error": None, "iss": None} + + class _Handler(BaseHTTPRequestHandler): + def do_GET(self) -> None: # noqa: N802 + parsed = _parse_redirect_query(urlparse(self.path).query) + result.update(auth_code=parsed["code"], state=parsed["state"], error=parsed["error"], iss=parsed["iss"]) + body = ("

Authorization Successful

You can close this tab and return to Hermes.

" if parsed["code"] + else f"

Authorization Failed

Error: {html.escape(parsed['error'] or 'unknown')}

") + self.send_response(200) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.end_headers() + self.wfile.write(f"{body}".encode()) + + def log_message(self, fmt: str, *args: Any) -> None: + logger.debug("OAuth callback: %s", fmt % args) + + return _Handler, result + + +def _paste_callback_reader(result: dict) -> None: + """Read one stdin line as an OAuth redirect (full URL, bare query, or a ``_SKIP_TOKENS`` word that + exits without auth) into *result*. Parse failures, EOF and interrupts are swallowed — best-effort + fallback racing the HTTP listener, which stays primary.""" + try: + line = sys.stdin.readline() + except (KeyboardInterrupt, OSError, ValueError): + return + line = (line or "").strip() + if not line or _result_taken(result): + return # EOF / blank, or the HTTP listener already won + if line.lower() in _SKIP_TOKENS: + result["error"] = _USER_SKIPPED_SENTINEL + print( + " OAuth skipped. Run `hermes mcp login ` later to authenticate, " + "or set ``enabled: false`` on that server in config.yaml to disable persistently.", + file=sys.stderr) + return + # Full URL or "?code=...": take everything after the first "?". + query = line.split("?", 1)[1] if "?" in line else line + try: + parsed = _parse_redirect_query(query.removeprefix("?")) + except (ValueError, TypeError): + print(" Could not parse pasted input as an OAuth redirect — ignoring.", file=sys.stderr) + return + if not parsed["code"] and not parsed["error"]: + print(" Pasted input did not contain ``code=`` or ``error=`` — ignoring.", file=sys.stderr) + return + if _result_taken(result): # one more race-check before writing + return + result.update(auth_code=parsed["code"], state=parsed["state"], error=parsed["error"], iss=parsed["iss"]) + if parsed["code"]: + print(" Got authorization code from paste — completing flow.", file=sys.stderr) + + +# Remote-session hints printed under the authorization URL: a proxy callback forwards the redirect +# here (no tunnel needed); on loopback it misses this machine, so the user pastes the URL back or SSH-forwards the port. +_SSH_HINT_PROXY = ( + " Remote session detected. After you authorize, the provider redirects to\n" + " {redirect_uri}\n" + " which forwards to the callback listener on this machine — no SSH tunnel needed.\n") +_SSH_HINT_LOOPBACK = ( + " Remote session detected. After you authorize, the provider redirects to\n" + " http://127.0.0.1:{port}/callback\n" + " which only the listener on THIS machine can receive. Two options:\n" + "\n" + " 1. Easiest — when your browser shows a connection error after\n" + " authorizing, copy the full URL from the address bar and paste\n" + " it at the prompt below. The pasted ``code=...&state=...`` is\n" + " enough to complete the flow.\n" + "\n" + " 2. Or forward the port first in a separate terminal:\n" + " ssh -N -L {port}:127.0.0.1:{port} @\n" + " then open the URL above and let it redirect normally.\n" + "\n" + " See: https://hermes-agent.nousresearch.com/docs/guides/oauth-over-ssh\n") + + +def _announce_authorization_url(authorization_url: str, port: int, redirect_uri: str | None) -> None: + """Print the URL (always, as the fallback) and open the browser when possible.""" + print(f"\n MCP OAuth: authorization required.\n Open this URL in your browser:\n\n {authorization_url}\n", file=sys.stderr) + if os.getenv("SSH_CLIENT") or os.getenv("SSH_TTY"): + if redirect_uri: + print(_SSH_HINT_PROXY.format(redirect_uri=redirect_uri), file=sys.stderr) + elif port: + print(_SSH_HINT_LOOPBACK.format(port=port), file=sys.stderr) + if not _can_open_browser(): + note = "Headless environment detected — open the URL manually." + else: + opened = False + with contextlib.suppress(Exception): + opened = webbrowser.open(authorization_url) + note = "Browser opened automatically." if opened else "Could not open browser — please open the URL manually." + print(f" ({note})\n", file=sys.stderr) + + +def _make_redirect_handler(port: int, redirect_uri: str | None = None): + """Redirect handler closing over this flow's port (a closure, not ``_oauth_port``, keeps concurrent + flows isolated). ``redirect_uri`` is a configured proxy callback (None for loopback) and only tailors the hint. + + Using a closure instead of reading the module-level ``_oauth_port`` avoids cross-server state pollution + when multiple MCP servers run OAuth concurrently (fixes #44588). + """ + async def _redirect_handler(authorization_url: str) -> None: + dashboard_flow = get_dashboard_oauth_flow() + if dashboard_flow is not None: + await dashboard_flow.publish_authorization_url(authorization_url) + return + # Fail fast when non-interactive: a cached-but-unusable token makes the SDK fall through to the + # authorization-code flow past the token-file guard, and the waiter would block for the full timeout. + # Fail fast at the authorization boundary in non-interactive contexts (systemd gateway, cron, + # background MCP discovery). Without this check we would print a URL and launch a browser flow no + # operator can complete, then block in _wait_for_callback for the full timeout. Raise before + # launching so gateway adapters start promptly and the caller can skip this server with an + # actionable warning. This intentionally re-checks interactivity here rather than trusting the + # token-file existence guard alone. See #57836. + _raise_if_non_interactive( + "MCP OAuth requires browser authorization but no interactive session is available (non-interactive/background context)." + ) + _announce_authorization_url(authorization_url, port, redirect_uri) + + return _redirect_handler + + +def _start_callback_server(port: int, handler_cls: type) -> HTTPServer: + """Bind the callback listener on *port*, adopting a parked reserved socket (closes the select→bind + TOCTOU window). ``allow_reuse_address`` is set BEFORE binding (a no-op afterwards) so a lingering + TIME_WAIT socket from a previous flow cannot block the next.""" + try: + server = HTTPServer(("127.0.0.1", port), handler_cls, bind_and_activate=False) + reserved = _reserved_sockets.pop(port, None) + if reserved is not None: + server.socket.close() + server.socket, server.server_address = reserved, reserved.getsockname() + else: + server.allow_reuse_address = True + server.server_bind() + server.server_activate() + except OSError as exc: # genuinely in use (concurrent flow / leftover listener / colliding redirect_port): say so, not "timed out" + raise OAuthNonInteractiveError( + f"OAuth callback port {port} is already in use ({exc}). Close any other in-progress login, " + "or set a free `oauth.redirect_port` in the server config, then retry." + ) from exc + return server + + +def _callback_outcome(result: dict, cimd_url: str | None): + """Turn a filled/empty result dict into the SDK's callback value, or raise.""" + if result["error"] == _USER_SKIPPED_SENTINEL: + raise OAuthNonInteractiveError("user_skipped") + if result["error"]: + raise RuntimeError(f"OAuth authorization failed: {result['error']}") + if result["auth_code"] is None: + hint = ( + " If the browser showed an invalid-client error instead of an approval prompt, the authorization " + f"server rejected Hermes' Client ID Metadata Document ({cimd_url}); set ``cimd: false`` under that " + "server's ``oauth:`` block in config.yaml to authorize via dynamic client registration instead." + ) if cimd_url else "" + raise OAuthNonInteractiveError( + "OAuth callback timed out — no authorization code received. Ensure you completed the browser authorization flow." + hint + ) + return _authorization_code_result(result["auth_code"], result["state"], result.get("iss")) + + +def _make_callback_waiter(port: int, cimd_url: str | None = None, timeout: float = 300.0): + """Callback waiter bound to one flow's port. ``timeout`` is where ``oauth.timeout`` applies (mcp 2.0 + dropped the provider's own). ``cimd_url`` only tailors the timeout message: a server refusing the + document aborts at the authorization endpoint, so no redirect arrives and a bare "timed out" would + hide the cause. Raises ``OAuthNonInteractiveError`` on timeout or when non-interactive. + + Closing over the port (instead of reading the module-level ``_oauth_port``) keeps concurrent OAuth flows + isolated: flow A's waiter listens on flow A's port even when flow B's ``_configure_callback_port`` + overwrites the legacy global afterwards (#34260, the callback-side sibling of the #44588 + redirect-handler fix). + """ + async def _wait(): + dashboard_flow = get_dashboard_oauth_flow() + if dashboard_flow is not None: + # Dashboard flow speaks the legacy tuple; normalize to one shape. + return _authorization_code_result(*await dashboard_flow.wait_for_callback()) + # The SDK entered the authorization-code flow, so any cached token is unusable. Reject BEFORE + # binding: binding would block for the full timeout and collide with the TIME_WAIT port on retry. + # Reject before binding the callback listener in non-interactive contexts. Reaching here means the + # SDK entered the authorization-code flow (a valid or refreshable token would never call the + # callback handler), so a cached token file is present but unusable. Binding the listener here would + # block for the full 300s timeout and — on the next connection retry — collide with the + # still-bound/TIME_WAIT port, surfacing as ``OSError: [Errno 98] Address already in use``. Failing + # fast keeps gateway startup independent of an unusable optional MCP server. This guard holds + # "regardless of whether a token file exists" — the point the build_oauth_auth token-file guard + # cannot cover. See #57836. + _raise_if_non_interactive( + "OAuth callback requires an interactive session but none is available (non-interactive/background " + "context); skipping browser authorization without binding a callback listener.") + handler_cls, result = _make_callback_handler() + server = _start_callback_server(port, handler_cls) + threading.Thread(target=server.handle_request, daemon=True).start() + # Paste fallback races the HTTP listener; whichever fills result first wins. + if _is_interactive(): + print( + "\n Or paste the redirect URL here (or the ``?code=...&state=...`` portion) and press Enter. " + "Type ``skip`` + Enter to continue without this server:", + file=sys.stderr, flush=True) + threading.Thread(target=_paste_callback_reader, args=(result,), daemon=True).start() + elapsed = 0.0 + try: + while elapsed < timeout and not _result_taken(result): + await asyncio.sleep(0.5) + elapsed += 0.5 + finally: + server.server_close() + return _callback_outcome(result, cimd_url) + + return _wait + + +# Legacy build_oauth_auth provider class, built lazily (SDK) and cached here. +HermesOAuthClientProvider: Any = None + + +def remove_oauth_tokens(server_name: str, *, hermes_home: str | Path | None = None) -> None: + """Delete stored OAuth tokens and client info for a server.""" + HermesTokenStorage(server_name, hermes_home=hermes_home).remove() + logger.info("OAuth tokens removed for '%s'", server_name) + + +# CIMD (OAuth Client ID Metadata Documents): the client_id IS an HTTPS URL the server fetches for our +# name/logo/redirect URIs, replacing per-install DCR. The SDK does the protocol; Hermes only decides +# eligibility. Published from ``website/static/oauth/client-metadata.json``; the github.io origin is +# deliberate — servers MUST NOT follow redirects when fetching it, and hermes-agent.nousresearch.com/docs/* 301s here. +_CIMD_CLIENT_METADATA_URL = "https://nousresearch.github.io/hermes-agent/docs/oauth/client-metadata.json" +# Loopback ports/hosts declared in that document (exact match, so no ephemeral port under CIMD); +# below Linux's 32768 ephemeral floor. tests/tools/test_mcp_cimd.py keeps them in sync. +_CIMD_PORTS = (27890, 27891, 27892, 27893, 27894) +_CIMD_REDIRECT_HOSTS = frozenset({"127.0.0.1", "localhost"}) + + +def _is_valid_cimd_url(url: str) -> bool: + """True when *url* is usable as a CIMD client_id on the installed SDK (ImportError = SDK predates + CIMD → DCR only). The SDK checks only https + non-root path; userinfo, fragments and dot segments + are rejected here because they fail mid-browser-flow as an opaque invalid-client page.""" + try: + from mcp.client.auth.utils import is_valid_client_metadata_url + if not is_valid_client_metadata_url(url): + return False + parsed = urlparse(url) + has_userinfo = bool(parsed.username or parsed.password) # netloc parse can raise + except (ImportError, ValueError): + return False + return not (has_userinfo or parsed.fragment or any(seg in {".", ".."} for seg in parsed.path.split("/"))) + + +# Pinned ports this process committed to (never released: a provider keeps its port for the process +# lifetime), including ports restored from a cached registration. +# Includes a port restored from a cached client registration, so a sibling server is never handed a port +# another one is already registered on (#34260). +_assigned_cimd_ports: "list[int]" = [] + + +def _pick_cimd_port() -> int | None: + """Reserve a pinned CIMD callback port, or None when none is usable. Holding the bound socket makes + contention cooperative: a sibling finds the bind refused and moves down the range. Once every pinned + port belongs to this process the range wraps rather than falling back to DCR — a reused port only + bites if both servers authorize at the same moment (reported by the waiter); DCR may be unsupported entirely. + + Holding the bound socket until ``_wait_for_callback`` adopts it does the same job here as + ``_reserve_callback_port`` does for ephemeral ports (#22161): a fixed port is just as stealable in the + minutes between selection and the browser redirect arriving. + """ + for port in _CIMD_PORTS: + if port not in _assigned_cimd_ports and _bind_reserved(port) is not None: + _assigned_cimd_ports.append(port) + return port + return _assigned_cimd_ports[0] if _assigned_cimd_ports else None + + +def _server_declined_cimd(storage: "HermesTokenStorage | None") -> bool: + """True when cached metadata shows this server doesn't advertise CIMD. The SDK decides CIMD vs DCR + in its 401 branch — after Hermes must fix the redirect URI — so cached metadata closes the gap; + only a genuinely unknown server pays the optimistic pin.""" + try: + metadata = storage.load_oauth_metadata() if storage is not None else None + except (AttributeError, TypeError, ValueError): + return False + return metadata is not None and getattr(metadata, "client_id_metadata_document_supported", None) is not True + + +def _maybe_use_cimd(cfg: dict, storage: "HermesTokenStorage | None" = None) -> "tuple[str, int] | None": + """``(client_id URL, pinned callback port)``, or None to use DCR. Each ineligibility case means the + redirect URI is not one the document declares, the client identity is already settled, or the + server is known not to want a document — a metadata URL would be rejected.""" + url = cfg.get("client_metadata_url") or _CIMD_CLIENT_METADATA_URL + ineligible = ( + cfg.get("cimd") is False + or not _is_valid_cimd_url(url) + # pinned client = explicit choice; a secret = confidential client, which the document forbids + or cfg.get("client_id") or cfg.get("client_secret") + # the document supplies name + auth method; setting either asks for an identity CIMD can't present + or cfg.get("client_name") or (cfg.get("token_endpoint_auth_method") or "none") != "none" + # dashboard/desktop flows redirect to a deployment-specific URL no static document declares + or get_dashboard_oauth_flow() is not None + or cfg.get("redirect_uri") or cfg.get("redirect_port") + or (cfg.get("redirect_host") or "127.0.0.1") not in _CIMD_REDIRECT_HOSTS + # an existing registration is bound to its redirect URI; swapping client_id would drop tokens + or _cached_client_info(storage) is not None + or (storage is not None and storage.cimd_rejected()) + or _server_declined_cimd(storage)) + port = None if ineligible else _pick_cimd_port() + return None if port is None else (url, port) + + +def cimd_provider_kwargs(cfg: dict) -> dict[str, Any]: + """``client_metadata_url=`` kwargs for ``OAuthClientProvider`` when CIMD applies; omitted entirely + on a DCR flow because an SDK too old for CIMD rejects the keyword outright.""" + url = cfg.get("_cimd_url") + return {"client_metadata_url": url} if url else {} + + +def token_request_user_agent(cfg: dict) -> str | None: + """Configured ``oauth.user_agent`` for token-endpoint requests (exchange + refresh only, never MCP + traffic or discovery), or None; a null/empty YAML value never sends a blank header. No other + headers are configurable (secrets would land in config.yaml).""" + ua = cfg.get("user_agent") + return ua.strip() if isinstance(ua, str) and ua.strip() else None + + +def _configure_callback_port(cfg: dict, storage: "HermesTokenStorage | None" = None) -> int: + """Resolve the callback port into ``cfg['_resolved_port']`` (0 = non-loopback URI). Precedence: + dashboard flow / cached https redirect URI → CIMD pinned port (sets ``cfg['_cimd_url']``) → + ``oauth.redirect_port`` → cached registration port → fresh ephemeral port (the only parked one). + Also sets the legacy ``_oauth_port``. + + NOTE: also sets the legacy module-level ``_oauth_port`` so existing calls to ``_wait_for_callback`` keep + working. The legacy global is the root cause of issue #5344 (port collision on concurrent OAuth flows); + replacing it with a ContextVar is out of scope for this consolidation PR. + """ + global _oauth_port + dashboard_flow = get_dashboard_oauth_flow() + if dashboard_flow is not None: + cfg["_resolved_port"] = 0 + cfg["redirect_uri"] = cfg.get("redirect_uri") or dashboard_flow.redirect_uri + return 0 + cached_uri, cached_port = _cached_redirect(storage) + if cached_uri and not cfg.get("redirect_uri"): + cfg["redirect_uri"] = cached_uri + cfg["_resolved_port"] = 0 + return 0 + cimd = _maybe_use_cimd(cfg, storage) + if cimd is not None: + cfg["_cimd_url"], port = cimd + else: + port = int(cfg.get("redirect_port", 0)) or cached_port or _reserve_callback_port() + # A cached port may be a pinned CIMD port from an earlier login; claim it from siblings. + if port in _CIMD_PORTS and port not in _assigned_cimd_ports: + _assigned_cimd_ports.append(port) + # Precedence: explicit config port → cached client-registration port → fresh ephemeral port. The cached + # port keeps re-auth consistent with the redirect URI pinned at dynamic client registration (providers + # reject a mismatched URI). Only a truly fresh ephemeral pick goes through _reserve_callback_port(), + # which keeps the socket bound until _wait_for_callback adopts it — closing the select→bind TOCTOU race + # (#22161). Explicit and cached ports are fixed, known values and bind via the reuse_address path + # instead. + cfg["_resolved_port"] = port + _oauth_port = port + return port + + +def _resolve_redirect_uri(cfg: dict, port: int) -> str: + """Configured ``redirect_uri`` (proxy) or ``http://:/callback``; the single + derivation so client metadata and pre-registered info stay identical. ``redirect_host`` only changes + the hostname (some WAFs reject a literal ``127.0.0.1``); the listener still binds ``127.0.0.1``.""" + return cfg.get("redirect_uri") or f"http://{cfg.get('redirect_host') or '127.0.0.1'}:{port}/callback" + + +# Figma's remote MCP allowlists DCR by client_name ("Claude Code"/"Codex" register, others 403); +# register under an allowlisted name so the flow can start. oauth.client_name overrides. +_FIGMA_DCR_CLIENT_NAME = "Claude Code" +_FIGMA_DEFAULT_SCOPE = "mcp:connect" + + +def _is_figma_remote_mcp(server_name: str | None = None, server_url: str | None = None) -> bool: + """True when this MCP server is Figma's hosted remote endpoint.""" + from utils import base_url_host_matches, base_url_hostname + url = (server_url or "").lower() + if base_url_host_matches(url, "mcp.figma.com") or (base_url_host_matches(url, "figma.com") and "/mcp" in url): + return True + # Name-only match only when the URL isn't some other host called figma-*. + return "figma" in (server_name or "").lower() and (not url or "figma" in base_url_hostname(url)) + + +def apply_oauth_provider_defaults(cfg: dict, *, server_name: str = "", server_url: str | None = None) -> dict: + """Mutate *cfg* with provider-specific OAuth workarounds (before building client metadata / + pre-registering); returns *cfg*. Only fills keys the user left unset — explicit values win.""" + if _is_figma_remote_mcp(server_name, server_url): + if not cfg.get("client_name"): + cfg["client_name"] = _FIGMA_DCR_CLIENT_NAME + logger.info( + "MCP OAuth '%s': Figma DCR allowlist — registering as client_name=%r (override via oauth.client_name)", + server_name or server_url, _FIGMA_DCR_CLIENT_NAME) + if not cfg.get("scope"): + cfg["scope"] = _FIGMA_DEFAULT_SCOPE + # Figma advertises auth_method=none yet demands the returned client_secret at the token + # endpoint; request a confidential registration so the SDK posts it. + cfg["token_endpoint_auth_method"] = cfg.get("token_endpoint_auth_method") or "client_secret_post" + return cfg + + +def _build_client_metadata(cfg: dict) -> "OAuthClientMetadata": + """Build OAuthClientMetadata; requires ``_configure_callback_port`` first.""" + port = cfg.get("_resolved_port") + if port is None: + raise ValueError("_configure_callback_port() must be called before _build_client_metadata()") + metadata_cls = _sdk_class("OAuthClientMetadata") + # Public client by default; confidential only with a known secret or a provider (Figma) needing confidential-style token posts. + auth_method = cfg.get("token_endpoint_auth_method") or ("client_secret_post" if cfg.get("client_secret") else "none") + metadata_kwargs: dict[str, Any] = { + "client_name": cfg.get("client_name", "Hermes Agent"), + "redirect_uris": [AnyUrl(_resolve_redirect_uri(cfg, port))], + "grant_types": ["authorization_code", "refresh_token"], + "response_types": ["code"], + "token_endpoint_auth_method": auth_method, + # SEP-837: OIDC-strict servers need application_type to accept loopback redirects; "native" + # for a CLI/desktop app, overridable for a hosted https dashboard. + "application_type": cfg.get("application_type", "native")} + if cfg.get("scope"): + metadata_kwargs["scope"] = cfg["scope"] + try: + return metadata_cls.model_validate(metadata_kwargs) + except Exception: # mcp 1.x metadata models predate SEP-837 and reject the unknown field + metadata_kwargs.pop("application_type", None) + return metadata_cls.model_validate(metadata_kwargs) + + +def _invalidate_tokens_on_client_change( + storage: "HermesTokenStorage", new_client_id: str, new_client_secret: str | None) -> None: + """Drop cached tokens when the configured client identity changes: tokens minted under the old + ``client_id`` fail refresh with ``invalid_client``, and pre-registered clients are exempt from + auto-poison, so stale tokens would wedge every request until a manual wipe. Compares on-disk + ``client.json`` BEFORE it is overwritten; a matching identity is a no-op. + + Matching identity is a no-op so live sessions and valid tokens are preserved. Port of + cline/cline#12983's "invalidate tokens when OAuth client changes" invariant. + """ + existing = _read_json(storage._client_info_path()) + old_client_id = existing.get("client_id") if isinstance(existing, dict) else None + if not old_client_id or (old_client_id == new_client_id and (existing.get("client_secret") or None) == (new_client_secret or None)): + return + removed = False + for path in (storage._tokens_path(), storage._meta_path()): + if not path.exists(): + continue + try: + path.unlink() + removed = True + except OSError as exc: # non-fatal — stale tokens fail later anyway + logger.warning("MCP OAuth '%s': could not remove stale %s after client change: %s", storage._server_name, path.name, exc) + if removed: + logger.warning( + "MCP OAuth '%s': configured OAuth client changed (client_id %r -> %r); discarded tokens minted under " + "the previous client. Re-authorize with: hermes mcp login %s", + storage._server_name, old_client_id, new_client_id, storage._server_name) + + +def _maybe_preregister_client(storage: "HermesTokenStorage", cfg: dict, client_metadata: "OAuthClientMetadata") -> None: + """If cfg has a pre-registered client_id, persist it to storage.""" + client_id = cfg.get("client_id") + if not client_id: + return + info_cls = _sdk_class("OAuthClientInformationFull") + _invalidate_tokens_on_client_change(storage, client_id, cfg.get("client_secret")) + info_dict: dict[str, Any] = { + "client_id": client_id, + "redirect_uris": [_resolve_redirect_uri(cfg, cfg["_resolved_port"])], + "grant_types": client_metadata.grant_types, + "response_types": client_metadata.response_types, + "token_endpoint_auth_method": client_metadata.token_endpoint_auth_method, + **{key: cfg[key] for key in ("client_secret", "client_name", "scope") if cfg.get(key)}} + _write_json(storage._client_info_path(), _model_json(info_cls.model_validate(info_dict))) + logger.debug("Pre-registered client_id=%s for '%s'", client_id, storage._server_name) + + +def humanize_oauth_registration_error( + server_name: str, exc: BaseException | str, *, server_url: str | None = None) -> str | None: + """Turn a DCR 403/Forbidden into a useful next step; None for anything else so the caller keeps the + original text. Figma gates DCR on exact ``client_name`` (auto-set to ``Claude Code``), so this fires + when the user overrode it or an older Hermes is running.""" + msg = str(exc) + lowered = msg.lower() + looks_like_registration = ("403" in msg or "forbidden" in lowered) and ( + any(k in lowered for k in ("regist", "dcr", "dynamic client")) + or lowered.strip() in {"forbidden", "403 forbidden", "http 403: forbidden"} + or ("403" in msg and "forbidden" in lowered)) + if not looks_like_registration: + return None + if _is_figma_remote_mcp(server_name, server_url): + return ( + f"'{server_name}' is Figma's remote MCP — DCR is allowlisted by exact client_name " + f"(\"{_FIGMA_DCR_CLIENT_NAME}\" and \"Codex\" work; most other names 403). Hermes defaults to " + f"client_name: {_FIGMA_DCR_CLIENT_NAME!r} automatically. If you set oauth.client_name yourself, " + f"change it to one of those, or clear it and re-run:\n hermes mcp login {server_name}") + return ( + f"'{server_name}' only allows pre-approved OAuth clients — it rejected client registration (403), so no " + "browser flow can start. Options: set oauth.client_name to a name the provider allowlists, add a " + "pre-registered client (oauth: {client_id: ..., client_secret: ...}), or use the provider's stdio / " + "API-key / local server instead.") + + +def build_oauth_auth(server_name: str, server_url: str, oauth_config: dict | None = None) -> "OAuthClientProvider | None": + """``httpx.Auth`` OAuth handler for an MCP server; None if the SDK lacks OAuth. Legacy API — new code + uses :func:`tools.mcp_oauth_manager.get_manager` so state is shared across config-time, runtime and reconnect paths.""" + global HermesOAuthClientProvider + if not _OAUTH_AVAILABLE or _sdk_class("OAuthClientProvider") is None: + logger.warning("MCP OAuth requested for '%s' but SDK auth types are not available. Install with: pip install 'mcp>=1.26.0'", server_name) + return None + from tools.mcp_oauth_provider import build_provider_kwargs, prepare_oauth_config + + cfg, storage = prepare_oauth_config(server_name, server_url, oauth_config) + if not _is_interactive() and not storage.has_cached_tokens(): + raise OAuthNonInteractiveError( + f"MCP OAuth for '{server_name}': non-interactive environment and no cached tokens found. The OAuth flow " + f"requires browser authorization. Run `hermes mcp login {server_name}` interactively first to complete " + "initial authorization, then cached tokens will be reused.") + kwargs = build_provider_kwargs(cfg, storage, ssh_proxy_hint=True) + if HermesOAuthClientProvider is None: + from tools.mcp_oauth_provider import HermesProviderMixin + + HermesOAuthClientProvider = type("HermesOAuthClientProvider", (HermesProviderMixin, _sdk_class("OAuthClientProvider")), { + "__doc__": "SDK provider plus Hermes' token-endpoint fixes (see ``HermesProviderMixin``).", + "__module__": __name__, "_hermes_logger": logger}) + return HermesOAuthClientProvider(server_url=server_url, **kwargs) + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. +from contextlib import contextmanager # noqa: F401,E402 + +OAuthClientInformationFull: Any = None + +OAuthClientMetadata: Any = None + +OAuthClientProvider: Any = None + +OAuthMetadata: Any = None + +OAuthToken: Any = None +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/mcp_oauth_device.py b/tools/mcp_oauth_device.py new file mode 100644 index 0000000000000000000000000000000000000000..0acb847d18292aca38a997da40439474a197355a --- /dev/null +++ b/tools/mcp_oauth_device.py @@ -0,0 +1,198 @@ +"""Explicit RFC 8628 MCP login, sharing SDK discovery, client auth and token storage. + +The SDK still owns runtime requests and refresh. Device authorization is only +started by `hermes mcp login/reauth`, never a background reconnect. +""" +from __future__ import annotations + +import asyncio +import math +import sys +import time + +from mcp.shared.auth import OAuthMetadata +from pydantic import AnyHttpUrl + +DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code" + + +class DeviceOAuthMetadata(OAuthMetadata): + # RFC 8414 makes authorization_endpoint optional for grants not using it. + authorization_endpoint: AnyHttpUrl | None = None + device_authorization_endpoint: AnyHttpUrl + + +async def _discover(client, provider): + from mcp.client.auth.utils import ( + build_oauth_authorization_server_metadata_discovery_urls, + build_protected_resource_metadata_discovery_urls, + extract_resource_metadata_from_www_auth, + handle_protected_resource_response, + validate_metadata_issuer, + ) + context = provider.context + response = await client.get(context.server_url) + challenge = extract_resource_metadata_from_www_auth(response) + for url in build_protected_resource_metadata_discovery_urls(challenge, context.server_url): + response = await client.get(url) + prm = await handle_protected_resource_response(response) + if prm: + await provider._validate_resource_match(prm) + context.protected_resource_metadata = prm + context.auth_server_url = str(prm.authorization_servers[0]) + break + for url in build_oauth_authorization_server_metadata_discovery_urls(context.auth_server_url, context.server_url): + response = await client.get(url) + if response.status_code == 404: + continue + data = _payload(response, "OAuth metadata") + if not data.get("device_authorization_endpoint"): + raise RuntimeError("Server does not advertise device authorization; use --flow browser if supported") + metadata = DeviceOAuthMetadata.model_validate(data) + if context.auth_server_url: + validate_metadata_issuer(metadata, context.auth_server_url) + grants = metadata.grant_types_supported + if grants is not None and DEVICE_GRANT not in grants: + raise RuntimeError("Server does not advertise the device_code grant") + context.oauth_metadata = metadata + return + raise RuntimeError("No OAuth authorization server metadata found") + + +def _payload(response, label): + try: + data = response.json() + except ValueError: + raise RuntimeError(f"{label}: invalid JSON response") from None + if not isinstance(data, dict): + raise RuntimeError(f"{label}: expected a JSON object") + if not 200 <= response.status_code < 300: + # Descriptions and arbitrary error values may contain credentials. + raise RuntimeError(f"{label} failed (HTTP {response.status_code})") + return data + + +async def _register(client, provider, cfg): + from mcp.shared.auth import OAuthClientInformationFull + from mcp.client.auth.oauth2 import OAuthRegistrationError, check_registration_usable + + context = provider.context + metadata = context.client_metadata.model_dump(mode="json", exclude_none=True) + metadata.update(grant_types=[DEVICE_GRANT, "refresh_token"], response_types=[]) + if cfg.get("client_id"): + data = {**metadata, "client_id": cfg["client_id"]} + if cfg.get("client_secret"): + data["client_secret"] = cfg["client_secret"] + else: + endpoint = context.oauth_metadata.registration_endpoint + if not endpoint: + raise RuntimeError("Server has no registration endpoint; configure oauth.client_id (and client_secret if required)") + response = await client.post(str(endpoint), json=metadata) + data = _payload(response, "Client registration") + data["issuer"] = str(context.oauth_metadata.issuer) + context.client_info = OAuthClientInformationFull.model_validate(data) + provider._coerce_client_secret_post() + try: + check_registration_usable(context.client_info) + except OAuthRegistrationError: + raise RuntimeError("Device OAuth client has unsupported or incomplete token endpoint authentication") from None + + +def _positive_seconds(value, label): + value = float(value) + if not math.isfinite(value) or value <= 0: + raise RuntimeError(f"Device authorization has invalid {label}") + return value + + +async def _authorize(client, provider, cfg): + from tools.mcp_tool import sdk_httpx + + context = provider.context + resource = context.get_resource_url() + data = {"client_id": context.client_info.client_id, "resource": resource} + if context.client_metadata.scope: + data["scope"] = context.client_metadata.scope + data, headers = context.prepare_token_auth(data, {}) + response = await client.post(str(context.oauth_metadata.device_authorization_endpoint), data=data, headers=headers) + authorization = _payload(response, "Device authorization") + for key in ("device_code", "user_code", "verification_uri"): + if not isinstance(authorization.get(key), str) or not authorization[key]: + raise RuntimeError(f"Device authorization is missing {key}") + verification = AnyHttpUrl(authorization["verification_uri"]) + interval = _positive_seconds(authorization.get("interval", 5), "interval") + deadline = time.monotonic() + min(_positive_seconds(authorization["expires_in"], "expires_in"), + _positive_seconds(cfg.get("timeout", 300), "timeout")) + print(f"\n MCP OAuth: open {verification} on any device.\n Code: {authorization['user_code']}\n" + " Waiting for approval...\n", file=sys.stderr, flush=True) + token_data = {"client_id": context.client_info.client_id, "device_code": authorization["device_code"], + "grant_type": DEVICE_GRANT, "resource": resource} + token_data, headers = context.prepare_token_auth(token_data, {}) + httpx = sdk_httpx() + while True: + remaining = deadline - time.monotonic() + if remaining <= interval: + raise RuntimeError("Device authorization expired before approval; run login again") + await asyncio.sleep(interval) + request = provider._prepare_token_request(httpx.Request("POST", str(context.oauth_metadata.token_endpoint), + data=token_data, headers=headers)) + try: + response = await asyncio.wait_for(client.send(request), timeout=deadline - time.monotonic()) + except (TimeoutError, httpx.TimeoutException): + # RFC 8628 requires reducing polling frequency after connection timeouts. + interval *= 2 + continue + if 200 <= response.status_code < 300: + from mcp.shared.auth import OAuthToken + tokens = OAuthToken.model_validate(_payload(response, "Device token")) + if not tokens.access_token: + raise RuntimeError("Device token response has no access token") + if tokens.scope is None: + tokens.scope = context.client_metadata.scope + return tokens + try: + error = response.json().get("error") + except (ValueError, AttributeError): + error = None + if error == "authorization_pending": + continue + if error == "slow_down": + interval += 5 + continue + safe_error = error if error in {"access_denied", "expired_token"} else f"HTTP {response.status_code}" + raise RuntimeError(f"Device authorization failed: {safe_error}") + + +async def login_device(name, server_url, oauth_config): + """Authorize then commit state in the active profile; failed grants preserve old state.""" + from tools.mcp_oauth import _build_client_metadata + from tools.mcp_oauth_manager import HermesMCPOAuthProvider, get_manager + from tools.mcp_oauth_provider import prepare_oauth_config + from tools.mcp_tool import sdk_httpx + + cfg, storage = prepare_oauth_config(name, server_url, oauth_config) + # Device flow never binds a callback socket or uses the hosted browser CIMD. + cfg["_resolved_port"] = cfg.get("redirect_port", 8420) + provider = HermesMCPOAuthProvider(server_url=server_url, server_name=name, storage=storage, + client_metadata=_build_client_metadata(cfg), + token_user_agent=cfg.get("user_agent")) + httpx = sdk_httpx() + try: + async with httpx.AsyncClient(timeout=10, follow_redirects=False) as client: + await _discover(client, provider) + await _register(client, provider, cfg) + tokens = await _authorize(client, provider, cfg) + except (ValueError, TypeError, KeyError): + raise RuntimeError("Device OAuth response has invalid fields") from None + except httpx.HTTPError: + raise RuntimeError("Device OAuth network request failed") from None + # Validate the entire grant before touching disk; reuse the existing scoped store. + previous = storage.snapshot() + try: + await storage.set_client_info(provider.context.client_info) + storage.save_oauth_metadata(provider.context.oauth_metadata) + await storage.set_tokens(tokens) + except OSError: + storage.restore(previous) + raise + get_manager().evict(name) diff --git a/tools/mcp_oauth_provider.py b/tools/mcp_oauth_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..3db0f5fb4dd81b1db2ca4d376ea8d22187409c48 --- /dev/null +++ b/tools/mcp_oauth_provider.py @@ -0,0 +1,427 @@ +"""Shared ``OAuthClientProvider`` customizations for Hermes MCP OAuth. + +Two code paths build an SDK provider — ``tools.mcp_oauth.build_oauth_auth`` (legacy public +API) and ``tools.mcp_oauth_manager.MCPOAuthManager`` — and both need the same real-world +fixes and config → constructor-kwargs plumbing. This module holds that core once; the origin +modules keep their own subclass (logger name, disk-watch hooks) on top of it. +""" + +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from tools.mcp_oauth import HermesTokenStorage +logger = logging.getLogger(__name__) + + + +class _RefreshCompletedByPeer(Exception): + """Restart the SDK auth flow: a peer rotated the grant we were about to present.""" + +class HermesProviderMixin: + """Token-endpoint fixes layered over the SDK's ``OAuthClientProvider`` (must precede it in + the MRO; subclasses set ``_hermes_logger`` to keep their own logger name). + + - Supabase-style dynamic registration returns a ``client_secret`` but omits + ``token_endpoint_auth_method``; the SDK then treats the client as public and the token + endpoint rejects the exchange (looping the browser page) — coerce ``client_secret_post``. + - ``token_user_agent`` (``oauth.user_agent``) is stamped onto token-endpoint requests only + (some authorization servers/WAFs reject httpx's default). + - Any 2xx token/refresh response is accepted; token bodies never leak into errors/logs.""" + + _hermes_logger: logging.Logger = logger + + def __init__(self, *args: Any, token_user_agent: str | None = None, oauth_flow: str = "browser", **kwargs: Any): + super().__init__(*args, **kwargs) + self._hermes_oauth_flow = oauth_flow + # oauth.user_agent — stamped onto token-endpoint requests only; some authorization servers/WAFs + # reject httpx's default (#75576). + self._hermes_token_user_agent = token_user_agent + + async def _perform_authorization(self): + info = self.context.client_info + grants = getattr(info, "grant_types", None) or [] + if (getattr(self, "_hermes_oauth_flow", "browser") == "device" + or ("urn:ietf:params:oauth:grant-type:device_code" in grants and "authorization_code" not in grants)): + from tools.mcp_oauth import OAuthNonInteractiveError + raise OAuthNonInteractiveError( + "MCP device authorization requires `hermes mcp login --flow device`; " + "background reconnects cannot start a device login") + return await super()._perform_authorization() + + def _prepare_token_request(self, request): + """Stamp the configured User-Agent onto a token/refresh request.""" + ua = getattr(self, "_hermes_token_user_agent", None) # tests build via __new__ + if ua: + request.headers["User-Agent"] = ua + return request + + def _coerce_client_secret_post(self) -> None: + """Same rule as ``HermesTokenStorage._coerce_secret_auth_method``, applied to the + in-memory client info BEFORE the SDK builds a token-endpoint request from it.""" + info = self.context.client_info + if not info: + return + from mcp.shared.auth import OAuthClientInformationFull + from tools.mcp_oauth import HermesTokenStorage + data = info.model_dump(mode="json", exclude_none=True) + if HermesTokenStorage._coerce_secret_auth_method(data): + self.context.client_info = OAuthClientInformationFull.model_validate(data) + + async def _exchange_token_authorization_code(self, *args: Any, **kwargs: Any): + self._coerce_client_secret_post() + return self._prepare_token_request(await super()._exchange_token_authorization_code(*args, **kwargs)) + + # Locked descriptor while this provider owns the refresh fence; cleared by + # _hermes_release_refresh_fence. Never shared across instances. + _hermes_fence: int | None = None + + async def async_auth_flow(self, request): + """Guarantee fence release even if the auth generator is abandoned. + + The SDK drives the refresh as a generator: ``_refresh_token`` yields a + request and ``_handle_refresh_response`` consumes the response. If the + caller cancels in between (timeout, task cancellation, transport + teardown), GeneratorExit/CancelledError is raised at the yield and + ``_handle_refresh_response`` never runs. Without this wrapper the fence + file would stay locked for the life of the process and every later + refresh would fail closed -- trading a race for a deadlock. + + When a peer already rotated the grant while we waited for the fence, + ``_refresh_token`` adopts it and raises ``_RefreshCompletedByPeer``; + the SDK flow is then restarted so it re-evaluates validity and sends + the original request with the winner's access token, never POSTing + the burned refresh token. + """ + while True: + inner = super().async_auth_flow(request) + try: + sent, thrown = None, None + while True: + try: + if thrown is not None: + exc, thrown = thrown, None + out = await inner.athrow(exc) + else: + out = await inner.asend(sent) + except StopAsyncIteration: + return + except _RefreshCompletedByPeer: + break + # Full bidirectional delegation: the SDK drives this flow with + # asend(response), so `async for` would swallow the response and + # feed the inner generator None. Async generators have no + # `yield from`, hence the manual pump. + try: + sent = yield out + except GeneratorExit: + await inner.aclose() + raise + except BaseException as exc: + sent, thrown = None, exc + finally: + await self._hermes_release_refresh_fence() + + async def _refresh_token(self): + """Take the refresh fence, then build the request from the token we own. + + The fence is acquired BEFORE the final read of the refresh token and is + released only after _handle_refresh_response has persisted the + replacement, so one refresh generation is consumed by exactly one + process. See tools.mcp_oauth.acquire_refresh_fence for the interleaving this + closes. + + Holding a lock across ``yield`` in the SDK's generator-based auth flow + is safe here because the SDK already serializes the whole flow under + ``self.context.lock``: the generator is always driven to completion (or + aborted) by one task, and async_auth_flow cannot interleave two + refreshes inside one process. + """ + self._coerce_client_secret_post() + await self._hermes_acquire_refresh_fence() + try: + # Re-read under the fence: a peer may have rotated while we waited + # for it, in which case the token we were about to POST is dead. + # If disk already holds a different refresh token, the peer that held + # the fence before us won this generation; its value is the only one + # the provider will still accept, so install it even when its access + # token has already expired (the POST we build needs the new grant). + candidate = await self._hermes_rotated_candidate() + if candidate is not None: + if not self._hermes_install_disk_pair(candidate): + # Issuer binding stripped the peer's refresh token: nothing + # left to POST. Restart the flow so the SDK lands in 401 -> + # full authorization instead of raising over a dead grant. + raise _RefreshCompletedByPeer + if self._hermes_live_ttl() and self.context.is_token_valid(): + # The peer's access token is live: presenting our copy of the + # refresh token would only burn a generation on a single-use + # provider. Skip the POST and let the flow restart. + raise _RefreshCompletedByPeer + return self._prepare_token_request(await super()._refresh_token()) + except BaseException: + # Never hold the fence when no POST will follow. + await self._hermes_release_refresh_fence() + raise + + def _hermes_live_ttl(self) -> bool: + """True when the installed token is not known to be past due. + + Storage clamps a past-due token to ``expires_in == 0`` on read (see + HermesTokenStorage.get_tokens); the SDK's is_token_valid() compares + ``time.time() <= expiry`` and still reports True for that boundary, + which would make us adopt a token the server rejects immediately. + ``expires_in`` is optional in RFC 6749: None means no expiry was + issued, which the SDK treats as valid, so it counts as live here too. + """ + if self.context.current_tokens is None: + return False + exp = getattr(self.context.current_tokens, "expires_in", None) + return exp is None or int(exp) > 0 + + async def _hermes_acquire_refresh_fence(self) -> None: + """Enter the fence, or let RefreshFenceTimeout abort this attempt. + + Fails closed on purpose: a refresh we are not certain we own must not + be POSTed. A stale fence from an aborted attempt is replaced rather + than stacked, so a crashed generator cannot leak ownership. + """ + from tools.mcp_oauth import acquire_refresh_fence + + await self._hermes_release_refresh_fence() + storage = self.context.storage + tokens_path = getattr(storage, "_tokens_path", None) + if tokens_path is None: # pragma: no cover - non-Hermes storage + return + self._hermes_fence = await acquire_refresh_fence(tokens_path()) + + async def _hermes_release_refresh_fence(self) -> None: + """Release the fence if held. Idempotent and never raises.""" + from tools.mcp_oauth import release_refresh_fence + + fd, self._hermes_fence = self._hermes_fence, None + if fd is not None: + release_refresh_fence(fd) + + async def _hermes_rotated_candidate(self): + """The on-disk pair, if a peer rotated it past the one we hold. + + A candidate must carry a refresh token different from ours (same + token: disk has nothing newer) and a non-empty access token. A disk + entry with no refresh token is never adopted: its access token may + still be inside its TTL, but taking it trades an explicit reauth now + for a silent one at expiry with no way to refresh in between. + ``get_tokens`` already returns None for absent or corrupt files. + """ + stored = await self.context.storage.get_tokens() + if stored is None: + return None + current = self.context.current_tokens + stored_refresh = getattr(stored, "refresh_token", None) + if not stored_refresh or not getattr(stored, "access_token", None): + return None + if stored_refresh == getattr(current, "refresh_token", None): + return None + return stored + + def _hermes_install_disk_pair(self, tokens) -> bool: + """Publish a disk pair to the context and re-run issuer binding on it. + + Returns False when the enforcer strips the refresh token (the pair was + minted by a different issuer): there is nothing left to refresh with, + and each caller decides what that means for its own flow. + """ + self.context.current_tokens = tokens + self.context.update_token_expiry(tokens) + enforce_refresh_token_issuer(self.context) + return bool(getattr(self.context.current_tokens, "refresh_token", None)) + + async def _initialize(self) -> None: + """Load stored state, restore persisted server metadata when the SDK has none (so the issuer + check and any refresh see the discovered ``issuer``/``token_endpoint`` instead of SDK guesses), + then enforce refresh-token issuer binding.""" + await super()._initialize() + storage = self.context.storage + from tools.mcp_oauth import HermesTokenStorage + if isinstance(storage, HermesTokenStorage) and self.context.oauth_metadata is None: + meta = storage.load_oauth_metadata() + if meta is not None: + self.context.oauth_metadata = meta + enforce_refresh_token_issuer(self.context) + + async def _store_tokens(self, token_response) -> None: + self.context.current_tokens = token_response + self.context.update_token_expiry(token_response) + bind_issuer_from_context(self.context) + await self.context.storage.set_tokens(token_response) + + async def _handle_token_response(self, response): + """Accept any 2xx token response; never echo the body into errors.""" + from mcp.client.auth.oauth2 import OAuthTokenError + if not (200 <= response.status_code < 300): + raise OAuthTokenError(f"Token exchange failed ({response.status_code})") + from httpx import HTTPError + from mcp.client.auth.utils import handle_token_response_scopes + try: + token_response = await handle_token_response_scopes(response) + except (HTTPError, OAuthTokenError): + raise OAuthTokenError("Invalid token response") from None + await self._store_tokens(token_response) + + async def _handle_refresh_response(self, response) -> bool: + """Accept any 2xx refresh response; never log the body. + + Always releases the refresh fence: this is the single exit point of the + fenced section, whatever the outcome. + """ + try: + return await self._hermes_handle_refresh_response(response) + finally: + await self._hermes_release_refresh_fence() + + async def _hermes_handle_refresh_response(self, response) -> bool: + if not (200 <= response.status_code < 300): + self._hermes_logger.warning("Token refresh failed: %s", response.status_code) + # A writer outside the fence (interactive `hermes mcp login`, or a + # pre-fence Hermes sharing this HERMES_HOME) may have rotated the + # grant and persisted the replacement. Providers issuing single-use + # refresh tokens reject our stale copy with a 400. Re-read disk + # before destroying the session. + if await self._hermes_reload_tokens_after_refresh_failure(): + self._hermes_logger.info( + "Recovered a peer-rotated refresh token instead of clearing the session" + ) + return True + self.context.clear_tokens() + return False + from httpx import HTTPError + from mcp.shared.auth import OAuthToken + from pydantic import ValidationError + try: + token_response = OAuthToken.model_validate_json(await response.aread()) + except (HTTPError, ValidationError): + self._hermes_logger.warning("Invalid refresh response: %s", response.status_code) + self.context.clear_tokens() + return False + # RFC 6749 §6: a refresh response may omit refresh_token (AS does not rotate) and scope + # (unchanged). The SDK's own _handle_refresh_response carries both forward; this override + # must too, or every non-rotating refresh erases the stored refresh_token and the server + # dies at the NEXT expiry with a forced browser re-auth (#62333). + prior = self.context.current_tokens + if prior is not None: + if token_response.refresh_token is None: + token_response.refresh_token = prior.refresh_token + if token_response.scope is None: + token_response.scope = prior.scope + await self._store_tokens(token_response) + return True + + async def _hermes_reload_tokens_after_refresh_failure(self) -> bool: + """Re-read tokens from disk after a rejected refresh. + + Returns True only when disk holds a pair that is BOTH different from + the one we just failed with AND still live. That is the signature of + a writer outside the fence (an interactive ``hermes mcp login`` or a + pre-fence Hermes) having rotated the grant between our read and our + POST -- a recoverable race, not a dead credential. + + Returns False for the genuinely-expired case (nobody wrote a newer + pair), so the caller still clears state and surfaces the reauth + prompt. + """ + candidate = await self._hermes_rotated_candidate() + if candidate is None: + return False + # Publish, then restore on rejection. is_token_valid() reads the + # context rather than taking a token argument, so the candidate has + # to be installed to be tested; a losing probe must leave the context + # exactly as it found it. + previous_tokens = self.context.current_tokens + if ( + self._hermes_install_disk_pair(candidate) + and self._hermes_live_ttl() + and self.context.is_token_valid() + ): + return True + self.context.current_tokens = previous_tokens + self.context.update_token_expiry(previous_tokens) + return False + + +def _metadata_issuer(context: Any) -> str | None: + """Discovered authorization-server issuer from the SDK auth context, without trailing slash.""" + meta = getattr(context, "oauth_metadata", None) + issuer = getattr(meta, "issuer", None) if meta is not None else None + return (str(issuer).rstrip("/") or None) if issuer else None + + +def bind_issuer_from_context(context: Any) -> None: + """Record the discovered issuer so the next ``storage.set_tokens`` (exchange or refresh) carries + it. No-op when metadata is not discovered yet or storage is not Hermes'.""" + from tools.mcp_oauth import HermesTokenStorage + storage = getattr(context, "storage", None) + issuer = _metadata_issuer(context) + if isinstance(storage, HermesTokenStorage) and issuer: + storage.bind_issuer(issuer) + + +def enforce_refresh_token_issuer(context: Any) -> None: + """Refuse to reuse a refresh token minted by a different issuer. + + The authorization server discovered for an MCP server can change (DNS takeover, protected-resource + metadata edit, server migration); sending the stored refresh token to the new issuer hands it a + long-lived credential. On mismatch the refresh token is stripped (memory + disk) while an unexpired + access token stays usable; full re-authorization happens at expiry. Token files predating the field + adopt the current issuer once rather than forcing a re-login. Runs after ``_initialize`` restored + tokens + metadata, before the SDK's ``can_refresh_token()`` decision.""" + from tools.mcp_oauth import HermesTokenStorage + storage = getattr(context, "storage", None) + tokens = getattr(context, "current_tokens", None) + if not isinstance(storage, HermesTokenStorage) or tokens is None or not getattr(tokens, "refresh_token", None): + return + current = _metadata_issuer(context) + if current is None: # not discovered yet; the SDK's 401-branch discovery + _store_tokens stamp it later + return + stored = (storage.loaded_issuer or "").rstrip("/") or None + if stored is None: + storage.stamp_issuer(current) + return + if stored != current: + logger.warning("MCP OAuth: authorization server issuer changed (%s -> %s); dropping the stored " + "refresh token rather than sending it to a different issuer", stored, current) + storage.strip_refresh_token() + tokens.refresh_token = None + + +def prepare_oauth_config(server_name: str, server_url: str, oauth_config: dict | None) -> tuple[dict, "HermesTokenStorage"]: + """Copy the ``oauth:`` block, apply provider defaults, open its token storage. The copy + matters: later steps record ``_resolved_port`` / ``_cimd_url`` in the dict, which must + never leak back into the caller's config.""" + from tools import mcp_oauth as mo + cfg = dict(oauth_config or {}) + mo.apply_oauth_provider_defaults(cfg, server_name=server_name, server_url=server_url) + return cfg, mo.HermesTokenStorage(server_name) + + +def build_provider_kwargs(cfg: dict, storage: "HermesTokenStorage", *, ssh_proxy_hint: bool) -> dict[str, Any]: + """Resolve the callback port and return the shared provider constructor kwargs. Order + matters: metadata needs the resolved port, pre-registration needs the metadata. + ``ssh_proxy_hint`` lets the redirect handler tailor its remote-session hint to a configured + proxy ``redirect_uri``. Helpers are looked up on ``tools.mcp_oauth`` so tests can patch them.""" + from tools import mcp_oauth as mo + port = mo._configure_callback_port(cfg, storage) + client_metadata = mo._build_client_metadata(cfg) + mo._maybe_preregister_client(storage, cfg, client_metadata) + redirect_uri = (cfg.get("redirect_uri") or None) if ssh_proxy_hint else None + return { + "client_metadata": client_metadata, + "storage": storage, + "redirect_handler": mo._make_redirect_handler(port, redirect_uri=redirect_uri), + # mcp 2.0 dropped OAuthClientProvider's own `timeout`; the configured + # `oauth.timeout` bounds the callback waiter's poll loop instead. + "callback_handler": mo._make_callback_waiter(port, cfg.get("_cimd_url"), timeout=float(cfg.get("timeout", 300))), + "token_user_agent": mo.token_request_user_agent(cfg), + "oauth_flow": cfg.get("flow", "browser"), + **mo.cimd_provider_kwargs(cfg)} diff --git a/tools/mcp_schema_cache.py b/tools/mcp_schema_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..98e150edb17d9d07f30df65242a49aae1ef0d1bf --- /dev/null +++ b/tools/mcp_schema_cache.py @@ -0,0 +1,126 @@ +"""Persistent MCP tool-schema cache for lazy server startup: per-server tool manifests on +disk so Hermes can register MCP tools into the agent snapshot without spawning the stdio +child at idle dashboard startup. Entries are keyed by server name + a fingerprint of the +connection config (command/args/url/tools filters).""" + +from __future__ import annotations + +import hashlib +import json +import logging +import threading +import time +from pathlib import Path +from typing import Any, Dict, List, Optional + +logger = logging.getLogger(__name__) + +_CACHE_FILENAME = "mcp_schema_cache.json" +_cache_lock = threading.Lock() + + +def _cache_path() -> Path: + from hermes_constants import get_hermes_home + return get_hermes_home() / "cache" / _CACHE_FILENAME + + +def config_fingerprint(config: dict) -> str: + """Stable hash of the connection-defining parts of an MCP server config.""" + tools_filter = config.get("tools") or {} + payload = { + "command": config.get("command"), + "args": config.get("args") or [], + "url": config.get("url"), + "transport": config.get("transport"), + "tools_include": sorted(tools_filter.get("include") or []), + "tools_exclude": sorted(tools_filter.get("exclude") or [])} + raw = json.dumps(payload, sort_keys=True, separators=(",", ":")) + return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16] + + +def _load_all() -> Dict[str, Any]: + path = _cache_path() + if not path.exists(): + return {} + try: + data = json.loads(path.read_text(encoding="utf-8")) + return data if isinstance(data, dict) else {} + except Exception as exc: + logger.debug("Could not read MCP schema cache %s: %s", path, exc) + return {} + + +def _save_all(data: Dict[str, Any]) -> None: + from utils import atomic_json_write + # 0o600: the cache file is trusted input on the lazy registration path, keep it user-only. + atomic_json_write(_cache_path(), data, mode=0o600) + + +def get_cached_entry(server_name: str, fingerprint: str) -> Optional[dict]: + """Return cached entry when fingerprint matches (and TTL holds), else None. ``tools/list`` + results may carry ``ttlMs`` (SEP-2549); an entry older than a recorded TTL is a miss so the + next startup re-probes instead of serving a stale manifest forever. Entries without a TTL + never expire. ``cacheScope`` is irrelevant: this cache is per-user local disk.""" + with _cache_lock: + entry = _load_all().get(server_name) + if not isinstance(entry, dict) or entry.get("fingerprint") != fingerprint: + return None + ttl_ms = entry.get("ttl_ms") + written_at = entry.get("written_at") + expired = (isinstance(ttl_ms, (int, float)) and isinstance(written_at, (int, float)) + and (time.time() - written_at) * 1000.0 >= float(ttl_ms)) + return None if expired else entry + + +def write_cache_entry(server_name: str, fingerprint: str, *, tools: List[dict], + utility_tools: Optional[List[dict]] = None, ttl_ms: Optional[float] = None, + cache_scope: Optional[str] = None) -> None: + """Persist tool schemas after a successful live connect. ``ttl_ms`` / ``cache_scope`` are + the server's ``tools/list`` SEP-2549 hints; ``written_at`` anchors TTL expiry.""" + entry = {"fingerprint": fingerprint, "tools": tools, "utility_tools": utility_tools or []} + if isinstance(ttl_ms, (int, float)): + entry["ttl_ms"] = ttl_ms + entry["written_at"] = time.time() + if cache_scope: + entry["cache_scope"] = cache_scope + with _cache_lock: + data = _load_all() + # Write-through fires on every registration (reconnects, list_changed); skip the + # rewrite when the entry is byte-identical on disk. TTL'd entries always rewrite: + # written_at must advance or the entry would expire at its ORIGINAL write time. + if "written_at" not in entry and data.get(server_name) == entry: + return + data[server_name] = entry + _save_all(data) + + +def _list_field(entry: dict, key: str) -> List[dict]: + value = entry.get(key) + return list(value) if isinstance(value, list) else [] + + +def tools_from_cache_entry(entry: dict) -> List[dict]: + """Return cached MCP tool dicts (name, description, inputSchema).""" + return _list_field(entry, "tools") + + +def utility_tools_from_cache_entry(entry: dict) -> List[dict]: + """Return cached ``{schema, handler_key}`` utility rows.""" + return _list_field(entry, "utility_tools") + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. + +def clear_cache_entry(server_name: str) -> None: + with _cache_lock: + data = _load_all() + if server_name in data: + del data[server_name] + _save_all(data) + +def has_cached_entry(server_name: str, fingerprint: str) -> bool: + return get_cached_entry(server_name, fingerprint) is not None +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/mcp_tool_agent.py b/tools/mcp_tool_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..5e8af44da0be15a5642e77c244bd1fdc2bf695f5 --- /dev/null +++ b/tools/mcp_tool_agent.py @@ -0,0 +1,265 @@ +"""Live-agent tool-list maintenance after MCP (re)discovery: refreshing an +AIAgent's tools/tool names, preserving the cached tools[] prefix across rebuilds, +and re-injecting post-build tools.""" + +import logging +import json +import threading +from typing import Optional +from tools.mcp_tool_common import _core + +logger = logging.getLogger("tools.mcp_tool") + +# Serializes in-place swaps of ``agent.tools`` / ``agent.valid_tool_names`` by +# the reload RPC, gateway reload and late-binding refresh thread; the run loop +# reads them during tool iteration and must never see a half-updated pair. +_agent_tools_lock = threading.Lock() + + +def _def_name(tool_def: dict) -> str: + return (tool_def.get("function") or {}).get("name", "") + + +def _agent_tool_defs(agent) -> list: + return list(getattr(agent, "tools", None) or []) + + +def agent_tool_names(agent) -> list: + """Names of ``agent.tools`` in wire order (unnamed entries skipped).""" + return [name for name in map(_def_name, _agent_tool_defs(agent)) if name] + + +def _resolve_refresh_toolsets(agent, enabled_override, disabled_override): + """Explicit reloads pass freshly-resolved toolsets (so a server just ENABLED in config is + picked up) and the agent's selection is updated to match; automatic paths pass nothing + and reuse the build-time selection.""" + enabled = getattr(agent, "enabled_toolsets", None) + disabled = getattr(agent, "disabled_toolsets", None) + if enabled_override is not None or disabled_override is not None: + enabled = enabled_override if enabled_override is not None else enabled + disabled = disabled_override if disabled_override is not None else disabled + agent.enabled_toolsets, agent.disabled_toolsets = enabled, disabled + return enabled, disabled + + +def _tool_defs_content_changed(agent, new_defs: list) -> bool: + """Byte-level diff of the serialized tool arrays (dynamic schemas change CONTENT under + stable names); False if either side fails to serialize.""" + try: + dump = lambda defs: json.dumps(defs, sort_keys=True, separators=(",", ":"), default=str) # noqa: E731 + return dump(_agent_tool_defs(agent)) != dump(new_defs) + except Exception: # noqa: BLE001 + return False + + +def _publish_tool_snapshot( + agent, new_defs: list, new_names: set, *, snapshot_generation: int, + staged_engine_names: set, content_aware: bool, prefix_registered: Optional[set]) -> Optional[set]: + """Single atomic read-diff-publish under ``_agent_tools_lock`` so ``added`` matches what + was published and a stale (older-generation) rebuild can't overwrite a newer one. Returns + the added names, or None when nothing was published (unchanged, or a newer snapshot won).""" + with _agent_tools_lock: + # Tolerate an agent that never set the generation (or a non-int mock). + published_gen = getattr(agent, "_tool_snapshot_generation", -1) + published_gen = published_gen if isinstance(published_gen, int) else -1 + if snapshot_generation < published_gen: + return None # a newer snapshot already won + current_defs = _agent_tool_defs(agent) + current = {_def_name(t) for t in current_defs} + if prefix_registered is not None: + new_defs, new_names = _merge_preserving_prefix(current_defs, new_defs, prefix_registered) + # Record the generation even when unchanged so an in-flight older caller can't clobber. + agent._tool_snapshot_generation = max(published_gen, snapshot_generation) + # Same NAME set: no change for MCP-reload callers. Content-aware callers + # (compaction boundary) also diff serialized bytes. + if new_names == current and not (content_aware and _tool_defs_content_changed(agent, new_defs)): + return None + agent.tools = new_defs + agent.valid_tool_names = new_names + # Publish context-engine routing names atomically with the snapshot. + engine_names = getattr(agent, "_context_engine_tool_names", None) + if isinstance(engine_names, set): + engine_names.clear() + engine_names.update(staged_engine_names) + return new_names - current + + +def refresh_agent_mcp_tools( + agent, *, enabled_override=None, disabled_override=None, quiet_mode: bool = True, + content_aware: bool = False, preserve_prefix: bool = False) -> set: + """Re-derive an already-built agent's tool snapshot from the live registry; returns the + newly-added tool names (empty when unchanged). The agent snapshots ``agent.tools`` at build + time, so servers that connect later (slow OAuth, ``/reload-mcp``) are invisible until + rebuilt. Shared by the TUI RPC, gateway reload, late-binding thread and between-turns + refresh: respects the toolset filter, diffs by tool NAME (a count compare misses an + equal-size swap), re-injects the memory-provider / context-engine tools ``agent_init`` + appends after ``get_tool_definitions`` plus guarded session capabilities, and publishes + ``(tools, valid_tool_names)`` together. + + ``preserve_prefix``: for rebuilds inside a live conversation the tool array is a cached + request prefix and any moved byte re-prefills the whole history — existing tools keep their + slot (schemas still refresh), a still-registered tool whose ``check_fn`` merely flapped is + carried forward (``check_fn`` gates exposure, never invocation), a deregistered tool is + dropped, new tools append at the tail. The caller owns the prompt-cache contract.""" + from model_tools import get_tool_definitions + from tools.registry import registry + enabled, disabled = _resolve_refresh_toolsets(agent, enabled_override, disabled_override) + # Generation captured BEFORE the slow get_tool_definitions call (a slower caller holding an + # OLDER set must not clobber a newer one); definitions computed OUTSIDE the lock. + snapshot_generation = registry._generation + new_defs = list(get_tool_definitions(enabled_toolsets=enabled, disabled_toolsets=disabled, quiet_mode=quiet_mode) or []) + new_names = {_def_name(t) for t in new_defs} + # Post-build families re-appended on LOCALS only; live attributes untouched until publish. + staged_engine_names = _reinject_post_build_tools(agent, new_defs, new_names) + _reinject_authorized_dynamic_tools(agent, new_defs, new_names) + # Registry membership is read OUTSIDE ``_agent_tools_lock``: taking ``registry._lock`` + # under the tools lock would be the first nesting of the two. + prefix_registered: Optional[set] = None + if preserve_prefix: + try: + prefix_registered = {entry.name for entry in registry.get_all_entries()} + except Exception: # noqa: BLE001 + pass # fail open to the plain rebuild + added = _publish_tool_snapshot( + agent, new_defs, new_names, snapshot_generation=snapshot_generation, + staged_engine_names=staged_engine_names, content_aware=content_aware, prefix_registered=prefix_registered) + if added is None: + return set() + persist_agent_tool_names(agent) # re-pin so a rebuild after agent-cache eviction restores this order + return added + + +def reprobe_tool_availability() -> None: + """Explicit ``/reload-mcp`` hatch out of the tools[] freeze: drop the ``check_fn`` verdict + cache AND the ``get_tool_definitions`` memo (keyed on registry generation, so it would + otherwise replay the stale verdicts).""" + from model_tools import _clear_tool_defs_cache + from tools.registry import invalidate_check_fn_cache + invalidate_check_fn_cache() + _clear_tool_defs_cache() + + +def persist_agent_tool_names(agent) -> None: + """Best-effort: write ``agent.tools`` names to the session row (freeze pin).""" + db = getattr(agent, "_session_db", None) + session_id = getattr(agent, "session_id", None) + if not db or not session_id: + return + try: + db.update_session_tool_names(session_id, [_def_name(t) for t in _agent_tool_defs(agent)]) + except Exception: # noqa: BLE001 + logger.debug("tool_names persist skipped", exc_info=True) + + +def restore_agent_tool_prefix(agent, saved_names: list) -> bool: + """Fold a freshly built agent's ``tools`` onto the session's saved order; True if changed. + After agent-cache eviction the gateway rebuilds a NEW AIAgent with no predecessor to + preserve, so the saved name list stands in (``_merge_preserving_prefix`` rule; a saved + tool still registered but failing its probe is carried forward from the registry schema).""" + if not saved_names: + return False + from tools.registry import registry + fresh_defs = _agent_tool_defs(agent) + fresh = {_def_name(t): t for t in fresh_defs} + + def _saved_def(name): + if name in fresh: + return fresh[name] + entry = registry.get_entry(name) + return None if entry is None else {"type": "function", "function": {**entry.schema, "name": entry.name}} + + saved_defs = [d for d in map(_saved_def, saved_names) if d is not None] + registered_names = {entry.name for entry in registry.get_all_entries()} + merged, merged_names = _merge_preserving_prefix(saved_defs, fresh_defs, registered_names) + _reinject_authorized_dynamic_tools(agent, merged, merged_names) + with _agent_tools_lock: + if merged == fresh_defs: + return False + agent.tools = merged + agent.valid_tool_names = merged_names + if [_def_name(t) for t in merged] != list(saved_names): + persist_agent_tool_names(agent) + return True + + +def _merge_preserving_prefix(current_defs: list, new_defs: list, registered_names: set) -> tuple[list, set]: + """Fold a fresh tool snapshot into a live one without moving existing bytes. Ordered by + ``current_defs`` (the cached request prefix): a name in both keeps its slot but takes the + fresh schema; a name only in the live list is kept if still registered (``check_fn`` + flapped), else dropped; a name only in the fresh list is appended at the tail. + + The bridge tools keep their BUILT entry, not the fresh one: ``tool_search``'s description + is derived from the session (deferred count, listing, whether ``manage_connections`` was + present), so a late MCP server or a ``check_fn`` flap would rewrite it every turn. Search + reads the live catalog at dispatch, so the stale count costs nothing.""" + from tools.tool_search_catalog import BRIDGE_TOOL_NAMES + fresh = {_def_name(entry): entry for entry in new_defs if _def_name(entry)} + merged = [] + for entry in current_defs: + name = _def_name(entry) + replacement = fresh.pop(name, None) + if name in BRIDGE_TOOL_NAMES: + merged.append(entry) + elif replacement is not None: + merged.append(replacement) + elif name and name in registered_names: + merged.append(entry) + merged.extend(fresh.values()) + return merged, {_def_name(t) for t in merged} + + +def _reinject_authorized_dynamic_tools(agent, tools_list: list, name_set: set) -> None: + """``message_agent`` is injected by an auth gate, never registered, so a registry-derived + rebuild drops it. Scrub any stale copy from the STAGED pair and re-add it only when the live + gate re-authorizes, so the publisher exposes a coherent ``(tools, valid_tool_names)``.""" + from tools.bot_mode_dm import MESSAGE_AGENT_TOOL_NAME, message_agent_authorized, message_agent_tool_schema + + tools_list[:] = [entry for entry in tools_list if _def_name(entry) != MESSAGE_AGENT_TOOL_NAME] + name_set.discard(MESSAGE_AGENT_TOOL_NAME) + if message_agent_authorized(agent): + tools_list.append(message_agent_tool_schema()) + name_set.add(MESSAGE_AGENT_TOOL_NAME) + + +def _reinject_post_build_tools(agent, tools_list: list, name_set: set) -> set: + """Append memory-provider and context-engine tools onto the caller's staged ``tools_list`` + / ``name_set`` (never the live agent attributes), mirroring ``agent_init``'s post-build + injection. Idempotent and fail-soft. Returns the context-engine routing names THIS rebuild + appended: a name already owned by a registry/plugin tool is not claimed, matching agent_init.""" + def _add(schema) -> bool: + name = schema.get("name", "") if isinstance(schema, dict) else "" + if not name or name in name_set: + return False + tools_list.append({"type": "function", "function": schema}) + name_set.add(name) + return True + + def _schema_getter(attr: str, method: str): + getter = getattr(getattr(agent, attr, None) or None, method, None) + return getter if callable(getter) else None + + enabled = getattr(agent, "enabled_toolsets", None) + try: + get_mem_schemas = _schema_getter("_memory_manager", "get_all_tool_schemas") + if get_mem_schemas is not None: + from agent.memory_manager import memory_provider_tools_enabled # same gate inject_memory_provider_tools uses + if memory_provider_tools_enabled( + enabled, getattr(agent, "disabled_toolsets", None), memory_tool_present="memory" in name_set): + for schema in get_mem_schemas(): + _add(schema) + except Exception: + logger.debug("Memory-provider tool re-injection skipped", exc_info=True) + + # The `context_engine` toolset is intentionally empty, so lcm_* tools exist only via this + # append. Honor the enabled_toolsets gate agent_init uses, or a restricted-toolset platform + # would re-leak tools the build excluded. + # See #5544. + staged_engine_names: set = set() + try: + get_schemas = _schema_getter("context_compressor", "get_tool_schemas") + if (enabled is None or "context_engine" in enabled) and get_schemas is not None: + # Claim the routing name only when WE appended the schema. + staged_engine_names.update(s["name"] for s in get_schemas() if _add(s)) + except Exception: + logger.debug("Context-engine tool re-injection skipped", exc_info=True) + return staged_engine_names diff --git a/tools/mcp_tool_discovery.py b/tools/mcp_tool_discovery.py new file mode 100644 index 0000000000000000000000000000000000000000..8a0429c2a7d4b6447a4dc74a616cb88da2799aca --- /dev/null +++ b/tools/mcp_tool_discovery.py @@ -0,0 +1,620 @@ +"""Connecting and discovery for tools.mcp_tool: per-server connect cooldown, connect / +lazy-start / recycled-stdio wake-up, ``register_mcp_servers`` / ``discover_mcp_tools`` and +the status / probe public API. Origin state (``_servers``, ``_lock``, the loop, patchable +helpers) is read through ``_core`` so ``mock.patch("tools.mcp_tool.X")`` keeps working.""" + +from __future__ import annotations + +import asyncio +import logging +import time +from typing import Dict, List, Optional, Tuple +from tools.mcp_tool_common import _core, _parse_boolish +from tools import mcp_tool_config as _config +from tools import mcp_tool_errors as _errors +from tools import mcp_tool_lifecycle as _lifecycle +from tools import mcp_tool_loop as _loop +from tools import mcp_tool_registration as _registration +from tools.mcp_tool_schema import MCP_TOOL_NAME_PREFIX +from tools.mcp_tool_scope import _key_name, _key_scope, _resolve_server_key, _server_key + +logger = logging.getLogger("tools.mcp_tool") + + +def _record_connect_failure(server_name: str) -> None: + """Stamp a geometric, capped retry cooldown after a failed connect (under ``_lock``).""" + key = _server_key(server_name) + n = _core._server_connect_failures.get(key, 0) + 1 + _core._server_connect_failures[key] = n + backoff = min(_core._CONNECT_RETRY_BASE_BACKOFF_SEC * (2 ** (n - 1)), _core._CONNECT_RETRY_MAX_BACKOFF_SEC) + _core._server_connect_retry_after[key] = time.monotonic() + backoff + + +def _clear_connect_failure(server_name: str) -> None: + """Clear the connect-cooldown state after a successful connection.""" + key = _server_key(server_name) + _core._server_connect_failures.pop(key, None) + _core._server_connect_retry_after.pop(key, None) + + +def _connect_cooldown_active(server_name: str) -> bool: + """True if ``server_name`` is still within its retry cooldown (this scope's connection: one + profile's failing ``x`` must not shadow another profile's healthy ``x``).""" + deadline = _core._server_connect_retry_after.get(_server_key(server_name)) + return deadline is not None and time.monotonic() < deadline + + +def _enabled(cfg: dict) -> bool: + return _parse_boolish(cfg.get("enabled", True), default=True) + + +async def _connect_server(name: str, config: dict) -> _core.MCPServerTask: + """Create an MCPServerTask, start it, return once ready (tear down with ``server.shutdown()`` + on the same loop). Raises on bad config, missing HTTP support or connect failure.""" + server = _core.MCPServerTask(name) + claim = _core._connect_server_claim.get() + if claim is not None: + claim(server) + # The run task copies this context: don't retain the discovery closure for its life. + claim_token = _core._connect_server_claim.set(None) if claim is not None else None + try: + await server.start(config) + except asyncio.CancelledError: + raise # start() already reaps server._task; shutdown() here could swallow the cancel + except BaseException: + # Discovery owns claimed tasks (recoverable park); standalone probes must reap locally. + if claim is None: + try: + await server.shutdown() + except Exception as shutdown_exc: # noqa: BLE001 -- best-effort reap, don't mask the real error + logger.debug("MCP server '%s' shutdown during orphan-reap failed: %s", name, shutdown_exc) + raise + finally: + if claim_token is not None: + _core._connect_server_claim.reset(claim_token) + return server + + +def _request_lazy_reconnect(server_name: str, server: _core.MCPServerTask) -> bool: + """Wake a recycled stdio server and wait briefly for a fresh session.""" + loop = _loop._running_loop() if server._is_recycled_stdio() else None + if loop is None: + return False + + def _wake() -> None: + server._ready.clear() + server._reconnect_event.set() + + loop.call_soon_threadsafe(_wake) + + async def _await_ready() -> bool: + deadline = time.monotonic() + _core._RECYCLED_RECONNECT_TIMEOUT + while time.monotonic() < deadline: + if server.session is not None and server._ready.is_set(): + return True + await asyncio.sleep(0.05) + return False + + try: + return bool(_loop._run_on_mcp_loop(_await_ready, timeout=_core._RECYCLED_RECONNECT_TIMEOUT)) + except Exception as exc: + logger.warning("MCP server '%s': lazy reconnect after stdio recycle failed: %s", server_name, exc) + return False + + +def _resolve_server_lazy(name: str, config: dict) -> bool: + """True when ``mcp_servers..lazy`` defers connect to first tool use (default off). + + Gated per-server by ``mcp_servers..lazy`` in config (default OFF), following the same per-server + key pattern as ``idle_timeout_seconds``. Design from #56832 (Vansh5632). + """ + return _parse_boolish(config.get("lazy", False), default=False) + + +def _note_connect_failure(name: str, exc: BaseException) -> str: + """Record a failed connect (under ``_lock``): error text for status, cooldown stamp.""" + message = _errors._format_connect_error(exc) + with _core._lock: + key = _server_key(name) + _core._server_connecting.discard(key) + _core._server_connect_errors[key] = message + _record_connect_failure(name) + return message + + +def _note_connect_success(name: str) -> None: + """Clear connecting/error/cooldown state after a successful connect (under ``_lock``).""" + with _core._lock: + key = _server_key(name) + _core._server_connecting.discard(key) + _core._server_connect_errors.pop(key, None) + _clear_connect_failure(name) + + +def _adopt_server(name: str, server: _core.MCPServerTask) -> None: + """Publish *server* into ``_servers`` under the connecting scope's key (under ``_lock``).""" + with _core._lock: + key = _server_key(name) + _core._servers[key] = server + _core._server_scope_keys[key] = _core._mcp_registry_scope() + + +def _ensure_lazy_server_connected(server_name: str) -> bool: + """Connect a lazily-registered server on demand (sync; blocks). Honours the cooldown and the + ``_server_connecting`` dedup set; routes through ``_discover_and_register_server`` so + park/recycle/cooldown bookkeeping stays in one place. True when a live session exists. + + See #50394. + """ + with _core._lock: + key = _resolve_server_key(server_name) + server = _core._servers.get(key) + if server is not None and server.session is not None: + return True + config = _core._lazy_server_configs.get(key) + if (not config or _connect_cooldown_active(server_name) + or key in _core._server_connecting): + return False + _core._server_connecting.add(key) + _core._server_connect_errors.pop(key, None) + logger.info("MCP server '%s': lazy start on first use", server_name) + _loop._ensure_mcp_loop() + connect_timeout = config.get("connect_timeout", _core._DEFAULT_CONNECT_TIMEOUT) + try: + _loop._run_on_mcp_loop(lambda: _discover_and_register_server(server_name, config), + timeout=float(connect_timeout) + 30.0) + except BaseException as exc: + logger.warning("Lazy MCP connect failed for '%s': %s", server_name, _note_connect_failure(server_name, exc)) + return False + _note_connect_success(server_name) + with _core._lock: + _core._lazy_server_configs.pop(key, None) + stale_fingerprint = _core._lazy_server_fingerprints.pop(key, None) + cached_names = _core._lazy_server_tool_names.pop(key, None) or [] + server = _core._servers.get(key) + live_names = set(getattr(server, "_registered_tool_names", []) or []) + # The cached manifest may advertise tools the live server no longer serves. + phantom_names = [n for n in cached_names if n not in live_names] + if phantom_names: + for tool_name in phantom_names: + _registration._deregister_mcp_tool_all_scopes(key, tool_name) + logger.info("MCP server '%s': deregistered %d phantom cached tool(s) not served live (stale schema-cache " + "fingerprint %s): %s", server_name, len(phantom_names), stale_fingerprint, ", ".join(phantom_names)) + return server is not None and server.session is not None + + +def _get_connected_server_for_call(server_name: str) -> Optional[_core.MCPServerTask]: + """Return a connected server; the single first-use connect point for lazy servers and + the wake-up point for recycled stdio ones. + + Also the single first-use connect point for lazy (schema-cache registered) servers, so raw tool calls + AND the resource/prompt utility handlers all trigger the deferred spawn (#56832). + """ + with _core._lock: + key = _resolve_server_key(server_name) + server = _core._servers.get(key) + is_lazy = key in _core._lazy_server_configs + if is_lazy and (server is None or server.session is None): + _ensure_lazy_server_connected(server_name) + elif server is not None and server.session is None and server._is_recycled_stdio(): + _request_lazy_reconnect(server_name, server) + else: + return server + with _core._lock: + return _core._servers.get(key) + + +async def _discover_and_register_server(name: str, config: dict) -> List[str]: + """Connect one server, register its tools; return the registered names.""" + # The claim fires inside _connect_server while this frame is suspended (list, not nonlocal). + claimed: List[_core.MCPServerTask] = [] + claim_token = _core._connect_server_claim.set(claimed.append) + try: + server = await asyncio.wait_for(_connect_server(name, config), + timeout=config.get("connect_timeout", _core._DEFAULT_CONNECT_TIMEOUT)) + except BaseException: + server = claimed[0] if claimed else None + task = server._task if server is not None else None + task_cancelling = task.cancelling() if task is not None and hasattr(task, "cancelling") else 0 + if (server is not None and server._error is not None and task is not None + and not task.done() and not task_cancelling): + # Recoverable park: the run task self-probes, so adopt it for shutdown/revival. + _adopt_server(name, server) + elif server is not None: + await server.shutdown() + raise + finally: + _core._connect_server_claim.reset(claim_token) + with _core._lock: + key = _server_key(name) + _core._server_connecting.discard(key) + _core._server_connect_errors.pop(key, None) + _adopt_server(name, server) + registered_names = _registration._register_server_tools(name, server, config) + server._registered_tool_names = list(registered_names) + logger.info("MCP server '%s' (%s): registered %d tool(s): %s", name, + "HTTP" if "url" in config else "stdio", len(registered_names), ", ".join(registered_names)) + return registered_names + + +def _select_new_servers(servers: Dict[str, dict]) -> Dict[str, dict]: + """Pick connect candidates (enabled, not connected/connecting/lazy, not in backoff) and + refresh per-server bookkeeping. Known servers without a live session are parked or + mid-reconnect with tools deregistered, so nothing else can nudge them: signal a reconnect.""" + with _core._lock: + current_scope = _core._mcp_registry_scope() + # This scope's own connections OR shared ones it adopted (``register_connected_into_current_scope`` + # ran first): a same-named server owned by ANOTHER profile with other credentials is not + # "connected" for us and must be a candidate, or this profile ends up silently tool-less. + keys = {k: _resolve_server_key(k, current_scope, current=False) for k in servers} + # Only attempt servers that aren't already connected (or currently connecting) and are enabled. + # Checking ``_server_connecting`` prevents duplicate subprocess spawns when ``discover_mcp_tools()`` + # is called from multiple entry-points before the first batch finishes (#58862). + new_servers = { + k: v for k, v in servers.items() + if keys[k] not in _core._servers and keys[k] not in _core._server_connecting + and keys[k] not in _core._lazy_server_configs + and _enabled(v) and not _connect_cooldown_active(k)} + stale_cached = [_core._servers[keys[k]] for k, v in servers.items() + if keys[k] in _core._servers and _enabled(v) + and getattr(_core._servers[keys[k]], "session", None) is None] + for srv_name in new_servers: + _core._server_connecting.add(keys[srv_name]) + _core._server_scope_keys[keys[srv_name]] = current_scope + _core._server_connect_errors.pop(keys[srv_name], None) + # Track which servers opt-in to parallel tool calls (idempotent). Keyed by THIS profile's own + # key: the opt-in is the calling profile's policy, so B's parallel-safe `x` never makes A's + # same-named serial `x` (own connection or adopted) run two calls at once. + for srv_name, srv_cfg in servers.items(): + own_key = _server_key(srv_name, current_scope, current=False) + if _parse_boolish(srv_cfg.get("supports_parallel_tool_calls", False), default=False): + _core._parallel_safe_servers.add(own_key) + else: + _core._parallel_safe_servers.discard(own_key) + for srv in stale_cached: + _loop._signal_reconnect(srv) + return new_servers + + +def _register_lazy_from_cache(new_servers: Dict[str, dict]) -> Tuple[Dict[str, dict], int, int]: + """Register ``lazy: true`` servers from a valid schema-cache entry without connecting + (missing/stale entry or failed registration -> eager). Returns (eager servers, lazy tool + count, lazy server count).""" + # A missing or stale cache entry falls back to the normal eager connect below (which write-through + # refreshes the cache for next time). See #56832. + eager_servers: Dict[str, dict] = dict(new_servers) + lazy_registered = 0 + lazy_server_count = 0 + try: + from tools.mcp_schema_cache import config_fingerprint, get_cached_entry + except Exception: # pragma: no cover - cache module missing + return eager_servers, 0, 0 + for name, cfg in new_servers.items(): + if not _resolve_server_lazy(name, cfg): + continue + entry = get_cached_entry(name, config_fingerprint(cfg)) + if not entry: + continue + with _core._lock: + _core._server_connecting.discard(_server_key(name)) + try: + names = _registration._register_from_cache_sync(name, cfg, entry) + except Exception as exc: + logger.warning("Failed lazy MCP registration for '%s': %s", name, exc) + with _core._lock: + _core._server_connecting.add(_server_key(name)) + continue + eager_servers.pop(name, None) + lazy_registered += len(names) + lazy_server_count += 1 + return eager_servers, lazy_registered, lazy_server_count + + +async def _discover_all(new_servers: Dict[str, dict]) -> None: + """Connect every candidate concurrently; record per-server outcome.""" + results = await asyncio.gather( + *(_discover_and_register_server(name, cfg) for name, cfg in new_servers.items()), + return_exceptions=True) + for name, result in zip(new_servers, results): + if isinstance(result, BaseException): + command = new_servers.get(name, {}).get("command") + message = _note_connect_failure(name, result) + logger.warning("Failed to connect to MCP server '%s'%s: %s", + name, f" (command={command})" if command else "", message) + else: + _note_connect_success(name) + + +def _run_discovery_pass(new_servers: Dict[str, dict]) -> None: + """Run ``_discover_all`` on the MCP loop with the interrupt flag parked; clean up + ``_server_connecting`` when the pass dies early.""" + # Executor threads are reused: a prior session's stale interrupt must not cancel this pass. + from tools.interrupt import is_interrupted as _is_interrupted, set_interrupt as _set_interrupt + _was_interrupted = _is_interrupted() + if _was_interrupted: + _set_interrupt(False) + try: + _loop._run_on_mcp_loop(lambda: _discover_all(new_servers), timeout=120) + except (TimeoutError, InterruptedError) as _e: + # Stranded _server_connecting entries would block future reconnects. + how = "timed out" if isinstance(_e, TimeoutError) else "interrupted" + with _core._lock: + stale = [n for n in new_servers if _server_key(n) in _core._server_connecting] + if stale: + logger.warning("MCP discovery %s while %d server(s) were still connecting; clearing stale " + "connecting set: %s", how, len(stale), ", ".join(stale)) + for _sn in stale: + _core._server_connecting.discard(_server_key(_sn)) + _core._server_connect_errors.setdefault( + _server_key(_sn), f"Connection attempt {how} during discovery") + raise + finally: + if _was_interrupted: + _set_interrupt(True) + + +def _connected_summary(names, *, lazy_tools: int = 0, lazy_servers: int = 0) -> Tuple[int, int, int]: + """(tool count, connected count, failed count) for candidate names, plus lazy servers.""" + with _core._lock: + keys = {n: _server_key(n) for n in names} + connected = [n for n in names + if keys[n] in _core._servers and keys[n] not in _core._server_connect_errors] + tool_count = sum(len(getattr(_core._servers[keys[n]], "_registered_tool_names", [])) for n in connected) + failed = len(names) - len(connected) + return tool_count + lazy_tools, len(connected) + lazy_servers, failed + + +def _log_summary(prefix: str, names, **lazy) -> None: + """Log `` N tool(s) from M server(s) (K failed)`` when anything happened.""" + new_tool_count, connected_count, failed = _connected_summary(names, **lazy) + if new_tool_count or failed: + summary = f"{prefix} {new_tool_count} tool(s) from {connected_count} server(s)" + if failed: + summary += f" ({failed} failed)" + logger.info(summary) + + +def register_mcp_servers(servers: Dict[str, dict]) -> List[str]: + """Connect ``{name: config}`` servers and register their tools; idempotent for connected + names, ``enabled: false`` skipped without disconnecting. Returns every MCP tool name.""" + if not _core._ensure_mcp_sdk(): + logger.debug("MCP SDK not available -- skipping explicit MCP registration") + return [] + servers = _config._filter_suspicious_mcp_servers(servers) + try: + return _register_mcp_servers(servers) + finally: + # An owner's scoped reload orphaned adopters of its shared connections: now that this + # pass (its rediscovery) is done, give them their tools back under their own scope. + _lifecycle._reregister_orphaned_adopters() + + +def _register_mcp_servers(servers: Dict[str, dict]) -> List[str]: + scoped_healed = _registration.register_connected_into_current_scope(servers) + if not servers: + logger.debug("No explicit MCP servers provided") + return _registration._existing_tool_names() if _core._mcp_registry_scope() is not None else [] + new_servers = _select_new_servers(servers) + if scoped_healed: + logger.info("MCP: registered %d already-connected server(s) into this profile scope", scoped_healed) + if not new_servers: + return _registration._existing_tool_names() + new_servers, lazy_registered, lazy_server_count = _register_lazy_from_cache(new_servers) + if not new_servers: + if lazy_registered: + logger.info("MCP: registered %d lazy tool(s) from schema cache (no processes spawned)", + lazy_registered) + return _registration._existing_tool_names() + _loop._ensure_mcp_loop() + _run_discovery_pass(new_servers) + _log_summary("MCP: registered", new_servers, lazy_tools=lazy_registered, lazy_servers=lazy_server_count) + return _registration._existing_tool_names() + + +def _acquire_discovery_lock_with_retry(): + """Cross-process guard: a lock loser waits for the holder then discovers itself; unavailable + locking or an expired wait runs unguarded (fail-soft). None / _LOCK_UNAVAILABLE = unguarded.""" + cookie = _loop._try_acquire_mcp_discovery_lock() + if cookie is not None: + return cookie + logger.debug("Another process holds MCP discovery lock -- retrying with backoff") + for _ in range(_core._MCP_DISCOVERY_LOCK_MAX_RETRIES): + time.sleep(_core._MCP_DISCOVERY_LOCK_RETRY_DELAY_S) + cookie = _loop._try_acquire_mcp_discovery_lock() + if cookie is not None: + break + # Cross-process discovery guard (#62771). A lock loser waits for the holder, then performs its own + # process-local discovery. If locking is unavailable or the bounded wait expires, preserve the previous + # fail-soft behavior by running discovery unguarded. + if cookie is None: + logger.warning("MCP discovery lock still held after %d retries -- running discovery unguarded", + _core._MCP_DISCOVERY_LOCK_MAX_RETRIES) + elif cookie is not _core._LOCK_UNAVAILABLE: + logger.debug("Retry succeeded -- acquired MCP discovery lock") + return cookie + + +def discover_mcp_tools(allowed_mcp_names: Optional[List[str]] = None) -> List[str]: + """Entry point: load config, connect servers, register tools. [] without the ``mcp`` + package; idempotent (only servers missing from a previous call are retried). + + ``allowed_mcp_names``: spawn only the MCP servers named in it (built-in toolset names in the + list simply don't match); ``None`` spawns every configured server. Used by + ``hermes -z -t `` to skip cold-starting servers the caller doesn't need (10-60s + each); it only affects which servers start, not which names ``-t`` validation can see.""" + servers = _config._load_mcp_config() + if not servers: + logger.debug("No MCP servers configured") + return [] + if allowed_mcp_names is not None: + allowed_set = {str(n) for n in allowed_mcp_names} + filtered = {name: cfg for name, cfg in servers.items() if name in allowed_set} + if len(filtered) != len(servers): + logger.debug("MCP discovery filter: spawning %d/%d configured server(s) per --toolsets filter " + "(skipped: %s)", len(filtered), len(servers), ",".join(sorted(set(servers) - set(filtered)))) + servers = filtered + if not servers: + logger.debug("No MCP servers in --toolsets filter; skipping MCP load entirely") + return [] + # SDK import deferred to here so a config without servers — or a -t filter that keeps + # none — never pays it. + if not _core._ensure_mcp_sdk(): + logger.debug("MCP SDK not available -- skipping MCP tool discovery") + return [] + cookie = _acquire_discovery_lock_with_retry() + try: + with _core._lock: + keys = {name: _resolve_server_key(name) for name in servers} + new_server_names = [name for name, cfg in servers.items() + if keys[name] not in _core._servers and keys[name] not in _core._server_connecting + and _enabled(cfg)] + tool_names = register_mcp_servers(servers) + if new_server_names: + _log_summary(" MCP:", new_server_names) + return tool_names + finally: + if cookie not in (None, _core._LOCK_UNAVAILABLE): + cookie.release() + + +def reconcile_mcp_servers_with_config() -> Dict[str, List[str]]: + """Bring the live server set in step with ``mcp_servers`` as it is on disk NOW: tear down + servers that were removed from config or set ``enabled: false`` (a parked server keeps + self-probing forever otherwise — for hours after the user deleted its entry), then connect + anything newly configured via :func:`discover_mcp_tools`. Scoped to the current registry + scope (one multiplexed profile's config prunes only its own connections). A lazily registered + (schema-cache) server loses its cached tools; one still mid-connect cannot be torn down yet and + is reported under ``"pending"`` so the caller retries. Returns + ``{"removed": [...], "added": [...], "pending": [...]}``; a no-op when nothing changed.""" + servers = _config._load_mcp_config() + wanted = {name for name, cfg in servers.items() if _enabled(cfg)} + scope = _core._mcp_registry_scope() + with _core._lock: + owned = [key for key, owner in _core._server_scope_keys.items() if owner == scope] + live = {_key_name(key) for key in owned if key in _core._servers} + connecting = {_key_name(key) for key in owned if key in _core._server_connecting} + lazy = {key for key in _core._lazy_server_configs + if _key_scope(key) == scope and _key_name(key) not in wanted} + stale = sorted(live - wanted) + if stale: + logger.info("MCP server(s) %s no longer in config (or disabled); disconnecting", ", ".join(stale)) + _lifecycle.shutdown_mcp_servers(scope=scope, names=set(stale)) + for key in lazy: + _forget_lazy_server(key) + with _core._lock: + known = {_key_name(key) for key, owner in _core._server_scope_keys.items() + if owner == scope and (key in _core._servers or key in _core._server_connecting)} + known |= {_key_name(key) for key in _core._lazy_server_configs} + added = sorted(wanted - known) + if added: + discover_mcp_tools() + return {"removed": stale + sorted(_key_name(k) for k in lazy), "added": added, + "pending": sorted(connecting - wanted)} + + +def _forget_lazy_server(key) -> None: + """Drop a schema-cache (lazy) registration whose config entry is gone: its cached tools would + otherwise stay callable and spawn the server on first use.""" + with _core._lock: + _core._lazy_server_configs.pop(key, None) + _core._lazy_server_fingerprints.pop(key, None) + cached_names = _core._lazy_server_tool_names.pop(key, None) or [] + for tool_name in cached_names: + _registration._deregister_mcp_tool_all_scopes(key, tool_name) + + +def is_mcp_tool_parallel_safe(tool_name: str) -> bool: + """True when the tool's server opted into ``supports_parallel_tool_calls`` (provenance + captured at registration, never the ambiguous ``mcp__{server}__{tool}`` shape).""" + if not tool_name.startswith(MCP_TOOL_NAME_PREFIX): + return False + with _core._lock: + server_name = _core._mcp_tool_server_names.get(tool_name) + return bool(server_name and _server_key(server_name) in _core._parallel_safe_servers) + + +def get_mcp_status(configured: Optional[Dict[str, dict]] = None, *, include_runtime: bool = True) -> List[dict]: + """Per-server status dicts for banner/TUI: name, transport, tools, connected, disabled, + status (connected / disabled / connecting / failed / configured) and error for failed. + Reads cached runtime state only; never connects.""" + configured = _config._load_mcp_config() if configured is None else dict(configured) + if not configured: + return [] + current_scope = _core._mcp_registry_scope() + with _core._lock: + def visible(key) -> bool: + # Runtime state belongs to the profile that adopted it; under a multiplexer only that + # profile's view may show it, and ``include_runtime=False`` hides the launch profile's + # servers from a status read scoped to a different profile. + return include_runtime and _core._server_visible_in_scope(key, current_scope) + + active_servers = {_key_name(k): s for k, s in _core._servers.items() if visible(k)} + connecting = {_key_name(k) for k in _core._server_connecting if visible(k)} + connect_errors = {_key_name(k): e for k, e in _core._server_connect_errors.items() if visible(k)} + + result: List[dict] = [] + for name, cfg in configured.items(): + enabled = _enabled(cfg) # evaluated unconditionally: malformed values warn even when connected + server = active_servers.get(name) + live = server is not None and server.session is not None + status = ("connected" if live else "disabled" if not enabled else "connecting" if name in connecting + else "failed" if name in connect_errors else "configured") + entry = {"name": name, "transport": cfg.get("transport", "http") if "url" in cfg else "stdio", + "tools": 0, "connected": False, "disabled": status == "disabled", "status": status} + if live: + entry["connected"] = True + entry["tools"] = (len(server._registered_tool_names) if hasattr(server, "_registered_tool_names") + else len(server._tools)) + if server._sampling: + entry["sampling"] = dict(server._sampling.metrics) + elif status == "failed": + entry["error"] = connect_errors[name] + result.append(entry) + return result + + +def probe_mcp_server_tools() -> Dict[str, List[tuple]]: + """Connect each enabled server, list ``(tool_name, description)``, disconnect; nothing is + registered and failed servers are omitted.""" + if not _core._ensure_mcp_sdk(): + return {} + enabled = {k: v for k, v in (_config._load_mcp_config() or {}).items() if _enabled(v)} + if not enabled: + return {} + _loop._ensure_mcp_loop() + result: Dict[str, List[tuple]] = {} + probed_servers: List[_core.MCPServerTask] = [] + + async def _probe_all(): + coros = [asyncio.wait_for(_connect_server(name, cfg), + timeout=cfg.get("connect_timeout", _core._DEFAULT_CONNECT_TIMEOUT)) + for name, cfg in enabled.items()] + outcomes = await asyncio.gather(*coros, return_exceptions=True) + for name, outcome in zip(enabled, outcomes): + if isinstance(outcome, Exception): + logger.debug("Probe: failed to connect to '%s': %s", name, outcome) + continue + probed_servers.append(outcome) + result[name] = [(t.name, getattr(t, "description", "") or "") for t in outcome._tools] + await asyncio.gather(*(s.shutdown() for s in probed_servers), return_exceptions=True) + + try: + _loop._run_on_mcp_loop(_probe_all, timeout=120) + except Exception as exc: + logger.debug("MCP probe failed: %s", exc) + finally: + _lifecycle._stop_mcp_loop_if_idle() + return result + + +def has_registered_mcp_tools() -> bool: + """True if any MCP server has registered TOOLS (not merely connected), so the per-turn + refresh hook stays idle for zero-tool servers.""" + with _core._lock: + return bool(_core._mcp_tool_server_names) + + +def get_registered_mcp_server_names() -> set: + """Server names that registered at least one tool (live, filtered — not config.yaml).""" + with _core._lock: + return set(_core._mcp_tool_server_names.values()) diff --git a/tools/mcp_tool_errors.py b/tools/mcp_tool_errors.py new file mode 100644 index 0000000000000000000000000000000000000000..13167317e552260bd774f833406ef72aeb244239 --- /dev/null +++ b/tools/mcp_tool_errors.py @@ -0,0 +1,411 @@ +"""MCP connection/transport error classification: URL validation, TLS client certs, identity +headers, redirect header stripping, exception-group unwrapping, auth/session-expired/ +method-not-found detection and connect-error formatting. Split from tools/mcp_tool.py.""" + +import asyncio +import contextlib +import errno +import importlib +import logging +import os +import re +from typing import Any, List, Optional +from urllib.parse import urlparse +from tools.mcp_tool_common import _sanitize_error, _core + +logger = logging.getLogger("tools.mcp_tool") + +# Stateless (2026-07-28) servers reject a legacy ``initialize`` with this or plain method-not-found. +_JSONRPC_UNSUPPORTED_PROTOCOL_VERSION = -32022 + + +def _jsonrpc_matches(exc: BaseException, codes: tuple, markers: tuple, code=None) -> bool: + """Structural ``MCPError.error.code`` (or *code*) in *codes*, else any *marker* in ``str(exc).lower()``. Never + ``isinstance`` on SDK exception types: they arrive wrapped in ExceptionGroups and drift across generations.""" + code = getattr(getattr(exc, "error", None), "code", None) or code + return code in codes or any(marker in str(exc).lower() for marker in markers) + + +def _handshake_rejected_as_modern(exc: BaseException) -> bool: + """True when a failed ``initialize`` signals a stateless-only (2026-07-28) server.""" + return _jsonrpc_matches( + exc, (_JSONRPC_UNSUPPORTED_PROTOCOL_VERSION, _core._JSONRPC_METHOD_NOT_FOUND), + ("unsupported protocol version", str(_JSONRPC_UNSUPPORTED_PROTOCOL_VERSION)), + code=getattr(exc, "code", None)) or _is_method_not_found_error(exc) + + +def _is_method_not_found_error(exc: BaseException) -> bool: + """True if *exc* is a JSON-RPC ``method not found`` (-32601; ``ping`` is optional in MCP). The + substring fallback includes "Unknown method: " — without it the ping→list_tools keepalive + fallback never latches and reconnect-loops. + + The substring fallback matters when a server reports method-not-found without a structural ``-32601`` + code (e.g. surfaced as a plain exception string). Besides the canonical "method not found", many + JSON-RPC implementations phrase it as "Unknown method: " — agentmemory's MCP server is one such + case (#50028). + """ + return _jsonrpc_matches( + exc, (_core._JSONRPC_METHOD_NOT_FOUND,), + (str(_core._JSONRPC_METHOD_NOT_FOUND), "method not found", "unknown method", "not found: ping")) + + +class InvalidMcpUrlError(ValueError): + """A remote MCP server's ``url`` is not parseable http(s):// — validated once at startup to fail fast. + + Validated once at startup so we fail fast with a clear message instead of burning through the + reconnect-backoff loop on every attempt. (Ported from anomalyco/opencode#25019.) + """ + + +class NonMcpEndpointError(ConnectionError): + """An HTTP MCP URL served a non-MCP 2xx (e.g. ``text/html``). Non-retryable: every attempt gets + the same page, so backoff is skipped and the server fails immediately. Subclasses ConnectionError + so broad catches still see a connection problem.""" + + +# Streamable-HTTP rejection statuses an SSE-only server (or its load balancer) produces for the +# chunked ``initialize`` POST: Bad Request, Method Not Allowed, Not Acceptable, Length Required. +_STREAMABLE_REJECT_STATUSES = (400, 405, 406, 411) + + +def _is_streamable_http_rejection(exc: BaseException) -> bool: + """True when a Streamable-HTTP connect failure looks like a transport mismatch rather than a + broken server: a 400-family rejection of the initialize POST, or the SDK's opaque INTERNAL_ERROR + (-32603 ``Server returned an error response``) it maps such rejections to on mcp >= 2.0 (error + class per PR #104363, @RohithPariki). Timeouts and auth errors never qualify — neither carries + these markers — so a slow or 401ing server is not retried on the wrong transport. + """ + root = _unwrap_exception_group(exc) + if getattr(getattr(root, "response", None), "status_code", None) in _STREAMABLE_REJECT_STATUSES: + return True + code = getattr(getattr(root, "error", None), "code", None) + return code == -32603 and "server returned an error response" in str(root).lower() + + +def _unwrap_exception_group(exc: BaseException) -> BaseException: + """Root-cause leaf of anyio ``(Base)ExceptionGroup`` wrappers (group ``str()`` is opaque). A + ``KeyboardInterrupt``/``SystemExit`` leaf anywhere is re-raised, never flattened into a loggable + error; a non-cancellation leaf is preferred over the ``CancelledError`` noise anyio sprays on siblings.""" + while isinstance(exc, BaseExceptionGroup) and exc.exceptions: + leaf: BaseException = exc.split((KeyboardInterrupt, SystemExit))[0] + if leaf is not None: + while isinstance(leaf, BaseExceptionGroup) and leaf.exceptions: + leaf = leaf.exceptions[0] + raise leaf + exc = next((sub for sub in exc.exceptions if not _contains_only_cancellation(sub)), exc.exceptions[0]) + return exc + + +def _contains_only_cancellation(exc: BaseException) -> bool: + """True if ``exc`` is (or a group containing only) CancelledError.""" + if isinstance(exc, BaseExceptionGroup): + return all(_contains_only_cancellation(sub) for sub in exc.exceptions) + return isinstance(exc, asyncio.CancelledError) + + +def _classify_mcp_failure(exc: BaseException) -> str: + """``'permanent'`` (``run()`` parks instead of burning the retry ladder: auth 401/403, + NonMcpEndpointError, InvalidMcpUrlError, missing stdio command) or ``'transient'`` (backoff retry).""" + root = _unwrap_exception_group(exc) + permanent = (_is_auth_error(root) + or isinstance(root, (NonMcpEndpointError, InvalidMcpUrlError, FileNotFoundError)) + or (isinstance(root, OSError) and getattr(root, "errno", None) == errno.ENOENT) + # 401/403 HTTPStatusError that _is_auth_error's type-gate missed (auth types not importable here) + or getattr(getattr(root, "response", None), "status_code", None) in (401, 403)) + return "permanent" if permanent else "transient" + + +def _validate_remote_mcp_url(server_name: str, url: Any) -> str: + """The stripped URL if valid http(s); else InvalidMcpUrlError naming the server (non-string, other scheme — + stdio servers use ``command`` — or empty host).""" + def _bad(detail: str) -> InvalidMcpUrlError: + return InvalidMcpUrlError(f"Invalid MCP URL for '{server_name}': {detail}") + if not isinstance(url, str): + raise _bad(f"expected a string, got {type(url).__name__}") + stripped = url.strip() + if not stripped: + raise _bad("empty url") + try: + parsed = urlparse(stripped) + except Exception as exc: # urlparse is very permissive — belt and braces + raise _bad(f"{stripped!r} ({exc})") from exc + if parsed.scheme.lower() not in {"http", "https"}: + raise _bad(f"scheme must be http or https, got {parsed.scheme!r} ({stripped!r})") + if not parsed.netloc: + raise _bad(f"missing host ({stripped!r})") + if not parsed.hostname: # ``urlparse`` accepts ``http://:8080`` (empty host, explicit port) + raise _bad(f"missing hostname ({stripped!r})") + return stripped + + +def _resolve_client_cert(server_name: str, config: dict): + """``client_cert`` / ``client_key`` in httpx's ``cert=`` shape: None, a combined-PEM path, + ``(cert, key)`` or ``(cert, key, password)``. ``~`` is expanded; missing files raise a + server-scoped FileNotFoundError instead of an opaque TLS handshake error.""" + raw_cert = config.get("client_cert") + raw_key = config.get("client_key") + if raw_cert is None and raw_key is None: + return None + prefix = f"MCP server '{server_name}': " + + def _expand(path: Any, label: str) -> str: + if not isinstance(path, str) or not path.strip(): + raise ValueError(f"{prefix}{label} must be a non-empty string path (got {type(path).__name__})") + expanded = os.path.expanduser(path.strip()) + if not os.path.isfile(expanded): + raise FileNotFoundError(f"{prefix}{label} not found at {expanded!r}") + return expanded + if not isinstance(raw_cert, (list, tuple)): + cert_path = _expand(raw_cert, "client_cert") + return (cert_path, _expand(raw_key, "client_key")) if raw_key is not None else cert_path # combined PEM + if raw_key is not None: + raise ValueError(f"{prefix}specify either client_cert as a list [cert, key] OR client_cert + client_key, not both") + if len(raw_cert) not in (2, 3): + raise ValueError(f"{prefix}client_cert list form must have 2 or 3 elements (got {len(raw_cert)})") + pair = (_expand(raw_cert[0], "client_cert[0]"), _expand(raw_cert[1], "client_cert[1]")) + if len(raw_cert) == 2: + return pair + if not isinstance(raw_cert[2], str): + raise ValueError(f"{prefix}client_cert[2] (key passphrase) must be a string") + return (*pair, raw_cert[2]) + + +def _resolve_identity_header(server_name: str, config: dict): + """``identity_header`` ``{name, value_from: "static"|"profile", value}`` → ``(name, value)`` or + None. Invalid configs warn and are ignored — an identity header must never break the connection. + ``profile`` resolves once at connect time.""" + raw = config.get("identity_header") + if raw is None: + return None + + def _ignore(detail: str, *args): + logger.warning("MCP server '%s': identity_header " + detail + " — ignoring", server_name, *args) + return None + if not isinstance(raw, dict): + return _ignore("must be a mapping with 'name' and 'value'/'value_from' keys (got %s)", type(raw).__name__) + name = raw.get("name") + if not isinstance(name, str) or not name.strip(): + return _ignore("requires a non-empty 'name'") + value_from = (raw.get("value_from") or "static").strip().lower() + if value_from == "profile": + from hermes_cli.profiles import get_active_profile_name + return (name.strip(), get_active_profile_name()) + if value_from != "static": + return _ignore("value_from must be 'static' or 'profile' (got %r)", value_from) + value = raw.get("value") + if not isinstance(value, str) or not value.strip(): + return _ignore("with value_from: static requires a non-empty string 'value'") + return (name.strip(), value) + + +def _apply_identity_header(server_name: str, config: dict, headers: dict) -> dict: + """Merge the identity header into ``headers`` in place; an explicit entry of the same name (any + casing) wins — never silently override user config.""" + name, value = _resolve_identity_header(server_name, config) or (None, None) + if name is None: + return headers + if any(key.lower() == name.lower() for key in headers): + logger.debug("MCP server '%s': identity_header '%s' already set via explicit " + "headers config — keeping the explicit value", server_name, name) + else: + headers[name] = value + return headers + + +def _make_redirect_header_stripper(original_url, *, strict: bool = False, + configured_header_names: "set[str] | frozenset[str]" = frozenset()): + """httpx response hook: strips ``Authorization`` when a redirect leaves the original origin; + with *strict* (Agent Plugins v1 ``strict_redirect_headers``) every configured header (lowercase + names in *configured_header_names*) is stripped too — v1 forbids forwarding them cross-origin.""" + origin = (original_url.scheme, original_url.host, original_url.port) + + async def _strip_on_cross_origin_redirect(response): + target = response.next_request.url if response.is_redirect and response.next_request else None + if target is None or (target.scheme, target.host, target.port) == origin: + return + headers = response.next_request.headers + headers.pop("authorization", None) + headers.pop("Authorization", None) + for _name in configured_header_names if strict else (): + while _name in headers: + del headers[_name] + return _strip_on_cross_origin_redirect + + +# Wire-body cap, applied at the httpx transport before the SDK buffers/JSON-parses a response. A +# hostile or misbehaving remote MCP server can stream an unbounded catalog/tool-result body and none +# of the post-parse limits (resource cap, tool-result truncation) run before the parse blows up. +# Finite HTTP bodies are capped at this many bytes (a larger Content-Length is rejected up front); +# each SSE *event* is capped, with the counter reset at completed event boundaries so a long-lived +# stream and its keepalives have no cumulative limit. Violations raise the SDK httpx's ReadError and +# flow through the ordinary transport teardown/reconnect path (#66092). +_MCP_HTTP_MAX_BODY_BYTES = 10 * 1024 * 1024 +_SSE_EVENT_BOUNDARIES = (b"\n\n", b"\r\n\r\n") + + +def _make_mcp_body_cap_transport(httpx_mod, inner_transport, limit: int = _MCP_HTTP_MAX_BODY_BYTES): + """Wrap ``inner_transport`` so every response body is size-capped. ``httpx_mod`` must be the SDK's + own httpx module (``sdk_httpx()``): the transport is handed to that SDK's ``AsyncClient``.""" + + class _CappedStream(httpx_mod.AsyncByteStream): + def __init__(self, inner, is_sse: bool, url: str): + self._inner, self._is_sse, self._url = inner, is_sse, url + + def _reject(self, kind: str): + return httpx_mod.ReadError(f"MCP {kind} exceeds {limit} bytes (from {self._url})") + + async def __aiter__(self): + counted = 0 + async for chunk in self._inner: + if self._is_sse: + # Bytes up to the last completed event boundary belong to finished events (they must + # still fit the per-event cap together with the carried prefix); the remainder starts + # the next event's budget. + boundary_end = max(chunk.rfind(sep) + len(sep) if sep in chunk else -1 for sep in _SSE_EVENT_BOUNDARIES) + if boundary_end != -1: + if counted + boundary_end > limit: + raise self._reject("SSE event") + counted = len(chunk) - boundary_end + else: + counted += len(chunk) + else: + counted += len(chunk) + if counted > limit: + raise self._reject("SSE event" if self._is_sse else "HTTP response") + yield chunk + + async def aclose(self): + await self._inner.aclose() + + class _BodyCapTransport(httpx_mod.AsyncBaseTransport): + def __init__(self, inner): + self._inner = inner + + async def handle_async_request(self, request): + response = await self._inner.handle_async_request(request) + declared = response.headers.get("content-length") + with contextlib.suppress(ValueError): # malformed header: the streamed cap still applies + if declared is not None and int(declared) > limit: + await response.aclose() + raise httpx_mod.ReadError(f"MCP HTTP response declares Content-Length {declared} > {limit} " + f"bytes cap (from {request.url})") + is_sse = "text/event-stream" in response.headers.get("content-type", "").lower() + response.stream = _CappedStream(response.stream, is_sse, str(request.url)) + return response + + async def aclose(self): + await self._inner.aclose() + + return _BodyCapTransport(inner_transport) + + +def _exc_children(exc: BaseException) -> List[BaseException]: + """Sub-exceptions of a group, else ``__cause__``/``__context__`` when they are exceptions.""" + nested = getattr(exc, "exceptions", None) + return list(nested) if nested else [c for c in (exc.__cause__, exc.__context__) if isinstance(c, BaseException)] + + +def _format_connect_error(exc: BaseException) -> str: + """Render nested MCP connection errors into an actionable short message.""" + def _find_missing(current: BaseException) -> Optional[str]: + if isinstance(current, FileNotFoundError): + if getattr(current, "filename", None): + return str(current.filename) + match = re.search(r"No such file or directory: '([^']+)'", str(current)) + if match: + return match.group(1) + return next(filter(None, map(_find_missing, _exc_children(current))), None) + + def _flatten_messages(current: BaseException) -> List[str]: + # A group's own str() is opaque — only its children speak. + text = "" if getattr(current, "exceptions", None) else str(current).strip() + messages = ([text] if text else []) + [m for child in _exc_children(current) for m in _flatten_messages(child)] + return messages or [current.__class__.__name__] + missing = _find_missing(exc) + if not missing: + return _sanitize_error("; ".join(list(dict.fromkeys(_flatten_messages(exc)))[:3])) + message = f"missing executable '{missing}'" + if os.path.basename(missing) in {"npx", "npm", "node"}: + message += (" (ensure Node.js is installed and PATH includes its bin directory, " + "or set mcp_servers..command to an absolute path and include " + "that directory in mcp_servers..env.PATH)") + return _sanitize_error(message) + + +def _optional_types(module: str, *names: str) -> list: + """``[module.name, ...]`` or ``[]`` when the module/attribute is unavailable.""" + try: + mod = importlib.import_module(module) + return [getattr(mod, name) for name in names] + except (ImportError, AttributeError): + return [] + + +# Lazily-built ``(auth_types, http_status_types)`` so this module imports without the SDK OAuth module. +_AUTH_ERROR_TYPES: Optional[tuple] = None + + +def _get_auth_error_types() -> tuple: + """Cached ``(auth_types, http_status_types)``: SDK ``OAuthFlowError``/``OAuthTokenError`` (+ legacy + ``UnauthorizedError``), our ``OAuthNonInteractiveError``, and ``HTTPStatusError`` from both httpx + flavours — a 401 may come from the SDK's own stack (``httpx2`` on mcp >= 2.0) or Hermes' pinned + ``httpx``; the classes are unrelated and still need the 401 check in :func:`_is_auth_error`.""" + global _AUTH_ERROR_TYPES + if not (_AUTH_ERROR_TYPES and _AUTH_ERROR_TYPES[0]): # retry while empty (SDK may import later) + sdk_mod = _core.sdk_httpx() + http_types = tuple(dict.fromkeys( + ([sdk_mod.HTTPStatusError] if sdk_mod is not None else []) + _optional_types("httpx", "HTTPStatusError"))) + auth_types = (*_optional_types("mcp.client.auth", "OAuthFlowError", "OAuthTokenError"), + *_optional_types("mcp.client.auth", "UnauthorizedError"), # older SDKs + *_optional_types("tools.mcp_oauth", "OAuthNonInteractiveError"), *http_types) + _AUTH_ERROR_TYPES = (auth_types, http_types) + return _AUTH_ERROR_TYPES + + +def _is_auth_error(exc: BaseException) -> bool: + """True if ``exc`` indicates an MCP OAuth failure; ``HTTPStatusError`` counts only with status 401.""" + auth_types, http_types = _get_auth_error_types() + if not isinstance(exc, auth_types): + return False + return getattr(exc.response, "status_code", None) == 401 if isinstance(exc, http_types) else True + + +# Lower-cased substrings meaning the transport session expired / was GC'd (OAuth token still valid). +# Substrings (lower-cased match) that indicate the MCP server rejected the request because its server-side +# transport session expired / was garbage-collected. See #13383. +_SESSION_EXPIRED_MARKERS: tuple = ( + "invalid or expired session", "expired session", "session expired", "session not found", + "unknown session", "session terminated", "closedresourceerror", "closed resource", + "transport is closed", "connection closed", "broken pipe", "end of file") + +# Node budget for ``_is_session_expired_error`` (the visited set breaks cycles; this bounds acyclic blow-ups). +# Well above ``sys.getrecursionlimit()`` so deep task-group nesting is fully scanned. +_EXC_TRAVERSAL_MAX_NODES = 10_000 + + +def _is_session_expired_error(exc: BaseException) -> bool: + """True if ``exc`` looks like a transport session expiry (Streamable-HTTP servers GC session state on idle TTL / + restart / pod rotation while the OAuth token stays valid) — the fix is a transport reconnect, not an OAuth + refresh. Iterative walk over ``exceptions`` / ``__cause__`` / ``__context__`` with a visited set AND a node + budget; every reachable node is inspected so an InterruptedError anywhere overrides transport markers, and the + chain walk matters because SDK wrappers raise a generic RuntimeError *from* a message-less ClosedResourceError.""" + # AnyIO stream exceptions are often message-less, so type checks complement marker matching. + transport_error_types = tuple(_optional_types("anyio", "BrokenResourceError", "ClosedResourceError", "EndOfStream")) + stack: "list[BaseException | None]" = [exc] + seen: set[int] = set() + found = False + budget = _EXC_TRAVERSAL_MAX_NODES + while stack and budget > 0: + current = stack.pop() + if current is None or id(current) in seen: + continue + seen.add(id(current)) + budget -= 1 + if isinstance(current, InterruptedError): + return False + # Messages vary across SDK versions/servers: a narrow allow-list of stable substrings avoids false positives. + msg = str(current).lower() + found = found or isinstance(current, transport_error_types) or any(m in msg for m in _SESSION_EXPIRED_MARKERS) + stack.extend((*getattr(current, "exceptions", ()), getattr(current, "__cause__", None), + getattr(current, "__context__", None))) + return found diff --git a/tools/mcp_tool_handlers.py b/tools/mcp_tool_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..e8df28d9a929b694a59008cd33dce776ee490a37 --- /dev/null +++ b/tools/mcp_tool_handlers.py @@ -0,0 +1,618 @@ +"""Registry-facing sync handlers for MCP tools and utility tools (resources/prompts), plus the per-call recovery +ladder: trust gating, circuit breaker, auth (401) refresh, session-expired reconnect and dead-stdio respawn retry.""" + +import logging +import asyncio +import contextvars +import inspect +import json +import time +from contextlib import asynccontextmanager +from types import SimpleNamespace +from typing import Any, Callable, Dict, List, Optional, Tuple +from tools.registry import tool_error +from tools.ansi_strip import strip_unicode_tags +from tools.mcp_tool_common import _exc_str, _sanitize_error, mcp_field, _core +from tools import mcp_tool_loop as _loop +from tools.mcp_tool_content import ( + _MCP_HARD_RESULT_CAP_CHARS, _cache_mcp_audio_block, _cache_mcp_image_block, + _render_mcp_dropped_block_notice, _render_mcp_resource_block, _strip_reserved_meta_keys, + _truncate_mcp_text_result) +from tools.mcp_tool_errors import _is_auth_error, _is_session_expired_error + +logger = logging.getLogger("tools.mcp_tool") +_MISSING = object() + +_NEEDS_REAUTH_MSG = ( + "MCP server '{s}' requires re-authentication. Run `hermes mcp login {s}` (or delete the tokens file under " + "~/.hermes/mcp-tokens/ and restart). Do NOT retry this tool — ask the user to re-authenticate.") +_STDIO_NO_RESPAWN_MSG = ( + "MCP server '{s}' stdio subprocess had exited (this is not a timeout — the call never reached the server). A " + "respawn was requested but no fresh session came back within {t:.0f}s. Wait a few seconds before retrying; if it " + "keeps failing the server is not starting and needs the user.") +_STDIO_DIED_AGAIN_MSG = ( + "MCP server '{s}' respawned its stdio subprocess and it exited again immediately. The server is not starting " + "cleanly — do NOT retry this tool; ask the user to check the server's command and its stderr log.") +_STDIO_OUTCOME_UNCERTAIN_MSG = ( + "MCP server '{s}' lost its stdio subprocess after the tool call began. The operation may have completed, so " + "Hermes did not replay it. Do NOT retry automatically; inspect the external state first.") + + +def _trust_gate_check(server_name: str, tool_name: str) -> Optional[str]: + """Approval gate for write-capable tools on ``trust: untrusted`` servers. None to proceed, + else a ``tool_error``. Fail-closed: approval-system errors block.""" + from tools.mcp_tool_scope import _resolve_server_key, _server_key + # Trust is the calling profile's own policy (an adopter of a shared connection keeps its own tier); + # readOnlyHint is a property of the connection's tools, so it lives under the connection key. + trust = _core._server_trust_levels.get(_server_key(server_name), _core._TRUST_FULL) + if (trust != _core._TRUST_UNTRUSTED + or _core._tool_read_only_hints.get(_resolve_server_key(server_name), {}).get(tool_name) is True): + return None + try: # lazy: tools.approval routes the prompt to whichever surface owns the session + from tools.approval_prompt import request_elicitation_consent + answer = request_elicitation_consent( + f"MCP tool '{tool_name}' on UNTRUSTED server '{server_name}' wants to run. This tool is write-capable " + f"(no readOnlyHint=true annotation) and may modify external state.", + f"Server '{server_name}' is configured 'trust: untrusted'. " + f"Approve to run '{tool_name}' once, or deny to block it.", + surface=f"mcp-trust/{server_name}") + except Exception as exc: + logger.error("MCP trust gate: approval check failed for %s.%s: %s", server_name, tool_name, exc, exc_info=True) + return tool_error(f"MCP tool '{tool_name}' on untrusted server '{server_name}' was blocked: the approval " + f"system was unavailable (fail-closed).") + if answer == "accept": + return None + logger.info("MCP trust gate: user %s '%s' on untrusted server '%s'", + "cancelled" if answer == "cancel" else "denied", tool_name, server_name) + return tool_error(f"The user did not approve running write-capable MCP tool '{tool_name}' on untrusted server " + f"'{server_name}'. The command was NOT run. Do not retry without explicit user direction.") + + +def _check_circuit_breaker(server_name: str) -> Optional[str]: + """Open-breaker error, or None when calls may proceed. After the cooldown the breaker is + half-open: the next call probes; success resets, failure re-bumps and re-arms the cooldown.""" + from tools.mcp_tool_scope import _resolve_server_key + key = _resolve_server_key(server_name) + failures = _core._server_error_counts.get(key, 0) + age = time.monotonic() - _core._server_breaker_opened_at.get(key, 0.0) + if failures < _core._CIRCUIT_BREAKER_THRESHOLD or age >= _core._CIRCUIT_BREAKER_COOLDOWN_SEC: + return None + retry_in = max(1, int(_core._CIRCUIT_BREAKER_COOLDOWN_SEC - age)) + if _core._server_errors_all_application.get(key): + # The server answered every time; the calls were rejected. Calling it "unreachable" sent the + # model to the user instead of to its own arguments (#11113). + return tool_error(f"MCP server '{server_name}' rejected the last {failures} calls (it is reachable; see the " + f"error text those calls returned). Paused for ~{retry_in}s. Do NOT repeat the same call — " + f"fix the arguments/URL/target or use a different approach.") + return tool_error(f"MCP server '{server_name}' is unreachable after {failures} consecutive failures. " + f"Auto-retry available in ~{retry_in}s. Do NOT retry " + f"this tool yet — use alternative approaches or ask the user to check the MCP server.") + + +def _acquire_call_server(server_name: str, tool_timeout: float): + """``(server, None)`` when a call may be dispatched, else ``(None, error)``. No session: a + reconnect may be completing, so wait briefly before a breaker strike; still down -> ask the + server task to rebuild (probing a dead transport would re-arm the breaker forever).""" + from tools import mcp_tool_discovery as _discovery # lazy: discovery -> registration -> handlers cycle + not_connected = tool_error(f"MCP server '{server_name}' is not connected") + server = _discovery._get_connected_server_for_call(server_name) + wait = min(5.0, float(tool_timeout or 5.0)) + if server and (server.session or _loop._wait_for_server_session_ready(server, timeout=wait)): + return server, None + _core._bump_server_error(server_name) + if server and _loop._signal_reconnect(server): + return None, tool_error(f"MCP server '{server_name}' transport is down; reconnect requested. Do NOT retry this " + f"tool immediately — give it a few seconds to come back.") + return None, not_connected + + +def _result_is_error(result) -> bool: + """True only for a JSON payload carrying an ``error`` key (non-JSON = success).""" + try: + return "error" in json.loads(result) + except (json.JSONDecodeError, TypeError): + return False + + +def _record_call_outcome(server_name: str, result) -> Any: + """Breaker bookkeeping: an error payload from the tool itself still counts as a strike (#10447), + flagged as an application error so the open-breaker message stays truthful.""" + if _result_is_error(result): + _core._bump_server_error(server_name, application=True) + else: + _core._reset_server_error(server_name) + return result + + +def _strike(server_name: str, message: str, **extra) -> str: + """Breaker strike + the ``tool_error`` payload for *message*.""" + _core._bump_server_error(server_name) + return tool_error(message, **extra) + + +def _mcp_loop_running() -> bool: + return _core._mcp_loop is not None and _core._mcp_loop.is_running() + + +def _lookup_reconnectable_server(server_name: str, require_loop: bool = False): + """The registered server object when it can be signalled to reconnect, else None. + With *require_loop*, also None unless the MCP loop is running (nothing to wait on).""" + from tools.mcp_tool_scope import _resolve_server_key + with _core._lock: + srv = _core._servers.get(_resolve_server_key(server_name)) + ok = srv is not None and hasattr(srv, "_reconnect_event") and (_mcp_loop_running() or not require_loop) + return srv if ok else None + + +def _retry_once(server_name: str, retry_call, op_description: str, what: str): + """Re-run ``retry_call`` after a recovery step. Returns the result when the RPC completed + (an application error is still the tool's real answer, and still a breaker strike per #10447); + None when the retry raised (caller falls through).""" + try: + result = retry_call() + except Exception as retry_exc: + logger.warning("MCP %s/%s retry after %s failed: %s", server_name, op_description, what, retry_exc) + return None + return _record_call_outcome(server_name, result) + + +def _handle_auth_error_and_retry(server_name: str, exc: BaseException, retry_call, op_description: str): + """OAuth recovery + one retry; None when *exc* is not an auth error. ``handle_401`` decides + viability; if viable, signal a reconnect (fresh credentials), wait ready, retry once. Any + failure returns the structured ``needs_reauth`` error so the model stops refreshing.""" + if not _is_auth_error(exc): + return None + from tools.mcp_oauth_manager import get_manager + try: + recovered = _loop._run_on_mcp_loop(lambda: get_manager().handle_401(server_name, None), timeout=10) + except Exception as rec_exc: + logger.warning("MCP OAuth '%s': recovery attempt failed: %s", server_name, rec_exc) + recovered = False + if recovered: + srv = _lookup_reconnectable_server(server_name) + # Recovery + reconnect is independent evidence of viability: close the breaker here, not only on + # retry success (else a failing retry pins it open forever). + if srv is not None and _loop._signal_reconnect_and_wait( + server_name, srv, op_description=f"{op_description} after OAuth recovery", timeout=15): + _core._reset_server_error(server_name) + result = _retry_once(server_name, retry_call, op_description, "auth recovery") + if result is not None: + return result + return _strike(server_name, _NEEDS_REAUTH_MSG.format(s=server_name), needs_reauth=True, server=server_name) + + +def _handle_session_expired_and_retry(server_name: str, exc: BaseException, retry_call, op_description: str): + """Transport reconnect + one retry on session expiry; None to fall through. Skips + ``handle_401``: the token is valid, only the server-side session is stale. + + Unlike :func:`_handle_auth_error_and_retry`, this does **not** call the OAuth manager's ``handle_401`` — + the access token is still valid, only the server-side session state is stale. Setting + ``_reconnect_event`` causes the server task's lifecycle loop to tear down the current + ``streamablehttp_client`` + ``ClientSession`` and rebuild them, reusing the existing OAuth provider + instance. See #13383. + """ + srv = _lookup_reconnectable_server(server_name, require_loop=True) if _is_session_expired_error(exc) else None + if srv is None: + return None + logger.info("MCP server '%s': %s failed with session-expired error (%s); signalling transport reconnect " + "and retrying once.", server_name, op_description, exc) + if not _loop._signal_reconnect_and_wait(server_name, srv, op_description=op_description, timeout=15): + logger.warning("MCP server '%s': reconnect did not ready within 15s after session-expired error; " + "falling through to error response.", server_name) + return None + return _retry_once(server_name, retry_call, op_description, "session reconnect") + + +class _StdioChildExited(RuntimeError): + """Stdio subprocess gone when (or while) a call ran. Deliberately NOT a TimeoutError.""" + + def __init__(self, message: str, *, in_flight: bool): + super().__init__(message) + self.in_flight = in_flight + + +def _handle_stdio_child_exited_and_retry(server_name: str, exc: Exception, retry_call, op_description: str): + """Respawn a dead stdio child; retry once only when it was dead before dispatch. + + A mid-call exit is ambiguous: the server may have applied a side effect before its + response pipe disappeared. Reconnect for future calls but never replay that operation. + None means this is not our error. This function never spawns itself: it sets + ``_reconnect_event`` and waits, so spawn frequency stays governed by ``run()``'s rapid-drop + budget. A pre-dispatch retry whose child dies again reports and stops. + + Why retrying here cannot hot-cycle respawns: this function never spawns anything. It sets + ``_reconnect_event`` (one signal, same as before) and waits for the server task to publish a fresh + session. Spawn frequency stays governed entirely by ``run()``'s rapid-drop budget, which parks a + transport that keeps dropping without proving healthy (#62212). + """ + if not isinstance(exc, _StdioChildExited): + return None + reconnected = False + srv = _lookup_reconnectable_server(server_name) + if srv is not None: + action = "reconnecting without replay" if exc.in_flight else "respawning and retrying once" + logger.info("MCP server '%s': %s found the stdio subprocess dead (%s); %s.", + server_name, op_description, exc, action) + if _mcp_loop_running(): + reconnected = _loop._signal_reconnect_and_wait( + server_name, srv, op_description=op_description, timeout=_core._STDIO_RESPAWN_WAIT_SEC) + else: # No MCP loop to wait on (non-async adapters, tests): still request the respawn. + _loop._signal_reconnect(srv) + if exc.in_flight: + return _strike( + server_name, + _STDIO_OUTCOME_UNCERTAIN_MSG.format(s=server_name), + outcome_uncertain=True, + ) + if not reconnected: + return _strike(server_name, _STDIO_NO_RESPAWN_MSG.format(s=server_name, t=_core._STDIO_RESPAWN_WAIT_SEC)) + try: + return _record_call_outcome(server_name, retry_call()) + except _StdioChildExited as retry_exc: + # Died again right after respawn: broken server; run()'s budget takes it to the park. + logger.warning("MCP server '%s': %s stdio subprocess exited again right after respawn (%s); not retrying " + "further.", server_name, op_description, retry_exc) + if retry_exc.in_flight: + return _strike( + server_name, + _STDIO_OUTCOME_UNCERTAIN_MSG.format(s=server_name), + outcome_uncertain=True, + ) + return _strike(server_name, _STDIO_DIED_AGAIN_MSG.format(s=server_name)) + except Exception as retry_exc: + logger.warning("MCP %s/%s retry after stdio respawn failed: %s", server_name, op_description, retry_exc) + return _strike(server_name, _sanitize_error( + f"MCP call failed after respawning the stdio subprocess for '{server_name}': " + f"{type(retry_exc).__name__}: {_exc_str(retry_exc)}")) + + +def _dispatch(server_name: str, server: Any, op: str, call, tool_timeout: float, recoverers, + on_final_failure: Callable[[BaseException], None], record_outcome: bool = False) -> str: + """Mark the call started on *server* (doubles may lack ``mark_tool_call``), run coroutine function *call* + on the MCP loop and, on failure, walk ``recoverers`` (``(server_name, exc, retry_call, op) -> Optional[str]``, + None = not its kind; order matters). Unrecovered exceptions go through ``on_final_failure`` and become the + generic call-failed error. ``record_outcome`` applies breaker bookkeeping to the FIRST attempt only.""" + if callable(getattr(server, "mark_tool_call", None)): + server.mark_tool_call() + + def call_once(): + return _loop._run_on_mcp_loop(call, timeout=tool_timeout) + + try: + result = call_once() + return _record_call_outcome(server_name, result) if record_outcome else result + except InterruptedError: + return tool_error("MCP call interrupted: user sent a new message") + except Exception as exc: + for recover in recoverers: + recovered = recover(server_name, exc, call_once, op) + if recovered is not None: + return recovered + on_final_failure(exc) + return tool_error(_sanitize_error(f"MCP call failed: {type(exc).__name__}: {_exc_str(exc)}")) + + +@asynccontextmanager +async def _track_inflight_rpc(server: Any, server_name: str, op: str): + """Register the running RPC so teardown can fail it fast. A deliberate teardown + (``_reconnecting`` set first) turns the cancel into a retryable RuntimeError; external + cancels propagate unchanged. Doubles without ``_inflight_tasks`` skip tracking. + + Every user-visible request family wraps its RPC in this context (#48069 salvage). If a deliberate + reconnect/shutdown teardown cancels the task (``_fail_inflight_calls`` sets ``_reconnecting`` first), + the cancel is converted into a clean retryable RuntimeError instead of a raw CancelledError; external + cancels (caller timeout, user interrupt) propagate unchanged. + """ + inflight, task = getattr(server, "_inflight_tasks", None), asyncio.current_task() + tracked = task is not None and inflight is not None + if tracked: + inflight.add(task) + try: + yield + except asyncio.CancelledError: + if getattr(server, "_reconnecting", False): + raise RuntimeError(f"MCP {op} on '{server_name}' was aborted by a reconnect teardown; retry the " + f"request on the rebuilt session") from None + raise + finally: + if tracked: + inflight.discard(task) + + +async def _call_tool_racing_stdio_death(server, server_name: str, tool_name: str, args: dict): + """``session.call_tool`` that fails fast when the stdio child is/gets dead: pre-call (a dead + child must not hold the slot for the full timeout) and mid-call (race against + ``_watch_stdio_children``). Both raise :class:`_StdioChildExited` for the respawn path, which + owns the reconnect signal; only pre-call failure is safe to replay. callable()/``is True`` + because MagicMock attributes are truthy.""" + # Fast-fail (#81995): a stdio subprocess that is already dead must not own this call slot — fail + # immediately instead of waiting out the full tool timeout on a transport nobody will ever answer. + _stdio_dead = getattr(server, "_stdio_children_dead", None) + if callable(_stdio_dead) and _stdio_dead() is True: + raise _StdioChildExited( + f"MCP stdio subprocess for '{server_name}' had already exited when the call was dispatched", + in_flight=False, + ) + _call_coro = server.session.call_tool(tool_name, arguments=args) + _watch_children = getattr(server, "_watch_stdio_children", None) + if not (inspect.iscoroutinefunction(_watch_children) and asyncio.iscoroutine(_call_coro)): + # Stubbed sessions return a non-awaitable, or there is no child-watcher to race: plain await. + return await _call_coro if asyncio.iscoroutine(_call_coro) else _call_coro + # Fast-fail machinery (#81995): the RPC races a stdio-children watcher so a dead subprocess fails the + # call immediately instead of riding out the full tool timeout. + rpc_task = asyncio.ensure_future(_call_coro) + watch_task = asyncio.ensure_future(_watch_children()) + try: + done, _pending = await asyncio.wait({rpc_task, watch_task}, return_when=asyncio.FIRST_COMPLETED) + if watch_task in done and not rpc_task.done(): + rpc_task.cancel() + raise _StdioChildExited( + f"MCP stdio subprocess for '{server_name}' exited mid-call", + in_flight=True, + ) + try: + return await rpc_task + except Exception as exc: + # The SDK usually sees the closed pipe before the 250 ms watcher poll does. On a stdio + # server a transport-closure error after dispatch is the same ambiguous mid-call death; + # it must not fall through to the session-expired recoverer, which replays the call. + _is_http = getattr(server, "_is_http", None) + if callable(_is_http) and _is_http() is False and _is_session_expired_error(exc): + raise _StdioChildExited( + f"MCP stdio subprocess for '{server_name}' closed its transport mid-call", + in_flight=True, + ) from exc + raise + finally: + watch_task.cancel() + if not rpc_task.done(): + rpc_task.cancel() + await asyncio.gather(rpc_task, watch_task, return_exceptions=True) + + +# ---------------------------------------------------------- result rendering + +def _error_result_text(result) -> str: + """Concatenated text of an ``isError`` result's blocks (EmbeddedResource error payloads + carry text under ``.resource.text``).""" + texts = (getattr(b, "text", None) or getattr(getattr(b, "resource", None), "text", None) for b in (result.content or [])) + return "".join(str(t) for t in texts if t) + + +def _render_content_blocks(result, server_name: str) -> Tuple[str, int]: + """Text passes through; image/audio blocks are cached (MEDIA: tags); resource blocks are + materialized rather than silently dropped; unsupported blocks become an inline drop notice + (kimi-code#3227). Returns ``(text, usable_parts)`` — the count of REAL rendered blocks + (whitespace-only text and drop notices excluded) that the structuredContent arbitration uses.""" + parts: List[str] = [] + usable_parts = 0 + # MCP tool results can also include ImageContent blocks (screenshot / Blockbench / Playwright etc.); + # cache those via the gateway's image-cache helper so they flow through Hermes' MEDIA: tag convention + # and out to messaging adapters that render images natively. Without this, image blocks were silently + # dropped and the agent got an empty response. Distilled from #17915 (c3115644151) and #10848 + # (gnanirahulnutakki), both too stale to cherry-pick. #10848's approach (integrate with Hermes' MEDIA + # tag + cache_image_from_bytes) was the cleaner of the two — plugs into existing infrastructure. + for block in (result.content or []): + if getattr(block, "text", None): + parts.append(strip_unicode_tags(block.text)) + if block.text.strip(): + usable_parts += 1 + continue + rendered = _cache_mcp_image_block(block) or _cache_mcp_audio_block(block) or _render_mcp_resource_block(block, server_name) + if rendered: + parts.append(rendered) + usable_parts += 1 + continue + block_type = getattr(block, "type", None) or type(block).__name__ + if block_type in {"text", "resource", "audio", "image"}: # benign empty render + logger.debug("MCP %s: content block type %r rendered empty", server_name, block_type) + else: + logger.warning("MCP %s: dropping unsupported content block type %r", server_name, block_type) + # Surface the drop to the MODEL, not just the log: a silent drop leaves the agent + # believing the tool returned less than it did, with no way to recover. + parts.append(_render_mcp_dropped_block_notice(block, block_type)) + # Hard-cap pathological payloads; ordinary large results pass to spillover. + return _truncate_mcp_text_result("\n".join(parts)), usable_parts + + +def _capped_structured_content(result): + """``structuredContent`` (or None); over the hard cap it degrades to the head+tail + truncated JSON string (multi-MB JSON flood guard).""" + # Hard-cap pathological payloads before they propagate (#56059); ordinary large results pass untouched + # to the spillover layer. + # content and structuredContent are ALTERNATIVES — never both forwarded (ported from + # MoonshotAI/kimi-code#3234). Spec-following servers already render their data into content (the + # verbatim dual-emit SHOULD, or a faithful human reorganisation), so forwarding both sent the same + # information to the model twice. content wins whenever it rendered anything usable; there is no + # reliable signal that the structured payload is richer than what the server put in content (semantic + # equality misses faithful reorganisations, size ratios misjudge both directions), so no heuristic is + # attempted. structuredContent fills in only when the content blocks rendered effectively empty, which + # keeps structuredContent-only servers working. Server-level `_meta` is also surfaced (ported from + # MoonshotAI/kimi-code#2596): servers return namespaced metadata there (validated contracts, + # browser-handoff payloads, ...) that was previously invisible to the agent. Protocol-reserved keys are + # dropped first (kimi-code#2600) — per the MCP spec's key-name rules a prefix is reserved when a + # `modelcontextprotocol` or `mcp` label is followed by at least one more label (e.g. + # `modelcontextprotocol.io/...`, `tools.mcp.com/...`); those carry host/protocol plumbing, not + # model-facing data. Unprefixed and vendor-namespaced keys (`com.example.mcp/...`) pass through — their + # semantics belong to the server. + structured = mcp_field(result, "structured_content", "structuredContent") + try: + as_json = json.dumps(structured, ensure_ascii=False, default=str) if structured is not None else "" + except (TypeError, ValueError): + return structured + return _truncate_mcp_text_result(as_json) if len(as_json) > _MCP_HARD_RESULT_CAP_CHARS else structured + + +def _render_call_tool_result(result, server_name: str) -> str: + """Pure: ``CallToolResult`` -> handler JSON. ``content`` and ``structuredContent`` are + ALTERNATIVES, never both forwarded (kimi-code#3234): spec-following servers already render + their data into content, so forwarding both sent it twice. content wins whenever it rendered + anything usable (no richness heuristic is attempted — none is reliable); structuredContent + fills in only when the blocks rendered effectively empty, keeping structuredContent-only + servers working. ``_meta`` minus reserved keys is always surfaced.""" + if mcp_field(result, "is_error", "isError", False): + return tool_error(_sanitize_error(_truncate_mcp_text_result(_error_result_text(result) or "MCP tool returned an error"))) + text_result, usable_parts = _render_content_blocks(result, server_name) + structured = _capped_structured_content(result) + meta = _strip_reserved_meta_keys(mcp_field(result, "meta", "meta")) + if structured is not None and usable_parts > 0: + structured = None # drop notices do not count as usable content + if structured is None and meta is None: + return json.dumps({"result": text_result}, ensure_ascii=False) + # Key order is part of the output: "result" leads when there is text, otherwise "_meta" precedes it. + payload: Dict[str, Any] = {"result": text_result} if text_result else {} + # Cap structuredContent too — a malicious server could flood context via a multi-MB JSON payload + # (#56059). When the serialized form exceeds the hard cap, replace it with the truncated string (head + + # tail preserved) so it degrades gracefully instead of flooding downstream. + if structured is not None: + payload["structuredContent" if text_result else "result"] = structured + if meta is not None: + payload["_meta"] = meta + payload.setdefault("result", text_result) + try: + return json.dumps(payload, ensure_ascii=False) + except (TypeError, ValueError): # Non-serializable metadata: drop the extras, keep the call. + return json.dumps({"result": text_result}, ensure_ascii=False) + + +def _make_tool_handler(server_name: str, tool_name: str, tool_timeout: float): + """Sync registry handler (``handler(args_dict, **kwargs) -> str``) calling an MCP tool via the background loop.""" + op = f"tools/call {tool_name}" + + def _handler(args: dict, **kwargs) -> str: + # Security boundary: untrusted-server write tools need approval before ANY transport work (incl. lazy spawn). + error = _trust_gate_check(server_name, tool_name) or _check_circuit_breaker(server_name) + if error is not None: + return error + server, error = _acquire_call_server(server_name, tool_timeout) + if server is None: + return error + + async def _call(): + async with server._rpc_lock, _track_inflight_rpc(server, server_name, op): + server._pending_call_context = contextvars.copy_context() # for the elicitation callback + try: + result = await _call_tool_racing_stdio_death(server, server_name, tool_name, args) + finally: + server._pending_call_context = None + if getattr(server, "_mark_session_proven", None) is not None: # round-trip done: transport healthy + server._mark_session_proven() + return _render_call_tool_result(result, server_name) + + def _on_failure(exc): + _core._bump_server_error(server_name) + logger.error("MCP tool %s/%s call failed: %s", server_name, tool_name, exc) + return _dispatch( + server_name, server, op, _call, tool_timeout, + (_handle_stdio_child_exited_and_retry, _handle_auth_error_and_retry, _handle_session_expired_and_retry), + _on_failure, record_outcome=True) + return _handler + + +def _make_utility_handler(op: str, log_label: str, rpc, render, required: Optional[str] = None): + """``(server_name, tool_timeout) -> sync handler`` for one utility tool: ``rpc(session, args, + server_name)`` awaited under ``_rpc_lock``, ``render(result, server_name)`` -> JSON-able + payload, ``required`` validated before any transport work.""" + def _factory(server_name: str, tool_timeout: float): + def _handler(args: dict, **kwargs) -> str: + from tools import mcp_tool_discovery as _discovery # lazy: import cycle + server = _discovery._get_connected_server_for_call(server_name) + if not server or not server.session: + return tool_error(f"MCP server '{server_name}' is not connected") + if required and not args.get(required): + return tool_error(f"Missing required parameter '{required}'") + + async def _call(): + async with server._rpc_lock: + result = await rpc(server.session, args, server_name) + return json.dumps(render(result, server_name), ensure_ascii=False) + return _dispatch( + server_name, server, op, _call, tool_timeout, + (_handle_auth_error_and_retry, _handle_session_expired_and_retry), + lambda exc: logger.error("MCP %s/%s failed: %s", server_name, log_label, exc)) + return _handler + return _factory + + +def _pick(obj, *specs) -> dict: + """``{out_key: value}`` for each ``(out_key, attr[, truthy])`` present on *obj* (presence check so SDK models + and stubs behave alike; ``truthy`` also skips falsy). Key order = spec order.""" + entry = {} + for out_key, attr, *truthy in specs: + value = getattr(obj, attr, _MISSING) + if value is not _MISSING and (value or not (truthy and truthy[0])): + entry[out_key] = value + return entry + + +def _render_resource_list(all_resources, server_name: str) -> dict: + resources = [] + for r in all_resources: + entry = _pick(r, ("uri", "uri"), ("name", "name"), ("description", "description", True)) + if "uri" in entry: + entry["uri"] = str(entry["uri"]) + mime = mcp_field(r, "mime_type", "mimeType") + if mime: + entry["mimeType"] = mime # camelCase: this is the tool's own JSON output shape + resources.append(entry) + return {"resources": resources} + + +def _render_read_resource(result, server_name: str) -> dict: + parts: List[str] = [] + for block in getattr(result, "contents", []): + if getattr(block, "text", None) is not None: + parts.append(strip_unicode_tags(block.text)) + elif getattr(block, "blob", None) is not None: # binary -> document cache, like EmbeddedResource blocks + rendered = _render_mcp_resource_block(SimpleNamespace(type="resource", resource=block), server_name) + parts.append(rendered or f"[binary data, {len(block.blob)} bytes]") + return {"result": "\n".join(parts)} + + +def _render_prompt_list(all_prompts, server_name: str) -> dict: + prompts = [] + for p in all_prompts: + entry = _pick(p, ("name", "name"), ("description", "description", True)) + if getattr(p, "arguments", None): + entry["arguments"] = [{"name": a.name, **_pick(a, ("description", "description", True), ("required", "required"))} + for a in p.arguments] + prompts.append(entry) + return {"prompts": prompts} + + +def _render_get_prompt(result, server_name: str) -> dict: + messages = [] + for msg in getattr(result, "messages", []): + entry = _pick(msg, ("role", "role")) + if hasattr(msg, "content"): + entry["content"] = strip_unicode_tags(msg.content.text if hasattr(msg.content, "text") else str(msg.content)) + messages.append(entry) + return {"messages": messages, **_pick(result, ("description", "description", True))} + + +_make_list_resources_handler = _make_utility_handler( + "resources/list", "list_resources", + lambda session, args, sn: _core._paginate_full_list(session.list_resources, "resources", sn), _render_resource_list) +_make_read_resource_handler = _make_utility_handler( + "resources/read", "read_resource", + lambda session, args, sn: session.read_resource(args["uri"]), _render_read_resource, required="uri") +_make_list_prompts_handler = _make_utility_handler( + "prompts/list", "list_prompts", + lambda session, args, sn: _core._paginate_full_list(session.list_prompts, "prompts", sn), _render_prompt_list) +_make_get_prompt_handler = _make_utility_handler( + "prompts/get", "get_prompt", + lambda session, args, sn: session.get_prompt(args["name"], arguments=args.get("arguments", {})), + _render_get_prompt, required="name") + + +def _make_check_fn(server_name: str): + """Connection-alive check; lazy (schema-cache registered) servers count as available.""" + from tools.mcp_tool_scope import _resolve_server_key + + def _check() -> bool: + with _core._lock: + key = _resolve_server_key(server_name) + server = _core._servers.get(key) + return ((server is not None and (server.session is not None or server._is_recycled_stdio())) + or key in _core._lazy_server_configs) + return _check diff --git a/tools/mcp_tool_lifecycle.py b/tools/mcp_tool_lifecycle.py new file mode 100644 index 0000000000000000000000000000000000000000..cbff4e77b5a53e1e24277eeb123b1986de00a545 --- /dev/null +++ b/tools/mcp_tool_lifecycle.py @@ -0,0 +1,323 @@ +"""MCP process lifecycle: stdio child PID tracking and orphan cleanup, graceful +server shutdown and draining of the background MCP loop.""" + +import logging +import asyncio +import os +import time +from typing import Dict, Optional +from tools.mcp_tool_common import _core +from tools import mcp_tool_loop as _loop + +logger = logging.getLogger("tools.mcp_tool") + +# Live stdio MCP children (pid -> server_name), added after connection and removed on normal +# shutdown, so they can be force-killed if SDK teardown fails. +_stdio_pids: Dict[int, str] = {} +# PIDs that survived their session context exit (detected in _run_stdio's finally, reaped by +# _kill_orphaned_mcp_children). Separate from _stdio_pids so sweeps never race active sessions. +_orphan_stdio_pids: set = set() +_orphan_stdio_pid_servers: Dict[int, str] = {} +# pid -> pgid captured at spawn. The SDK spawns with start_new_session=True (PGID == PID); +# grandchildren keep that PGID after the direct child exits, so killpg still reaches them. +# Separate from _stdio_pids so the PGID survives the child's removal. Empty on Windows. +_stdio_pgids: Dict[int, int] = {} + + +def _snapshot_child_pids() -> set: + """Current direct-child PIDs: /proc on Linux, else psutil, else empty set.""" + my_pid = os.getpid() + # /proc//task//children is per-THREAD, and stdio_client() spawns from the MCP + # loop thread, so union every task's children — reading only the main thread's file + # returns an empty set on every Linux install. + try: + # ``/proc//task//children`` is per-THREAD — a child forked from thread T is listed only + # under T's task dir. stdio_client() spawns from the background MCP loop thread, so reading only the + # main thread's file (``task//children``) returned an empty set on every Linux install and left + # ``_stdio_child_pids`` / ``_stdio_pids`` empty: the #81995 dead-child fast-fail, the #96452 respawn + # signal, and the killpg shutdown sweep never saw the subprocess. + task_dir = f"/proc/{my_pid}/task" + found: set = set() + for tid in os.listdir(task_dir): + try: + with open(f"{task_dir}/{tid}/children", encoding="utf-8") as f: + found.update(int(p) for p in f.read().split() if p.strip()) + except (FileNotFoundError, OSError, ValueError): + continue # thread exited between listdir and open + return found + except (FileNotFoundError, OSError, ValueError): + pass + try: + import psutil + return {c.pid for c in psutil.Process(my_pid).children()} + except Exception: + return set() + + +# argv markers of non-MCP gateway children that can race into the snapshot delta during an +# MCP spawn (defense-in-depth; LSP/slash_worker already use start_new_session). Matched against +# argv[1:] because Python/Java children start with the interpreter path. +_NON_MCP_CHILD_CMDLINE_MARKERS: tuple[str, ...] = ( + "tui_gateway.slash_worker", "tui_gateway.entry", + "-dorg.eclipse.equinox.launcher", "eclipse.jdt.ls", "org.eclipse.equinox.launcher_", # jdtls +) + + +def _filter_mcp_children(pids: set) -> set: + """Drop non-MCP children from a PID snapshot delta. Tracking a stray child in _stdio_pgids + is catastrophic if it lacks start_new_session: its pgid can be the TUI parent's, so the + shutdown killpg() would kill the TUI itself.""" + if not pids: + return pids + try: + import psutil + except ImportError: + return pids # keep all PIDs (prior behavior) + kept = set() + for pid in pids: + try: + argv = psutil.Process(pid).cmdline() + except (psutil.NoSuchProcess, psutil.AccessDenied, OSError): + continue # raced away or zombie — cannot be our fresh server, unsafe to track + if not any(marker in arg for arg in argv[1:] for marker in _NON_MCP_CHILD_CMDLINE_MARKERS): + kept.add(pid) + return kept + + +def _clear_connect_cooldowns(keys=None) -> None: + """Drop connect-retry cooldowns: a restart must re-attempt every server immediately, not + honour a stale per-server backoff. Caller holds ``_core._lock``.""" + if keys is None: + _core._server_connect_retry_after.clear() + _core._server_connect_failures.clear() + else: + for key in keys: + _core._server_connect_retry_after.pop(key, None) + _core._server_connect_failures.pop(key, None) + + +def _reregister_orphaned_adopters() -> None: + """Re-run MCP registration for profiles whose ADOPTED shared connection an owner's + ``/reload-mcp`` just tore down. Their tools vanished with the owner's teardown and nothing + re-runs their discovery until THEY reload, so they sat tool-less behind a healthy-looking + status (#106005). Runs after the owner's rediscovery, under each adopter's own home + secret + scope (its ``${VAR}`` refs must resolve to ITS credentials): the adopter re-adopts the owner's + new identical connection or connects its own.""" + with _core._lock: + pending = dict(_core._orphaned_adopters) + _core._orphaned_adopters.clear() + if not pending: + return + from pathlib import Path + from agent.secret_scope import build_profile_secret_scope, reset_secret_scope, set_secret_scope + from hermes_constants import reset_hermes_home_override, set_hermes_home_override + from tools import mcp_tool_discovery as _discovery + from tools.mcp_tool_config import _load_mcp_config + for adopter, names in pending.items(): + home_token = set_hermes_home_override(adopter) + secret_token = set_secret_scope(build_profile_secret_scope(Path(adopter))) + try: + servers = {n: c for n, c in (_load_mcp_config() or {}).items() if n in names} + if servers: + _discovery.register_mcp_servers(servers) + except Exception: + logger.debug("MCP: re-registration for profile scope %s failed", adopter, exc_info=True) + finally: + reset_secret_scope(secret_token) + reset_hermes_home_override(home_token) + + +def shutdown_mcp_servers(*, scope: Optional[str] = None, names: Optional[set] = None): + """Close MCP server connections (in parallel) and stop the background loop. Each server + Task is signalled to exit its own ``async with`` so the anyio cancel-scope cleanup runs in + the Task that opened it. ``scope`` restricts teardown to one multiplexed profile's servers + (its ``/reload-mcp`` must not kill other profiles') and leaves the shared loop running if + anything else is still connected. ``names`` restricts it further to those server names + (dropped-from-config pruning); other servers' bookkeeping is untouched.""" + from tools.mcp_tool_scope import _key_name + with _core._lock: + selected = [key for key in _core._servers if scope is None or _core._server_scope_keys.get(key) == scope] + if names is not None: + selected = [key for key in selected if _key_name(key) in names] + servers_snapshot = [_core._servers[key] for key in selected] + if names is not None: + selected_status = set(selected) + elif scope is None: + selected_status = ( + set(_core._servers) | set(_core._server_scope_keys) + | set(_core._server_tool_scopes) + | set(_core._server_connecting) | set(_core._server_connect_errors)) + else: + selected_status = {key for key, owner in _core._server_scope_keys.items() if owner == scope} + # Adopters of the connections being torn down lose their overlays with the tasks' own + # ``_deregister_tools``; remember them so the next discovery pass re-registers them + # (``_reregister_orphaned_adopters``). + if scope is not None: + for key in selected: + for adopter in _core._server_tool_scopes.get(key, ()): + if adopter != scope: + _core._orphaned_adopters.setdefault(adopter, set()).add(_key_name(key)) + + def clear_selected_status(): + _core._server_connecting.difference_update(selected_status) + for key in selected_status: + _core._server_connect_errors.pop(key, None) + _core._server_scope_keys.pop(key, None) + _core._server_tool_scopes.pop(key, None) + + # Fast path: nothing to shut down. The connect-cooldown maps can still be populated here — a server that + # failed to connect is never recorded in ``_servers`` (that is the very premise of the #50394 cooldown), + # so "no live servers" is the MOST likely state in which stale backoff entries exist. Clear them so a + # post-shutdown restart re-attempts every configured server immediately. + if servers_snapshot: + async def _shutdown(): + results = await asyncio.gather(*(server.shutdown() for server in servers_snapshot), return_exceptions=True) + for server, result in zip(servers_snapshot, results): + if isinstance(result, Exception): + logger.debug("Error closing MCP server '%s': %s", server.name, result) + with _core._lock: + for key in selected: + _core._servers.pop(key, None) + _core._server_scope_keys.pop(key, None) + clear_selected_status() + _clear_connect_cooldowns(None if scope is None and names is None else selected_status) + + with _core._lock: + loop = _core._mcp_loop + if loop is not None and loop.is_running(): + from agent.async_utils import safe_schedule_threadsafe + future = safe_schedule_threadsafe(_shutdown(), loop, logger=logger, log_message="MCP shutdown: failed to schedule") + if future is not None: + try: + future.result(timeout=15) + except BaseException as exc: + logger.debug("Error during MCP shutdown: %s", exc) + + # Unconditional final sweep: whether ``_shutdown`` ran, timed out, or was never scheduled + # (a server that failed to connect is never in ``_servers`` — the most likely state for + # stale backoff entries), no connect-cooldown state may survive shutdown. + with _core._lock: + if not servers_snapshot: + clear_selected_status() + _clear_connect_cooldowns(None if scope is None and names is None else selected_status) + _loop._stop_mcp_loop(only_if_idle=scope is not None or names is not None) + + +def _take_reapable_pids(include_active: bool, server_name: Optional[str]) -> tuple[Dict[int, str], Dict[int, int]]: + """Pop the PIDs to reap (and their spawn-time pgids) out of the ledgers under the lock, so + a future spawn can't collide with stale state. Returns ``(pid -> owner, pid -> pgid)``.""" + def _owned(entries: Dict[int, str]) -> Dict[int, str]: + return {pid: owner for pid, owner in entries.items() if server_name is None or owner == server_name} + + with _core._lock: + pids = _owned({opid: _orphan_stdio_pid_servers.get(opid, "orphan") for opid in _orphan_stdio_pids}) + _orphan_stdio_pids.difference_update(pids) + for opid in pids: + _orphan_stdio_pid_servers.pop(opid, None) + if include_active: + active = _owned(_stdio_pids) + pids.update(active) + for pid in active: + _stdio_pids.pop(pid, None) + pgids = {pid: _stdio_pgids.pop(pid) for pid in pids if pid in _stdio_pgids} + return pids, pgids + + +def _signal_mcp_process(pid: int, sig: int, server_name: str, pgid: Optional[int], my_pgid: Optional[int]) -> None: + """SIGTERM/SIGKILL via the spawn-time pgroup on POSIX (reaches reparented grandchildren), + falling back to a per-pid signal.""" + killpg = getattr(os, "killpg", None) + if pgid is not None and killpg is not None: + if my_pgid is not None and pgid == my_pgid: + # Child shares the gateway's pgroup: killpg would kill the gateway too, so use + # per-pid kill. Warn because per-pid kill can't reach grandchildren in this group. + logger.warning("MCP server '%s' pgid %d matches gateway pgid; skipping " + # Fall through to the per-pid kill() path instead. Warn because per-pid kill + # cannot reach grandchildren in this shared group — if the direct child has + # already exited, they may leak (inherent: group-killing them would also kill the + # gateway). See #47134. + "killpg to avoid self-kill and using per-pid kill — any " + "grandchildren in this group may not be reaped", server_name, pgid) + else: + try: + killpg(pgid, sig) + return + except (ProcessLookupError, PermissionError, OSError) as exc: + # Pgroup gone or refused — still try the direct child. + logger.debug("killpg(%d, %d) failed for MCP server '%s': %s; falling back to kill(pid)", + pgid, sig, server_name, exc) + try: + os.kill(pid, sig) + except (ProcessLookupError, PermissionError, OSError): + pass + + +def _kill_orphaned_mcp_children(include_active: bool = False, server_name: Optional[str] = None) -> None: + """Best-effort reap of stdio MCP subprocesses: SIGTERM, wait 2s, SIGKILL survivors. By + default only ``_orphan_stdio_pids`` are reaped so concurrent cron jobs / live sessions are + untouched; ``include_active=True`` also kills every ``_stdio_pids`` entry and is only for + final shutdown after the MCP loop has stopped. ``server_name`` limits the sweep to one + server (stdio reconnects cleaning up their old transport).""" + import signal as _signal + pids, pgids = _take_reapable_pids(include_active, server_name) + if not pids: # skip the 2s sleep every MCP-free shutdown would otherwise pay + return + + try: # our own pgid, so we never killpg() the gateway itself + my_pgid = os.getpgrp() + except (AttributeError, OSError): + my_pgid = None # Windows or restricted environment + + for pid, owner in pids.items(): + _signal_mcp_process(pid, _signal.SIGTERM, owner, pgids.get(pid), my_pgid) + logger.debug("Sent SIGTERM to orphaned MCP process %d (%s)", pid, owner) + time.sleep(2) + sigkill = getattr(_signal, "SIGKILL", _signal.SIGTERM) + from gateway.status import _pid_exists # ``os.kill(pid, 0)`` is NOT a no-op on Windows + for pid, owner in pids.items(): + if _pid_exists(pid): # survived SIGTERM + _signal_mcp_process(pid, sigkill, owner, pgids.get(pid), my_pgid) + logger.warning("Force-killed MCP process %d (%s) after SIGTERM timeout", pid, owner) + # These groups are reaped. Release them last, so a crash partway through the SIGTERM/SIGKILL + # dance still leaves the supervisor holding them. + _core._update_death_supervisor("unregister", pgids.values()) + + +def _stop_mcp_loop_if_idle() -> bool: + """Stop the MCP loop only when no registered server still owns it. Probe paths create + temporary MCPServerTasks not placed in ``_servers``; they may clean up an idle loop but + must not tear down the process-global loop under live agent tools.""" + return _loop._stop_mcp_loop(only_if_idle=True) + + +async def _drain_mcp_loop_tasks(*, timeout: Optional[float] = None) -> None: + """Cancel every task still pending on the MCP loop and reap it. ``Task.cancel()`` only + schedules the throw, so tasks need a cancellation cycle before the loop goes away; wait + for them here, on their owning loop, bounded so a task that suppresses cancellation + cannot hang process exit.""" + if timeout is None: + timeout = _core._MCP_LOOP_DRAIN_TIMEOUT + current = asyncio.current_task() + pending = [t for t in asyncio.all_tasks() if t is not current and not t.done()] + if not pending: + return + logger.debug("Draining %d pending task(s) from the MCP loop", len(pending)) + for task in pending: + task.cancel() + done, still_pending = await asyncio.wait(pending, timeout=timeout) + for task in done: + if not task.cancelled(): + task.exception() # mark retrieved so asyncio doesn't warn "exception was never retrieved" + if still_pending: + logger.warning("%d MCP loop task(s) still pending after %.1fs drain", len(still_pending), timeout) + + +async def _drain_and_stop_mcp_loop() -> None: + """Drain pending tasks, then stop the loop from its owning thread. Both must run as one + loop-owned sequence: a ``loop.stop`` queued separately by a timed-out caller can overtake + the scheduled drain, leaving the drain coroutine itself pending when the loop is closed.""" + loop = asyncio.get_running_loop() + try: + await _drain_mcp_loop_tasks(timeout=_core._MCP_LOOP_DRAIN_TIMEOUT) + finally: + loop.call_soon(loop.stop) diff --git a/tools/mcp_tool_loop.py b/tools/mcp_tool_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..831ea81bb6db750b5cd37c1e1950c63d5b6d601f --- /dev/null +++ b/tools/mcp_tool_loop.py @@ -0,0 +1,308 @@ +"""Background-loop plumbing for tools.mcp_tool: cross-process discovery file lock, scheduling +coroutines onto the MCP loop from caller threads (with profile HOME override and dashboard OAuth +flow propagation) and the loop's exception handler. Origin state (``_lock``, ``_mcp_loop``) is +read through ``_core`` so ``mock.patch("tools.mcp_tool.X")`` keeps working.""" + +from __future__ import annotations + +import asyncio +import concurrent.futures +import contextlib +import errno +import logging +import os +import threading +import time +from typing import Any, Coroutine, Optional +from tools.mcp_tool_common import _core +from tools import mcp_tool_lifecycle as _lifecycle + +logger = logging.getLogger("tools.mcp_tool") + + +class _LockCookie: + """Holds a cross-process file lock; ``release()`` drops it. The file object MUST stay open while + held: both fcntl and portalocker locks are tied to the descriptor.""" + + def __init__(self, fh: Any) -> None: + self._fh = fh + + def release(self) -> None: + if self._fh is None: + return + # Best effort: an unlock/close failure must never propagate out of discovery. + with contextlib.suppress(Exception): + if os.name == "posix": + import fcntl + fcntl.flock(self._fh.fileno(), fcntl.LOCK_UN) + else: + import portalocker + portalocker.unlock(self._fh) + with contextlib.suppress(Exception): + self._fh.close() + self._fh = None + + +def _acquire_lock_on_fh(fh: Any) -> bool: + """Non-blocking exclusive lock (fcntl on POSIX, portalocker elsewhere). False when another process + holds it; unexpected errors propagate so the caller can treat locking as unavailable.""" + if os.name == "posix": + import fcntl + try: + fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError as e: + if e.errno in (errno.EACCES, errno.EAGAIN, errno.EWOULDBLOCK): + return False + raise + return True + import portalocker + try: + portalocker.lock(fh, portalocker.LOCK_EX | portalocker.LOCK_NB) + except portalocker.LockException: + return False + return True + + +def _try_acquire_mcp_discovery_lock() -> Any: + """``_LockCookie`` (acquired), ``None`` (held by another process) or ``_LOCK_UNAVAILABLE`` + (locking broken: run discovery unguarded).""" + # The cached path lives on the ORIGIN module (tests reset ``tools.mcp_tool._MCP_DISCOVERY_LOCK_PATH``). + # A routed profile (multiplexed gateway) locks under ITS home: the launch profile's lock file + # would serialize discovery across profiles and never coordinate with B's own single-profile processes. + from tools import mcp_tool as _origin + try: + from hermes_constants import get_hermes_home, get_hermes_home_override + if get_hermes_home_override() is not None: + lock_path = str(get_hermes_home() / ".mcp-discovery.lock") + else: + if _origin._MCP_DISCOVERY_LOCK_PATH is None: + _origin._MCP_DISCOVERY_LOCK_PATH = str(get_hermes_home() / ".mcp-discovery.lock") + lock_path = _origin._MCP_DISCOVERY_LOCK_PATH + fh = open(lock_path, "w", encoding="utf-8") + except Exception: + return _core._LOCK_UNAVAILABLE + try: + acquired = _acquire_lock_on_fh(fh) + except Exception: + fh.close() + return _core._LOCK_UNAVAILABLE + if acquired: + return _LockCookie(fh) + fh.close() + return None + + +def _mcp_loop_exception_handler(loop, context): + """Suppress the benign 'Event loop is closed' RuntimeError httpx finalizers raise against the + dead loop during shutdown; forward the rest.""" + exc = context.get("exception") + if not (isinstance(exc, RuntimeError) and "Event loop is closed" in str(exc)): + loop.default_exception_handler(context) + + +def _wrap_with_home_override(coro: "Coroutine") -> "Coroutine": + """Carry the caller's context-local HERMES_HOME override into ``coro`` (task-local on the MCP + loop, so concurrent scopes don't interfere).""" + try: + from hermes_constants import get_hermes_home_override, reset_hermes_home_override, set_hermes_home_override + home_override = get_hermes_home_override() + except Exception: + home_override = None + if not home_override: + return coro + + async def _scoped(): + token = set_hermes_home_override(home_override) + try: + return await coro + finally: + reset_hermes_home_override(token) + + return _scoped() + + +def _wrap_with_dashboard_oauth_flow(coro): + """Propagate a dashboard OAuth flow onto the dedicated MCP loop task.""" + try: + from tools.mcp_dashboard_oauth import dashboard_oauth_flow, get_dashboard_oauth_flow + flow = get_dashboard_oauth_flow() + except Exception: + flow = None + if flow is None: + return coro + + async def _scoped(): + with dashboard_oauth_flow(flow): + return await coro + + return _scoped() + + +def _running_loop() -> Optional[asyncio.AbstractEventLoop]: + """The MCP loop when it is up, else None (read under ``_lock``).""" + with _core._lock: + loop = _core._mcp_loop + return loop if loop is not None and loop.is_running() else None + + +def _run_on_mcp_loop(coro_or_factory, timeout: float = 30): + """Schedule a coroutine (or zero-arg factory — avoids leaking a never-awaited coroutine when the + loop is down) on the MCP loop and block until done, polling so user interrupts are honored.""" + from tools.interrupt import is_interrupted + from agent.async_utils import safe_schedule_threadsafe + + loop = _running_loop() + if loop is None: + if asyncio.iscoroutine(coro_or_factory): + coro_or_factory.close() + raise RuntimeError("MCP event loop is not running") + # run_coroutine_threadsafe copies the LOOP thread's context, so a per-request profile scope + # would vanish here; re-establish it inside the task's own context. + coro = _wrap_with_dashboard_oauth_flow(_wrap_with_home_override( + coro_or_factory() if callable(coro_or_factory) else coro_or_factory)) + future = safe_schedule_threadsafe(coro, loop, logger=logger, log_message="MCP scheduling failed") + if future is None: + raise RuntimeError("MCP event loop unavailable (failed to schedule)") + start_time = time.monotonic() + deadline = None if timeout is None else start_time + timeout + while True: + if is_interrupted(): + future.cancel() + raise InterruptedError("User sent a new message") + remaining = 0.1 if deadline is None else deadline - time.monotonic() + if remaining <= 0: + future.cancel() + raise TimeoutError(f"MCP call timed out after {time.monotonic() - start_time:.1f}s " + f"(configured timeout: {float(timeout):.1f}s)") + try: + return future.result(timeout=min(0.1, remaining)) + except concurrent.futures.TimeoutError: + # Aliases builtin TimeoutError, so it also fires for the coroutine's own timeout: a done + # future must yield its outcome. + if future.done(): + return future.result() + + +def _signal_reconnect(server: Any) -> bool: + """Ask a server task to rebuild its transport, thread-safely: the event lives on the MCP loop, + so set via ``call_soon_threadsafe`` when it runs (direct ``.set()`` otherwise). False when the + server has no reconnect machinery.""" + event = getattr(server, "_reconnect_event", None) + if event is None: + return False + loop = _core._mcp_loop + if isinstance(event, asyncio.Event) and loop is not None and loop.is_running(): + loop.call_soon_threadsafe(event.set) + else: + event.set() + return True + + +def reconnect_mcp_server(server_name: str) -> bool: + """Ask a currently-live MCP server to rebuild after external re-auth.""" + from tools.mcp_tool_scope import _resolve_server_key + with _core._lock: + server = _core._servers.get(_resolve_server_key(server_name)) + return server is not None and _signal_reconnect(server) + + +def _wait_for_server_session_ready(srv: Any, *, old_session: Any = None, timeout: float = 15.0) -> bool: + """Poll until the server exposes a usable, ready session (during a reconnect ``srv.session`` is + briefly None or stale; retrying blindly burns breaker strikes). With ``old_session`` the observed + session must differ. Iteration-bounded, not deadline-bounded: tests freeze ``time.monotonic``.""" + iterations = max(1, int(max(float(timeout), 0.0) / 0.25)) + for i in range(iterations): + session = getattr(srv, "session", None) + ready = getattr(srv, "_ready", None) + try: + is_ready = bool(ready.is_set()) if hasattr(ready, "is_set") else True + except Exception: + is_ready = True + if session is not None and session is not old_session and is_ready: + return True + if i < iterations - 1: + time.sleep(0.25) + return False + + +def _signal_reconnect_and_wait(server_name: str, srv: Any, *, op_description: str, timeout: float = 15.0) -> bool: + """Request a transport rebuild and wait for the fresh session. ``_ready`` is cleared on the loop + BEFORE ``_reconnect_event`` is set, else the readiness poll returns at once on the dead session.""" + loop = _core._mcp_loop + if loop is None or not loop.is_running(): + return False + + def _request_reconnect() -> None: + ready, reconnect_event = getattr(srv, "_ready", None), getattr(srv, "_reconnect_event", None) + if hasattr(ready, "clear"): + ready.clear() + if hasattr(reconnect_event, "set"): + reconnect_event.set() + + old_session = getattr(srv, "session", None) + logger.info("MCP server '%s': %s requesting transport reconnect", server_name, op_description) + loop.call_soon_threadsafe(_request_reconnect) + return _wait_for_server_session_ready(srv, old_session=old_session, timeout=timeout) + + +def _ensure_mcp_loop(): + """Start the background loop thread if not running. The loop/thread handles live on the ORIGIN + module (tests read and reset ``tools.mcp_tool._mcp_loop``), so they are written there.""" + from tools import mcp_tool as _origin + with _core._lock: + if _origin._mcp_loop is not None and _origin._mcp_loop.is_running(): + return + loop = _origin._mcp_loop = asyncio.new_event_loop() + loop.set_exception_handler(_mcp_loop_exception_handler) + _origin._mcp_thread = threading.Thread(target=loop.run_forever, name="mcp-event-loop", daemon=True) + _origin._mcp_thread.start() + + +def _stop_mcp_loop(*, only_if_idle: bool = False) -> bool: + """Stop the background event loop and join its thread.""" + from tools import mcp_tool as _origin + with _core._lock: + if only_if_idle and (_core._servers or _core._server_connecting): + logger.debug("Leaving MCP event loop running; active servers are registered or connecting") + return False + loop, thread = _origin._mcp_loop, _origin._mcp_thread + _origin._mcp_loop = _origin._mcp_thread = None + if loop is None: + return True + # Drain before stopping: tasks still suspended when the loop closes get resumed by the GC + # against a closed loop. shutdown_mcp_servers only reaps _servers; everything else ends here. + future = None + # Drain before stopping: closing the loop with tasks still suspended leaves their coroutines for the GC, + # whose finalizer then resumes them to run cleanup against a loop that is already closed -> "Event loop + # is closed" (#60197). + if loop.is_running(): + from agent.async_utils import safe_schedule_threadsafe + + future = safe_schedule_threadsafe( + _lifecycle._drain_and_stop_mcp_loop(), loop, logger=logger, + log_message="MCP loop drain: failed to schedule", log_level=logging.WARNING) + if future is not None: + try: + future.result(timeout=_core._MCP_LOOP_DRAIN_TIMEOUT + 1) + except TimeoutError: + logger.warning("Timed out waiting for MCP loop drain after %.1fs", _core._MCP_LOOP_DRAIN_TIMEOUT + 1) + except BaseException as exc: + logger.warning("Error draining MCP loop tasks: %s", exc) + elif not loop.is_closed(): + try: + loop.run_until_complete(_lifecycle._drain_mcp_loop_tasks(timeout=_core._MCP_LOOP_DRAIN_TIMEOUT)) + except BaseException as exc: + logger.warning("Error draining stopped MCP loop tasks: %s", exc) + if future is None and loop.is_running(): # drain-and-stop wasn't scheduled: stop it ourselves + loop.call_soon_threadsafe(loop.stop) + if thread is not None: + thread.join(timeout=5) + if thread.is_alive(): + logger.warning("MCP event loop thread did not stop within 5.0s") + try: + loop.close() + except Exception as exc: + logger.warning("Unable to close MCP event loop cleanly: %s", exc) + # The loop is gone, so no session can be in flight: reap active too. + _lifecycle._kill_orphaned_mcp_children(include_active=True) + return True diff --git a/tools/mcp_tool_registration.py b/tools/mcp_tool_registration.py new file mode 100644 index 0000000000000000000000000000000000000000..a01d24c2c53287e8c4aa446e286fd24789f0b694 --- /dev/null +++ b/tools/mcp_tool_registration.py @@ -0,0 +1,540 @@ +"""Registering a connected (or schema-cached) MCP server's tools into the tool registry: +include/exclude filtering, trust-tier metadata capture, utility-tool selection, name-collision +resolution and the schema-cache write-through. Both entry points (``_register_server_tools`` +live, ``_register_from_cache_sync`` lazy) build ``_Candidate`` records for ``_register_candidates``.""" + +import json +import logging +import threading +from dataclasses import dataclass +from types import SimpleNamespace +from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional +from tools.mcp_tool_common import _parse_boolish, _core, _resolve_tool_timeout, mcp_field +from tools import mcp_tool_handlers as _handlers +from tools import mcp_tool_schema as _schema +from tools.mcp_tool_handlers import ( + _make_check_fn, _make_get_prompt_handler, _make_list_prompts_handler, + _make_list_resources_handler, _make_read_resource_handler) +from tools.mcp_tool_schema import ( + _UTILITY_CAPABILITY_ATTRS, _build_utility_schemas, _normalize_name_filter, matches_name_filter) +from tools.mcp_tool_scope import _key_name, _key_scope, _resolve_server_key, _server_key + +if TYPE_CHECKING: # pragma: no cover + from tools.mcp_tool import MCPServerTask + +logger = logging.getLogger("tools.mcp_tool") +_SCOPE_REFRESH_LOCKS = tuple(threading.RLock() for _ in range(16)) + +_UTILITY_ORIGIN_PREFIX = "generated utility " +# Utility tool key -> handler factory; each takes (server_name, tool_timeout). +_UTILITY_HANDLER_FACTORIES = { + "list_resources": _make_list_resources_handler, "read_resource": _make_read_resource_handler, + "list_prompts": _make_list_prompts_handler, "get_prompt": _make_get_prompt_handler} + + +def _normalize_server_trust(value: Any) -> str: + """Config ``trust`` -> tier. None -> ``full`` (compat default); unrecognized -> ``untrusted`` (fail closed).""" + if value is None: + return _core._TRUST_FULL + text = str(value).strip().lower() + if text in (_core._TRUST_FULL, _core._TRUST_UNTRUSTED): + return text + logger.warning("MCP trust: unrecognized trust value %r — treating as 'untrusted' (valid values: full, untrusted)", + value) + return _core._TRUST_UNTRUSTED + + +def _annotation_read_only_hint(mcp_tool: Any) -> bool: + """True only when annotations (SDK object or cache dict) carry ``readOnlyHint is True``; unknown = write-capable.""" + annotations = getattr(mcp_tool, "annotations", None) + hint = annotations.get("readOnlyHint") if isinstance(annotations, dict) else getattr(annotations, "readOnlyHint", None) + return hint is True + + +def _record_tool_trust_metadata(server_name: str, config: dict, tools: List[Any], key=None) -> None: + """Capture per-server trust and per-tool readOnlyHint at discovery — the security boundary: the call-time gate + classifies from data we control, never re-read server-supplied state. *key* is the connection (default: the + registering profile's own); the ``trust`` policy is recorded under it for the profile that owns it — an + adopting profile records its own policy in ``_record_scope_trust``.""" + with _core._lock: + if key is None: + key = _server_key(server_name) + _core._server_trust_levels[key] = _normalize_server_trust((config or {}).get("trust")) + hints = _core._tool_read_only_hints.setdefault(key, {}) + hints.update({t.name: _annotation_read_only_hint(t) for t in tools if getattr(t, "name", None)}) + + +def _record_scope_trust(server_name: str, config: dict, scope: str) -> None: + """``trust`` is the CONSUMING profile's policy, never the connection's: an ``untrusted`` profile that + adopts a ``full`` profile's live connection must still be asked before every write-capable call.""" + with _core._lock: + _core._server_trust_levels[_server_key(server_name, scope, current=False)] = _normalize_server_trust( + (config or {}).get("trust")) + + +def _track_mcp_tool_server(tool_name: str, server_name: str) -> None: + """Remember the exact raw MCP server that registered *tool_name*.""" + with _core._lock: + _core._mcp_tool_server_names[tool_name] = server_name + + +def _forget_mcp_tool_server(tool_name: str) -> None: + """Forget MCP server provenance for a deregistered tool.""" + with _core._lock: + _core._mcp_tool_server_names.pop(tool_name, None) + + +def _server_key_for_task(server) -> object: + """Connection key of a live ``MCPServerTask`` (teardown runs on the MCP loop without the + discovering profile's context, so the key is found by identity, never re-derived).""" + with _core._lock: + for key, live in _core._servers.items(): + if live is server: + return key + return _server_key(server.name) + + +def _deregister_mcp_tool_all_scopes(server, tool_name: str) -> None: + """Deregister one server tool from every profile overlay that owns it. *server* is the + live task or a connection key.""" + from tools.registry import registry + + key = server if isinstance(server, (str, tuple)) else _server_key_for_task(server) + with _core._lock: + scopes = set(_core._server_tool_scopes.get(key, ())) + if not scopes: + scopes = {_core._server_registry_scope(key)} + for scope in scopes: + registry.deregister(tool_name, scope=scope) + _forget_mcp_tool_server(tool_name) + _restore_server_toolset_alias(key) + + +def _restore_server_toolset_alias(key) -> None: + """Keep the process-global alias while any profile still owns tools of a server with this + name — including another profile's same-named connection (the alias is per NAME; the + registry deregister dropped it after checking only one scope).""" + from tools.registry import registry + + server_name = _key_name(key) + with _core._lock: + owned = [(server, set(_core._server_tool_scopes.get(k, ()))) + for k, server in _core._servers.items() if _key_name(k) == server_name] + if any( + registry.snapshot_registration(tool_name, scope=scope) is not None + for server, scopes in owned for scope in scopes + for tool_name in getattr(server, "_registered_tool_names", ()) + ): + registry.register_toolset_alias(server_name, f"mcp-{server_name}") + + +def _remove_server_scope(key, scope: str) -> None: + """Remove one profile's MCP overlay for a shared live connection.""" + from tools.registry import registry + + server_name = _key_name(key) + for tool_name in registry.get_tool_names_for_toolset(f"mcp-{server_name}"): + registry.deregister(tool_name, scope=scope) + with _core._lock: + scopes = set(_core._server_tool_scopes.get(key, ())) + scopes.discard(scope) + if scopes: + _core._server_tool_scopes[key] = scopes + else: + _core._server_tool_scopes.pop(key, None) + _core._server_trust_levels.pop(_server_key(server_name, scope, current=False), None) + _restore_server_toolset_alias(key) + + +def _select_utility_schemas(server_name: str, server: "MCPServerTask", config: dict) -> List[dict]: + """Utility schemas allowed by config (``tools.resources``/``tools.prompts``) and advertised + capabilities. ``initialize_result.capabilities`` is the truth (sub-object non-None iff the + family is served); without it fall back to the legacy session-method check, which never + filters anything since ClientSession defines all four methods.""" + tools_filter = config.get("tools") or {} + enabled = {f: _parse_boolish(tools_filter.get(f), default=True) for f in ("resources", "prompts")} + advertised = getattr(getattr(server, "initialize_result", None), "capabilities", None) + + def _skip_reason(handler_key: str) -> Optional[str]: + family = _UTILITY_CAPABILITY_ATTRS[handler_key] + if not enabled[family]: + return f"{family} disabled" + if advertised is not None: + if getattr(advertised, family, None) is None: + return f"server does not advertise '{family}' capability" + return None + # Legacy gate (no initialize_result): the ClientSession method shares the handler key. + return None if hasattr(server.session, handler_key) else f"session lacks {handler_key}" + selected: List[dict] = [] + for entry in _build_utility_schemas(server_name): + reason = _skip_reason(entry["handler_key"]) + if reason: + logger.debug("MCP server '%s': skipping utility '%s' (%s)", server_name, entry["handler_key"], reason) + else: + selected.append(entry) + return selected + + +def _existing_tool_names() -> List[str]: + """Tool names for all connected servers plus lazy (cache-registered) servers, whose tools live only in the registry.""" + scope = _core._mcp_registry_scope() + if scope is not None: + from tools.registry import registry + + with _core._lock: + server_names = [ + _key_name(key) for key in _core._servers + if _core._server_visible_in_scope(key, scope) + ] + server_names.extend( + _key_name(key) for key in _core._lazy_server_tool_names + if key not in _core._servers and _core._server_visible_in_scope(key, scope) + ) + return sorted({ + tool_name + for server_name in server_names + for tool_name in registry.get_tool_names_for_toolset(f"mcp-{server_name}") + }) + + names: List[str] = [] + for server in _core._servers.values(): + names.extend(server._registered_tool_names if hasattr(server, "_registered_tool_names") + else (_schema._convert_mcp_schema(server.name, t)["name"] for t in server._tools)) + with _core._lock: + names.extend(n for key, tool_names in _core._lazy_server_tool_names.items() + if key not in _core._servers for n in tool_names) + return names + + +def _make_tool_filter(name: str, config: dict) -> Callable[[str], bool]: + """Include/exclude predicate for a server's tool names: ``tools.include`` is a whitelist (``[]`` = register + nothing), ``tools.exclude`` a blacklist; entries are exact names or fnmatch globs; include wins over exclude.""" + tools_filter = config.get("tools") or {} + # Selective tool loading: honour include/exclude lists from config. Rules (matching issue #690 spec, + # extended with glob support): tools.include — whitelist: only matching tool names are registered + # tools.exclude — blacklist: all tools EXCEPT matching ones are registered entries may be exact names or + # fnmatch globs (e.g. "*_radar_*") include takes precedence over exclude include: [] → register nothing + # (an explicit empty whitelist, as written by the install checklist's "uncheck everything" path) Neither + # set → register all tools (backward-compatible default) + include_raw = tools_filter.get("include") + include_set = _normalize_name_filter(include_raw, f"mcp_servers.{name}.tools.include") + exclude_set = _normalize_name_filter(tools_filter.get("exclude"), f"mcp_servers.{name}.tools.exclude") + if isinstance(include_raw, (str, list, tuple, set)): + return lambda tool_name: matches_name_filter(tool_name, include_set) + return lambda tool_name: not (exclude_set and matches_name_filter(tool_name, exclude_set)) + + +def _cached_tools(raws: Iterable[Any]) -> List[SimpleNamespace]: + """Schema-cache rows -> stand-ins for MCP Tool objects; rows that are not dicts or lack a name + are dropped. Missing or non-dict ``annotations`` (older cache files) fail closed to write-capable.""" + return [SimpleNamespace(name=raw["name"], description=raw.get("description") or "", + inputSchema=raw["inputSchema"] if isinstance(raw.get("inputSchema"), dict) else {}, + annotations=raw["annotations"] if isinstance(raw.get("annotations"), dict) else None) + for raw in raws if isinstance(raw, dict) and raw.get("name")] + + +@dataclass +class _Candidate: + """One registration attempt (native tool or generated utility); ``origin`` is the provenance text in diagnostics.""" + + registry_name: str + origin: str + schema: dict + handler: Callable + + @property + def is_utility(self) -> bool: + return self.origin.startswith(_UTILITY_ORIGIN_PREFIX) + + +def _tool_candidates(name: str, tools: Iterable[Any], should_register: Callable[[str], bool], + tool_timeout) -> List[_Candidate]: + """Native tools (live SDK objects or cache stand-ins) -> candidates. The injection scan runs on + BOTH paths: the cache file is user-writable JSON.""" + out: List[_Candidate] = [] + for t in tools: + if not should_register(t.name): + logger.debug("MCP server '%s': skipping tool '%s' (filtered by config)", name, t.name) + continue + _schema._scan_mcp_description(name, t.name, t.description or "") + schema = _schema._convert_mcp_schema(name, t) + handler = _handlers._make_tool_handler(name, t.name, tool_timeout) + out.append(_Candidate(schema["name"], f"tool {t.name!r}", schema, handler)) + return out + + +def _utility_candidates(name: str, entries: Iterable[Any], tool_timeout) -> List[_Candidate]: + """``{schema, handler_key}`` rows (live selection or cache) -> candidates; malformed rows dropped.""" + out: List[_Candidate] = [] + for raw in entries: + schema, key = (raw.get("schema"), raw.get("handler_key")) if isinstance(raw, dict) else (None, None) + if isinstance(schema, dict) and key in _UTILITY_HANDLER_FACTORIES and schema.get("name"): + out.append(_Candidate(schema["name"], f"{_UTILITY_ORIGIN_PREFIX}{key!r}", schema, + _UTILITY_HANDLER_FACTORIES[key](name, tool_timeout))) + return out + + +def _resolve_name_collisions(name: str, candidates: List[_Candidate]) -> List[_Candidate]: + """Preflight name collisions: exact duplicates dropped silently; a utility normalizing onto + a native tool's name is shadowed (native wins); any other multi-origin collision skips every + colliding entry (fail closed). Returns survivors in order.""" + unique: List[_Candidate] = [] + origins_by_name: Dict[str, set[str]] = {} + for c in candidates: + origins = origins_by_name.setdefault(c.registry_name, set()) + if c.origin in origins: + logger.debug("MCP server '%s': duplicate registration candidate %s for '%s'; keeping one", + name, c.origin, c.registry_name) + continue + origins.add(c.origin) + unique.append(c) + ambiguous: Dict[str, List[str]] = {} + shadowed: set[tuple[str, str]] = set() + # A generated resource/prompt utility that normalizes onto a server-native tool's name must not knock + # that native tool out of the registry: the native tool is the capability the user connected the server + # for, while the generated utility (read_resource/list_resources/list_prompts/get_prompt) is optional + # sugar that only matters when the server exposes no such tool of its own (#87112). Resolve that + # specific collision in favour of the native tool — keep it, drop the shadowed utility — and fall back + # to the conservative skip-everything only for genuinely ambiguous collisions (two or more native tools + # normalizing to one name, which we cannot disambiguate). The four utility keys are distinct, so a + # colliding set holds at most one utility origin. + for registry_name, origins in origins_by_name.items(): + if len(origins) <= 1: + continue + utility_origins = sorted(o for o in origins if o.startswith(_UTILITY_ORIGIN_PREFIX)) + native_origins = sorted(origins - set(utility_origins)) + if len(native_origins) == 1 and utility_origins: + shadowed.update((registry_name, o) for o in utility_origins) + logger.info( + "MCP server '%s': generated utility %s normalizes onto server-native %s — keeping the native tool " + "and dropping the utility (the utility only applies when the server has no such tool of its own)", + name, ", ".join(utility_origins), native_origins[0]) + else: + ambiguous[registry_name] = sorted(origins) + for registry_name, origins in sorted(ambiguous.items()): + logger.error("MCP server '%s': name normalization collision for '%s' from %s; skipping every colliding " + "entry instead of choosing an arbitrary handler", name, registry_name, ", ".join(origins)) + return [c for c in unique if c.registry_name not in ambiguous and (c.registry_name, c.origin) not in shadowed] + + +def _register_candidates(name: str, candidates: List[_Candidate], *, check_fn: Callable, + scope: Callable[[], Optional[str]], lazy: bool, key=None) -> List[str]: + """Register candidates under toolset ``mcp-{name}``; returns the names that landed. The + ownership pre-check is advisory (servers connect in parallel): ``registry.register()`` is + the atomic gate and its verdict is re-read after every call. *key* is the connection whose + ``_server_tool_scopes`` records the registering scope (default: this scope's own).""" + from tools.registry import registry + toolset_name = f"mcp-{name}" + registered: List[str] = [] + scope_value = scope() + if key is None: + key = _server_key(name, scope_value, current=False) + for c in candidates: + existing_toolset = registry.get_toolset_for_tool(c.registry_name) + if existing_toolset and existing_toolset != toolset_name: # foreign owner: skip, preserve it + if lazy: + if not c.is_utility: + logger.warning("MCP server '%s' (lazy): cached tool '%s' collides with toolset '%s' — skipping", + name, c.registry_name, existing_toolset) + elif existing_toolset.startswith("mcp-"): + logger.error("MCP server '%s': %s normalizes to '%s', already owned by MCP toolset '%s' — skipping to " + "preserve the existing owner", name, c.origin, c.registry_name, existing_toolset) + else: + logger.warning("MCP server '%s': %s (→ '%s') collides with built-in tool in toolset '%s' — skipping to " + "preserve built-in", name, c.origin, c.registry_name, existing_toolset) + continue + registry.register( + name=c.registry_name, toolset=toolset_name, schema=c.schema, handler=c.handler, check_fn=check_fn, + is_async=False, description=c.schema.get("description") or "", scope=scope_value) + if registry.get_toolset_for_tool(c.registry_name) == toolset_name: + _track_mcp_tool_server(c.registry_name, name) + if scope_value is not None: + with _core._lock: + _core._server_tool_scopes.setdefault(key, set()).add(scope_value) + registered.append(c.registry_name) + elif not lazy: + logger.error("MCP server '%s': registration of %s as '%s' was rejected by the registry; " + "skipping provenance/count updates", name, c.origin, c.registry_name) + if registered: + registry.register_toolset_alias(name, toolset_name) + return registered + + +def _write_schema_cache(name: str, server: "MCPServerTask", config: dict, should_register) -> None: + """Write-through: persist the manifest so the next startup registers this server lazily (no spawn). Never raises.""" + try: + # Write-through (#56832): refresh the on-disk schema cache after a live connect so the next startup + # can lazily register this server without spawning it. Cache failures never break registration. + from tools.mcp_schema_cache import config_fingerprint, write_cache_entry + tools_payload = [] + for t in server._tools: + if not should_register(t.name): + continue + # mcp 2.0 renamed every Tool model field to snake_case and left camelCase as a + # *serialization* alias only, which pydantic does not apply to attribute access: a bare + # camelCase getattr returns None on 2.x instead of raising. That silently wrote an empty + # ``inputSchema`` into the schema cache on every write-through, so a ``lazy: true`` server + # registered from cache with every parameter stripped. ``mcp_field`` reads both spellings. + schema_obj = mcp_field(t, "input_schema", "inputSchema") + tools_payload.append({ + "name": t.name, "description": t.description or "", + "inputSchema": schema_obj if isinstance(schema_obj, dict) else {}, + "annotations": {"readOnlyHint": _annotation_read_only_hint(t)}, # lazy path trust-gates identically + }) + utility_payload = [{"schema": e["schema"], "handler_key": e["handler_key"]} + for e in _select_utility_schemas(name, server, config)] + cache_meta = getattr(server, "_list_cache_meta", None) or {} + write_cache_entry(name, config_fingerprint(config), tools=tools_payload, utility_tools=utility_payload, + ttl_ms=cache_meta.get("ttl_ms"), cache_scope=cache_meta.get("cache_scope")) + except Exception as exc: + logger.debug("MCP schema cache write failed for '%s': %s", name, exc) + + +def _register_server_tools(name: str, server: "MCPServerTask", config: dict) -> List[str]: + """Register a connected server's tools plus utilities (initial discovery and list_changed + refresh); returns the names. Toolset aliases derive from the live registry, not + ``toolsets.TOOLSETS``; lossy normalization collisions (``read-file``/``read_file``) fail closed.""" + should_register = _make_tool_filter(name, config) + key = _server_key_for_task(server) + _record_tool_trust_metadata(name, config, server._tools, key) + candidates = _tool_candidates(name, server._tools, should_register, server.tool_timeout) + candidates += _utility_candidates(name, _select_utility_schemas(name, server, config), server.tool_timeout) + registered = _register_candidates( + name, _resolve_name_collisions(name, candidates), + check_fn=_make_check_fn(name), scope=lambda: _core._server_registry_scope(key), lazy=False, key=key) + if registered: + _write_schema_cache(name, server, config, should_register) + return registered + + +def _server_enabled(config: dict) -> bool: + return _parse_boolish(config.get("enabled", True), default=True) + + +def _connection_identity(config: dict) -> tuple: + """What makes one live connection reusable for another profile: the route fingerprint PLUS + everything that authenticates it (``config_fingerprint`` deliberately excludes credentials so + the schema cache survives a token rotation). Two profiles pointing at the same URL with different + headers/env/auth/client certificates are two identities; borrowing across them would call tools + as the other user.""" + from tools.mcp_schema_cache import config_fingerprint + + def _frozen(value): + return json.dumps(value or {}, sort_keys=True, default=str) + + return (config_fingerprint(config), _frozen(config.get("env")), _frozen(config.get("headers")), + _auth_type(config), _frozen(config.get("client_cert")), _frozen(config.get("client_key"))) + + +def _auth_type(config: dict) -> str: + return (config.get("auth") or "").lower().strip() + + +def _same_server_route(server: Any, config: dict, *, cross_profile: bool = False) -> bool: + """Whether *server* matches *config*, with OAuth connections never reusable across profiles. + + OAuth credentials live in the owning profile's token storage rather than the static config, + so identical OAuth configs cannot prove that two profiles authenticate as the same account. + """ + if _connection_identity(getattr(server, "_config", {}) or {}) != _connection_identity(config): + return False + # Identities match, so both sides carry the same normalised auth type. + return not (cross_profile and _auth_type(config) == "oauth") + + +def register_connected_into_current_scope(servers: dict) -> int: + """Serialize shared-scope reconciliation and registration for one discovery pass.""" + scope = _core._mcp_registry_scope() + if scope is None: + return 0 + with _SCOPE_REFRESH_LOCKS[hash(scope) % len(_SCOPE_REFRESH_LOCKS)]: + return _register_connected_into_current_scope(servers) + + +def _register_connected_into_current_scope(servers: dict) -> int: + """Heal the current profile's MCP overlay from already-connected shared servers. + + A shared live connection remains owned by the profile that opened it, but a profile with the + same route must still receive its callable tool entries. The current profile's config is the + allowlist, and route fingerprints prevent borrowing a differently-authenticated connection. + Missing or changed config entries remove only this profile's overlay. + """ + from tools.registry import registry + + scope = _core._mcp_registry_scope() + if scope is None: + return 0 + + with _core._lock: + stale = [] + for key, scopes in _core._server_tool_scopes.items(): + if scope not in scopes: + continue + server = _core._servers.get(key) + config = servers.get(_key_name(key)) + cross_profile = _key_scope(key) != scope + if (config is None or not _server_enabled(config) or server is None + or getattr(server, "session", None) is None + or not _same_server_route(server, config, cross_profile=cross_profile)): + stale.append(key) + for key in stale: + _remove_server_scope(key, scope) + + registered_servers = 0 + for name, config in servers.items(): + if not _server_enabled(config): + continue + with _core._lock: + if _server_key(name, scope, current=False) in _core._servers: + continue # this profile has its own connection for the name + # Any other profile's live connection with the same route AND credentials is shareable. + shared = [(key, live) for key, live in _core._servers.items() + if _key_name(key) == name and getattr(live, "session", None) is not None + and _same_server_route(live, config, cross_profile=True)] + if not shared: + continue + key, server = shared[0] + # Visibility for this profile: the owner keeps teardown, this scope sees the connection. + with _core._lock: + _core._server_tool_scopes.setdefault(key, set()).add(scope) + _record_scope_trust(name, config, scope) + if registry.get_tool_names_for_toolset(f"mcp-{name}"): + continue + candidates = _tool_candidates(name, server._tools, _make_tool_filter(name, config), server.tool_timeout) + candidates += _utility_candidates( + name, _select_utility_schemas(name, server, config), server.tool_timeout) + names = _register_candidates( + name, _resolve_name_collisions(name, candidates), + check_fn=_make_check_fn(name), scope=lambda: scope, lazy=False, key=key) + if names: + registered_servers += 1 + with _core._lock: + server._registered_tool_names = sorted( + set(getattr(server, "_registered_tool_names", []) or ()) | set(names)) + return registered_servers + + +def _register_from_cache_sync(name: str, config: dict, entry: dict) -> List[str]: + """Lazy startup: register from a cached manifest with no child process (first real call goes + through ``_ensure_lazy_server_connected``). Trust metadata is recorded first so the + call-time gate is identical for live and cached registrations. + + Lazy startup (#56832, design by Vansh5632): tools appear in the registry immediately; the first real + call routes through ``_get_connected_server_for_call`` → ``_ensure_lazy_server_connected``. + """ + from tools.mcp_schema_cache import config_fingerprint, tools_from_cache_entry, utility_tools_from_cache_entry + tool_timeout = _resolve_tool_timeout(config) + cached_tools = _cached_tools(tools_from_cache_entry(entry)) + _record_tool_trust_metadata(name, config, cached_tools) + candidates = _tool_candidates(name, cached_tools, _make_tool_filter(name, config), tool_timeout) + candidates += _utility_candidates(name, utility_tools_from_cache_entry(entry), tool_timeout) + registered = _register_candidates( + name, candidates, check_fn=_make_check_fn(name), scope=_core._mcp_registry_scope, lazy=True) + if registered: + with _core._lock: + key = _server_key(name) + _core._lazy_server_configs[key] = dict(config) + _core._lazy_server_fingerprints[key] = config_fingerprint(config) + _core._lazy_server_tool_names[key] = list(registered) + logger.info("MCP server '%s' (lazy): registered %d tool(s) from schema cache", name, len(registered)) + return registered diff --git a/tools/mcp_tool_schema.py b/tools/mcp_tool_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..e0967b01267c52e347857b89978d75fa679052fc --- /dev/null +++ b/tools/mcp_tool_schema.py @@ -0,0 +1,242 @@ +"""MCP tool schema conversion and naming: JSON-schema normalisation for provider +compatibility, mcp__server__tool naming, utility-tool schemas, include/exclude filters and +description injection scanning.""" + +import logging +import hashlib +import fnmatch +import re +from typing import Any, List +from tools.ansi_strip import strip_unicode_tags +from tools.mcp_tool_common import mcp_field + +logger = logging.getLogger("tools.mcp_tool") + +# Prompt-injection indicators in MCP tool descriptions. WARNING-level only: log but never +# block, since false positives would break legitimate servers. +_MCP_INJECTION_PATTERNS = [ + (re.compile(pattern, re.I), reason) + for pattern, reason in ( + (r"ignore\s+(all\s+)?previous\s+instructions", "prompt override attempt ('ignore previous instructions')"), + (r"you\s+are\s+now\s+a", "identity override attempt ('you are now a...')"), + (r"your\s+new\s+(task|role|instructions?)\s+(is|are)", "task override attempt"), + (r"system\s*:\s*", "system prompt injection attempt"), + (r"<\s*(system|human|assistant)\s*>", "role tag injection attempt"), + (r"do\s+not\s+(tell|inform|mention|reveal)", "concealment instruction"), + (r"(curl|wget|fetch)\s+https?://", "network command in description"), + (r"base64\.(b64decode|decodebytes)", "base64 decode reference"), + (r"exec\s*\(|eval\s*\(", "code execution reference"), + (r"import\s+(subprocess|os|shutil|socket)", "dangerous import reference"))] + + +def _scan_mcp_description(server_name: str, tool_name: str, description: str) -> List[str]: + """Scan a tool description for injection patterns; returns finding strings (empty = + clean) and logs a warning when any match.""" + if not description: + return [] + findings = [reason for pattern, reason in _MCP_INJECTION_PATTERNS if pattern.search(description)] + if findings: + logger.warning("MCP server '%s' tool '%s': suspicious description content — %s. Description: %.200s", + server_name, tool_name, "; ".join(findings), description) + return findings + + +_EMPTY_OBJECT_SCHEMA = {"type": "object", "properties": {}} + + +def _rewrite_local_refs(node): + """Promote legacy ``definitions`` to ``$defs`` (Moonshot rejects the draft-07 form) — ONLY + where it is a JSON Schema meta-keyword, never as a property NAME inside + ``properties``/``patternProperties``: a parameter legitimately named ``definitions`` + rewritten to ``$defs`` would 400 the whole tool array (Anthropic/OpenAI forbid ``$`` in + property names).""" + if isinstance(node, list): + return [_rewrite_local_refs(item) for item in node] + if not isinstance(node, dict): + return node + normalized = {} + for key, value in node.items(): + if key in ("properties", "patternProperties") and isinstance(value, dict): + normalized[key] = {name: _rewrite_local_refs(schema) for name, schema in value.items()} + else: + normalized["$defs" if key == "definitions" else key] = _rewrite_local_refs(value) + ref = normalized.get("$ref") + if isinstance(ref, str) and ref.startswith("#/definitions/"): + normalized["$ref"] = "#/$defs/" + ref[len("#/definitions/"):] + return normalized + + +def _repair_object_shape(node): + """Recursively fill a missing object ``type``, ensure ``properties`` (so ``required`` + can't dangle) and prune ``required`` to names present in ``properties`` (Gemini 400s + otherwise).""" + if isinstance(node, list): + return [_repair_object_shape(item) for item in node] + if not isinstance(node, dict): + return node + repaired = {k: _repair_object_shape(v) for k, v in node.items()} + if not repaired.get("type") and ("properties" in repaired or "required" in repaired): + repaired["type"] = "object" + if repaired.get("type") == "object": + if not isinstance(repaired.get("properties"), dict): + repaired["properties"] = {} + required = repaired.get("required") + if isinstance(required, list): + props = repaired.get("properties") or {} + valid = [r for r in required if isinstance(r, str) and r in props] + if len(valid) != len(required): + if valid: + repaired["required"] = valid + else: + repaired.pop("required", None) + return repaired + + +# Lazy (schema-cache registered) servers are available: the first real call spawns/connects them (#56832). +def _normalize_mcp_input_schema(schema: dict | None) -> dict: + """Normalize MCP input schemas so one form is valid on OpenAI, Anthropic, Gemini and + Moonshot. Order matters: ``definitions`` -> ``$defs``; nullable ``anyOf`` unions collapsed + to the non-null branch (Anthropic rejects nullable branches; optionality lives in the + parent's ``required``; the ``nullable: true`` hint is kept so runtime coercion can map a + model-emitted ``"null"`` string to ``None``); same-typed const unions -> enum (AFTER the + nullable strip); then object-shape repair. + + * Missing or ``null`` ``type`` on an object-shaped node is coerced to ``"object"`` (some servers omit + it). See PR #4897. * When an ``object`` node lacks ``properties``, an empty ``properties`` dict is added + so ``required`` entries don't dangle. * ``required`` arrays are pruned to only names that exist in + ``properties``; otherwise Google AI Studio / Gemini 400s with ``property is not defined``. See PR #4651. + * MCP/Pydantic optional fields commonly arrive as ``anyOf: [{...}, {"type": "null"}], default: null``. + """ + if not schema: + return dict(_EMPTY_OBJECT_SCHEMA) + from tools.schema_sanitizer import collapse_const_unions, strip_nullable_unions + normalized = _rewrite_local_refs(schema) + normalized = strip_nullable_unions(normalized, keep_nullable_hint=True) + normalized = collapse_const_unions(normalized) + normalized = _repair_object_shape(normalized) + if not isinstance(normalized, dict): + return dict(_EMPTY_OBJECT_SCHEMA) + if normalized.get("type") == "object" and "properties" not in normalized: + normalized = {**normalized, "properties": {}} + return normalized + + +def sanitize_mcp_name_component(value: str) -> str: + """Replace every char outside ``[A-Za-z0-9_]`` with ``_`` (hyphens included, the + historical behavior) so generated names pass provider validation.""" + return re.sub(r"[^A-Za-z0-9_]", "_", str(value or "")) + + +# ``mcp____``: the convention shared by Claude Code, Codex and OpenCode. The +# double underscore disambiguates the server/tool boundary even when either contains +# underscores, and matches the Anthropic-OAuth wire form. +# Native MCP tool-name prefix. It also aligns native registration with the Anthropic-OAuth wire form +# (``_MCP_TOOL_PREFIX`` in anthropic_adapter.py), removing the single->double rewrite that path previously +# had to perform. See #33533. +MCP_TOOL_NAME_PREFIX = "mcp__" + + +# OpenAI-compatible providers validate function names against ``^[a-zA-Z0-9_-]{1,64}$`` and 400 the +# whole request when one generated name is longer. Portable plugin server keys fold the plugin name in +# several times, so ``mcp____`` routinely passes 64 chars there (#81331). Clamp with a +# deterministic hash suffix (same idea as ``schema_sanitizer.sanitize_property_key``); dispatch is +# unaffected because handlers close over the original unprefixed tool name. +_MCP_TOOL_NAME_MAX_LENGTH = 64 +_MCP_TOOL_NAME_HASH_LENGTH = 8 +_clamped_names_warned: set[str] = set() + + +def mcp_prefixed_tool_name(server_name: str, tool_name: str) -> str: + """Registry/wire name: ``mcp____``, clamped to 64 chars with a + stable hash suffix when the natural name is longer.""" + full_name = f"{MCP_TOOL_NAME_PREFIX}{sanitize_mcp_name_component(server_name)}__{sanitize_mcp_name_component(tool_name)}" + if len(full_name) <= _MCP_TOOL_NAME_MAX_LENGTH: + return full_name + suffix = "_" + hashlib.sha256(full_name.encode("utf-8")).hexdigest()[:_MCP_TOOL_NAME_HASH_LENGTH] + if full_name not in _clamped_names_warned: # recomputed on every health refresh; warn once + _clamped_names_warned.add(full_name) + logger.warning("MCP tool name %r (%d chars) exceeds the %d-char provider limit; shortened to a " + "deterministic hash-suffixed name", full_name, len(full_name), _MCP_TOOL_NAME_MAX_LENGTH) + return full_name[:_MCP_TOOL_NAME_MAX_LENGTH - len(suffix)] + suffix + + +def _convert_mcp_schema(server_name: str, mcp_tool) -> dict: + """Convert an MCP ``Tool`` (``.input_schema``, or ``.inputSchema`` before mcp 2.0) to a + ``registry.register(schema=...)`` dict.""" + return { + "name": mcp_prefixed_tool_name(server_name, mcp_tool.name), + "description": strip_unicode_tags(mcp_tool.description or f"MCP tool {mcp_tool.name} from {server_name}"), + "parameters": _normalize_mcp_input_schema(mcp_field(mcp_tool, "input_schema", "inputSchema")), + } + + +# Utility tools generated per server: handler_key -> (description template, parameter +# properties, required names). Schemas are FROZEN wire bytes — the key order emitted by +# ``_build_utility_schemas`` must not change. +_UTILITY_TOOL_SPECS = ( + ("list_resources", "List available resources from MCP server '{server}'", {}, None), + ("read_resource", "Read a resource by URI from MCP server '{server}'", + {"uri": {"type": "string", "description": "URI of the resource to read"}}, ["uri"]), + ("list_prompts", "List available prompts from MCP server '{server}'", {}, None), + ("get_prompt", "Get a prompt by name from MCP server '{server}'", + { + "name": {"type": "string", "description": "Name of the prompt to retrieve"}, + "arguments": { + "type": "object", + "description": "Optional arguments to pass to the prompt", + "properties": {}, + "additionalProperties": True}, + }, ["name"])) + + +def _build_utility_schemas(server_name: str) -> List[dict]: + """Schemas for the resource/prompt utility tools as ``{schema, handler_key}`` dicts.""" + out = [] + for handler_key, description, properties, required in _UTILITY_TOOL_SPECS: + parameters = {"type": "object", "properties": {k: dict(v) for k, v in properties.items()}} + if required is not None: + parameters["required"] = list(required) + out.append({ + "schema": { + "name": mcp_prefixed_tool_name(server_name, handler_key), + "description": description.format(server=server_name), + "parameters": parameters}, + "handler_key": handler_key}) + return out + + +def _normalize_name_filter(value: Any, label: str) -> set[str]: + """Normalize include/exclude config to a set of exact names or fnmatch globs.""" + if value is None: + return set() + if isinstance(value, str): + return {value} + if isinstance(value, (list, tuple, set)): + return {str(item) for item in value} + logger.warning("MCP config %s must be a string or list of strings; ignoring %r", label, value) + return set() + + +def matches_name_filter(tool_name: str, patterns: set[str]) -> bool: + """True if ``tool_name`` matches any entry: exact names literally, entries with + ``*``/``?``/``[`` as case-sensitive globs (same semantics as ``approvals.deny``). Exact + membership is checked first so big lists stay O(1).""" + if not patterns: + return False + if tool_name in patterns: + return True + return any(fnmatch.fnmatchcase(tool_name, p) for p in patterns if "*" in p or "?" in p or "[" in p) + + +# Utility handler -> capability key that must be non-None on the server's ``initialize`` +# response for the handler to be registered. Without this gate a tools-only server got all +# four stubs and every call returned JSON-RPC -32601, making the model conclude the server +# was broken. +# Source of truth: MCP spec — capabilities.resources / capabilities.prompts are present on the response only +# when the server actually implements those request families. Context7 @upstash/context7-mcp, which +# advertises only ``tools``) had all four utility stubs registered and every model call to them came back +# with JSON-RPC ``-32601 Method not found``, which made the model conclude the server was broken even when +# the real tools worked. See #18051. +_UTILITY_CAPABILITY_ATTRS = { + "list_resources": "resources", "read_resource": "resources", + "list_prompts": "prompts", "get_prompt": "prompts"} diff --git a/tools/mcp_tool_transport.py b/tools/mcp_tool_transport.py new file mode 100644 index 0000000000000000000000000000000000000000..d6d6751cb0b6b6f36a1e26a7849d02154065e93b --- /dev/null +++ b/tools/mcp_tool_transport.py @@ -0,0 +1,498 @@ +"""Transport bring-up for MCPServerTask: stdio spawn (OSV preflight, cached-npx swap, child PID +ledger + death-supervisor registration), Streamable HTTP / SSE connect (preflight, identity header, client certs, OAuth), +protocol negotiation and initial tool discovery. Split from tools/mcp_tool.py.""" + +import logging +import asyncio +import os +from contextlib import asynccontextmanager +from typing import Dict, Optional, Set +from tools.mcp_tool_errors import NonMcpEndpointError, _apply_identity_header, _handshake_rejected_as_modern, _is_streamable_http_rejection, _make_mcp_body_cap_transport, _make_redirect_header_stripper, _resolve_client_cert, _unwrap_exception_group +from tools.mcp_tool_lifecycle import _filter_mcp_children, _orphan_stdio_pid_servers, _orphan_stdio_pids, _stdio_pgids, _stdio_pids +from tools.mcp_tool_common import _core +from tools import mcp_tool_config as _config +from tools import mcp_tool_lifecycle as _lifecycle +from tools import mcp_tool_registration as _registration + +logger = logging.getLogger("tools.mcp_tool") + +_PROBE_INITIALIZE_BODY = ( # JSON-RPC ``initialize`` body for the content-type preflight POST + '{"jsonrpc":"2.0","id":"_probe","method":"initialize","params":{"protocolVersion":"2025-03-26",' + '"capabilities":{},"clientInfo":{"name":"hermes-probe","version":"0.1"}}}') + + +def _content_type_base(resp) -> str: + """``content-type`` header of *resp* without parameters, lowercased.""" + return resp.headers.get("content-type", "").split(";")[0].strip().lower() + + +def _is_2xx(resp) -> bool: + return 200 <= resp.status_code < 300 + + +def _present(**kwargs) -> dict: + """*kwargs* minus the ``None`` values (optional httpx client arguments).""" + return {k: v for k, v in kwargs.items() if v is not None} + + +def _pgroup_alive(pgid: Optional[int]) -> bool: + """Signal 0 to the group succeeds iff any member is alive (POSIX only).""" + try: + os.killpg(pgid, 0) # windows-footgun: ok — guarded by AttributeError below + return True + except (AttributeError, TypeError, OSError): # non-POSIX / pgid None / gone + return False + + +class MCPServerTransportMixin: + """Methods of :class:`tools.mcp_tool.MCPServerTask` (mixed in; relies on its attributes).""" + + __slots__ = () + + def _advertises_tools(self) -> bool: + """False only when captured capabilities omit ``tools`` (prompt-/resource-only servers, + where ``tools/list`` raises -32601); True without capability info (legacy fallback). + + Per the MCP spec, ``InitializeResult.capabilities.tools`` is non-None iff the server implements the + ``tools/*`` request family. Prompt-only or resource-only servers omit it, and calling ``tools/list`` + against them raises ``MCPError(-32601 Method not found)`` — which previously killed the connection + during discovery and made every keepalive fail. (Ported from anomalyco/opencode#31271.) + """ + caps = getattr(self.initialize_result, "capabilities", None) + return caps is None or getattr(caps, "tools", None) is not None + + def _session_kwargs(self) -> dict: + """ClientSession kwargs: sampling, elicitation, notification + logging callbacks.""" + kwargs = {} + for handler in (self._sampling, self._elicitation): + if handler: + kwargs.update(handler.session_kwargs()) + if _core._MCP_NOTIFICATION_TYPES and _core._MCP_MESSAGE_HANDLER_SUPPORTED: + kwargs["message_handler"] = self._make_message_handler() + if _core._MCP_LOGGING_CALLBACK_SUPPORTED: + kwargs["logging_callback"] = self._make_logging_callback() + return kwargs + + async def _negotiate_session(self, session, connect_timeout: float): + """Negotiate the protocol era (``initialize`` vs ``server/discover``; both expose + ``.capabilities``). ``auto`` tries the legacy handshake FIRST, falling back to discover only + on a modern-only signal (-32022 / initialize -32601) — the reverse of the SDK's discover-first + mode, so handshake-era servers pay zero extra round-trips. ``stateless`` probes discover first + (one legacy retry on any error); ``legacy`` is handshake only. A TIMEOUT never falls back.""" + def call(method: str): + return asyncio.wait_for(getattr(session, method)(), timeout=connect_timeout) + + async def attempt(primary, fallback, should_fallback, log_fmt, *log_extra): + try: + return await call(primary) + except Exception as exc: + if isinstance(exc, asyncio.TimeoutError) or not should_fallback(exc): + raise + logger.info(log_fmt, self.name, exc, *log_extra) + return await call(fallback) + mode = str((self._config or {}).get("protocol", "auto")).lower().strip() + if mode in ("stateless", "modern", "2026-07-28"): + return await attempt("discover", "initialize", lambda exc: True, + "MCP server '%s': server/discover rejected (%s) despite " + "protocol=%s — falling back to the legacy handshake", mode) + if mode in ("legacy", "handshake"): + return await call("initialize") + if mode != "auto": + logger.warning("MCP server '%s': unknown protocol=%r — treating as 'auto' " + "(valid: auto, stateless, legacy)", self.name, mode) + # mcp 1.x has no server/discover client — nothing to fall back to. + return await attempt( + "initialize", "discover", lambda exc: _handshake_rejected_as_modern(exc) and hasattr(session, "discover"), + "MCP server '%s': legacy handshake rejected (%s) — retrying via server/discover (2026-07-28 stateless server)") + + async def _serve_session(self, session, connect_timeout: float, + label: str = "", mark_lifecycle: bool = False) -> str: + """Handshake, discover, publish readiness, then serve until a lifecycle event. Clears stale + breaker state but leaves the session UNPROVEN: flapping transports handshake fine and drop + moments later, so only keepalive/tool-call success clears the reconnect budget.""" + self.initialize_result = await self._negotiate_session(session, connect_timeout) + self.session = session + if mark_lifecycle: + self._mark_lifecycle_started() + await self._discover_tools() + self._ready.set() + self._ever_connected = True + _core._reset_server_error(self.name) + # Session is live again: clear any breaker state from a prior outage so the first call after + # recovery isn't gated on a stale consecutive-failure count (#16788). + # A completed handshake alone is NOT proof of health: a flapping transport can handshake fine and + # drop moments later, forever (#62212). The session must prove itself (keepalive success or a + # successful tool call) before the reconnect budget is cleared — see _mark_session_proven. + # Session is live again: clear any breaker state from a prior outage so the first call after + # recovery isn't gated on a stale consecutive-failure count (#16788). + # Unproven until keepalive/tool-call success (#62212). + # Session is live again: clear any breaker state from a prior outage so the first call after + # recovery isn't gated on a stale failure count (#16788). + # Unproven until keepalive/tool-call success (#62212). + # Session is live again: clear any breaker state from a prior outage so the first call after + # recovery isn't gated on a stale consecutive-failure count (#16788). + # Unproven until keepalive/tool-call success (#62212). + self._session_proven = False + reason = await self._wait_for_lifecycle_event() + if label and reason == "reconnect": + logger.info("MCP server '%s': reconnect requested — tearing down %s session", self.name, label) + return reason + + async def _serve_transport(self, transport_cm, label: str, connect_timeout: float) -> str: + """Open *transport_cm*, wrap its streams in a ClientSession and serve it. Streams are indexed, + not unpacked (mcp 1.x yields a 3-tuple, 2.x a pair); a TaskGroup drop maps to ``"reconnect"``.""" + try: + async with transport_cm as _streams: + async with _core.ClientSession(_streams[0], _streams[1], **self._session_kwargs()) as session: + return await self._serve_session(session, connect_timeout, label) + except BaseExceptionGroup as _eg: + return self._reconnect_or_reraise_group(_eg) + + # ------------------------------------------------------------------ stdio + + def _track_spawned_children(self, new_pids: Set[int]) -> None: + """Ledger the freshly spawned stdio children (pids, pgids, machine spawn ledger). pgids are + captured while alive (getpgid fails after exit; the sweep needs them for reparented descendants).""" + new_pgids: Dict[int, int] = {} + for pid in new_pids: + try: + new_pgids[pid] = os.getpgid(pid) + except ProcessLookupError: + # Raced and already exited. The SDK spawns with start_new_session=True, so the + # child was its own group leader (pgid == pid): keep that group covered — any + # descendant it left behind still has to be reaped; the prune forgets the group + # once nothing in it is alive. + new_pgids[pid] = pid + except (AttributeError, OSError): # Windows (os.getpgid is POSIX-only) + pass + with _core._lock: + _stdio_pids.update(dict.fromkeys(new_pids, self.name)) + _stdio_pgids.update(new_pgids) + # Machine spawn ledger (startup sweeps reap orphans after an unclean exit); best-effort. + for _pid in new_pids: + try: + from hermes_cli.process_identity import register_child + register_child(_pid, "mcp-helper") + except Exception: + logger.debug("spawn-ledger register_child failed for MCP helper pid %s", _pid, exc_info=True) + # Hand the pgroups to the shared parent-death supervisor so an ungraceful exit of this + # process (kill -9, crash, force-quit) can't leave this server — or its descendants, e.g. + # mcp-remote's spawned `node` — running forever. The graceful paths (shutdown, + # _kill_orphaned_mcp_children) still reap as before; this only covers when they never run. + _core._update_death_supervisor("register", new_pgids.values()) + + def _release_spawned_children(self, new_pids: Set[int]) -> None: + """Drop the ledger entries; a child (or its pgroup) still alive means SDK teardown failed + (common on mid-way cancel on Linux: setsid() children escape) — mark it orphaned for the sweep.""" + from gateway.status import _pid_exists + # Groups with nothing left alive; the supervisor forgets them after the lock is released. + # Groups still alive stay registered on purpose, so the supervisor still reaps them if this + # process dies before the orphan sweep runs. + released_pgids: list = [] + with _core._lock: + for pid in new_pids: + _stdio_pids.pop(pid, None) + # Windows-safe pid probe; the child may be gone while descendants remain in its pgroup. + if _pid_exists(pid) or _pgroup_alive(_stdio_pgids.get(pid)): + _orphan_stdio_pids.add(pid) + _orphan_stdio_pid_servers[pid] = self.name + else: # nothing to reap — drop the pgid so PID reuse can't surface stale pgroup state + dropped = _stdio_pgids.pop(pid, None) + if dropped is not None: + released_pgids.append(dropped) + _core._update_death_supervisor("unregister", released_pgids) + + async def _run_stdio(self, config: dict): + """Run the server using stdio transport.""" + if config.get("identity_header") is not None: # copy-pasted HTTP block: warn, don't mislead + logger.warning("MCP server '%s': identity_header is only supported on " + "HTTP/SSE transports — ignored for stdio servers", self.name) + if not _core._ensure_mcp_sdk(): + raise ImportError(f"MCP server '{self.name}' requires the 'mcp' Python SDK, but " + "it is not installed. Run `hermes setup` to install MCP support, then retry.") + command = config.get("command") + if not command: + raise ValueError(f"MCP server '{self.name}' has no 'command' in config") + command, safe_env = _config._resolve_stdio_command(command, _config._build_safe_env(config.get("env"))) + # OSV malware preflight, then the cached-npx swap (ordering enforced there). + command, args = await _core._preflight_stdio_command(self.name, command, config.get("args", [])) + server_params = _core.StdioServerParameters( + command=command, args=args, env=safe_env or None, cwd=config.get("cwd"), + # Windows pipes can split non-UTF-8 bytes at chunk boundaries; substitute, don't raise. + encoding_error_handler="replace") + # Reap orphans of prior attempts first (else retries pile up zombie pairs); unscoped on purpose; + # off-loop because the reaper blocks up to 2s. + await asyncio.to_thread(_lifecycle._kill_orphaned_mcp_children) + pids_before = _lifecycle._snapshot_child_pids() # so the new child can be identified after spawn + # Reap any orphaned subprocesses from prior failed connection attempts before spawning a new one. + # Without this, each retry in the run() reconnect loop spawns a fresh process pair while the + # previous failed pair lingers — leading to rapid zombie accumulation (see #57355, #57228). The + # unscoped sweep also opportunistically reaps orphans left by *other* servers that never reconnect; + # per-server filtering via ``server_name`` remains available for scoped call sites. Run in a worker + # thread: the reaper blocks up to 2s (SIGTERM → wait → SIGKILL) when orphans exist, which would + # otherwise stall the shared MCP event loop. + new_pids: set = set() + # Subprocess stderr goes to ~/.hermes/logs/mcp-stderr.log so banners can't corrupt the TUI. + _config._write_stderr_log_header(self.name) + try: + errlog = _config._get_mcp_stderr_log() + async with _core.stdio_client(server_params, errlog=errlog) as (read_stream, write_stream): + # New PIDs for force-kill cleanup, minus non-MCP children (slash_worker, LSP) racing + # into the window: they share the TUI's pgid — leaking them would killpg() the TUI. + new_pids = _filter_mcp_children(_lifecycle._snapshot_child_pids() - pids_before) + if new_pids: + self._track_spawned_children(new_pids) + self._stdio_child_pids = set(new_pids) # so in-flight calls fail fast when the child dies + async with _core.ClientSession(read_stream, write_stream, **self._session_kwargs()) as session: + # Bound the handshake here (``connect_timeout`` only bounds the caller's ``.result()``): + # a server that never answers ``initialize`` would leak child + pipes per retry until EMFILE. + connect_timeout = float(config.get("connect_timeout", _core._DEFAULT_CONNECT_TIMEOUT)) + return await self._serve_session(session, connect_timeout, mark_lifecycle=True) + finally: # clean exit, exceptions AND cancellation + if new_pids: + self._release_spawned_children(new_pids) + + # ------------------------------------------------------------------- HTTP + + async def _preflight_content_type(self, url: str, *, headers: Optional[dict] = None, + ssl_verify: bool = True, client_cert=None, timeout: float = 5.0) -> None: + """Probe *url* before the SDK connects: a plain web page would make the SDK sit out the full + ``connect_timeout`` before an opaque ``CancelledError``; this raises NonMcpEndpointError within + ``timeout``. Allow-list based: only a 2xx with a definite non-MCP content type is rejected, and + only after a JSON-RPC ``initialize`` POST also fails to look like MCP (some servers serve a UI + on GET but speak MCP via POST). Anything else passes — the handshake stays the source of truth. + Own httpx client, OUTSIDE the SDK's anyio task group, so the error isn't group-wrapped.""" + try: + import httpx as _httpx + except ImportError: + return # No httpx → skip probe; SDK import would have failed first. + + def _non_mcp_2xx(resp) -> bool: + # Only judge 2xx (4xx/5xx may be an auth challenge); no content type advertised → trust the SDK. + ct = _content_type_base(resp) + return _is_2xx(resp) and bool(ct) and ct not in self._MCP_CONTENT_TYPES + probe_headers = dict(headers) if headers else {} + try: + async with _httpx.AsyncClient(verify=ssl_verify, follow_redirects=True, timeout=_httpx.Timeout(timeout), + **_present(cert=client_cert)) as client: + resp = await client.head(url, headers=probe_headers) # cheapest; GET on 405/501 + if resp.status_code in (405, 501): + resp = await client.get(url, headers=probe_headers) + # Non-MCP content type on HEAD/GET: try a JSON-RPC POST so POST-only servers pass. + if _non_mcp_2xx(resp): + post_resp = await client.post( + url, content=_PROBE_INITIALIZE_BODY, + headers={**probe_headers, "Content-Type": "application/json", + "Accept": "application/json, text/event-stream"}) + if _is_2xx(post_resp) and _content_type_base(post_resp) in self._MCP_CONTENT_TYPES: + resp = post_resp + except _httpx.HTTPError: + return # DNS/connect/timeout/transport error — let the SDK try. + if not _non_mcp_2xx(resp): + return + ct_base = _content_type_base(resp) + raise NonMcpEndpointError(f"MCP server '{self.name}' at {url} returned Content-Type '{ct_base}', not an MCP " + f"response (expected one of: {', '.join(self._MCP_CONTENT_TYPES)}). The URL most likely " + "points at a web page rather than an MCP endpoint — check it resolves to a Streamable " + "HTTP / SSE endpoint (e.g. https://host/mcp, not https://host/).") + + def _reconnect_or_reraise_group(self, eg: BaseExceptionGroup) -> str: + """Map an SDK transport TaskGroup failure to a clean ``"reconnect"``: HTTP/SSE stream pumps run in an anyio + TaskGroup, so a transient drop escapes as a ``BaseExceptionGroup`` that would otherwise park the server for + 300s over a sub-second glitch. Re-raise when it is not one: shutdown in progress (``_shutdown_event`` is + set before cancel), KeyboardInterrupt/SystemExit or a real CancelledError in the group, or no live session + this attempt (``_ready`` unset — connect failures must back off, not hot-loop). + + Streamable-HTTP / SSE transports run their stream pump inside an anyio TaskGroup. A transient stream + drop (idle timeout, brief backend blip, server-side TCP close) surfaces as a ``BaseExceptionGroup`` + escaping the transport context manager. Left unwrapped it reaches ``run()``'s error path, which + applies exponential backoff and eventually *parks* the server for 300s and deregisters its tools — a + multi-minute tool outage for what is usually a sub-second glitch while the POST path stays healthy + (issue #66092). + - the group carries a ``KeyboardInterrupt`` / ``SystemExit`` — fatal signals must propagate to the + interpreter, never be converted into a reconnect; - the group carries a real ``CancelledError`` + (task cancellation must propagate to asyncio, mirroring the ``run()`` guard for #9930); - we never + reached a live session this attempt (``_ready`` unset) — a connect/handshake failure SHOULD fall + through to ``run()``'s backoff rather than hot-loop reconnects against a broken endpoint. + """ + if (self._shutdown_event.is_set() + or eg.split((KeyboardInterrupt, SystemExit))[0] is not None + or eg.split(asyncio.CancelledError)[0] is not None + or not self._ready.is_set()): + raise eg + logger.debug("MCP server '%s': transport TaskGroup exited after a live session " + "(%r) — reconnecting immediately instead of backing off", self.name, eg) + return "reconnect" + + def _build_oauth_auth(self, url: str, config: dict): + """OAuth 2.1 PKCE via the central MCPOAuthManager (one provider reused across reconnects and + CLI paths). Setup failures re-raise (after a warning) so only this server is reported failed.""" + if self._auth_type != "oauth": + return None + try: + from tools.mcp_oauth_manager import get_manager + return get_manager().get_or_build_provider(self.name, url, config.get("oauth")) + except Exception as exc: + logger.warning("MCP OAuth setup failed for '%s': %s", self.name, exc) + raise + + def _sse_transport(self, url: str, headers: dict, connect_timeout: float, + ssl_verify, client_cert, oauth_auth, strict_cfg_headers: bool): + """``sse_client`` context manager for ``transport: sse`` entries.""" + if strict_cfg_headers: # fail closed: SSE cannot enforce the redirect boundary + raise ValueError(f"MCP server '{self.name}': strict_redirect_headers is " + "not supported on the SSE transport.") + if _core.sse_client is None: + raise ImportError(f"MCP server '{self.name}' requires SSE transport but " + "mcp.client.sse.sse_client is not available. " + "Upgrade the mcp package to get SSE support.") + # sse_read_timeout bounds the gap between events: SSE servers idle for minutes, so 300s (the + # Streamable HTTP read timeout), not tool_timeout. ``auth`` must be forwarded or OAuth SSE 401s silently. + sse_kwargs: dict = {"url": url, "headers": headers or None, "timeout": float(connect_timeout), + "sse_read_timeout": 300.0, **_present(auth=oauth_auth)} + # Always own the client: the httpx_client_factory forwards the SDK's (headers, auth, timeout), + # installs the wire-body cap and layers TLS on the inner transport (client-level verify/cert are + # inert once a custom transport= is passed). Client MUST come from the SDK's httpx (httpx2 on mcp >= 2.0). + _httpx_mod = _core.sdk_httpx() + sse_kwargs["httpx_client_factory"] = lambda headers=None, timeout=None, auth=None: _httpx_mod.AsyncClient( + follow_redirects=True, + timeout=timeout if timeout is not None else _httpx_mod.Timeout(30.0, read=300.0), + transport=_make_mcp_body_cap_transport( + _httpx_mod, _httpx_mod.AsyncHTTPTransport(verify=ssl_verify, **_present(cert=client_cert))), + **_present(headers=headers, auth=auth)) + return _core.sse_client(**sse_kwargs) + + def _streamable_http_transport(self, url: str, headers: dict, connect_timeout: float, + ssl_verify, client_cert, oauth_auth, + strict_cfg_headers: bool, configured_header_names: set): + """Streamable HTTP context manager: mcp >= 1.24.0 gets a caller-owned httpx client; on the + deprecated API (mcp < 1.24.0) the SDK owns the client.""" + if not _core._MCP_NEW_HTTP: + if strict_cfg_headers: # fail closed: without an owned client redirects can't be hooked + raise ImportError(f"MCP server '{self.name}' requires mcp >= 1.24.0 to " + "enforce the portable redirect-header boundary " + "(strict_redirect_headers). Upgrade the mcp package.") + return _core.streamablehttp_client(url, headers=headers, timeout=float(connect_timeout), verify=ssl_verify, + **_present(auth=oauth_auth)) + # Explicit AsyncClient matching the SDK's create_mcp_http_client defaults; MUST come from the + # SDK's httpx (httpx2 on mcp >= 2.0) since the SDK sends its own Requests through it. + httpx = _core.sdk_httpx() + _strip_auth_on_cross_origin_redirect = _make_redirect_header_stripper( + httpx.URL(url), strict=strict_cfg_headers, configured_header_names=configured_header_names) + # verify/cert live on the inner transport: a custom transport= makes client-level TLS kwargs inert. + client_kwargs: dict = {"follow_redirects": True, "timeout": httpx.Timeout(float(connect_timeout), read=300.0), + **({"headers": headers} if headers else {}), + "event_hooks": {"response": [_strip_auth_on_cross_origin_redirect]}, + "transport": _make_mcp_body_cap_transport( + httpx, httpx.AsyncHTTPTransport(verify=ssl_verify, **_present(cert=client_cert))), + **_present(auth=oauth_auth)} + + @asynccontextmanager + async def _owned_client_streams(): # the SDK skips cleanup when http_client is provided + async with httpx.AsyncClient(**client_kwargs) as http_client: + async with _core.streamable_http_client(url, http_client=http_client) as streams: + yield streams + return _owned_client_streams() + + async def _run_http(self, config: dict): + """Run the server using HTTP/StreamableHTTP (or SSE) transport.""" + _core._ensure_mcp_sdk() + if not _core._MCP_HTTP_AVAILABLE: + raise ImportError(f"MCP server '{self.name}' requires HTTP transport but " + "mcp.client.streamable_http is not available. " + "Upgrade the mcp package to get HTTP support.") + url = config["url"] + headers = dict(config.get("headers") or {}) + # Agent Plugins v1 strict_redirect_headers: configured headers MUST NOT follow a cross-origin + # redirect — capture their names BEFORE client-generated headers are merged in. + configured_header_names = {key.lower() for key in headers} + headers = _apply_identity_header(self.name, config, headers) # explicit same-name headers win + # Seed MCP-Protocol-Version (user override wins) from the HANDSHAKE version, not the latest: a + # 2026-07-28 header routes the handshake-era ``initialize()`` onto the envelope ladder, which rejects it. + if not any(key.lower() == "mcp-protocol-version" for key in headers): + headers["mcp-protocol-version"] = _core.LATEST_HANDSHAKE_VERSION + connect_timeout = config.get("connect_timeout", _core._DEFAULT_CONNECT_TIMEOUT) + common = (url, headers, connect_timeout, config.get("ssl_verify", True), _resolve_client_cert(self.name, config), + self._build_oauth_auth(url, config), bool(config.get("strict_redirect_headers"))) + if config.get("transport") == "sse": + return await self._serve_transport(self._sse_transport(*common), "SSE", float(connect_timeout)) + if self._sse_fallback: + # A prior connect already proved this server SSE-only: skip the doomed Streamable + # HTTP attempt on reconnects instead of flapping into the retry budget. + logger.info("MCP server '%s': using latched SSE fallback transport", self.name) + return await self._serve_transport(self._sse_transport(*common), "SSE", float(connect_timeout)) + transport = self._streamable_http_transport(*common, configured_header_names) + label = "HTTP" if _core._MCP_NEW_HTTP else "legacy HTTP" + try: + return await self._serve_transport(transport, label, float(connect_timeout)) + except Exception as exc: + # SSE-only servers (or their load balancers) reject the Streamable HTTP chunked + # ``initialize`` POST — with a 400-family status or an opaque SDK INTERNAL_ERROR — + # previously a permanent failure with 0 active tools unless the user set + # ``transport: sse`` (#53676, #104343). Retry over SSE on the initial connect, as + # the MCP spec's transport-fallback behavior describes. Never on reconnect after a + # proven session (``_ever_connected``: a genuine rejection on an established + # transport must not silently switch transports), never on a timeout (not a + # transport mismatch — ``_is_streamable_http_rejection`` matches neither), and never + # with ``strict_redirect_headers`` (SSE cannot enforce that boundary). + if (self._ever_connected or common[-1] or not _is_streamable_http_rejection(exc)): + raise + logger.warning( + "MCP server '%s': Streamable HTTP rejected the initial connect (%s) — retrying " + "over SSE. If this connects, set `transport: sse` for this server in config.yaml " + "to skip the failed attempt on future startups.", + self.name, _unwrap_exception_group(exc)) + try: + self._sse_fallback = True + return await self._serve_transport(self._sse_transport(*common), "SSE", float(connect_timeout)) + except Exception as sse_exc: + if self._ever_connected: # SSE session was live and dropped: transient, keep the latch + raise + self._sse_fallback = False + raise ConnectionError( + f"MCP server '{self.name}': both Streamable HTTP and SSE transports failed " + f"(Streamable HTTP: {_unwrap_exception_group(exc)}; SSE: " + f"{_unwrap_exception_group(sse_exc)}). Check the URL points at an MCP " + "endpoint, or pin `transport: sse` if the server is SSE-only.") from sse_exc + + # -------------------------------------------------------------- discovery + + # Legacy Streamable-HTTP transport TaskGroup dropped: reconnect immediately instead of backoff/park + # (#66092). + async def _discover_tools(self): + """Discover tools from the connected session. Capability-gated: prompt-/resource-only + servers raise ``MCPError(-32601)`` on ``tools/list``, which would abort the connection. + + Skip the call when the server doesn't advertise the ``tools`` capability. (Ported from + anomalyco/opencode#31271.) + """ + self._ping_unsupported = False # fresh transport: re-probe ``ping`` across the reconnect + if self.session is None: + return + if not self._advertises_tools(): + logger.info("MCP server '%s': does not advertise 'tools' capability — " + "skipping tools/list (prompts/resources remain available)", self.name) + self._tools = [] + else: + async with self._rpc_lock: + self._list_cache_meta = {} + self._tools = await _core._paginate_full_list( + self.session.list_tools, "tools", self.name, cache_meta_out=self._list_cache_meta) + self._register_discovered_tools_if_needed() + + def _register_discovered_tools_if_needed(self) -> None: + """Publish freshly discovered tools when none are registered (initial registration normally happens in + ``_discover_and_register_server``). Outage handling may clear ``_ready`` and deregister stale tools; + ownership via ``_servers`` authorizes publishing before readiness is restored so a revival (or a server + retained after a recoverable initial failure) never comes back with zero tools.""" + if self._registered_tool_names: + return + with _core._lock: + owned = [key for key, live in _core._servers.items() if live is self] + if not owned and not self._ready.is_set(): + return + self._registered_tool_names = _registration._register_server_tools(self.name, self, self._config) + with _core._lock: # a retained initial-failure server that just published tools has recovered + for key in owned: + if _core._servers.get(key) is self: + _core._server_connect_errors.pop(key, None) diff --git a/tools/openrouter_client.py b/tools/openrouter_client.py new file mode 100644 index 0000000000000000000000000000000000000000..9037f3ab0df3021ee7270169426cea3b7e6afc4e --- /dev/null +++ b/tools/openrouter_client.py @@ -0,0 +1,43 @@ +"""OpenRouter API key probe shared by Hermes tools.""" + +import os + + +def check_api_key() -> bool: + """Return True if OPENROUTER_API_KEY is present. + + Scope-aware: an installed profile secret scope is authoritative under + multiplex; unscoped CLI probes fall back to the plain env read. + """ + try: + from agent.secret_scope import UnscopedSecretError, get_secret + try: + return bool(get_secret("OPENROUTER_API_KEY")) + except UnscopedSecretError: + pass + except Exception: + pass + return bool(os.getenv("OPENROUTER_API_KEY")) + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. + +def get_async_client(): + """Return a shared async OpenAI-compatible client for OpenRouter. + + The client is created lazily on first call and reused thereafter. + Uses the centralized provider router for auth and client construction. + Raises ValueError if OPENROUTER_API_KEY is not set. + """ + global _client + if _client is None: + from agent.auxiliary_client import resolve_provider_client + client, _model = resolve_provider_client("openrouter", async_mode=True) + if client is None: + raise ValueError("OPENROUTER_API_KEY environment variable not set") + _client = client + return _client +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/patch_parser.py b/tools/patch_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..39b469d9a9333faf11e25207ac7e6d5a06041d67 --- /dev/null +++ b/tools/patch_parser.py @@ -0,0 +1,418 @@ +"""V4A patch parser/applier (codex, cline). ``*** Begin Patch``/``*** End Patch`` wrap ops: +``*** Update File: p`` + hunks (``@@ hint @@``, `` ctx``, ``-old``, ``+new``); ``*** Add File: n`` ++ ``+`` lines; ``*** Delete File: o``; ``*** Move File: a -> b``. Entry points: +``parse_v4a_patch(text) -> (ops, error)`` and ``apply_v4a_operations(ops, file_ops)``.""" + +import contextlib +import difflib +import inspect +import re +from dataclasses import dataclass, field +from enum import Enum +from typing import Any, Callable, Dict, List, Optional, Tuple + +from tools.file_operations_common import PatchResult + + +class OperationType(Enum): + ADD = "add" + UPDATE = "update" + DELETE = "delete" + MOVE = "move" + + +@dataclass +class HunkLine: + prefix: str # ' ', '-', or '+' + content: str + + +@dataclass +class Hunk: + context_hint: Optional[str] = None + lines: List[HunkLine] = field(default_factory=list) + + +@dataclass +class PatchOperation: + operation: OperationType + file_path: str + new_path: Optional[str] = None # MOVE only + hunks: List[Hunk] = field(default_factory=list) + + +# Markers must occupy the whole line at column 0 so content lines that merely +# mention the format ("+*** End Patch") can't truncate or reset the patch. +_BEGIN_MARKER = re.compile(r'^\*\*\*\s*Begin\s+Patch\s*$') +_END_MARKER = re.compile(r'^\*\*\*\s*End\s+Patch\s*$') +_OP_MARKERS: List[Tuple[OperationType, re.Pattern]] = [ + (OperationType.UPDATE, re.compile(r'\*\*\*\s*Update\s+File:\s*(.+)')), + (OperationType.ADD, re.compile(r'\*\*\*\s*Add\s+File:\s*(.+)')), + (OperationType.DELETE, re.compile(r'\*\*\*\s*Delete\s+File:\s*(.+)')), + (OperationType.MOVE, re.compile(r'\*\*\*\s*Move\s+File:\s*(.+?)\s*->\s*(.+)'))] +_HINT_RE = re.compile(r'@@\s*(.+?)\s*@@') + + +def parse_v4a_patch(patch_content: str) -> Tuple[List[PatchOperation], Optional[str]]: + """-> ``(operations, None)`` (empty patch = ``[]``, no error) or ``([], "Parse error: …")``.""" + # Tolerate CRLF: a stray ``\r`` would land in every HunkLine.content and defeat the markers. + lines = [ln[:-1] if ln.endswith('\r') else ln for ln in patch_content.split('\n')] + start_idx = -1 # parse from the top when no Begin marker is present + end_idx = len(lines) + for i, line in enumerate(lines): + if _BEGIN_MARKER.match(line): + start_idx = i + elif _END_MARKER.match(line): + end_idx = i + break + operations: List[PatchOperation] = [] + current_op: Optional[PatchOperation] = None + current_hunk: Optional[Hunk] = None + + def _flush_hunk() -> None: + if current_op and current_hunk and current_hunk.lines: + current_op.hunks.append(current_hunk) + + def _flush() -> None: + if current_op: + _flush_hunk() + operations.append(current_op) + + for line in lines[start_idx + 1:end_idx]: + op_match = next(((kind, m) for kind, rx in _OP_MARKERS if (m := rx.match(line))), None) + if op_match: + kind, m = op_match + _flush() + current_op = PatchOperation( + operation=kind, + file_path=m.group(1).strip(), + new_path=m.group(2).strip() if kind is OperationType.MOVE else None) + # UPDATE hunks start lazily ('@@' or first hunk line); ADD collects all '+' lines + # into one hunk; DELETE/MOVE are complete. + current_hunk = Hunk() if kind is OperationType.ADD else None + if kind in (OperationType.DELETE, OperationType.MOVE): + operations.append(current_op) + current_op = None + elif line.startswith('@@'): + if current_op: + _flush_hunk() + hint_match = _HINT_RE.match(line) + current_hunk = Hunk(context_hint=hint_match.group(1) if hint_match else None) + elif current_op and line: + if current_hunk is None: + current_hunk = Hunk() + if line[0] in '+- ': + current_hunk.lines.append(HunkLine(line[0], line[1:])) + elif line[0] != '\\': # "\ No newline at end of file" marker is skipped + current_hunk.lines.append(HunkLine(' ', line)) # implicit context line + _flush() + parse_errors: List[str] = [] + for op in operations: + if not op.file_path: + parse_errors.append("Operation with empty file path") + if op.operation is OperationType.UPDATE and not op.hunks: + parse_errors.append(f"UPDATE {op.file_path!r}: no hunks found") + if op.operation is OperationType.MOVE and not op.new_path: + parse_errors.append( + f"MOVE {op.file_path!r}: missing destination path (expected 'src -> dst')") + return ([], "Parse error: " + "; ".join(parse_errors)) if parse_errors else (operations, None) + + +def _count_occurrences(text: str, pattern: str) -> int: + """Count occurrences of *pattern* in *text*, advancing one char per hit (overlaps count).""" + return sum(1 for i in range(len(text) + 1) if text.startswith(pattern, i)) + + +def _split_hunk(hunk: Hunk) -> Tuple[List[str], List[str]]: + """``(search_lines, replace_lines)``: context+removed vs context+added.""" + return ([l.content for l in hunk.lines if l.prefix != '+'], + [l.content for l in hunk.lines if l.prefix != '-']) + + +def _no_match_hint(error: Optional[str], search_pattern: str, content: str) -> str: + """Best-effort 'Did you mean...' suffix; never lets a hint failure mask the real error.""" + with contextlib.suppress(Exception): + from tools.fuzzy_match import format_no_match_hint + return format_no_match_hint(error, 0, search_pattern, content) + return "" + + +def _hint_ambiguity(content: str, hint: str, tail: str = "") -> Tuple[int, str]: + """(occurrences, error) for an addition-only hunk's context hint; error is '' when unique.""" + n = _count_occurrences(content, hint) + return n, f"context hint '{hint}' is ambiguous ({n} occurrences){tail}" if n > 1 else "" + + +def _validate_operations(operations: List[PatchOperation], file_ops: Any) -> List[str]: + """Dry-run every operation -> error strings (empty = safe). UPDATE hunks are simulated in + order so later hunks see post-earlier-hunk content, exactly as apply will.""" + from tools.fuzzy_match import fuzzy_find_and_replace, is_already_applied + errors: List[str] = [] + real_change_count = 0 + # Overlay so inter-op state validates (a MOVE creating the path a later UPDATE targets). + pending_content: dict = {} + removed_paths: set = set() + + def _read(path: str) -> Tuple[Optional[str], Optional[str]]: + if path in pending_content: + return pending_content[path], None + if path in removed_paths: + return None, "file not found" + r = file_ops.read_file_raw(path) + return (None, r.error) if r.error else (r.content, None) + + def _validate_update(op: PatchOperation) -> None: + nonlocal real_change_count + simulated, read_err = _read(op.file_path) + if read_err: + errors.append(f"{op.file_path}: {read_err}") + return + for hunk_index, hunk in enumerate(op.hunks, start=1): + search_lines, replace_lines = _split_hunk(hunk) + if search_lines == replace_lines: + # Context-only anchor hunks (models emit these between changes) are inert; identical + # -/+ lines are skipped by apply as a no-op — neither may fail validation. + real_change_count += any(l.prefix in '-+' for l in hunk.lines) + continue + real_change_count += 1 + if not search_lines: # addition-only: the context hint must be unique + if hunk.context_hint: + occurrences, ambiguous = _hint_ambiguity(simulated, hunk.context_hint) + if occurrences == 0: + errors.append(f"{op.file_path}: addition-only hunk context hint " + f"'{hunk.context_hint}' not found") + elif ambiguous: + errors.append(f"{op.file_path}: addition-only hunk {ambiguous}") + continue + search_pattern, replacement = '\n'.join(search_lines), '\n'.join(replace_lines) + new_simulated, count, _strategy, match_error = fuzzy_find_and_replace( + simulated, search_pattern, replacement, replace_all=False) + if count: + simulated = new_simulated + elif not is_already_applied(simulated or "", search_pattern, replacement): + # Already-applied hunks are no-ops (apply performs the same skip). + label = f"'{hunk.context_hint}'" if hunk.context_hint else "(no hint)" + errors.append( + f"{op.file_path}: hunk {hunk_index} {label} not found" + + (f" — {match_error}" if match_error else "") + + _no_match_hint(match_error, search_pattern, simulated)) + pending_content[op.file_path] = simulated + + def _remove(path: str) -> None: + removed_paths.add(path) + pending_content.pop(path, None) + + for op in operations: + if op.operation == OperationType.UPDATE: + _validate_update(op) + continue + real_change_count += 1 + if op.operation == OperationType.DELETE: + if _read(op.file_path)[1]: + errors.append(f"{op.file_path}: file not found for deletion") + else: + _remove(op.file_path) + elif op.operation == OperationType.MOVE: + if not op.new_path: + errors.append(f"{op.file_path}: MOVE operation missing destination path") + continue + src_content, src_err = _read(op.file_path) + if src_err: + errors.append(f"{op.file_path}: source file not found for move") + if not _read(op.new_path)[1]: + errors.append(f"{op.new_path}: destination already exists — move would overwrite") + elif not src_err: # only a cleanly-validated move updates the overlay + pending_content[op.new_path] = src_content if src_content is not None else "" + _remove(op.file_path) + elif op.operation == OperationType.ADD: + # An Add must create a NEW file. If the target already exists, write_file + # would clobber it with only the patch's '+' lines and report success, + # silently destroying the original contents (models frequently confuse Add + # with Update). Reject it here so the two-phase contract holds, mirroring + # the MOVE destination guard. Overlay-aware: an Add after a Delete of the + # same path in this patch stays legal, and the added content enters the + # overlay so later hunks against it validate. + if not _read(op.file_path)[1]: + errors.append(f"{op.file_path}: file already exists — use Update File, not Add File") + else: + removed_paths.discard(op.file_path) + pending_content[op.file_path] = '\n'.join( + line.content for hunk in op.hunks for line in hunk.lines if line.prefix == '+') + if not errors and real_change_count == 0: + errors.append("Patch contains no changes (only context lines were provided)") + return errors + + +# Every _apply_* returns (success, diff_or_error, lsp_diagnostics, lint_result). +ApplyResult = Tuple[bool, str, Optional[str], Optional[dict]] + + +def _fail(error: str) -> ApplyResult: + return False, error, None, None + + +def _written(result: Any, diff: str) -> ApplyResult: + """Outcome of a write: its error, else success with LSP/lint propagated from the WriteResult.""" + if result.error: + return _fail(result.error) + return True, diff, getattr(result, "lsp_diagnostics", None), getattr(result, "lint", None) + + +def _unified_diff(path: str, old: str, new: Optional[str]) -> str: + """Unified diff ``a/path`` -> ``b/path`` (``new=None`` = deletion, ``/dev/null``).""" + return ''.join(difflib.unified_diff( + old.splitlines(keepends=True), [] if new is None else new.splitlines(keepends=True), + fromfile=f"a/{path}", tofile="/dev/null" if new is None else f"b/{path}")) + + +def apply_v4a_operations(operations: List[PatchOperation], file_ops: Any) -> PatchResult: + """Two-phase: validate everything, then apply (atomic on validation failure). A phase-2 + failure (validate/apply race) carries a ``git diff`` note since state may be inconsistent. + ``file_ops`` needs read_file_raw/write_file/delete_file/move_file.""" + + def _bullets(errs: List[str]) -> str: + return "\n".join(f" • {e}" for e in errs) + + if errors := _validate_operations(operations, file_ops): + return PatchResult( + success=False, + error="Patch validation failed (no files were modified):\n" + _bullets(errors)) + files: Dict[str, List[str]] = {"created": [], "deleted": [], "modified": []} + all_diffs: List[str] = [] + # V4A bypasses write_file's WriteResult plumbing: LSP diagnostics and lint propagate per file. + lsp_blocks: List[str] = [] + lint_results: Dict[str, dict] = {} + for op in operations: + handler, verb, bucket = _APPLY_DISPATCH[op.operation] + try: + ok, payload, lsp, lint = handler(op, file_ops) + except Exception as e: + ok, payload = None, str(e) + if not ok: + prefix = f"Failed to {verb}" if ok is False else "Error processing" + errors.append(f"{prefix} {op.file_path}: {payload}") + continue + is_move = op.operation is OperationType.MOVE + files[bucket].append(f"{op.file_path} -> {op.new_path}" if is_move else op.file_path) + all_diffs.append(payload) + if lsp: + lsp_blocks.append(lsp) + if lint: + lint_results[op.file_path] = lint + # Each LSP block carries its own header; joining keeps attribution. + return PatchResult( + success=not errors, + error=("Apply phase failed (state may be inconsistent — run `git diff` to assess):\n" + + _bullets(errors)) if errors else None, + diff='\n'.join(all_diffs), + files_modified=files["modified"], files_created=files["created"], files_deleted=files["deleted"], + lint=lint_results or None, lsp_diagnostics="\n\n".join(lsp_blocks) or None) + + +def _write_file_accepts_pre_content(file_ops: Any) -> bool: + """Whether ``file_ops.write_file`` accepts ``pre_content`` — read from the signature, not by + catching TypeError around the call, so a TypeError raised *inside* it can't double-write.""" + try: + params = inspect.signature(file_ops.write_file).parameters + except (TypeError, ValueError): + return False + return "pre_content" in params or any( + p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values()) + + +def _apply_add(op: PatchOperation, file_ops: Any) -> ApplyResult: + """Create a file from the hunks' '+' lines. Fails closed when the target already + exists: validation confirmed the path was free (or freed by an earlier DELETE in + this patch, which has already applied by now), so an existing file here is a + validate/apply race — never clobber.""" + read_back = file_ops.read_file_raw(op.file_path) + if not read_back.error: + return _fail(f"{op.file_path}: file already exists — use Update File, not Add File") + content_lines = [line.content for hunk in op.hunks for line in hunk.lines if line.prefix == '+'] + result = file_ops.write_file(op.file_path, '\n'.join(content_lines)) + diff = f"--- /dev/null\n+++ b/{op.file_path}\n" + '\n'.join(f"+{line}" for line in content_lines) + return _written(result, diff) + + +def _apply_delete(op: PatchOperation, file_ops: Any) -> ApplyResult: + """Delete a file, producing a real unified diff of the removed content.""" + read_result = file_ops.read_file_raw(op.file_path) # re-read guards validate/apply races + if read_result.error: + return _fail(f"Cannot delete {op.file_path}: file not found") + result = file_ops.delete_file(op.file_path) + diff = _unified_diff(op.file_path, read_result.content, None) or f"# Deleted: {op.file_path}" + return _fail(result.error) if result.error else (True, diff, None, None) + + +def _apply_move(op: PatchOperation, file_ops: Any) -> ApplyResult: + result = file_ops.move_file(op.file_path, op.new_path) + return _fail(result.error) if result.error else ( + True, f"# Moved: {op.file_path} -> {op.new_path}", None, None) + + +def _insert_addition_only(new_content: str, hunk: Hunk, insert_text: str) -> Tuple[Optional[str], Optional[str]]: + """Place an addition-only hunk after its context hint (or at EOF). Returns (content, error).""" + if hunk.context_hint: + occurrences, ambiguous = _hint_ambiguity( + new_content, hunk.context_hint, " — provide a more unique hint") + if ambiguous: + return None, f"Addition-only hunk: {ambiguous}" + if occurrences == 1: + eol = new_content.find('\n', new_content.find(hunk.context_hint)) + if eol == -1: + return new_content + '\n' + insert_text, None + return new_content[:eol + 1] + insert_text + '\n' + new_content[eol + 1:], None + # No hint / hint not found — append at end as a safe fallback. + return new_content.rstrip('\n') + '\n' + insert_text + '\n', None + + +def _apply_update(op: PatchOperation, file_ops: Any) -> ApplyResult: + """Apply each hunk via fuzzy replace, then write once.""" + from tools.fuzzy_match import fuzzy_find_and_replace, is_already_applied + read_result = file_ops.read_file_raw(op.file_path) # raw: no line numbers / truncation + if read_result.error: + return _fail(f"Cannot read file: {read_result.error}") + current_content = new_content = read_result.content + for hunk in op.hunks: + search_lines, replace_lines = _split_hunk(hunk) + if search_lines and search_lines == replace_lines: + continue + search_pattern, replacement = '\n'.join(search_lines), '\n'.join(replace_lines) + if not search_lines: + new_content, err = _insert_addition_only(new_content, hunk, replacement) + if err: + return _fail(err) + continue + new_content, count, _strategy, error = fuzzy_find_and_replace( + new_content, search_pattern, replacement, replace_all=False) + if not (error and count == 0): + continue + # Retry inside a window around the context hint, if any. + hint_pos = new_content.find(hunk.context_hint) if hunk.context_hint else -1 + if hint_pos != -1: + window_start = max(0, hint_pos - 500) + window_end = min(len(new_content), hint_pos + 2000) + window_new, count, _strategy, error = fuzzy_find_and_replace( + new_content[window_start:window_end], search_pattern, replacement, replace_all=False) + if count > 0: + new_content = new_content[:window_start] + window_new + new_content[window_end:] + error = None + if error: + # Mirror validation's already-applied skip, else the two phases disagree and fail here. + if is_already_applied(new_content, search_pattern, replacement): + continue + hint = _no_match_hint(error, search_pattern, new_content) + return _fail(f"Could not apply hunk: {error}" + hint) + # Pass pre_content to skip a redundant re-read inside write_file when supported. + extra = {"pre_content": current_content} if _write_file_accepts_pre_content(file_ops) else {} + write_result = file_ops.write_file(op.file_path, new_content, **extra) + return _written(write_result, _unified_diff(op.file_path, current_content, new_content)) + + +# operation -> (handler, verb for error text, files_* bucket) +_APPLY_DISPATCH: Dict[OperationType, Tuple[Callable[[PatchOperation, Any], ApplyResult], str, str]] = { + OperationType.ADD: (_apply_add, "add", "created"), + OperationType.DELETE: (_apply_delete, "delete", "deleted"), + OperationType.MOVE: (_apply_move, "move", "modified"), + OperationType.UPDATE: (_apply_update, "update", "modified"), +} diff --git a/tools/path_security.py b/tools/path_security.py new file mode 100644 index 0000000000000000000000000000000000000000..b58232df2f5c2f0a062afac75acd238ca2f13d7d --- /dev/null +++ b/tools/path_security.py @@ -0,0 +1,41 @@ +"""Shared path validation helpers for tool implementations (skills, cron, credential files).""" + +from pathlib import Path +from typing import Optional + + +def validate_within_dir(path: Path, root: Path) -> Optional[str]: + """Error message if *path* does not resolve inside *root* (symlinks and ``..`` followed).""" + try: + path.resolve().relative_to(root.resolve()) + except (ValueError, OSError) as exc: + return f"Path escapes allowed directory: {exc}" + return None + + +def has_traversal_component(path_str: str) -> bool: + """Cheap pre-check for a literal ``..`` component before full resolution.""" + return ".." in Path(path_str).parts + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. +import logging # noqa: F401,E402 + + +_PLUGIN_COMPAT_LAZY = { + 'logger': ('tools.approval', 'logger'), +} + + +def __getattr__(name): # PEP 562 — lazy so no import cycles + target = _PLUGIN_COMPAT_LAZY.get(name) + if target is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + import importlib + from hermes_cli.plugin_compat import warn_once + warn_once(__name__, name, *target) + return getattr(importlib.import_module(target[0]), target[1]) +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/plugin_guard.py b/tools/plugin_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..cc9fa1ed869d14cc2aad739ad86f2f76bbdc4f2b --- /dev/null +++ b/tools/plugin_guard.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python3 +"""Plugin Guard — ``skills_guard`` engine applied to ``hermes plugins install``/``update``. + +Plugins run in-process but are *expected* to read their own env keys, call provider APIs +and spawn subprocesses, so: full pattern set on docs/config files (where prompt-injection +lives); the "reads own secret"/"HTTP call with key" family exempt on *code* files; +plugin-sized structural limits; VCS/venv noise skipped. ``safe`` installs, ``caution`` +needs confirmation, ``dangerous`` is blocked and ``--force`` does NOT override. +""" + +from __future__ import annotations + +from datetime import datetime, timezone +from pathlib import Path +from typing import Iterator, List, Optional, Tuple + +from tools.skills_guard import ( + Finding, ScanResult, SUSPICIOUS_BINARY_EXTENSIONS, _determine_verdict, format_scan_report, + scan_file) + +PLUGIN_SCANNER_VERSION = "plugin-guard-v3" + +# Never scanned: VCS internals, caches, vendored envs. +EXCLUDED_DIRS = { + ".git", "__pycache__", "node_modules", ".venv", "venv", + ".mypy_cache", ".pytest_cache", ".ruff_cache", ".tox"} + +# Top-level test trees ARE scanned (``plugins_loader`` sets ``submodule_search_locations`` +# to the plugin root, so ``from .tests import evil`` runs whatever lives there), but a +# critical found under one is capped at ``high``: fixtures deliberately hold hostile +# strings to prove the plugin rejects them, and an un-overridable ``dangerous`` made +# such plugins uninstallable and taught authors to obfuscate their own tests (#89610). +# The cap keeps the verdict at ``caution`` — blocked by default, ``--force`` overridable. +# Root-level names only: ``src/spec/handler.py`` is runtime code and gets no cap. +TEST_TREE_DIRS = {"tests", "test", "testing", "spec", "specs", "fixtures"} + +# Code files, where "reads an env secret" / "HTTP call with a key" is normal (requires_env). +CODE_FILE_EXTENSIONS = {".py", ".js", ".ts", ".sh", ".bash", ".rb", ".pl", ".php"} + +# Line-comment marker per code extension. Whole-line comments explain intent; hardening +# notes like "# a symlink could point at /etc/passwd" are prose *about* a defense. +COMMENT_PREFIXES_BY_EXTENSION = { + ".py": "#", ".sh": "#", ".bash": "#", ".rb": "#", ".pl": "#", ".r": "#", ".jl": "#", + ".js": "//", ".ts": "//", ".php": "//"} + +# One severity step down from the pattern's default. +_COMMENT_SEVERITY_CAP = {"critical": "high", "high": "medium"} + +# History, not an agent-facing instruction surface: a hardening entry mentioning the threat +# it fixed ("A symlink could point at /etc/passwd, so ...") is documentation, not the attack. +CHANGELOG_FILENAMES = {"changelog.md"} + +# Pattern ids exempt on code files (every legitimate provider plugin trips them); still +# applied in full to docs/config files. +CODE_EXEMPT_PATTERN_IDS = { + "python_environ_get_secret", "python_getenv_secret", "python_os_environ", "node_process_env", + "ruby_env_secret", "env_exfil_httpx", "env_exfil_requests", "env_exfil_fetch", + "env_exfil_curl", "env_exfil_wget", + # Agent-facing instruction patterns are meaningless inside code (prompt docstrings trip them). + "context_exfil", "send_to_url", "fake_policy", + # Plugins legitimately write config.yaml in post_setup and base64 credentials (Basic auth). + "agent_config_mod", "agent_config_contract", "encoded_exfil"} + +# Severity remaps: a bundled binary is warn-tier (repos occasionally vendor one); a mere +# ``~/.hermes/.env`` mention is how READMEs say where keys go (READING it still trips +# ``read_secrets_file``, critical); ``curl | sh`` in READMEs is caution, not a hard block. +SEVERITY_REMAP = { + "binary_file": "high", "hermes_env_access": "medium", "curl_pipe_shell": "high"} + +# In JS/TS, these text matches cannot distinguish a UI label or DNS lookup +# template from a write or exfiltration operation. Keep them visible and require +# confirmation; do not silently allow them. Shell commands and instructions keep +# their critical severity, as do separate credential-read/exfiltration findings. +JS_CAPABILITY_REMAP = {"dns_exfil": "high", "ssh_backdoor": "high"} + +# Plugin scans gate a HOST install: what matters is what executes on the host. Two critical +# families describe the author's own dev workflow when they appear in documentation files, so +# they are demoted one tier (critical -> high) there instead of hard-blocking an otherwise +# auditable plugin; the same content in runtime code keeps its critical severity. +DOC_PROSE_EXTENSIONS = {".md", ".txt", ".rst", ".html"} +DOC_PROSE_DEMOTIONS = { + # Prose modification bullets ("- Modify: `CLAUDE.md`") in plan/design docs describe the + # repo's own files; only executable intent (shell writes, code) stays critical. + "agent_config_mod": "high", + # Example/demo credentials quoted in docs (placeholder hex, test tokens). Real token-shaped + # literals (sk-, ghp_, AKIA, glpat-, private keys) keep their own critical patterns. + "hardcoded_secret": "high", +} + +# Structural limits — plugins are real codebases, far larger than skills. +MAX_PLUGIN_FILE_COUNT = 400 +MAX_PLUGIN_TOTAL_SIZE_KB = 10 * 1024 # 10MB of scannable tree +MAX_PLUGIN_SINGLE_FILE_KB = 1024 # 1MB single file + + +def _walk(plugin_dir: Path) -> Iterator[Tuple[Path, str]]: + """Yield (path, "a/b/c" relative path) for every non-excluded entry under plugin_dir.""" + for f in plugin_dir.rglob("*"): + try: + rel_parts = f.relative_to(plugin_dir).parts + except ValueError: + continue + if not any(part in EXCLUDED_DIRS for part in rel_parts): + yield f, "/".join(rel_parts) + + +def _finding(pattern_id: str, severity: str, category: str, file: str, match: str, description: str) -> Finding: + return Finding(pattern_id, severity, category, file, 0, match, description) + + +def _filter_findings(findings: List[Finding], rel_path: str) -> List[Finding]: + """Apply plugin-specific exemptions and severity remaps to raw findings.""" + is_code = Path(rel_path).suffix.lower() in CODE_FILE_EXTENSIONS + in_test_tree = Path(rel_path).parts[0] in TEST_TREE_DIRS + is_js = Path(rel_path).suffix.lower() in {".js", ".ts"} + is_doc_prose = Path(rel_path).suffix.lower() in DOC_PROSE_EXTENSIONS + out: List[Finding] = [] + for f in findings: + if is_code and f.pattern_id in CODE_EXEMPT_PATTERN_IDS: + continue + f.severity = ( + (JS_CAPABILITY_REMAP.get(f.pattern_id) if is_js else None) + or SEVERITY_REMAP.get(f.pattern_id) or f.severity + ) + if is_doc_prose and f.pattern_id in DOC_PROSE_DEMOTIONS: + f.severity = DOC_PROSE_DEMOTIONS[f.pattern_id] + if in_test_tree and f.severity == "critical": + f.severity = "high" + if ( + _is_defensive_documentation(f, rel_path) + and f.severity in _COMMENT_SEVERITY_CAP + ): + f.severity = _COMMENT_SEVERITY_CAP[f.severity] + out.append(f) + return out + + +def _is_defensive_documentation(finding: Finding, rel_path: str) -> bool: + """A whole-line code comment or a changelog entry *describes* threats (the attack a + defense rejects, the hardening a release shipped) instead of executing them, so its + findings cap one severity step lower — visible and reviewable, never un-overridable + ``dangerous`` from prose alone. Runtime code and agent-facing docs keep full severity. + """ + if Path(rel_path).name.lower() in CHANGELOG_FILENAMES: + return True + prefix = COMMENT_PREFIXES_BY_EXTENSION.get(Path(rel_path).suffix.lower()) + if prefix is None or not finding.match: + return False + stripped = finding.match.lstrip() + if not stripped.startswith(prefix): + return False + if prefix == "#" and stripped.startswith(("#!", "#:")): + return False + return True + + +def _dangerous_findings_summary(findings: List[Finding]) -> str: + """Describe the critical findings that made a plugin install dangerous.""" + critical = [finding for finding in findings if finding.severity == "critical"] + pattern_ids = sorted({finding.pattern_id for finding in critical}) + names = f" ({', '.join(pattern_ids)})" if pattern_ids else "" + return f"{len(critical)} critical of {len(findings)} findings{names}" + + +def _check_plugin_structure(plugin_dir: Path) -> List[Finding]: + """Structural checks sized for plugin repositories.""" + findings: List[Finding] = [] + file_count = 0 + total_size = 0 + resolved_root = plugin_dir.resolve() + for f, rel in _walk(plugin_dir): + if f.is_symlink(): + file_count += 1 + try: + resolved = f.resolve() + except OSError: + findings.append(_finding("broken_symlink", "medium", "traversal", rel, + "broken symlink", "broken or circular symlink")) + continue + if not resolved.is_relative_to(resolved_root): + findings.append(_finding("symlink_escape", "critical", "traversal", rel, + f"symlink -> {resolved}", "symlink points outside the plugin directory")) + continue + if not f.is_file(): + continue + file_count += 1 + try: + size = f.stat().st_size + except OSError: + continue + total_size += size + if size > MAX_PLUGIN_SINGLE_FILE_KB * 1024: + findings.append(_finding("oversized_file", "medium", "structural", rel, f"{size // 1024}KB", + f"file is {size // 1024}KB (limit: {MAX_PLUGIN_SINGLE_FILE_KB}KB)")) + ext = f.suffix.lower() + if ext in SUSPICIOUS_BINARY_EXTENSIONS: + findings.append(_finding("binary_file", SEVERITY_REMAP["binary_file"], "structural", rel, + f"binary: {ext}", f"binary/executable file ({ext}) bundled in plugin (cannot be scanned)")) + if file_count > MAX_PLUGIN_FILE_COUNT: + findings.append(_finding("too_many_files", "medium", "structural", "(directory)", f"{file_count} files", + f"plugin has {file_count} files (limit: {MAX_PLUGIN_FILE_COUNT})")) + if total_size > MAX_PLUGIN_TOTAL_SIZE_KB * 1024: + findings.append(_finding("oversized_bundle", "medium", "structural", "(directory)", f"{total_size // 1024}KB", + f"plugin is {total_size // 1024}KB total (limit: {MAX_PLUGIN_TOTAL_SIZE_KB}KB)")) + return findings + + +def scan_plugin(plugin_dir: Path, source: str = "") -> ScanResult: + """Scan a plugin directory (typically the temp clone); every external plugin is ``community`` trust.""" + all_findings: List[Finding] = [] + if plugin_dir.is_dir(): + all_findings.extend(_check_plugin_structure(plugin_dir)) + for f, rel in sorted(_walk(plugin_dir)): + if f.is_file() and not f.is_symlink(): + all_findings.extend(_filter_findings(scan_file(f, rel_path=rel), rel)) + verdict = _determine_verdict(all_findings) + if all_findings: + categories = sorted({f.category for f in all_findings}) + summary = f"{plugin_dir.name}: {verdict} — {len(all_findings)} finding(s) in {', '.join(categories)}" + else: + summary = f"{plugin_dir.name}: clean scan, no threats detected" + result = ScanResult( + skill_name=plugin_dir.name, source=source or plugin_dir.name, trust_level="community", + verdict=verdict, findings=all_findings, scanned_at=datetime.now(timezone.utc).isoformat(), + summary=summary) + result.scan_provenance = { + "scanner_version": PLUGIN_SCANNER_VERSION, "verdict": verdict, "source": result.source} + return result + + +def should_allow_plugin_install( + result: ScanResult, force: bool = False) -> Tuple[Optional[bool], str]: + """Map a verdict to ``(allowed, reason)``: True installs, None asks to confirm, False blocks.""" + n = len(result.findings) + if result.verdict == "safe": + return True, "Allowed (clean scan)" + if result.verdict == "caution": + if force: + return True, f"Force-installed despite caution verdict ({n} findings)" + return None, f"Requires confirmation (caution verdict, {n} findings)" + return False, ( + f"Blocked (dangerous verdict, {_dangerous_findings_summary(result.findings)}). " + f"--force does not override a dangerous verdict.") + + +__all__ = [ + "scan_plugin", "should_allow_plugin_install", "format_scan_report", "PLUGIN_SCANNER_VERSION"] diff --git a/tools/preview_tool.py b/tools/preview_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..a5271a7e04fd52853624722875a62b507d9912f3 --- /dev/null +++ b/tools/preview_tool.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""The `desktop_preview` tool — the preview pane beside the chat, as ONE tool. + +open/close/read used to be three tools that each re-taught "the preview pane" world; +one action enum states it once (~576 -> ~210 schema tokens). action=read keeps its +agent-level callback dispatch (agent_runtime_helpers -> agent.read_preview_callback). +Lives in the ``desktop_ui`` toolset — desktop-app sessions only. +""" + +from tools import desktop_ui +from tools.open_preview_tool import _normalize_target, open_preview_tool +from tools.registry import registry, tool_error + + +def preview_close(url: str = "") -> str: + target = _normalize_target(url or "") + return desktop_ui.emit_or_error( + "preview.close", + {"url": target}, + "Failed to close the preview: ", + "The preview pane is only available in the Hermes desktop app.", + {"success": True, "closed": target or "all"}, + ) + + +_ACTIONS = { + "open": lambda args: open_preview_tool(url=args.get("url", ""), label=args.get("label", "")), + "close": lambda args: preview_close(url=args.get("url", "")), + # read needs the GUI callback and is dispatched at the agent level. + "read": lambda args: tool_error( + "preview read must run inside a desktop session (no GUI callback here)."), +} + + +def _handle_preview(args, **kw): + """Non-read actions only: action=read is dispatched at the agent level.""" + fn = _ACTIONS.get((args.get("action") or "").strip()) + if fn is None: + return tool_error("action must be one of: open, close, read.") + return fn(args) + + +PREVIEW_SCHEMA = { + "name": "desktop_preview", + "description": ( + "Open, close, or read the preview pane beside the chat. open: show " + "a web URL (bare domains fine), a localhost dev server, or a file path " + "(HTML renders live) — opens for the current window only. close: dismiss " + "the whole pane, or one tab via url. read: what the pane currently shows " + "— returns {kind, url, title, text, start, end, total_chars}; a Browser " + "tab's text is the rendered page's visible text, paged with start/count " + "(char offsets); a file tab answers identity only (read the file with " + "read_file)." + ), + "parameters": { + "type": "object", + "properties": { + "action": {"type": "string", "enum": ["open", "close", "read"]}, + "url": { + "type": "string", + "description": "open: the target. close: one tab (omit for the whole pane).", + }, + "label": {"type": "string", "description": "open: optional tab label."}, + "start": {"type": "integer", "description": "read: 0-indexed char offset."}, + "count": {"type": "integer", "description": "read: chars to return (capped per read)."}, + }, + "required": ["action"], + }, +} + + +registry.register( + name="desktop_preview", + toolset="desktop_ui", + schema=PREVIEW_SCHEMA, + handler=_handle_preview, + emoji="🖼️", +) + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. +import json # noqa: F401,E402 + +def preview_open(url: str, label: str = "") -> str: + return open_preview_tool(url=url, label=label) +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/process_registry.py b/tools/process_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..8300c745dc4225d5af206f5a3d7e5c99e131478e --- /dev/null +++ b/tools/process_registry.py @@ -0,0 +1,2337 @@ +"""Process Registry -- in-memory registry for background processes spawned via +terminal(background=true): rolling 200KB output buffer, poll/log/wait/kill, JSON +checkpoint for crash recovery, session-scoped tracking for gateway reset protection. +Nothing runs on the host unless TERMINAL_ENV=local; other backends run in their sandbox. +""" + +import codecs +from contextlib import suppress +import json +import logging +import os +import platform +import shlex +import signal +import stat +import subprocess +import threading +import time +import uuid +from pathlib import Path + +_IS_WINDOWS = platform.system() == "Windows" +# systemd transient scopes exist only on Linux; gate every scope-path branch on this +# (not merely "not Windows") so macOS and other POSIX platforms never touch systemd. +# See #70716. +_IS_LINUX = platform.system() == "Linux" +from tools.environments.local import _find_shell, _resolve_safe_cwd, _sanitize_subprocess_env +from hermes_cli._subprocess_compat import windows_hide_flags +from dataclasses import dataclass, field +from typing import Any, Dict, List, Literal, NamedTuple, Optional + +from hermes_cli.config import get_hermes_home + +from tools.process_registry_notifications import format_process_notification +from tools.process_registry_checkpoint import ProcessCheckpointMixin +from tools.process_registry_results import load_completed_results, save_completed_result + +logger = logging.getLogger(__name__) + +# Crash-recovery checkpoint (gateway only) +CHECKPOINT_PATH = get_hermes_home() / "processes.json" +_CHECKPOINT_PATH_AT_IMPORT = CHECKPOINT_PATH + + +def _checkpoint_path() -> Path: + """Active profile's checkpoint file at call time: the patched ``CHECKPOINT_PATH`` when a test + changed it, else live profile-scoped HERMES_HOME — the multiplexed gateway serves every + profile from one process, so the import-time constant would pin every profile's process + checkpoint to the launch home.""" + return CHECKPOINT_PATH if CHECKPOINT_PATH != _CHECKPOINT_PATH_AT_IMPORT else get_hermes_home() / "processes.json" + +MAX_OUTPUT_CHARS = 200_000 # rolling output buffer +FINISHED_TTL_SECONDS = 1800 # keep finished processes 30 minutes +MAX_PROCESSES = 64 # max tracked processes (LRU pruning) + +# Watch-pattern rate limiting, PER SESSION: one watch-match notification per +# WATCH_MIN_INTERVAL_SECONDS; a match inside the cooldown is dropped and counts as one +# strike per window; WATCH_STRIKE_LIMIT consecutive strike windows permanently disable +# watching and fall back to notify_on_complete semantics. +WATCH_MIN_INTERVAL_SECONDS = 15 +WATCH_STRIKE_LIMIT = 3 +# Lifetime cap, independent of strikes: a pattern recurring just above the cooldown never +# strikes yet forces a full-context agent turn each time; watch_patterns is "ONLY for +# rare one-shot signals", so after this many deliveries fall back to notify_on_complete. +# MAX_ACTIVE_PROCESS_AGE = 86400 # 24h default — see session_reset.bg_process_max_age_hours (#29177) +# A process whose pattern recurs at a cadence just above WATCH_MIN_INTERVAL_SECONDS (e.g. a service +# restarted repeatedly over a day) never trips the consecutive-strike limit, since each match lands in its +# own clean cooldown window, yet still forces a full-context agent turn every single time (#93513). +# watch_patterns is documented as "ONLY for rare one-shot mid-process signals", so once a session has +# delivered this many matches over its whole life we disable it and fall back to notify_on_complete, same as +# the strike-limit path. +WATCH_LIFETIME_MAX_HITS = 8 +# Global circuit breaker across all sessions so concurrent siblings can't collectively +# flood the user even when each is under its own cap. +WATCH_GLOBAL_MAX_PER_WINDOW = 15 +WATCH_GLOBAL_WINDOW_SECONDS = 10 +WATCH_GLOBAL_COOLDOWN_SECONDS = 30 + + +# --- systemd cgroup isolation for gateway-spawned local executors ------------------ +# Under a systemd gateway with MemoryMax, local background commands inherit the gateway's +# cgroup, so a memory-heavy executor can get the ENTIRE gateway killed by systemd-oomd; +# ``systemd-run --user --scope`` gives the worker its own transient cgroup. Usability is +# probed once (binary present but user D-Bus absent in system services/containers). +# A memory-heavy executor (Codex, tests, Node) can push the whole cgroup past MemoryMax and trigger +# systemd-oomd to kill the ENTIRE gateway — taking down the messaging control plane and silently losing the +# active turn. We probe *once* whether ``systemd-run --user --scope`` is actually usable (the binary can +# exist on the PATH while the user D-Bus session is unavailable — common for system services and +# containers), and cache the result for the process lifetime. See #70716. +_SYSTEMD_SCOPE_AVAILABLE: Optional[bool] = None +_SYSTEMD_SCOPE_PROBE_LOCK = threading.Lock() +_SYSTEMD_SCOPE_PROBED_AT = 0.0 +_SYSTEMD_SCOPE_FAILURE_TTL_SECONDS = 60.0 +_MIN_WORKER_MEMORY_MAX_BYTES = 64 * 1024 * 1024 +_DEFAULT_WORKER_MEMORY_MAX_BYTES = 1024 * 1024 * 1024 +_WORKER_MEMORY_MAX_CAP_BYTES = 4 * 1024 * 1024 * 1024 + + +def _worker_memory_max_bytes() -> int: + """Finite per-worker cgroup limit that can never widen host risk. + ``TERMINAL_LOCAL_MEMORY_MAX_MB`` is honored only when it *tightens* the safe + bound (min of the gateway's cgroup-v2 ``memory.max`` and half of physical RAM, + capped at 4 GiB), so an oversized override cannot exceed the enclosing slice. + + The proposed local-memory-guard environment override is honored when it tightens the safe bound, so this + isolation composes with PR #57121 instead of inventing a second knob. + """ + override_bound: Optional[int] = None + override = os.getenv("TERMINAL_LOCAL_MEMORY_MAX_MB", "").strip() + if override: + try: + parsed = int(override) * 1024 * 1024 + except ValueError: + parsed = -1 + if parsed >= _MIN_WORKER_MEMORY_MAX_BYTES: + override_bound = parsed + else: + logger.warning( + "Ignoring invalid TERMINAL_LOCAL_MEMORY_MAX_MB=%r; " + "expected an integer representing at least %d MiB", + override, _MIN_WORKER_MEMORY_MAX_BYTES // (1024 * 1024)) + candidates: List[int] = [] + with suppress(OSError, ValueError): + lines = Path("/proc/self/cgroup").read_text(encoding="utf-8").splitlines() + v2 = next((ln for ln in lines if ln.startswith("0::")), None) + if v2 is not None: + relative = v2.partition("::")[2].lstrip("/") + raw_limit = (Path("/sys/fs/cgroup") / relative / "memory.max").read_text(encoding="utf-8").strip() + if raw_limit.isdigit() and int(raw_limit) >= _MIN_WORKER_MEMORY_MAX_BYTES: + candidates.append(int(raw_limit)) + with suppress(OSError, ValueError, TypeError): + physical_bytes = int(os.sysconf("SC_PHYS_PAGES")) * int(os.sysconf("SC_PAGE_SIZE")) + candidates.append(min(_WORKER_MEMORY_MAX_CAP_BYTES, max(_MIN_WORKER_MEMORY_MAX_BYTES, physical_bytes // 2))) + safe_bound = min(candidates) if candidates else _DEFAULT_WORKER_MEMORY_MAX_BYTES + return min(override_bound, safe_bound) if override_bound else safe_bound + + +def _systemd_scope_argv(binary: str, unit_name: str, *argv: str) -> List[str]: + """``systemd-run --user --scope`` argv shared by the probe and real spawns. + ``--collect`` self-cleans the scope after exit; ``--unit`` names it for systemctl. + No ``OOMPolicy=``: transient scopes reject it on systemd <253 (#102486).""" + return [ + binary, "--user", "--scope", "--quiet", "--unit", unit_name, "--collect", + "--property", "MemoryAccounting=yes", + "--property", f"MemoryMax={_worker_memory_max_bytes()}", + "--", *argv, + ] + + +def _default_user_runtime_dir() -> Path: + """``/run/user/``; a function so tests can point it at a temp dir with a real socket.""" + return Path(f"/run/user/{os.getuid()}") # windows-footgun: ok — only reached behind the _IS_LINUX gate in systemd_user_bus_env + + +def _secure_user_runtime_dir(path: Path) -> bool: + """Accept only an absolute, owned, non-writable real directory.""" + try: + metadata = path.lstat() + return ( + path.is_absolute() + and stat.S_ISDIR(metadata.st_mode) + and metadata.st_uid == os.getuid() # windows-footgun: ok — only reached behind the _IS_LINUX gate in systemd_user_bus_env + and metadata.st_mode & 0o022 == 0 + ) + except OSError: + return False + + +def systemd_user_bus_env(base_env: Optional[Dict[str, str]] = None) -> Dict[str, str]: + """Build an environment that can reach this user's lingering systemd manager. + + System-level gateway units run as an unprivileged ``User=`` but normally do + not inherit login-session variables. When the conventional runtime + directory is owned by this uid and its bus exists, derive the two standard + variables. Derived fresh on every call rather than adopted once at boot: + linger may be enabled after the gateway started (existing installs), so + the bus can appear later and the probe's failure TTL must be able to + recover (#104893). + The returned copy is passed explicitly to the probe and every scoped spawn; + ``os.environ`` is left unchanged. + """ + env = dict(os.environ if base_env is None else base_env) + if not _IS_LINUX: + return env + configured = env.get("XDG_RUNTIME_DIR") + if configured and _secure_user_runtime_dir(Path(configured)): + runtime_dir = Path(configured) + else: + runtime_dir = _default_user_runtime_dir() + if not _secure_user_runtime_dir(runtime_dir): + return env + + bus_path = runtime_dir / "bus" + try: + bus_metadata = bus_path.lstat() + except OSError: + return env + if not stat.S_ISSOCK(bus_metadata.st_mode) or bus_metadata.st_uid != os.getuid(): # windows-footgun: ok — behind the _IS_LINUX gate above + return env + + env["XDG_RUNTIME_DIR"] = str(runtime_dir) + env["DBUS_SESSION_BUS_ADDRESS"] = f"unix:path={bus_path}" + return env + + +def _systemd_scope_cached() -> Optional[bool]: + """Cached probe verdict, or None when a (re)probe is due. True is permanent; False + expires after ``_SYSTEMD_SCOPE_FAILURE_TTL_SECONDS`` so a D-Bus blip isn't sticky.""" + if _SYSTEMD_SCOPE_AVAILABLE is True: + return True + stale = time.monotonic() - _SYSTEMD_SCOPE_PROBED_AT >= _SYSTEMD_SCOPE_FAILURE_TTL_SECONDS + return None if _SYSTEMD_SCOPE_AVAILABLE is None or stale else False + + +def _systemd_run_user_scope_available() -> bool: + """True if ``systemd-run --user --scope`` can create a cgroup. + ``shutil.which`` alone is insufficient: system services and containers may lack + the user D-Bus bus even with the binary on PATH (every spawn would fail with + ``Failed to connect to user bus``), so a cheap probe is run and cached. + + Use ``/bin/sh -c 'exit 0'``: NixOS provides ``/bin/sh`` but not ``/bin/true`` + (#105365), regardless of the gateway service's PATH.""" + global _SYSTEMD_SCOPE_AVAILABLE, _SYSTEMD_SCOPE_PROBED_AT + verdict = _systemd_scope_cached() + if verdict is not None: + return verdict + # Double-checked locking: a concurrent first-use spawn must not observe a temporary + # False mid-probe, or it would launch back inside the gateway cgroup. + with _SYSTEMD_SCOPE_PROBE_LOCK: + verdict = _systemd_scope_cached() + if verdict is not None: + return verdict + available = False + if _IS_LINUX: + try: + import shutil + + binary = shutil.which("systemd-run") + if binary: + # Unique unit avoids collisions; the timeout bounds D-Bus. + probe_unit = f"hermes-probe-scope-{os.getpid()}-{uuid.uuid4().hex[:8]}" + result = subprocess.run( + _systemd_scope_argv(binary, probe_unit, "/bin/sh", "-c", "exit 0"), + capture_output=True, + timeout=3, + env=systemd_user_bus_env(), + ) + available = result.returncode == 0 + if not available: + logger.debug( + "systemd-run --user --scope probe failed (rc=%s): %s", + result.returncode, (result.stderr or b"").decode("utf-8", "replace").strip(), + ) + except Exception as exc: + logger.debug("systemd-run --user --scope probe error: %s", exc) + _SYSTEMD_SCOPE_AVAILABLE = available + _SYSTEMD_SCOPE_PROBED_AT = time.monotonic() + return available + + +def _is_supervised_gateway_process() -> bool: + """Whether this process is the live, supervised Hermes gateway itself. + Supervisor markers and ``_HERMES_GATEWAY`` are inherited by every descendant (and + importing ``gateway.run`` sets the latter), so also require ownership of the live + gateway PID file — scopes are for the gateway, not terminal children or CLIs.""" + if os.environ.get("_HERMES_GATEWAY") != "1": + return False + try: + from gateway.restart import is_gateway_supervisor_process + from gateway.status import get_running_pid + + return is_gateway_supervisor_process() and get_running_pid(cleanup_stale=False) == os.getpid() + except Exception as exc: + logger.debug("Could not verify supervised gateway process identity: %s", exc) + return False + + +def _build_systemd_scope_argv(shell_argv: List[str], unit_suffix: str) -> List[str]: + """Wrap *shell_argv* in a ``systemd-run --user --scope`` invocation with its own + memory accounting, so an OOM in the worker cannot kill the gateway cgroup. + + ``--collect`` makes the transient scope self-clean after exit; ``--unit`` gives it a recognisable name + for ``systemctl --user status`` / journalctl. See #70716. + """ + import shutil + + binary = shutil.which("systemd-run") + if binary is None: + # Caller should have probed availability; never pass None into Popen anyway. + return shell_argv + return _systemd_scope_argv(binary, f"hermes-worker-{unit_suffix}", *shell_argv) + + +_scope_degraded_warned = False + + +def _warn_scope_degraded_once(detail: str) -> None: + """Warn once per process: the condition is host-level and the probe verdict + is cached, so this would otherwise fire on every cron dispatch.""" + global _scope_degraded_warned + if _scope_degraded_warned: + return + _scope_degraded_warned = True + logger.warning( + "managed gateway: %s; cron children are dispatched as direct external subprocesses " + "without restart-safe cgroup isolation (killed if the gateway restarts mid-job). " + "Set cron.require_restart_safe_scope=true in config.yaml to fail closed instead.", + detail, + ) + + +class GatewayChildDispatch(NamedTuple): + """How a managed-gateway child is launched. + + ``in_process``: not a managed systemd gateway, ``argv is command``, the caller + keeps its in-process path. ``scoped``: ``argv`` is the systemd-run wrapper. + ``degraded``: no user scope could be created; ``argv`` is the direct command but + the caller MUST still launch it as an external subprocess — the distinct mode + exists so this case can never collapse into ``in_process`` and recreate the + restart interruption #101940 closed. + """ + + mode: Literal["in_process", "scoped", "degraded"] + argv: List[str] + + +def restart_safe_gateway_child_argv( + command: List[str], *, unit_suffix: str, require_restart_safe_scope: bool, +) -> GatewayChildDispatch: + """Place a managed-systemd gateway child outside the gateway cgroup. + + A systemd-supervised gateway restart kills every process in the service + cgroup, so children that must survive it run in a transient user scope. + Hosts with no user systemd session (containers, LXCs without linger) cannot + create one; hard-failing there is a silent cron outage, so callers state the + policy: ``require_restart_safe_scope=True`` raises (kanban's long-lived + workers), ``False`` degrades to a direct external subprocess with a + once-per-process warning (cron, behind ``cron.require_restart_safe_scope``). + """ + if not _IS_LINUX: + return GatewayChildDispatch("in_process", command) + if not _is_supervised_gateway_process() or not os.environ.get("INVOCATION_ID"): + return GatewayChildDispatch("in_process", command) + + def _degrade(detail: str) -> GatewayChildDispatch: + if require_restart_safe_scope: + # Stored as the cron execution's error and shown on the job row: name the remedy. + raise RuntimeError(f"cannot create restart-safe systemd scope for gateway child: {detail}") + _warn_scope_degraded_once(detail) + return GatewayChildDispatch("degraded", command) + + if not _systemd_run_user_scope_available(): + return _degrade( + "systemd-run --user --scope is unavailable (usually no reachable user D-Bus session at " + f"/run/user/{os.getuid()}/bus). On a system-level service install, run " # windows-footgun: ok — behind the _IS_LINUX return above + "`sudo loginctl enable-linger ` and restart the gateway." + ) + scoped = _build_systemd_scope_argv(command, unit_suffix=unit_suffix) + if scoped == command: + return _degrade("systemd-run disappeared after the availability probe") + return GatewayChildDispatch("scoped", scoped) + + +def _stop_systemd_unit(unit_name: str) -> bool: + """Stop a transient systemd user scope by unit name. + Reaps the *entire* cgroup — catching double-forked descendants reparented to init + inside the scope that survive a plain PID signal (SIGTERM all, SIGKILL after + ``TimeoutStopSec``). True if stopped or already gone; False if ``systemctl`` is + unavailable or the stop failed. + + See #70716. + """ + import shutil + + binary = shutil.which("systemctl") + if binary is None: + return False + try: + result = subprocess.run( + [binary, "--user", "stop", unit_name], + capture_output=True, + timeout=15, + stdin=subprocess.DEVNULL, + env=systemd_user_bus_env(), + ) + if result.returncode != 0: + stderr = (result.stderr or b"").decode(errors="replace").strip() + if any(marker in stderr.lower() for marker in ("not loaded", "not found", "does not exist")): + return True + logger.debug("systemctl --user stop %s exited %d: %s", unit_name, result.returncode, stderr) + return False + return True + except Exception as exc: + logger.debug("systemctl --user stop %s failed: %s", unit_name, exc) + return False + + +def format_uptime_short(seconds: int) -> str: + s = max(0, int(seconds)) + if s < 60: + return f"{s}s" + mins, secs = divmod(s, 60) + if mins < 60: + return f"{mins}m {secs}s" + hours, mins = divmod(mins, 60) + return f"{hours}h {mins}m" + + +def _not_found(session_id: str) -> dict: + return {"status": "not_found", "error": f"No process with ID {session_id}"} + + +def _output_tail(session: "ProcessSession", n: int) -> str: + """Last *n* chars of the session output with ANSI sequences stripped.""" + from tools.ansi_strip import strip_ansi + + return strip_ansi(session.output_buffer[-n:]) + + +@dataclass +class ProcessSession: + """A tracked background process with output buffering.""" + id: str # "proc_xxxxxxxxxxxx" + command: str + task_id: str = "" # Task/sandbox isolation key (CONTAINER key, + # may be collapsed by _resolve_container_task_id) + owner_task_id: str = "" # RAW spawning task id ("sa-..."); ownership + # checks must use this, not task_id + session_key: str = "" # Gateway session key (reset protection) + pid: Optional[int] = None + process: Optional[subprocess.Popen] = None # Popen handle (local only) + env_ref: Any = None # Environment object (sandbox spawns) + cwd: Optional[str] = None + started_at: float = 0.0 # time.time() of spawn + host_start_time: Optional[int] = None # kernel start ticks (/proc//stat f22) — PID-reuse guard + exited: bool = False + exit_code: Optional[int] = None # None while running + completion_reason: str = "exited" # exited|killed|lost|failed_start|already_exited + termination_source: str = "" # process.kill|kill_all|backend_lost|failed_start + output_buffer: str = "" # Rolling tail (last max_output_chars) + max_output_chars: int = MAX_OUTPUT_CHARS + detached: bool = False # Recovered from checkpoint (no pipe) + pid_scope: str = "host" # "host" for local/PTY PIDs, "sandbox" for env-local PIDs + systemd_unit: str = "" # transient scope unit name when spawned under systemd-run + handoff_note: str = "" # why a subagent handed this process to its parent (rides the notice) + # Watcher/notification routing (persisted for crash recovery) + # systemd_unit: str = "" # transient scope unit name when spawned under systemd-run + # (#70716) + watcher_platform: str = "" + watcher_chat_id: str = "" + watcher_user_id: str = "" + watcher_user_name: str = "" + watcher_thread_id: str = "" + watcher_message_id: str = "" # Triggering message id — reply anchor for topic routing + watcher_interval: int = 0 # 0 = no watcher configured + # Session-db id of the spawning conversation; lets the gateway drop completions whose + # session was closed at a user boundary (/new) instead of injecting into the NEW one. + parent_session_id: str = "" + notify_on_complete: bool = False # Queue agent notification on exit + watch_patterns: List[str] = field(default_factory=list) + _watch_hits: int = field(default=0, repr=False) # total matches delivered + _watch_suppressed: int = field(default=0, repr=False) # matches dropped by rate limit + _watch_disabled: bool = field(default=False, repr=False) # permanently killed after strike limit + # Rate-limit window state (see WATCH_*). A strike is a WINDOW with drops, not a drop. + _watch_cooldown_until: float = field(default=0.0, repr=False) + _watch_strike_candidate: bool = field(default=False, repr=False) + _watch_consecutive_strikes: int = field(default=0, repr=False) + _completion_event: threading.Event = field(default_factory=threading.Event, repr=False) + _lock: threading.Lock = field(default_factory=threading.Lock) + _reader_thread: Optional[threading.Thread] = field(default=None, repr=False) + _pty: Any = field(default=None, repr=False) # ptyprocess handle (use_pty=True) + + def append_output(self, text: str) -> None: + """Append to the rolling output buffer under the session lock, keeping the tail.""" + with self._lock: + self.output_buffer += text + if len(self.output_buffer) > self.max_output_chars: + self.output_buffer = self.output_buffer[-self.max_output_chars:] + + def mark_exited(self, exit_code, reason: str = "exited", source: str = "") -> None: + """Record an exit. A kill that raced the observer already recorded its own + exit_code/reason; never overwrite it.""" + self.exited = True + if self.completion_reason != "killed": + self.exit_code = exit_code + self.completion_reason = reason + if source: + self.termination_source = source + + +# Watcher routing fields, in event-dict key order (``watcher_`` on the session). +_WATCHER_ROUTE_KEYS = ("platform", "chat_id", "user_id", "user_name", "thread_id", "message_id") +# Session fields persisted verbatim in the crash-recovery checkpoint (plus +# ``session_id``; ``command`` is redacted and ``owner_task_id`` defaulted on write). +_CHECKPOINT_FIELDS = ( + "command", "pid", "pid_scope", "host_start_time", "systemd_unit", "cwd", + "started_at", "task_id", "owner_task_id", "session_key", + *(f"watcher_{k}" for k in _WATCHER_ROUTE_KEYS), "watcher_interval", + "parent_session_id", "notify_on_complete", "watch_patterns") +_CHECKPOINT_DEFAULTS = { + f.name: ([] if f.name == "watch_patterns" else f.default) + for f in ProcessSession.__dataclass_fields__.values() + if f.name in _CHECKPOINT_FIELDS +} + + +class ProcessRegistry(ProcessCheckpointMixin): + """In-memory registry of running and finished background processes. + Thread-safe: accessed from executor threads (terminal_tool, process handlers), + the gateway asyncio loop (watchers, reset checks) and the cleanup thread.""" + + _SHELL_NOISE_SUBSTRINGS = ( + "no job control in this shell", "cannot set terminal process group", + "tcsetattr: Inappropriate ioctl for device") + + def __init__(self): + self._running: Dict[str, ProcessSession] = {} + self._finished: Dict[str, ProcessSession] = {} + self._lock = threading.Lock() + # Side-channel for check_interval watchers (gateway reads after agent run) + self.pending_watchers: List[Dict[str, Any]] = [] + # Unified queue for all background events (distinguished by "type"); the CLI + # process_loop and the gateway drain it after each agent turn to trigger new turns. + import queue as _queue_mod + self.completion_queue: _queue_mod.Queue = _queue_mod.Queue() + # Rehydrate durable delegation completions once, at registry startup. + try: + from tools.async_delegation import restore_undelivered_completions + restore_undelivered_completions(self.completion_queue) + except Exception as exc: + logger.warning("Could not restore async delegation completions: %s", exc) + # Completions the agent already consumed via wait()/read_log() (output in + # hand): drain loops AND gateway/tui watchers skip them. + self._completion_consumed: set = set() + # Sessions merely *observed* exited via poll(). poll() is read-only and must NOT + # mark consumed (a status check would suppress the watcher's autonomous delivery + # turn), but the CLI has the poll result inline in the same turn, so + # drain_notifications() skips these to avoid a duplicate [SYSTEM: ...]; + # gateway/tui watchers deliberately ignore this set. + # See #8228. + self._poll_observed: set = set() + # Global watch-match circuit breaker across all sessions. + self._global_watch_lock = threading.Lock() + self._global_watch_window_start = self._global_watch_tripped_until = 0.0 + self._global_watch_window_hits = self._global_watch_suppressed_during_trip = 0 + # Driver-installed sinks (desktop gateway): on_output(session, chunk) streams + # live output from reader threads; on_close(session_or_none, process_id) drops + # a read-only terminal tab without killing the process. + self.on_output = None + self.on_close = None + + @staticmethod + def _clean_shell_noise(text: str) -> str: + """Strip shell startup warnings from the beginning of output.""" + lines = text.split("\n") + while lines and any(noise in lines[0] for noise in ProcessRegistry._SHELL_NOISE_SUBSTRINGS): + lines.pop(0) + return "\n".join(lines) + + def _emit_output(self, session: ProcessSession, chunk: str) -> None: + """Forward a chunk to the live-output sink; called from reader threads, never raises.""" + sink = self.on_output + if sink is None or not chunk: + return + with suppress(Exception): + sink(session, chunk) + + def _check_watch_patterns(self, session: ProcessSession, new_text: str) -> None: + """Scan a freshly-read chunk for watch patterns and queue notifications. + Per-session rate limiting (see WATCH_* constants): one match per cooldown + window, a match inside the window is one strike, WATCH_STRIKE_LIMIT consecutive + strikes or WATCH_LIFETIME_MAX_HITS total deliveries disable watching and + promote the session to notify_on_complete.""" + if not session.watch_patterns or session._watch_disabled: + return + # Late chunks after the reader declared exit are post-exit noise; dropping them + # avoids stale notifications minutes after the process ended. + if session.exited: + return + hits = [ # (first matching pattern, line) — one match per line + (next(p for p in session.watch_patterns if p in line), line.rstrip()) + for line in new_text.splitlines() if any(p in line for p in session.watch_patterns)] + if not hits: + return + matched_pattern = hits[0][0] + matched_lines = [line for _, line in hits] + now = time.time() + with session._lock: + if session._watch_cooldown_until and now < session._watch_cooldown_until: + # Inside the cooldown: drop, count one strike per window, disable + + # promote once the strike limit is hit. + session._watch_suppressed += len(matched_lines) + if session._watch_strike_candidate: + return + session._watch_strike_candidate = True + session._watch_consecutive_strikes += 1 + if session._watch_consecutive_strikes < WATCH_STRIKE_LIMIT: + return + session._watch_disabled = True + # Promote so the agent still gets exactly one notification on exit, + # plus exactly one summary so it sees why things went quiet. + session.notify_on_complete = True + self._emit_watch_disabled( + session, session._watch_suppressed, + f"{WATCH_STRIKE_LIMIT} consecutive rate-limit windows triggered " + f"(min spacing {WATCH_MIN_INTERVAL_SECONDS}s). ") + return + # Cooldown expired. A prior window with no drops resets the + # consecutive-strike counter (healthy cadence again). + if session._watch_cooldown_until and not session._watch_strike_candidate: + session._watch_consecutive_strikes = 0 + session._watch_strike_candidate = False + # Emit and start a new cooldown window. + session._watch_cooldown_until = now + WATCH_MIN_INTERVAL_SECONDS + session._watch_hits += 1 + suppressed = session._watch_suppressed + session._watch_suppressed = 0 + # Lifetime cap: this match is still delivered, but no further ones. + lifetime_exhausted = session._watch_hits >= WATCH_LIFETIME_MAX_HITS + if lifetime_exhausted: + session._watch_disabled = True + session.notify_on_complete = True + output = "\n".join(matched_lines[:20]) + if len(output) > 2000: + output = output[:2000] + "\n...(truncated)" + if self._global_watch_admit(now): + notification = { + **self._watch_event_base(session), + "type": "watch_match", + "pattern": matched_pattern, + "output": output, + "suppressed": suppressed, + } + _redact_process_result(notification) + self.completion_queue.put(notification) + # Even when the breaker drops the final match, still explain the silence. + if lifetime_exhausted: + self._emit_watch_disabled( + session, 0, f"reached the lifetime cap of {WATCH_LIFETIME_MAX_HITS} delivered matches. ", + ) + + def _emit_watch_disabled(self, session: ProcessSession, suppressed: int, why: str) -> None: + """Queue the one-shot watch_disabled summary (strike-limit or lifetime-cap path).""" + self.completion_queue.put({ + **self._watch_event_base(session), + "type": "watch_disabled", + "suppressed": suppressed, + "message": ( + f"Watch patterns disabled for process {session.id} — {why}" + f"Falling back to notify_on_complete semantics; you'll get " + f"exactly one notification when the process exits."), + }) + + @staticmethod + def _watch_event_base(session: ProcessSession) -> dict: + """Session identity + watcher routing fields shared by every watch event.""" + return { + "session_id": session.id, + "session_key": session.session_key, + "task_id": session.task_id, + "owner_task_id": session.owner_task_id or session.task_id, + "command": session.command, + **{key: getattr(session, f"watcher_{key}") for key in _WATCHER_ROUTE_KEYS}, + } + + @staticmethod + def _global_watch_event(type_: str, message: str, **extra) -> dict: + """Unaddressed (all-sessions) watch breaker event.""" + return { + "session_id": "", "session_key": "", "command": "", "type": type_, **extra, + "message": message, + "platform": "", "chat_id": "", "user_id": "", "user_name": "", "thread_id": "", + } + + def _global_watch_admit(self, now: float) -> bool: + """True if this watch_match may pass the global breaker. + In cooldown: drop and count. Otherwise slide the rolling window; exceeding + the cap trips the breaker for WATCH_GLOBAL_COOLDOWN_SECONDS with ONE + "tripped" summary, and the cooldown's end emits ONE "released" summary.""" + events = [] # summary events, queued outside the lock + with self._global_watch_lock: + # Handle cooldown expiry first so we can emit the release summary. + if self._global_watch_tripped_until and now >= self._global_watch_tripped_until: + suppressed = self._global_watch_suppressed_during_trip + self._global_watch_tripped_until = 0.0 + self._global_watch_suppressed_during_trip = 0 + self._global_watch_window_start, self._global_watch_window_hits = now, 0 + if suppressed > 0: + events.append(self._global_watch_event( + "watch_overflow_released", + f"Watch-pattern notifications resumed. " + f"{suppressed} match event(s) were suppressed during the flood.", + suppressed=suppressed)) + if self._global_watch_tripped_until and now < self._global_watch_tripped_until: + # Still in cooldown — drop and count. + self._global_watch_suppressed_during_trip += 1 + admit = False + else: + if now - self._global_watch_window_start >= WATCH_GLOBAL_WINDOW_SECONDS: + self._global_watch_window_start, self._global_watch_window_hits = now, 0 + admit = self._global_watch_window_hits < WATCH_GLOBAL_MAX_PER_WINDOW + if admit: + self._global_watch_window_hits += 1 + else: + self._global_watch_tripped_until = now + WATCH_GLOBAL_COOLDOWN_SECONDS + self._global_watch_suppressed_during_trip += 1 + events.append(self._global_watch_event( + "watch_overflow_tripped", + f"Watch-pattern overflow: >{WATCH_GLOBAL_MAX_PER_WINDOW} " + f"notifications in {WATCH_GLOBAL_WINDOW_SECONDS}s across all processes. " + f"Suppressing further watch_match events for " + f"{WATCH_GLOBAL_COOLDOWN_SECONDS}s.")) + for msg in events: + self.completion_queue.put(msg) + return admit + + @staticmethod + def _is_host_pid_alive(pid: Optional[int]) -> bool: + """Best-effort liveness check for host-visible PIDs.""" + if not pid: + return False + # ``os.kill(pid, 0)`` is NOT a no-op on Windows (bpo-14484) — use the + # cross-platform existence check. + from gateway.status import _pid_exists + return _pid_exists(pid) + + @staticmethod + def _safe_host_start_time(pid: Optional[int]) -> Optional[int]: + """Kernel start ticks for a host PID, or None when unavailable.""" + try: + from gateway.status import get_process_start_time + return get_process_start_time(pid) if pid else None + except Exception: + return None + + @classmethod + def _host_pid_is_ours(cls, pid: Optional[int], expected_start: Optional[int]) -> bool: + """True only if ``pid`` is alive AND still the process we spawned. + The kernel recycles PIDs, so a stored number can later name an unrelated + process (seen in the wild: a browser's session leader tree-killed). The kernel + start time captured at spawn must match the live one; with no baseline + (legacy checkpoints, no ``/proc``) degrade to a bare liveness check.""" + return cls._is_host_pid_alive(pid) and ( + expected_start is None or cls._safe_host_start_time(pid) == expected_start) + + def _refresh_detached_session(self, session: Optional[ProcessSession]) -> Optional[ProcessSession]: + """Update recovered host-PID sessions when the underlying process has exited.""" + if session is None or session.exited or not session.detached or session.pid_scope != "host": + return session + # A recycled PID (alive but not ours) counts as "our process exited" so a + # later kill() can never tree-kill the stranger. + if self._host_pid_is_ours(session.pid, session.host_start_time): + return session + with session._lock: + if session.exited: + return session + # No waitable handle survives recovery, so the real exit code is unknown. + session.exited, session.exit_code = True, None + self._move_to_finished(session) + return session + + @staticmethod + def _proc_alive(proc) -> bool: + """True if a psutil.Process is running and not a zombie (already dead, just unreaped).""" + try: + import psutil + return proc.is_running() and proc.status() != psutil.STATUS_ZOMBIE + except Exception: + return False + + @staticmethod + def _config_value(section: str, key: str, fallback): + """``config.yaml`` value for ``section.key``, else the DEFAULT_CONFIG value. + Raises if config is unreadable; callers wrap with their own hard fallback so + registry code paths never crash on a broken config file.""" + from hermes_cli.config import DEFAULT_CONFIG, cfg_get, read_raw_config + + val = cfg_get(read_raw_config(), section, key) + return DEFAULT_CONFIG[section][key] if val is None else val + + @staticmethod + def _config_seconds(key: str, fallback: float) -> float: + """``terminal.`` as a non-negative float (0 disables); *fallback* if unreadable.""" + try: + return max(float(ProcessRegistry._config_value("terminal", key, fallback)), 0.0) + except Exception: + return fallback + + @staticmethod + def _daemon_term_grace_seconds() -> float: + """Grace (s) between SIGTERM and escalated SIGKILL; 0 disables escalation.""" + return ProcessRegistry._config_seconds("daemon_term_grace_seconds", 2.0) + + @classmethod + def _terminate_host_pid(cls, pid: int, expected_start: Optional[int] = None) -> None: + """Terminate a host-visible PID and its descendants. + ``expected_start`` (kernel start time at spawn) is re-validated first: a mismatch + or dead PID means the number was recycled onto a stranger and we refuse to touch + it — a leaked orphan beats tree-killing someone's browser. POSIX: psutil SIGTERMs + children before the parent (so trees aren't reparented to init and survive), then + SIGKILLs survivors after ``terminal.daemon_term_grace_seconds``. Windows: + ``taskkill /T /F`` (psutil's stale PPID links miss orphans there); ``os.kill`` + is the fallback.""" + if expected_start is not None and not cls._host_pid_is_ours(pid, expected_start): + logger.warning( + "Refusing to terminate host pid %d: start-time mismatch — " + "PID was recycled onto an unrelated process.", pid) + return + + def _sigterm_quietly(): + with suppress(OSError, ProcessLookupError, PermissionError): + os.kill(pid, signal.SIGTERM) + if _IS_WINDOWS: + try: + subprocess.run( + ["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True, text=True, + encoding='utf-8', errors='replace', timeout=10, creationflags=windows_hide_flags(), + stdin=subprocess.DEVNULL) + except (FileNotFoundError, subprocess.TimeoutExpired, OSError): + _sigterm_quietly() + return + import psutil + gone = (psutil.NoSuchProcess, psutil.AccessDenied, OSError) + try: + parent = psutil.Process(pid) + except psutil.NoSuchProcess: + return + except (OSError, PermissionError): + _sigterm_quietly() + return + # Snapshot the whole tree (children before parent) and SIGTERM each. + try: + targets = parent.children(recursive=True) + except gone: + targets = [] + targets.append(parent) + for proc in targets: + with suppress(gone): + proc.terminate() + # Escalate to SIGKILL for anything that ignored SIGTERM within the grace window. + # ``psutil.wait_procs``' gone/alive partition is deliberately NOT trusted: it + # reaps via ``Process.wait()`` and mis-partitions across zombie transitions in a + # parent/child tree, leaving survivors un-killed. Re-probing every target is + # deterministic. + grace = cls._daemon_term_grace_seconds() + if grace <= 0: + return + deadline = time.monotonic() + grace + while time.monotonic() < deadline and any(cls._proc_alive(_p) for _p in targets): + time.sleep(0.05) + for proc in targets: + with suppress(gone): + if cls._proc_alive(proc): + proc.kill() # SIGKILL on POSIX + logger.info("Escalated to SIGKILL for pid %d (ignored SIGTERM within %.1fs grace)", proc.pid, grace) + + # ----- Spawn ----- + + @staticmethod + def _new_session(command, task_id, owner_task_id, session_key, cwd, **extra) -> ProcessSession: + from gateway.session_context import get_session_env + + return ProcessSession( + id=f"proc_{uuid.uuid4().hex[:12]}", command=command, task_id=task_id, + owner_task_id=owner_task_id or task_id, session_key=session_key, cwd=cwd, + parent_session_id=get_session_env("HERMES_SESSION_ID", ""), + started_at=time.time(), **extra) + + @staticmethod + def _env_temp_dir(env: Any) -> str: + """Return the writable sandbox temp dir for env-backed background tasks.""" + get_temp_dir = getattr(env, "get_temp_dir", None) + if callable(get_temp_dir): + try: + temp_dir = get_temp_dir() + if isinstance(temp_dir, str) and temp_dir.startswith("/"): + return temp_dir.rstrip("/") or "/" + except Exception as exc: + logger.debug("Could not resolve environment temp dir: %s", exc) + return "/tmp" + + def _scope_argv(self, session: ProcessSession, safe_command: str, unit_suffix: str, label: str) -> List[str]: + """Login-shell argv for *safe_command* (parity with LocalEnvironment: rc files + sourced, user tools on PATH), wrapped in a transient systemd scope when we are + the supervised gateway (own cgroup: an OOM kills only the worker, not the + gateway and its messaging control plane).""" + argv = [_find_shell(), "-lic", f"set +m; {safe_command}"] + # This applies to both pipe mode and the PTY path above. See #70716. + in_supervised_gateway = _IS_LINUX and _is_supervised_gateway_process() + if in_supervised_gateway and _systemd_run_user_scope_available(): + session.systemd_unit = f"hermes-worker-{unit_suffix}.scope" + return _build_systemd_scope_argv(argv, unit_suffix=unit_suffix) + if in_supervised_gateway: + # Under a supervisor but no private cgroup: a worker OOM can still take + # the whole gateway down. + logger.debug( + "%s background executor not isolated in a systemd scope " + "(systemd-run --user unavailable); worker shares the gateway cgroup.", label) + return argv + + @staticmethod + def _spawn_env(env_vars: dict) -> dict: + """Sanitized child env; PYTHONUNBUFFERED so tqdm/datasets-style buffering + doesn't hide progress from process(action="poll").""" + env = _sanitize_subprocess_env(os.environ, env_vars) + env["PYTHONUNBUFFERED"] = "1" + return env + + def _track_started(self, session: ProcessSession, reader_target, reader_name: str, extra_args=()) -> None: + """Register before the reader can publish completion, even for an exited child.""" + from contextvars import copy_context + + # Reader completion must retain the producer's multiplex profile scope. + reader = threading.Thread(target=copy_context().run, args=(reader_target, session, *extra_args), + daemon=True, name=reader_name) + session._reader_thread = reader + with self._lock: + self._prune_if_needed() + # Completion takes this lock too. Starting here also leaves no + # ghost entry if the interpreter cannot start another thread. + reader.start() + self._running[session.id] = session + self._write_checkpoint() + + def _spawn_local_pty(self, session: ProcessSession, safe_command: str, env_vars: dict) -> ProcessSession: + """PTY spawn for interactive CLI tools (Codex, Claude Code, REPLs). + Raises ImportError when no PTY backend is installed and re-raises any spawn + failure; ``spawn_local`` falls back to pipe mode in both cases.""" + if _IS_WINDOWS: + from winpty import PtyProcess as _PtyProcessCls + else: + from ptyprocess import PtyProcess as _PtyProcessCls + pty_argv = self._scope_argv(session, safe_command, session.id, "PTY") + pty_env = self._spawn_env(env_vars) + if session.systemd_unit: + pty_env = systemd_user_bus_env(pty_env) + # A PTY is a real TTY, so pager-happy tools (git log/diff, man) WILL page and + # hang waiting for `q` — default them to cat, honoring any pager the user set. + pty_env.setdefault("GIT_PAGER", "cat") + pty_env.setdefault("PAGER", "cat") + pty_proc = _PtyProcessCls.spawn(pty_argv, cwd=session.cwd, env=pty_env, dimensions=(30, 120)) + session.pid = pty_proc.pid + session.host_start_time = self._safe_host_start_time(session.pid) + session._pty = pty_proc + self._track_started(session, self._pty_reader_loop, f"proc-pty-reader-{session.id}") + return session + + def spawn_local( + self, command: str, cwd: str = None, task_id: str = "", session_key: str = "", + env_vars: dict = None, use_pty: bool = False, owner_task_id: str = "") -> ProcessSession: + """Spawn a background process locally (TERMINAL_ENV=local; other backends use + spawn_via_env()). ``use_pty`` requests a pseudo-terminal via ptyprocess/pywinpty + for interactive CLIs, falling back to a plain pipe when unavailable or failing.""" + # Bash parses ``A && B &`` as ``(A && B) &`` — a subshell that holds our stdout + # pipe open forever when B is a long-running server. The rewriter turns it into + # ``A && { B & }``. Lazy import: terminal_tool imports this module. + # Guard against the `A && B &` subshell-wait trap (issue #68915). + from tools.terminal_tool_sudo import _rewrite_compound_background as _rewrite_bg + + safe_command = _rewrite_bg(command) + session = self._new_session(command, task_id, owner_task_id, session_key, _resolve_safe_cwd(cwd or os.getcwd())) + pty_scope_attempted = False + if use_pty: + try: + return self._spawn_local_pty(session, safe_command, env_vars) + except ImportError: + logger.warning("ptyprocess not installed, falling back to pipe mode") + except Exception as e: + logger.warning("PTY spawn failed (%s), falling back to pipe mode", e) + if session.systemd_unit: + pty_scope_attempted = True + if not _stop_systemd_unit(session.systemd_unit): + raise RuntimeError( + "PTY scope could not be reaped; refusing pipe fallback " + "to avoid duplicate command execution" + ) from e + session.systemd_unit = "" + # Pipe path (non-PTY or PTY fallback). + _popen_kwargs = {"creationflags": windows_hide_flags()} if _IS_WINDOWS else {} + unit_suffix = f"{session.id}-pipe-fallback" if pty_scope_attempted else session.id + spawn_argv = self._scope_argv(session, safe_command, unit_suffix, "Local") + spawn_env = self._spawn_env(env_vars) + if session.systemd_unit: + spawn_env = systemd_user_bus_env(spawn_env) + # start_new_session is REQUIRED with systemd-run --scope too: the scope does not + # give the worker a new session, so from an interactive TUI the worker would + # share the foreground process group and background spawns would stop the whole + # session (observed as dead TUIs in state T). Cgroup isolation is unaffected — + # the scope attaches to the invoked process, not the spawning session. + proc = subprocess.Popen( + spawn_argv, text=True, cwd=session.cwd, env=spawn_env, encoding="utf-8", + errors="replace", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, + start_new_session=True, **_popen_kwargs) + session.process = proc + session.pid = proc.pid + session.host_start_time = self._safe_host_start_time(session.pid) + try: + self._track_started(session, self._reader_loop, f"proc-reader-{session.id}") + except Exception: + self._reap_untracked(session, proc) + raise + return session + + def _reap_untracked(self, session: ProcessSession, proc: subprocess.Popen) -> None: + """Post-Popen setup failed: kill the orphaned subprocess (and any setsid + descendants) so nothing leaks untracked.""" + with suppress(Exception): + if session.systemd_unit: + # Scope teardown is the authoritative cleanup for the worker cgroup + # (never killpg here); the wrapper PID is terminated as fallback. + _stop_systemd_unit(session.systemd_unit) + # The worker runs in its own systemd scope and, since the #70716 session-isolation fix, its + # own session. Stop the scope (kills every process in the worker cgroup), then terminate the + # systemd-run wrapper PID as fallback. + self._terminate_host_pid(proc.pid, session.host_start_time) + elif not _IS_WINDOWS: + try: + kill_signal = getattr(signal, "SIGKILL", signal.SIGTERM) + os.killpg(os.getpgid(proc.pid), kill_signal) # windows-footgun: ok - guarded by _IS_WINDOWS above + except (ProcessLookupError, PermissionError, OSError): + proc.kill() + else: + proc.kill() + with suppress(Exception): + proc.wait(timeout=5) + + def adopt_local( + self, proc: subprocess.Popen, *, command: str, cwd: Optional[str], task_id: str = "", + session_key: str = "", owner_task_id: str = "", output_so_far: str = "", + notify_on_complete: bool = True) -> ProcessSession: + """Take over a still-running foreground Popen as a tracked background session + (yield-to-background: the user sent a message while the command was running). + The caller has stopped its own drain thread; the registry's reader continues from + the pipe's current position and ``output_so_far`` seeds the buffer so nothing + already captured is lost.""" + session = self._new_session(command, task_id, owner_task_id, session_key, cwd) + session.process = proc + session.pid = proc.pid + session.host_start_time = self._safe_host_start_time(session.pid) + session.notify_on_complete = notify_on_complete + if output_so_far: + session.append_output(output_so_far) + self._track_started(session, self._reader_loop, f"proc-reader-{session.id}") + return session + + def spawn_via_env( + self, env: Any, command: str, cwd: str = None, task_id: str = "", session_key: str = "", + timeout: int = 10, owner_task_id: str = "") -> ProcessSession: + """Spawn a background process inside a non-local backend's sandbox. + The command is wrapped to capture its in-sandbox PID and redirect output to a + log file that later execute() calls poll. No live pipe or stdin, but it runs in + the correct sandbox context.""" + session = self._new_session(command, task_id, owner_task_id, session_key, cwd, env_ref=env, pid_scope="sandbox") + temp_dir = self._env_temp_dir(env) + log_path, pid_path, exit_path = (f"{temp_dir}/hermes_bg_{session.id}.{ext}" for ext in ("log", "pid", "exit")) + q = shlex.quote + bg_command = ( + f"mkdir -p {q(temp_dir)} && " + f"( nohup bash -lc {q(command)} > {q(log_path)} 2>&1; " + f"rc=$?; printf '%s\\n' \"$rc\" > {q(exit_path)} ) & " + f"echo $! > {q(pid_path)} && cat {q(pid_path)}") + try: + result = env.execute(bg_command, timeout=timeout, rewrite_compound_background=False) + output = result.get("output", "").strip() + session.pid = next((int(ln) for ln in map(str.strip, output.splitlines()) if ln.isdigit()), None) + # No PID from the wrapper (syntax error, broken redirect): a failed launch, + # not a fake running session. + if session.pid is None: + session.mark_exited(int(result.get("returncode", -1)) or -1, "failed_start", "failed_start") + session.output_buffer = output + except Exception as e: + session.mark_exited(-1, "failed_start", "failed_start") + session.output_buffer = f"Failed to start: {e}" + if session.exited: + with self._lock: + self._prune_if_needed() + else: + self._track_started( + session, self._env_poller_loop, f"proc-poller-{session.id}", (env, log_path, pid_path, exit_path)) + return session + + # ----- Reader / Poller Threads ----- + + def _reader_loop(self, session: ProcessSession): + """Background thread: read stdout from a local Popen process. + ``buffer.read1(4096)`` not ``TextIOWrapper.read(4096)``: on pipes the latter + blocks until EOF, landing "live" output in one burst at exit. Orphaned-pipe + guard: a backgrounded grandchild (``node server.js &``) inherits our pipe's write + end so EOF never arrives while it lives, which would park this thread and never + fire ``notify_on_complete``; on POSIX we ``select()`` and stop draining shortly + after the direct child exits (mirrors ``environments/base.py::_wait_for_process``). + Windows pipes lack select(), so the lazy ``_reconcile_local_exit`` is the net. + + Windows pipes don't support select(); the blocking path is kept there and the lazy reconcile in + poll()/wait() remains the safety net. See #68915, #8340. + """ + first_chunk = True + # A split multibyte UTF-8 char would become U+FFFD with stateless decoding; the + # incremental decoder holds the partial sequence until the rest arrives. + decoder = codecs.getincrementaldecoder("utf-8")(errors="replace") + + # Incremental decoder: raw pipe reads can split a multibyte UTF-8 character across two read1() + # chunks. A stateless per-chunk ``bytes.decode(errors="replace")`` turns both halves into U+FFFD + # mojibake. The incremental decoder holds the partial sequence until the continuation bytes arrive — + # same treatment the foreground path already has in + # ``tools/environments/base.py::_wait_for_process``. (Ported from openclaw/openclaw#112325.) + def _append_chunk(chunk: str): + nonlocal first_chunk + if first_chunk: + chunk = self._clean_shell_noise(chunk) + first_chunk = False + self._ingest_output(session, chunk) + try: + proc = session.process + if proc is None or proc.stdout is None: + return + stdout = proc.stdout + raw_read = getattr(getattr(stdout, "buffer", None), "read1", None) + + def _read_once(): + """One 4 KiB read: decoded text ('' for a partial multibyte tail), None at EOF.""" + if raw_read is None: # mocked/alternate streams without a raw buffer: less "live" + return stdout.read(4096) or None + raw = raw_read(4096) + return decoder.decode(raw) if raw else None + # select() needs a real OS fd; mocked streams (tests, adapters) may lack + # fileno() and use the blocking read instead. + try: + fd = stdout.fileno() if raw_read is not None and not _IS_WINDOWS else None + except Exception: + fd = None + if not (isinstance(fd, int) and fd >= 0): + fd = None + if fd is not None: + import select as _select + idle_after_exit = 0 + while True: + if fd is not None: + try: + ready, _, _ = _select.select([fd], [], [], 0.2) + except (ValueError, OSError): + break # fd already closed + if not ready: + # Direct child gone and pipe idle ~200ms: a few more cycles for a + # buffered tail, then stop rather than wait forever on an orphaned + # grandchild's pipe. + if proc.poll() is not None: + # See #68915. + idle_after_exit += 1 + if idle_after_exit >= 3: + break + continue + chunk = _read_once() + if chunk is None: + break # true EOF — all writers closed + if chunk: + _append_chunk(chunk) + idle_after_exit = 0 + except Exception as e: + logger.debug("Process stdout reader ended: %s", e) + finally: + self._finish_reader( + session, decoder, _append_chunk, "Process", + lambda: session.process.wait(timeout=5), lambda: session.process.returncode) + + def _finish_reader(self, session, decoder, append, label, wait, exit_code) -> None: + """Reader-thread teardown: flush the decoder (a truncated multibyte tail becomes + one U+FFFD instead of vanishing), reap the child (no zombies), record the exit.""" + with suppress(Exception): + tail = decoder.decode(b"", final=True) + if tail: + append(tail) + try: + wait() + except Exception as e: + logger.debug("%s wait timed out or failed: %s", label, e) + self._finish_exited(session, exit_code()) + + @staticmethod + def _log_delta_command(quoted_log_path: str, offset: int) -> str: + """Shell command that reads only the log bytes written since ``offset`` + (``cat``-ing the whole file every poll re-sends all output over docker/SSH). + + Prints one header line ``" "`` then the bytes in [offset, size). + The size is read first and the tail cut at that same size, so a growing file + never sends a byte twice; a file that shrank was rotated/truncated, so the + offset drops to 0 and the reader starts over. The window end is pulled back + to a UTF-8 character boundary (the backend decodes each ``execute()`` result + on its own, so a straddling multibyte char would become U+FFFD and break watch + patterns at the seam): up to 3 trailing continuation bytes are held for the + next poll and the header reports the trimmed size.""" + return ( + f"O={offset}; " + f"S=$({{ wc -c < {quoted_log_path}; }} 2>/dev/null | tr -dc '0-9'); " + f"S=${{S:-0}}; " + f'if [ "$S" -lt "$O" ]; then O=0; fi; ' + # Scan back up to 3 continuation bytes (octal 200-277) to the lead byte; if + # the lead's declared length (3xx=2, 34x-35x=3, 36x-37x=4) exceeds the bytes + # present, trim to before it. Complete sequences and ASCII tails untouched. + f'N=0; P=$S; while [ "$P" -gt "$O" ] && [ "$N" -lt 3 ]; do ' + f"B=$(tail -c +$P {quoted_log_path} 2>/dev/null | head -c 1 | od -An -to1 | tr -dc '0-9'); " + f'case "$B" in 2[0-7][0-7]) P=$((P-1)); N=$((N+1));; *) break;; esac; done; ' + f'if [ "$N" -gt 0 ] || [ "$P" -eq "$S" ]; then ' + f"B=$(tail -c +$P {quoted_log_path} 2>/dev/null | head -c 1 | od -An -to1 | tr -dc '0-9'); " + f'case "$B" in 3[0-3][0-7]) L=2;; 3[4-5][0-7]) L=3;; 3[6-7][0-7]) L=4;; *) L=1;; esac; ' + f'if [ "$L" -gt $((N+1)) ]; then S=$((P-1)); fi; fi; ' + f'echo "$S $O"; ' + f'if [ "$S" -gt "$O" ]; then ' + f"tail -c +$((O+1)) {quoted_log_path} 2>/dev/null | head -c $((S-O)); fi" + ) + + def _env_poller_loop(self, session: ProcessSession, env: Any, log_path: str, pid_path: str, exit_path: str): + """Background thread: poll a sandbox log file for non-local backends.""" + q = shlex.quote + # Byte offset already read from the log (bytes, not chars: the shell counts bytes). + prev_output_bytes = 0 + while not session.exited: + time.sleep(2) + try: + # Read only the bytes written since the last poll. + raw = env.execute(self._log_delta_command(q(log_path), prev_output_bytes), + timeout=10).get("output", "") + header, _, delta = raw.partition("\n") + try: + size_str, offset_str = header.split() + new_size = int(size_str) + used_offset = int(offset_str) + except ValueError: + # No usable header (command failed, shell missing a tool): skip this + # poll rather than act on a half-read value. + new_size = None + used_offset = None + delta = "" + if new_size is not None: + if used_offset < prev_output_bytes: + # Log rotated/truncated: what we hold no longer lines up. Restart. + with session._lock: + session.output_buffer = "" + prev_output_bytes = new_size + if delta: + with session._lock: + session.output_buffer += delta + if len(session.output_buffer) > session.max_output_chars: + session.output_buffer = session.output_buffer[-session.max_output_chars:] + self._check_watch_patterns(session, delta) + self._emit_output(session, delta) + + check = env.execute( + f"kill -0 \"$(cat {q(pid_path)} 2>/dev/null)\" 2>/dev/null; echo $?", timeout=5) + check_output = check.get("output", "").strip() + if check_output and check_output.splitlines()[-1].strip() != "0": + # Exited -- read the exit code captured by the wrapper shell. + exit_str = env.execute(f"cat {q(exit_path)} 2>/dev/null", timeout=5).get("output", "").strip() + try: + exit_code = int(exit_str.splitlines()[-1].strip()) + except (ValueError, IndexError): + exit_code = -1 + session.exit_code = exit_code # unlike mark_exited, a raced kill still takes this code + self._finish_exited(session, exit_code) + return + except Exception: + # Environment might be gone (sandbox reaped, etc.) + session.exited, session.exit_code = True, -1 + session.completion_reason, session.termination_source = "lost", "backend_lost" + self._move_to_finished(session) + return + + def _pty_reader_loop(self, session: ProcessSession): + """Background thread: read output from a PTY process.""" + pty = session._pty + # Same split-multibyte handling as _reader_loop. + # PTY reads can split a multibyte UTF-8 character across chunks just like pipe reads — hold partial + # sequences until the rest arrives. (Ported from openclaw/openclaw#112325.) + decoder = codecs.getincrementaldecoder("utf-8")(errors="replace") + # Programs in a PTY can block waiting for replies to device-status / window-size / + # cursor-position / DEC private-mode queries. Answer the bounded set and strip the + # queries from captured output. POSIX only: Windows ConPTY is a real console host that + # answers itself (and pywinpty yields str chunks, not bytes). + responder = None + if not _IS_WINDOWS: + from tools.pty_query_responder import PtyQueryResponder + responder = PtyQueryResponder(rows=30, cols=120) + try: + while pty.isalive(): + try: + chunk = pty.read(4096) + if chunk: + # ptyprocess returns bytes; pywinpty returns str + if responder is not None and isinstance(chunk, bytes): + chunk, replies = responder.process(chunk) + if replies: + try: + pty.write(replies) + except Exception: + logger.debug( + "PTY query response write failed", + exc_info=True, + ) + text = chunk if isinstance(chunk, str) else decoder.decode(chunk) + if text: + self._ingest_output(session, text) + except Exception: # EOFError included + break + except Exception as e: + logger.debug("PTY stdout reader ended: %s", e) + if responder is not None: + # A query prefix split across the final reads is plain output after all. + tail = decoder.decode(responder.flush()) + if tail: + self._ingest_output(session, tail) + self._finish_reader( + session, decoder, lambda t: self._ingest_output(session, t), "PTY", + pty.wait, lambda: pty.exitstatus if hasattr(pty, 'exitstatus') else -1) + + def _ingest_output(self, session: ProcessSession, text: str) -> None: + """Buffer a freshly-read chunk, then scan watch patterns and stream it live.""" + session.append_output(text) + self._check_watch_patterns(session, text) + self._emit_output(session, text) + + def _finish_exited(self, session: ProcessSession, exit_code) -> None: + """Mark a reader-observed exit (a raced kill keeps its own code/reason) and finish.""" + session.mark_exited(exit_code) + self._move_to_finished(session) + + def _move_to_finished(self, session: ProcessSession): + """Move a session from running to finished. + Idempotent: kill_process() and the reader thread can both call this; only + the FIRST move enqueues the completion notification, so no duplicates.""" + with self._lock: + was_running = session.id in self._running + if was_running: + # Keep the session tracked until its result is durable. A finite + # parent must not observe completion and exit during this write. + save_completed_result(session) + self._running.pop(session.id) + self._finished[session.id] = session + # Release the retained Popen/PTY handles now: otherwise every + # finished-but-unpruned session keeps its stdout pipe (or PTY master) + # FD open until FINISHED_TTL_SECONDS elapses, and heavy background + # churn can exhaust the gateway's FD limit. On the reader-thread path + # the pipe is already at EOF; on the kill/reconcile paths the reader + # may still be draining — its next read raises on the closed stream + # and the loop exits, dropping at most the unread tail of a process + # that was just killed. poll()/wait()/read_log() serve from the + # buffered ``output_buffer``, never from the pipe. + self._release_finished_handles(session) + self._write_checkpoint() + if was_running and session.notify_on_complete: + notification = { + "type": "completion", + "session_id": session.id, + "session_key": session.session_key, + "task_id": session.task_id, + "owner_task_id": session.owner_task_id or session.task_id, + "command": session.command, + **({"handoff_note": session.handoff_note} if session.handoff_note else {}), + **self._exit_fields(session), + "output": _output_tail(session, 2000), + # Stable producer identity across checkpoint recovery (unlike a + # consumer-observed completion timestamp). + "started_at": session.started_at, + } + _redact_process_result(notification) + self.completion_queue.put(notification) + session._completion_event.set() + + @staticmethod + def _exit_fields(session: ProcessSession) -> dict: + return { + "exit_code": session.exit_code, + "completion_reason": session.completion_reason, + "termination_source": session.termination_source, + } + + def _release_finished_handles(self, session: ProcessSession): + """Close a finished session's OS handles (Popen pipes / PTY master). + + Best-effort and idempotent: the session may have no local Popen (env + backends, detached recovery), or the handles may already be closed by + the reader loop / kill path. Closing a Popen's stream objects does not + kill anything — the child has already exited — it only releases the + parent's pipe FDs, which is exactly the retained-resource leak. + """ + proc = session.process + if proc is not None: + for stream in (proc.stdout, proc.stderr, proc.stdin): + if stream is not None: + with suppress(OSError, ValueError): # a stdin flush can hit EPIPE + stream.close() + if session._pty is not None: + # ptyprocess/pywinpty close() is idempotent (``closed`` flag) and + # closes the master fd exactly once; it raises only if the child + # ignores SIGKILL, which we don't want to surface on the finish path. + with suppress(Exception): + session._pty.close() + + # ----- Query Methods ----- + + def is_completion_consumed(self, session_id: str) -> bool: + """Check if a completion notification was already consumed via wait/log.""" + return session_id in self._completion_consumed + + def is_session_waiting(self, session_id: str) -> bool: + """Whether a goal loop (``hermes_cli.goals`` wait barrier) should stay parked on + this session: still running AND, with ``watch_patterns``, none matched yet (a + long-lived watcher unblocks on its trigger, not on exit). Unknown/exited/ + already-fired sessions return False so a stale barrier can never wedge the loop.""" + with self._lock: + session = (self._running.get(session_id) or self._finished.get(session_id)) if session_id else None + if session is None: + return False + with suppress(Exception): + self._refresh_detached_session(session) + return not session.exited and not ( + session.watch_patterns and not session._watch_disabled and session._watch_hits > 0) + + def wait_for_pending_completions( + self, task_id: Optional[str] = None, *, timeout: float | None = None, poll_interval: float = 1.0, + ) -> dict: + """Bounded linger for ``notify_on_complete`` background processes at one-shot exit. + A one-shot CLI run (``hermes -q/-Q/-z``) exits when its turn ends; a background + process it spawned still holds a stdout pipe owned by the dying parent and dies of + SIGPIPE seconds later (Bot Mode handoff replies were the visible casualty). Only + ``notify_on_complete`` processes carry a completion contract — servers/daemons/ + watchers aren't the parent's to wait for. ``task_id=None`` waits on every tracked + process; ``timeout=None`` reads ``terminal.oneshot_completion_wait_seconds`` (``<= 0`` + disables). Each pass re-reconciles child state so an orphaned-pipe exit can't wedge + the linger. Returns ``{"waited", "completed", "timed_out"}`` id lists. + + Bot Mode handoff REPLIES are the visible casualty (#90879): a recipient invoked as ``hermes -p + chat -Q --query-file ...`` dispatches its reply via ``message_agent`` / ``bot_relay`` exactly this + way, then exits, and the reply process is destroyed ~3s later. The sender waits forever for a reply + that was already killed. + See #17327. + """ + if timeout is None: + timeout = self._oneshot_completion_wait_seconds() + result: dict = {"waited": [], "completed": [], "timed_out": []} + with self._lock: + # `_finished` too: `_move_to_finished` pops a session from `_running` and enqueues its completion + # only after releasing handles and writing the checkpoint. A parent whose turn ends inside that + # window would otherwise see nothing pending, drain nothing and exit without the follow-up turn. + pending = [ + s for store in (self._running, self._finished) for s in store.values() + if s.notify_on_complete and not s._completion_event.is_set() and (task_id is None or s.task_id == task_id) + ] + if not pending or timeout <= 0: + return result + result["waited"] = [s.id for s in pending] + logger.info( + "One-shot exit lingering (bounded %ss) for %d notify_on_complete " + "background process(es): %s", + timeout, len(pending), ", ".join(s.id for s in pending)) + deadline = time.monotonic() + max(float(timeout), 0.0) + interval = max(float(poll_interval), 0.05) + try: + from tools.interrupt import is_interrupted as _is_interrupted + except Exception: + _is_interrupted = lambda: False # noqa: E731 + interrupted = False + for session in pending: + try: + while not session._completion_event.is_set(): + if interrupted or _is_interrupted(): + interrupted = True + break + remaining = deadline - time.monotonic() + if remaining <= 0: + break + # Reconcile first so orphaned-pipe and detached exits fire the event. + with suppress(Exception): + # Reconcile first: catches direct-child exits whose reader is blocked on a pipe held + # open by a descendant (#17327) and detached/env sessions, so the event actually + # fires. + # Reconcile against real child state before reading session.exited. Guards against + # orphaned-pipe reader hangs (issue #17327). + # Reconcile against real child state — guards against orphaned- pipe reader hangs + # where the reader is blocked but the direct child has already exited (issue + # #17327). + self._reconcile_local_exit(session) + self._refresh_detached_session(session) + if session._completion_event.is_set(): + break + session._completion_event.wait(min(remaining, interval)) + except KeyboardInterrupt: + # Stop waiting, but never let the interrupt skip the caller's durable + # teardown (session flush, end_session) that follows. + interrupted = True + result["completed" if session._completion_event.is_set() else "timed_out"].append(session.id) + if result["timed_out"]: + logger.warning( + "One-shot exit linger timed out after %ss with %d background " + "process(es) still running: %s — they may be killed when this " + "process exits.", + timeout, len(result["timed_out"]), ", ".join(result["timed_out"])) + return result + + @staticmethod + def _oneshot_completion_wait_seconds() -> float: + """Linger (s) for one-shot exits with pending notify_on_complete processes; 0 disables.""" + return ProcessRegistry._config_seconds("oneshot_completion_wait_seconds", 600.0) + + def _drain_should_skip(self, session_id: str, *, skip_poll_observed: bool = True) -> bool: + """Skip a completion the CLI agent already has this turn — consumed via wait/log + or observed inline via poll(). Gateway/tui watchers check only + ``is_completion_consumed`` so a read-only poll never suppresses their turn. + + Skips when the agent has either truly consumed the output (wait/log → ``_completion_consumed``) or + observed the exit inline via poll() (``_poll_observed``). In both cases the CLI agent already has + the result this turn, so injecting a [SYSTEM: ...] completion would be a duplicate (#8228). + """ + return session_id in self._completion_consumed or (skip_poll_observed and session_id in self._poll_observed) + + @staticmethod + def _surface_child_process_notifications() -> bool: + """``delegation.surface_child_process_notifications``; False on any config + error — never crash the drain loop.""" + try: + return bool(ProcessRegistry._config_value("delegation", "surface_child_process_notifications", False)) + except Exception: + return False + + @staticmethod + def _owns_event(evt: dict, session_key: str, owns_event, is_async_delegation: bool) -> bool: + """Routing verdict for one drained event (see drain_notifications); False = requeue.""" + evt_session_key = str(evt.get("session_key") or "") + requires_positive_proof = is_async_delegation or bool(evt_session_key or evt.get("origin_ui_session_id")) + if owns_event is not None and requires_positive_proof: + try: + return bool(owns_event(evt)) + except Exception: + return False # fail closed — never leak on a broken check + if session_key and requires_positive_proof: + return evt_session_key == session_key + # Restored payloads from a previous process: an unfiltered drain cannot prove + # ownership, so leave them for the owner. + return not (is_async_delegation and evt.get("restored")) + + def drain_notifications( + self, session_key: str = "", owns_event=None, *, skip_poll_observed: bool = True, + ) -> "list[tuple[dict, str]]": + """Pop all pending events and return ``(raw_event, formatted_text)`` pairs. + Skips completions per ``_drain_should_skip`` (gateway/TUI pass + ``skip_poll_observed=False``). Routing (``_owns_event``): async-delegation events + always need ownership proof, ordinary events once they carry ``session_key`` or + ``origin_ui_session_id``; ``owns_event(evt)`` (strongest; the TUI passes a + compression-chain-aware check) consumes ONLY on True, ``session_key`` uses plain + equality; non-owned events are re-queued for their owner. No filter consumes + everything (legacy single-session) except restored delegation payloads (fail-closed).""" + results: "list[tuple[dict, str]]" = [] + requeue: "list[dict]" = [] + # delegation.surface_child_process_notifications, read at most once per drain + # and only when an sa- event shows up. + surface_child: "bool | None" = None + while not self.completion_queue.empty(): + try: + evt = self.completion_queue.get_nowait() + except Exception: + break + is_async_delegation = evt.get("type") == "async_delegation" + if not self._owns_event(evt, session_key, owns_event, is_async_delegation): + requeue.append(evt) + continue + # Routing happened first so a foreign session cannot drop the owner's + # event via its own consumed/observed state. + _evt_sid = evt.get("session_id", "") + if evt.get("type") == "completion" and self._drain_should_skip( + _evt_sid, skip_poll_observed=skip_poll_observed): + continue + # Subagent-owned process notifications are suppressed by default — the + # child's delegation result is the deliverable. Judge ownership on + # owner_task_id (RAW spawning id; task_id is the container key, collapsed + # by _resolve_container_task_id). Dropped, NOT requeued: children never + # drain, so a requeue would pin the event forever. 'async_delegation' + # is the result itself and is NEVER suppressed. + _evt_task_id = str(evt.get("owner_task_id") or evt.get("task_id") or "") + if not is_async_delegation and _evt_task_id.startswith("sa-"): + if surface_child is None: + surface_child = self._surface_child_process_notifications() + if not surface_child: + logger.debug( + "Suppressed subagent-owned process notification " + "(delegation.surface_child_process_notifications=false): " + "type=%s session_id=%s task_id=%s", + evt.get("type", "completion"), _evt_sid, _evt_task_id) + continue + if text := format_process_notification(evt): + results.append((evt, text)) + for evt in requeue: + self.completion_queue.put(evt) + return results + + # Minimum suffix chars for prefix resolution; "p"/"proc_1" are too collision-prone. + _MIN_PREFIX_CHARS = 4 + + def get(self, session_id: str) -> Optional[ProcessSession]: + """Session by full ID or unique prefix (``proc_4dae`` / bare ``4dae``, like git + short hashes); ambiguous or too-short prefixes resolve to None, never a guess.""" + if not isinstance(session_id, str) or not session_id: + return None + with self._lock: + session = self._running.get(session_id) or self._finished.get(session_id) + if session is None: + session = load_completed_results(session_id).get(session_id) + return self._refresh_detached_session(session if session is not None else self._resolve_prefix(session_id)) + + def _resolve_prefix(self, session_id: str) -> Optional[ProcessSession]: + """Resolve a unique session-ID prefix (a bare hex tail is normalized to + ``proc_``); :meth:`get` tries exact first.""" + query = session_id.strip() if isinstance(session_id, str) else "" + if not query: + return None + if not query.startswith("proc_"): + query = f"proc_{query}" + if len(query) - len("proc_") < self._MIN_PREFIX_CHARS: + return None + matches = load_completed_results(query) + with self._lock: + matches.update({ + sid: s for store in (self._running, self._finished) + for sid, s in store.items() if sid.startswith(query) + }) + return next(iter(matches.values())) if len(matches) == 1 else None + + def _reconcile_local_exit(self, session: "ProcessSession") -> None: + """Reconcile ``session.exited`` against the real child state. + The reader flips ``exited`` only at EOF; when the direct child has exited but a + descendant (e.g. a daemon from ``hermes update``) holds the pipe open, poll() + would report "running" forever. If ``Popen.poll()`` has an exit code, drain + readable bytes non-blocking and flip ``exited``. No-op for env/PTY, exited and + detached sessions. + + The reader thread (`_reader_loop`) sets `session.exited = True` only in its `finally` block, which + runs when `stdout.read()` returns EOF. If the direct `Popen` child has exited but a descendant + process (e.g. a daemon spawned by `hermes update` restarting the gateway) is still holding the + stdout pipe open, the reader blocks forever and poll() keeps returning "running" indefinitely (issue + #17327 — 74 polls over 7 minutes on Feishu). + """ + if session is None or session.exited: + return + proc = getattr(session, "process", None) + if proc is None: + return + try: + rc = proc.poll() + except Exception: + return + if rc is None: + return # Direct child still running — reader block is legitimate. + # Best-effort non-blocking drain of whatever the reader hasn't consumed. + stdout = getattr(proc, "stdout", None) + if stdout is not None and not _IS_WINDOWS: + try: + import fcntl + fd = stdout.fileno() + flags = fcntl.fcntl(fd, fcntl.F_GETFL) + fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) + try: + with suppress(BlockingIOError, OSError, ValueError): + chunk = stdout.read() + if chunk: + session.append_output(chunk if isinstance(chunk, str) else chunk.decode("utf-8", errors="replace")) + finally: + with suppress(Exception): + fcntl.fcntl(fd, fcntl.F_SETFL, flags) + except Exception as e: + logger.debug("Non-blocking drain failed for %s: %s", session.id, e) + with session._lock: + session.mark_exited(rc) + logger.info( + "Reconciled session %s: direct child exited with code %s but reader " + "was still blocked (orphaned pipe). Flipped to exited.", + session.id, rc) + self._move_to_finished(session) + + @staticmethod + def _status_head(session: ProcessSession) -> dict: + return {"session_id": session.id, "command": session.command, "status": "exited" if session.exited else "running"} + + def poll(self, session_id: str) -> dict: + """Check status and get new output for a background process.""" + session = self.get(session_id) + if session is None: + return _not_found(session_id) + self._reconcile_local_exit(session) # orphaned-pipe reader guard + with session._lock: + output_preview = _output_tail(session, 1000) + result = { + **self._status_head(session), "pid": session.pid, + "uptime_seconds": int(time.time() - session.started_at), "output_preview": output_preview} + if session.exited: + result.update(self._exit_fields(session)) + # Read-only: record in _poll_observed (CLI inline dedup) but NOT in + # _completion_consumed, or a status check would suppress the watcher's + # autonomous delivery turn. See __init__. + self._poll_observed.add(session_id) + if session.detached: + result.update(detached=True, note="Process recovered after restart -- output history unavailable") + return result + + def read_log(self, session_id: str, offset: int | None = None, limit: int = 200) -> dict: + """Read the full output log with optional pagination by lines.""" + from tools.ansi_strip import strip_ansi + + session = self.get(session_id) + if session is None: + return _not_found(session_id) + with session._lock: + full_output = strip_ansi(session.output_buffer) + lines = full_output.splitlines() + total_lines = len(lines) + # offset=None -> last N lines; an explicit offset=0 means the HEAD (don't + # conflate the two via falsiness). + # An explicit offset=0 means "start from the first line" — previously it was conflated with the + # default and silently returned the TAIL instead of the head (same falsy-coercion class as the + # wait() timeout guard; salvaged from PR #60004, credit @isheng-eqi). + if offset is None and limit > 0: + selected = lines[-limit:] + observed_completion_output = bool(selected) or total_lines == 0 + else: + offset = offset or 0 + selected = lines[offset:offset + limit] + stop = slice(offset, offset + limit).indices(total_lines)[1] + observed_completion_output = total_lines == 0 or (bool(selected) and stop == total_lines) + result = { + **self._status_head(session), "output": "\n".join(selected), + "total_lines": total_lines, "showing": f"{len(selected)} lines"} + if session.exited and observed_completion_output: + self._completion_consumed.add(session_id) + return result + + def wait(self, session_id: str, timeout: int = None) -> dict: + """Block until the process exits, the timeout elapses, the user interrupts, or a + mid-turn user message (steer/redirect → ``request_yield``) releases the wait. + ``timeout`` defaults to (and is clamped by) TERMINAL_TIMEOUT. Returns a dict + with status exited|timeout|interrupted|not_found|error and an output snapshot.""" + from tools.interrupt import consume_yield as _consume_yield, is_interrupted as _is_interrupted + + try: + max_timeout = int(os.getenv("TERMINAL_TIMEOUT", "180")) + except (ValueError, TypeError): + max_timeout = 180 + # The schema says minimum=1 but not every caller enforces it; timeout=0 is + # falsy and would silently fall through to the default wait. + if timeout is not None and timeout <= 0: + return {"status": "error", "error": f"timeout must be positive (got {timeout})"} + timeout_note = None + effective_timeout = timeout or max_timeout + if timeout and timeout > max_timeout: + effective_timeout = max_timeout + timeout_note = f"Requested wait of {timeout}s was clamped to configured limit of {max_timeout}s" + session = self.get(session_id) + if session is None: + return _not_found(session_id) + deadline = time.monotonic() + effective_timeout + while time.monotonic() < deadline: + session = self._refresh_detached_session(session) + if session is None: + return _not_found(session_id) + self._reconcile_local_exit(session) # orphaned-pipe reader guard + result = None + if session.exited: + self._completion_consumed.add(session_id) + result = self._exit_snapshot(session, "exited") + elif _is_interrupted(): + result = { + "status": "interrupted", "command": session.command, "output": _output_tail(session, 1000), + "note": "User sent a new message -- wait interrupted"} + elif _consume_yield(threading.current_thread().ident): + # A steer/redirect landed mid-turn: redirect() asks tool workers to YIELD so + # the user's message is delivered instead of parked behind this wait. The + # process is untouched and still notify-tracked; the model should read the + # steer text and respond, not re-issue the wait (kimi-code#3697 class). + result = { + "status": "interrupted", "command": session.command, "output": _output_tail(session, 1000), + "process_running": True, + "note": ("User sent a new message -- wait released; the process is still " + "running and you will be notified on exit. Respond to the user now.")} + if result is not None: + if timeout_note: + result["timeout_note"] = timeout_note + return result + remaining = deadline - time.monotonic() + if remaining <= 0: + break + session._completion_event.wait(timeout=min(1.0, remaining)) + result = { + "status": "timeout", "command": session.command, "output": _output_tail(session, 1000), + # Not a failure — models re-issued identical waits after misreading this as an error. + "process_running": True} + base_note = ( + f"Wait window of {effective_timeout}s elapsed — the process is still running. This is not an error.") + if session.started_at: + base_note += f" Uptime: {int(time.time() - session.started_at)}s." + base_note += ( + " notify_on_complete is set: you will be notified on exit — do more work instead of waiting again." + if session.notify_on_complete else + " Poll again later or use terminal(background=true, " + "notify_on_complete=true) next time for automatic notification.") + result["timeout_note"] = f"{timeout_note}. {base_note}" if timeout_note else base_note + return result + + @staticmethod + def _exit_snapshot(session: ProcessSession, status: str) -> dict: + """Result dict for an exited session: exit metadata + last 2000 chars of output.""" + return { + "status": status, "command": session.command, + **ProcessRegistry._exit_fields(session), "output": _output_tail(session, 2000)} + + def kill_process( + self, session_id: str, *, source: str = "process.kill", consume_output: bool = True, + ) -> dict: + """Kill a background process and return its output snapshot. + ``consume_output`` is true for explicit tool/RPC kills (the caller sees the + output). Bulk cleanup passes false so it doesn't suppress an autonomous + completion notification — except abandoned-turn reaping (``kill_started_since``), + which passes true so a killed abandoned process can't revive stopped work.""" + session = self.get(session_id) + if session is None: + return _not_found(session_id) + if session.exited: + # A double-forked descendant may still be alive in the systemd scope even + # though the main process exited — stop the scope to reap survivors. + # See #70716. + # If the worker was spawned in its own systemd scope (#70716), stop the entire unit to reap any + # double-forked descendants that were reparented inside the scope and survived the PID signal + # above (reviewer gap #2). ``systemctl --user stop`` sends SIGTERM to every process in the + # cgroup and escalates to SIGKILL after TimeoutStopSec. This is additive — the PID-based kill + # above already handled the main process; this catches stragglers. + if session.systemd_unit: + _stop_systemd_unit(session.systemd_unit) + with session._lock: + result = self._exit_snapshot(session, "already_exited") + # Only suppress the autonomous turn after its output is present in + # the explicit kill result, matching wait/log consumption. + if consume_output: + self._completion_consumed.add(session_id) + return result + try: + early = self._signal_kill(session, session_id, consume_output) + if early is not None: + return early + # Additive to the PID kill: stopping the scope reaps double-forked + # descendants reparented inside the cgroup. + if session.systemd_unit: + _stop_systemd_unit(session.systemd_unit) + # Capture output, mark consumed, THEN expose ``exited`` to watcher tasks — + # closes the delayed-notification race without losing the transcript. + with session._lock: + output = _output_tail(session, 2000) + if consume_output: + self._completion_consumed.add(session_id) + session.exited = True + session.exit_code = -15 # SIGTERM + session.completion_reason = "killed" + session.termination_source = source + self._move_to_finished(session) + self._write_checkpoint() + return { + "status": "killed", "session_id": session.id, "completion_reason": session.completion_reason, + "termination_source": session.termination_source, "output": output} + except Exception as e: + return {"status": "error", "error": str(e)} + + def _signal_kill(self, session: ProcessSession, session_id: str, consume_output: bool) -> Optional[dict]: + """Deliver the kill via PTY, local Popen tree, sandbox exec or recovered host + PID. Returns a final result dict when the kill cannot proceed (recycled/dead + recovered PID, or no runtime handle), else None.""" + if session._pty: + try: + session._pty.terminate(force=True) + except Exception: + if session.pid: + os.kill(session.pid, signal.SIGTERM) + elif session.process: + # Tree kill: on Windows Popen.terminate() only kills the shell wrapper and + # leaves Git Bash descendants behind. + self._terminate_host_pid(session.process.pid, session.host_start_time) + elif session.env_ref and session.pid: + session.env_ref.execute(f"kill {session.pid} 2>/dev/null", timeout=5) + elif session.detached and session.pid_scope == "host" and session.pid: + # Identity check, not bare liveness: a gone/recycled PID means our + # process exited — never tree-kill the stranger. Still stop an owned + # scope: a daemonized descendant may survive the wrapper PID. + # If this recovered session also carries an owned systemd scope, stop that scope before + # returning: a daemonized descendant may still be alive there even though the wrapper PID exited + # or was recycled across the gateway restart (#70716, teknium1 review). + if not self._host_pid_is_ours(session.pid, session.host_start_time): + if session.systemd_unit: + _stop_systemd_unit(session.systemd_unit) + with session._lock: + session.exited = True + session.exit_code = None + output = _output_tail(session, 2000) + if consume_output: + self._completion_consumed.add(session_id) + self._move_to_finished(session) + return {"status": "already_exited", "exit_code": session.exit_code, "output": output} + self._terminate_host_pid(session.pid, session.host_start_time) + else: + return { + # Reject non-positive timeouts — the schema declares minimum=1, but not every caller + # enforces schemas before dispatch. timeout=0 is falsy, so without this guard it silently + # fell through (`0 or max_timeout`) to the DEFAULT wait instead of erroring. Salvaged from + # PR #60004 (credit @isheng-eqi). + "status": "error", + "error": "Recovered process cannot be killed after restart because " + "its original runtime handle is no longer available", + } + return None + + def _stdin_op(self, session_id: str, pty_op, pipe_op, ok: dict) -> dict: + """Run a stdin operation on a running session — ``pty_op(pty)`` under PTY mode, + else ``pipe_op(stdin)`` on the Popen pipe — and return *ok* on success.""" + session = self.get(session_id) + if session is None: + return _not_found(session_id) + if session.exited: + return {"status": "already_exited", "error": "Process has already finished"} + try: + if session._pty: + pty_op(session._pty) + elif not session.process or not session.process.stdin: + return {"status": "error", "error": "Process stdin not available (non-local backend or stdin closed)"} + else: + pipe_op(session.process.stdin) + return ok + except Exception as e: + return {"status": "error", "error": str(e)} + + def write_stdin(self, session_id: str, data: str) -> dict: + """Send raw data to a running process's stdin (no newline appended).""" + + def via_pty(pty): + # pywinpty expects str on Windows; ptyprocess expects bytes on POSIX. + if _IS_WINDOWS: + pty.write(data.decode("utf-8") if isinstance(data, bytes) else str(data)) + else: + # surrogateescape: a PTY is a byte stream — round-trip the original + # bytes instead of crashing on surrogate content. + pty.write(data.encode("utf-8", "surrogateescape") if isinstance(data, str) else data) + + def via_pipe(stdin): + stdin.write(data) + stdin.flush() + return self._stdin_op(session_id, via_pty, via_pipe, {"status": "ok", "bytes_written": len(data)}) + + def submit_stdin(self, session_id: str, data: str = "") -> dict: + """Send data + newline to stdin (like pressing Enter). + On a Windows PTY, Enter is a carriage return: ConPTY treats ``\\r`` as + end-of-line and a bare ``\\n`` through pywinpty is NOT a line terminator — the + child's blocking line read (``readline()``, Go ``bufio.Scanner``) never returns + and the process hangs looking healthy. ``\\r\\n`` gives it both; POSIX keeps ``\\n``.""" + session = self.get(session_id) + return self.write_stdin(session_id, data + ("\r\n" if _IS_WINDOWS and session and session._pty else "\n")) + + def request_close_terminal(self, session_id: str) -> dict: + """Ask the desktop GUI to close this process's read-only terminal tab. Does NOT + kill the process — output keeps buffering and the tab can be reopened from the + status stack. Errors when no UI close sink is wired.""" + if self.on_close is None: + return {"status": "error", "error": "close_terminal is only available in the Hermes desktop app."} + # The session may already be finished (or pruned) — the tab can still + # linger and be closed, so a missing session is not an error here. + try: + self.on_close(self.get(session_id), session_id) + except Exception as e: + return {"status": "error", "error": str(e)} + return { + "status": "ok", "closed": session_id, + "note": "Closed the read-only terminal tab. The process was not killed; " + "its output remains available and the user can reopen the tab " + "from the status stack."} + + def close_stdin(self, session_id: str) -> dict: + """Close a running process's stdin / send EOF without killing the process.""" + session = self.get(session_id) + msg = "EOF sent" if session is not None and session._pty else "stdin closed" + return self._stdin_op( + session_id, lambda pty: pty.sendeof(), lambda stdin: stdin.close(), {"status": "ok", "message": msg}) + + def count_running(self) -> int: + """O(1) running count for status-bar polling; dict ``len()`` is atomic, no lock.""" + return len(self._running) + + def list_sessions(self, task_id: str = None, session_key: str = None, *, include_retained: bool = False) -> list: + """Running and recently-finished processes for ``task_id`` and/or ``session_key``; + cross-task entries sharing the gateway session (a forgotten preview server + blocking session reset) are flagged ``"session_scoped": true``. + + When ``task_id`` is given, processes for that task are included. When ``session_key`` is also given, + session-scoped background processes (``background: true``) registered under that gateway session are + surfaced too, even if they belong to a different task — so the agent can discover a forgotten + preview server that is blocking session reset (#29177). + """ + # Only an explicit tool query reads historical receipts. Status bars and + # gateway liveness scans call this frequently and need the live registry. + sessions = load_completed_results() if include_retained else {} + with self._lock: + sessions.update(self._finished) + sessions.update(self._running) + all_sessions = [self._refresh_detached_session(s) for s in sessions.values()] + if task_id or session_key: + all_sessions = [ + s for s in all_sessions + if (task_id and s.task_id == task_id) or (session_key and s.session_key == session_key) + ] + result = [] + for s in all_sessions: + # List-only refreshes must observe child exit even while descendants + # keep the capture pipe open; retain the existing completion owner. + self._reconcile_local_exit(s) + entry = { + "session_id": s.id, + "command": s.command[:200], + "cwd": s.cwd, + "pid": s.pid, + "owner_task_id": s.owner_task_id or s.task_id, + "started_at": time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(s.started_at)), + "uptime_seconds": int(time.time() - s.started_at), + "status": "exited" if s.exited else "running", + "output_preview": s.output_buffer[-200:] if s.output_buffer else "", + } + # Flag processes surfaced only because they share the gateway session (not the current task) — + # these are the long-lived background processes a user may have forgotten about (#29177). + if task_id and session_key and s.task_id != task_id and s.session_key == session_key: + entry["session_scoped"] = True + # Trigger metadata for goal-loop judges (a watcher may never exit). + if s.watch_patterns and not s._watch_disabled: + entry.update(watch_patterns=list(s.watch_patterns), watch_hit=s._watch_hits > 0) + if s.notify_on_complete: + entry["notify_on_complete"] = True + if s.exited: + entry["exit_code"] = s.exit_code + if s.detached: + entry["detached"] = True + result.append(entry) + return result + + # ----- Session/Task Queries (for gateway integration) ----- + + def _any_running(self, predicate) -> bool: + """True if any still-running session satisfies *predicate*, after refreshing + detached sessions so a finished-but-unreaped process reads as inactive.""" + with self._lock: + sessions = list(self._running.values()) + for session in sessions: + self._refresh_detached_session(session) + with self._lock: + return any(not s.exited and predicate(s) for s in self._running.values()) + + def has_active_processes(self, task_id: str) -> bool: + """Whether any process for ``task_id`` is still running.""" + return self._any_running(lambda s: s.task_id == task_id) + + def running_owned_by(self, owner_task_id: str) -> List[ProcessSession]: + """Running processes whose RAW spawning owner is ``owner_task_id``.""" + with self._lock: + return [s for s in self._running.values() if s.owner_task_id == owner_task_id and not s.exited] + + def unread_completions_owned_by(self, owner_task_id: str) -> List[ProcessSession]: + """Exited ``notify_on_complete`` processes of ``owner_task_id`` whose result nobody read (no wait/log/poll). + A child's completion notice is suppressed in the parent, so an unread exit is otherwise lost silently.""" + with self._lock: + return [s for s in self._finished.values() + if s.owner_task_id == owner_task_id and s.notify_on_complete + and s.id not in self._completion_consumed and s.id not in self._poll_observed] + + def transfer_ownership(self, session_id: str, *, from_owner: str, to_owner: str, to_task_id: str, + to_session_key: str, note: str = "") -> Optional[ProcessSession]: + """Move a RUNNING process from one owner to another under the registry lock. Ownership is the ``owner_task_id`` + field: completion notices are stamped from it at exit time and teardown kills by it, so flipping it here is the + whole transfer. Returns the session, or None when it is unknown, already exited, or not owned by ``from_owner`` + (the caller must not report a transfer that did not happen).""" + session = self.get(session_id) + with self._lock: + if session is None or session.exited or session.owner_task_id != from_owner: + return None + session.owner_task_id = to_owner + session.task_id = to_task_id + session.session_key = to_session_key + session.handoff_note = note + return session + + def has_active_for_session(self, session_key: str, max_active_age: Optional[float] = None) -> bool: + """Active processes for a gateway session key. Processes older than + ``max_active_age`` seconds are ignored as stale so a forgotten ``http.server`` + can't freeze session idle/daily reset forever; ``None`` keeps legacy behaviour + (any running process blocks).""" + now = time.time() + return self._any_running( + lambda s: s.session_key == session_key + and (max_active_age is None or (now - s.started_at) < max_active_age)) + + def has_any_active(self) -> bool: + """Whether ANY background process is running — scale-to-zero must not + suspend a gateway with live background work or the process is lost.""" + return self._any_running(lambda s: True) + + def snapshot_running_ids(self, task_id: str) -> frozenset[str]: + """Running IDs owned by ``task_id`` — a turn-boundary marker: on timeout + only processes absent from the starting snapshot belong to the abandoned + turn; older ones intentionally span turns and must survive.""" + with self._lock: + return frozenset(s.id for s in self._running.values() if s.task_id == task_id and not s.exited) + + def kill_started_since(self, task_id: str, baseline_ids, *, source: str) -> int: + """Kill ``task_id`` processes created after ``baseline_ids``. Output is + consumed so an abandoned turn can't enqueue a follow-up reviving work the + timeout deliberately stopped.""" + return self.kill_all(task_id, exclude_ids=frozenset(baseline_ids or ()), source=source, consume_output=True) + + def kill_all( + self, task_id: Optional[str] = None, *, exclude_ids: frozenset = frozenset(), + source: str = "kill_all", consume_output: bool = False) -> int: + """Kill all running processes, optionally filtered by task_id. Returns count killed.""" + with self._lock: + targets = [ + s for s in self._running.values() + if (task_id is None or s.task_id == task_id) and s.id not in exclude_ids and not s.exited + ] + return sum( + self.kill_process(s.id, source=source, consume_output=consume_output).get("status") + in {"killed", "already_exited"} + for s in targets) + + # ----- Cleanup / Pruning ----- + + def _prune_if_needed(self): + """Drop expired finished sessions, then the oldest survivor while over + MAX_PROCESSES. Must hold _lock.""" + now = time.time() + expired = [sid for sid, s in self._finished.items() if (now - s.started_at) > FINISHED_TTL_SECONDS] + over_cap = len(self._running) + len(self._finished) - len(expired) >= MAX_PROCESSES + if over_cap and (survivors := [sid for sid in self._finished if sid not in expired]): + expired.append(min(survivors, key=lambda sid: self._finished[sid].started_at)) + for sid in expired: + # Belt-and-suspenders handle release: sessions normally arrive in + # _finished via _move_to_finished(), which already released their + # Popen/PTY handles — but any session inserted into _finished + # directly (defensive paths, historical checkpoints) would + # otherwise carry its OS handles to the grave unreleased. The + # release is idempotent, so double-closing is safe. + self._release_finished_handles(self._finished[sid]) + del self._finished[sid] + # Belt-and-suspenders against module-lifetime growth: forget consumed / + # poll-observed marks for any session no longer tracked at all. + tracked = self._running.keys() | self._finished.keys() + self._completion_consumed &= tracked + self._poll_observed &= tracked + + + +process_registry = ProcessRegistry() + + +# --- the "process_manage" tool schema + handler ----------------------------------- +from tools.registry import registry, tool_error + +PROCESS_SCHEMA = { + "name": "process_manage", + # The enum names the verbs; the description keeps only non-obvious semantics + # (write-vs-submit is the one real trap: a lone \n on a Windows PTY is not Enter). + # See #95681. + "description": ( + "Poll, wait on, or kill background terminal processes (from " + "terminal(background=true)). " + "Completed results remain retrievable by session_id when resuming their owning conversation " + "(up to 7 days, newest 64 results per profile; rolling output tail). " + "poll: status + new output. log: full output, paged. wait: block " + "until exit or timeout (partial output on timeout). write vs " + "submit: submit appends Enter — use it to answer prompts; write " + "sends raw bytes, no newline. close: EOF stdin. kill: terminate. " + "handoff (subagents only): transfer a running process you started to your parent agent, which then " + "receives its completion; `data` = one sentence on its purpose. Subagent-owned processes are otherwise " + "killed when the subagent finishes and their notifications never reach the parent." + ), + "parameters": { + "type": "object", + "properties": { + "action": { + "type": "string", + "enum": ["list", "poll", "log", "wait", "kill", "write", "submit", "close", "handoff"] + }, + "session_id": { + "type": "string", + "description": "From terminal background output; any unique prefix works ('4dae' for proc_4dae56ca81f6). Required except for 'list'." + }, + "data": { + "type": "string", + "description": "Stdin text for write/submit; purpose sentence for handoff." + }, + "timeout": { + "type": "integer", + "description": "Max seconds for 'wait'.", + "minimum": 1 + }, + "offset": { + "type": "integer", + "description": "Log line offset (default: last 200)." + }, + "limit": { + "type": "integer", + "description": "Max log lines.", + "minimum": 1 + } + }, + "required": ["action"] + } +} + + +def _redact_process_result(result: dict) -> dict: + """Redact secrets from background-process output before it reaches the model, + session.db and CLI, mirroring the foreground ``terminal`` redaction so the two + surfaces can't diverge. Respects ``security.redact_secrets``; ``redact_terminal_output`` + picks ``code_file`` from the recorded command. The command itself is redacted too. + + The command string itself is also redacted in case it carried an inline credential. See #43025. + """ + if not isinstance(result, dict): + return result + from agent.redact import redact_sensitive_text, redact_terminal_output + + command = result.get("command") or "" + for key in ("output", "output_preview"): + if isinstance(value := result.get(key), str) and value: + result[key] = redact_terminal_output(value, command) + if isinstance(command, str) and command: + result["command"] = redact_sensitive_text(command, code_file=True) + return result + + +def _list_processes(task_id) -> dict: + # Also surface session-scoped background processes (e.g. a forgotten preview + # server): they share the gateway session_key and can block session reset. + session_key = "" + with suppress(Exception): + # See #29177. + from tools.approval_context import get_current_session_key + session_key = get_current_session_key(default="") or "" + return {"processes": [ + _redact_process_result(p) + for p in process_registry.list_sessions( + task_id=task_id, session_key=session_key or None, include_retained=True)]} + + +# action -> (handler(session_id, args) -> dict, redact output?). Output-bearing +# actions are redacted; stdin actions return only status. +_SESSION_ACTIONS = { + "poll": (lambda sid, a: process_registry.poll(sid), True), + "log": (lambda sid, a: process_registry.read_log(sid, offset=a.get("offset"), limit=a.get("limit", 200)), True), + "wait": (lambda sid, a: process_registry.wait(sid, timeout=a.get("timeout")), True), + "kill": (lambda sid, a: process_registry.kill_process(sid), True), + "write": (lambda sid, a: process_registry.write_stdin(sid, str(a.get("data", ""))), False), + "submit": (lambda sid, a: process_registry.submit_stdin(sid, str(a.get("data", ""))), False), + "close": (lambda sid, a: process_registry.close_stdin(sid), False), +} + + +def _handoff_process(session_id: str, args: dict, task_id: Optional[str]) -> dict: + """Subagent-only: transfer a running background process to the parent agent so its completion is delivered THERE + (child-owned process notices are suppressed and child teardown kills what it owns). Validated against the live spawn + tree: the caller must be a registered child and must own the process; anything else is an error, never a silent + no-op, so a PID mentioned in prose can't masquerade as a transfer.""" + from tools.delegate_tool_registry import _active_subagents, _active_subagents_lock + from tools.terminal_tool import _resolve_container_task_id + with _active_subagents_lock: + record = _active_subagents.get(str(task_id or "")) + child = record.get("agent") if record else None + parent_ref = getattr(child, "_delegate_parent_ref", None) + parent = parent_ref() if callable(parent_ref) else None + if parent is None: + return {"error": "handoff is only available to a running subagent with a live parent; you are not one."} + parent_owner = str(getattr(parent, "_current_task_id", "") or getattr(parent, "session_id", "") or "") + if not parent_owner: + return {"error": "parent has no process owner id yet; retry after the parent's turn has started."} + handed = getattr(child, "_handed_off_processes", None) + if handed is None: + handed = child._handed_off_processes = [] + if len(handed) >= _MAX_HANDOFFS_PER_CHILD: + return {"error": f"handoff cap reached ({_MAX_HANDOFFS_PER_CHILD} per subagent); wait on or kill the rest yourself."} + note = str(args.get("data") or "").strip() + if not note: + return {"error": "handoff requires `data`: one sentence saying what the process is for and what the parent should do with its result."} + session = process_registry.transfer_ownership( + session_id, from_owner=str(task_id or ""), to_owner=parent_owner, + to_task_id=_resolve_container_task_id(parent_owner), + to_session_key=str(getattr(parent, "session_id", "") or ""), note=note) + if session is None: + return {"error": f"cannot hand off {session_id}: not a running process you own (already exited? read its result " + "with poll/log and report it instead)."} + handed.append({"session_id": session.id, "command": session.command, "note": note}) + return {"status": "handed_off", "session_id": session.id, "command": session.command, + "note": "Your parent now owns this process and will receive its completion; you will not. Mention the handoff " + "in your final answer."} + + +_MAX_HANDOFFS_PER_CHILD = 3 + + +def _handle_process(args, **kw): + action = args.get("action", "") + # Coerce to string — some models send session_id as an integer + session_id = str(args.get("session_id", "")) if args.get("session_id") is not None else "" + if action == "list": + return json.dumps(_list_processes(kw.get("task_id")), ensure_ascii=False) + if action == "handoff": + if not session_id: + return tool_error("session_id is required for handoff") + return json.dumps(_handoff_process(session_id, args, kw.get("task_id")), ensure_ascii=False) + if action in _SESSION_ACTIONS: + if not session_id: + return tool_error(f"session_id is required for {action}") + handler, redact = _SESSION_ACTIONS[action] + result = handler(session_id, args) + return json.dumps(_redact_process_result(result) if redact else result, ensure_ascii=False) + return tool_error(f"Unknown process action: {action}. Use: list, poll, log, wait, kill, write, submit, close, handoff") + + +registry.register( + name="process_manage", + toolset="terminal", + schema=PROCESS_SCHEMA, + handler=_handle_process, + emoji="⚙️", +) + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. + +MAX_ACTIVE_PROCESS_AGE = 86400 # 24h default — see session_reset.bg_process_max_age_hours (#29177) +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/process_registry_notifications.py b/tools/process_registry_notifications.py new file mode 100644 index 0000000000000000000000000000000000000000..cf9576b7b864a6f9396b26d267398bec330b09bb --- /dev/null +++ b/tools/process_registry_notifications.py @@ -0,0 +1,411 @@ +"""Human-readable rendering of ``ProcessRegistry.completion_queue`` events (completion, +watch_match, watch_disabled, watch_overflow_*, async_delegation) into the +``[IMPORTANT: ...]`` / ``[ASYNC DELEGATION ...]`` text the CLI drain loop, gateway and +TUI inject into the agent conversation.""" + +import time +from dataclasses import dataclass +from contextlib import suppress + +_DONE = ("completed", "success") +_REASON_STATUS = {"lost": "marked lost because the process backend disappeared", "failed_start": "failed to start"} + + +@dataclass(frozen=True, slots=True) +class ProcessNotificationBatch: + """Keep completion identity until the owning surface starts its turn.""" + + notifications: tuple[tuple[dict, str], ...] + + def _live(self, registry) -> list: + return [(event, text) for event, text in self.notifications + if not registry.is_completion_consumed(event.get("session_id", ""))] + + def render(self, registry) -> str | None: + messages = [text for _event, text in self._live(registry)] + if not messages: + return None + if len(messages) == 1: + return messages[0] + header = (f"[IMPORTANT: {len(messages)} background processes completed. " + "Treat these results as one batch and give one consolidated response; " + "preserve failures and actionable results.]") + return "\n\n".join((header, *messages)) + + def display_text(self, registry) -> str: + return process_completion_display_text([event for event, _text in self._live(registry)]) + + +def group_process_notifications(notifications): + """Group consecutive completions only; watches and delegations are barriers.""" + batch = [] + for event, text in notifications: + if event.get("type", "completion") == "completion": + batch.append((event, text)) + else: + if batch: + yield tuple(batch) + batch = [] + yield ((event, text),) + if batch: + yield tuple(batch) + + + +def _format_age(seconds: float) -> str: + """Human-friendly elapsed string ('18m', '2h3m', '45s').""" + try: + s = int(max(0, seconds)) + except (TypeError, ValueError): + return "?" + if s < 60: + return f"{s}s" + m, s = divmod(s, 60) + if m < 60: + return f"{m}m" + (f"{s}s" if s else "") + h, m = divmod(m, 60) + return f"{h}h" + (f"{m}m" if m else "") + + +def _model_not_found_patterns() -> "list[str]": + """Model-not-found phrases from ``agent.error_classifier`` (the failover path's + own list, so nothing drifts); a minimal built-in set if the import fails. + + Imported from ``agent.error_classifier`` so the batch renderer applies the SAME classification the + failover path consumes — no hand-copied pattern list to drift. Fails open to a minimal built-in set so a + classifier import problem never hides the per-task blocks. See #97667. + """ + try: + from agent.error_classifier import _MODEL_NOT_FOUND_PATTERNS + return list(_MODEL_NOT_FOUND_PATTERNS) + except Exception: + return ["is not a valid model", "model not found", "model_not_found"] + + +def _delegation_config() -> dict: + """Active delegation config; ``{}`` on any error. Lazy: delegate_tool is heavy.""" + try: + from tools.delegate_tool import _load_config as _cfg + return _cfg() or {} + except Exception: + return {} + + +def _delegation_model_not_found(results, config) -> bool: + """True when a result reflects a config-level model_not_found rejection: needs a + model-not-found phrase AND the currently-configured model name in the same text, + so a stale task failing on a removed model is not mis-attributed to the config.""" + model = str((config or {}).get("model") or "").lower() + if not model: + return False + patterns = _model_not_found_patterns() + texts = (" ".join(str(x) for x in (r.get("error"), r.get("summary")) if x).lower() for r in results or []) + return any(model in text and any(p in text for p in patterns) for text in texts) + + +def _delegation_model_not_found_notice(results) -> "list[str] | None": + """Config-level model_not_found notice lines, or None (fail-open) — once per batch.""" + config = _delegation_config() + if not _delegation_model_not_found(results, config): + return None + model = config.get("model") or "?" + provider = config.get("provider") or "configured provider" + lines = [ + "⚠ SUBAGENT MODEL REJECTED: the configured Subagent Model " + f'"{model}" was rejected by provider "{provider}" ' + "(HTTP 400: not a valid model ID).", + "Every task in this batch failed for this reason before doing any work.", + "Check Settings → Advanced → Subagent Model (or: hermes config get delegation.model)."] + with suppress(Exception): + from hermes_cli.fallback_config import get_fallback_chain + if not get_fallback_chain(config): + lines.append("No fallback chain is configured, so no failover was attempted.") + return lines + + +_TRUNCATED_SUMMARY_NOTE = ( + "[TRUNCATED — subagent hit its iteration cap; the summary below " + "may be incomplete. Verify before relying on it, or re-dispatch " + "the unfinished part.]") + + +def _is_truncated(entry: dict) -> bool: + return bool(entry.get("truncated") or entry.get("exit_reason") == "max_iterations") + + +def _notice_lines(results) -> "list[str]": + """Blank + model_not_found notice block, or [] when the notice does not apply.""" + notice = _delegation_model_not_found_notice(results) + return ["", *notice] if notice else [] + + +def _preamble(evt: dict, title: str, intro: str, completed_at: float, *, with_goal: bool) -> "list[str]": + """Shared preamble: title, intro, blank, dispatch time, [goal], context/toolsets, role+model.""" + lines = [title, intro, ""] + dispatched_at = evt.get("dispatched_at") + if isinstance(dispatched_at, (int, float)): + ts = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(dispatched_at)) + lines.append(f"Dispatched: {ts} ({_format_age(completed_at - dispatched_at)} ago)") + if with_goal: + lines.append(f"Original goal: {evt.get('goal', '') or ''}") + if evt.get("context"): + lines.append(f"Context you provided: {evt['context']}") + if evt.get("toolsets"): + lines.append(f"Toolsets: {', '.join(evt['toolsets'])}") + lines.append(f"Role: {evt.get('role') or 'leaf'} Model: {evt.get('model') or '?'}") + return lines + + +def _format_task_failure_notice(evt: dict, deleg_id: str) -> str: + """One child of a still-running fan-out failed: say which, why, and that the batch goes on.""" + (r,) = (evt.get("results") or [{}])[:1] or [{}] + goals, idx, n = evt.get("goals") or [], r.get("task_index", 0), evt.get("n_tasks") or len(evt.get("goals") or []) + goal = goals[idx] if idx < len(goals) else r.get("goal", "") + err = str(r.get("error") or "").strip().replace("\n", " ")[:400] + lines = [ + f"[ASYNC DELEGATION TASK FAILED — {deleg_id}, task {idx + 1}/{n}]", + "One subagent in a background fan-out you dispatched has failed while its siblings are still running. " + "The batch's consolidated results will still arrive when the last sibling finishes; this is an early " + "warning so you can re-dispatch or investigate now instead of then.", + f"Task: {goal}" if goal else "", + f"Status: {r.get('status', '?')} Duration: {r.get('duration_seconds', '?')}s" + (f"\nError: {err}" if err else ""), + ] + if r.get("live_transcript"): + lines.append(f"Live transcript: {r['live_transcript']}") + return "\n".join(line for line in lines if line) + + +def _format_batch_delegation(evt: dict, deleg_id: str, completed_at: float) -> str: + """Consolidated block for a delegate_task fan-out that finished as one unit.""" + results, goals = evt.get("results") or [], evt.get("goals") or [] + # ``goals`` is the whole delegate_task call (task_index indexes it); ``results`` is this unit's subset. + n, n_unit = len(goals) or len(results), len(results) or len(goals) + group = evt.get("group") + unit = f"group '{group}' ({n_unit} subagent(s))" if group is not None else f"{n_unit} subagent(s)" + lines = _preamble( + evt, + f"[ASYNC DELEGATION BATCH COMPLETE — {deleg_id}]", + f"A background fan-out unit you dispatched earlier — {unit} — has finished; its consolidated results are " + "below. Any other units from the same delegate_task call report separately as they finish. You may have " + "moved on since dispatching — act on these or re-dispatch if things have changed. If you are still waiting " + "on siblings, end your turn after acting on this one.", + completed_at, with_goal=False) + lines[-1] += f" Total duration: {evt.get('total_duration_seconds', evt.get('duration_seconds', '?'))}s" + if evt.get("error") and not results: + lines += ["--- ERROR ---", f"The batch did not complete successfully: {evt['error']}"] + return "\n".join(lines) + # Config-level rejection notice BEFORE the per-task wall — a rejected + # delegation model fails every task identically and must not stay buried. + lines += _notice_lines(results) + for r in sorted(results, key=lambda x: x.get("task_index", 0)): + idx, r_truncated = r.get("task_index", 0), _is_truncated(r) + r_status, r_summary, r_error = r.get("status", "?"), r.get("summary"), r.get("error") + r_goal = goals[idx] if idx < len(goals) else r.get("goal", "") + icon = "⚠" if r_truncated else ("✓" if r_status in _DONE else "✗") + header = (f"--- {icon} TASK {idx + 1}/{n}" + (f": {r_goal}" if r_goal else "") + f" (status={r_status}" + + (f", api_calls={r['api_calls']}" if r.get("api_calls") else "") + + (f", {r['duration_seconds']}s" if r.get("duration_seconds") is not None else "") + + (", TRUNCATED: hit max_iterations — work may be incomplete" if r_truncated else "")) + lines += ["", header + ") ---"] + if r_status in _DONE and r_summary: + if r_truncated: + lines.append(_TRUNCATED_SUMMARY_NOTE) + lines.append(r_summary) + elif r_summary: + if r_error: + lines.append(f"({r_status}: {r_error})") + lines += ["Partial output:", r_summary] + else: + lines.append(f"(no summary — status={r_status}" + (f": {r_error}" if r_error else "") + ")") + if r.get("live_transcript"): + lines.append(f"Full live transcript (complete tool/assistant trace): {r['live_transcript']}") + lines += _process_accounting_lines(r) + return "\n".join(lines) + + +def _process_accounting_lines(r: dict) -> list: + """Runtime-truth lines about a child's background processes: what it handed to you (you own it now, its + completion lands here) and what it left running (terminated at teardown — never trust a child's "watcher running").""" + lines = [] + for h in r.get("handed_off_processes") or []: + lines.append(f"Handed off to you: {h.get('session_id')} ({h.get('command', '')[:120]}) — {h.get('note', '')}. " + "You own it now; its completion notice will arrive here.") + orphans = r.get("orphaned_processes") or [] + if orphans: + lines.append(f"Child left {len(orphans)} background process(es) running that were TERMINATED with it " + "(subagent process notices never reach you): " + + "; ".join(f"{o.get('session_id')} `{o.get('command', '')[:100]}` ({o.get('runtime_seconds')}s)" for o in orphans) + + ". Re-launch in this session anything you still need.") + for u in r.get("unread_completions") or []: + lines.append(f"Child's process {u.get('session_id')} `{u.get('command', '')[:100]}` finished (exit code " + f"{u.get('exit_code')}) but the child never read its result; output tail:\n{u.get('output_tail', '')}") + return lines + + +def _format_async_delegation(evt: dict) -> str: + """Self-contained re-injection for an async-delegation completion: the FULL + original task source (goal, context, toolsets, role, model), dispatch time, status + and result, so an agent deep in unrelated context can act on it or re-dispatch.""" + deleg_id = evt.get("delegation_id", "unknown") + completed_at = evt.get("completed_at") or time.time() + if evt.get("task_failure_notice"): + return _format_task_failure_notice(evt, deleg_id) + if evt.get("is_batch") or isinstance(evt.get("results"), list): + return _format_batch_delegation(evt, deleg_id, completed_at) + status, summary, error = evt.get("status") or "completed", evt.get("summary"), evt.get("error") + truncated = _is_truncated(evt) + lines = _preamble( + evt, + f"[ASYNC DELEGATION COMPLETE — {deleg_id}]", + "A background subagent you dispatched earlier has finished. You may " + "have moved on since dispatching it; the full task source is below so " + "you can act on the result or re-dispatch if things have changed.", + completed_at, with_goal=True) + lines += _notice_lines([evt]) + [ + f"Status: {status} API calls: {evt.get('api_calls', 0)} Duration: {evt.get('duration_seconds', '?')}s" + + (" [TRUNCATED: hit max_iterations — work may be incomplete]" if truncated else ""), + "--- RESULT ---"] + if status in _DONE and summary: + if truncated: + lines.append(_TRUNCATED_SUMMARY_NOTE) + lines.append(summary) + else: + if status == "interrupted": + lines.append("The subagent was interrupted before completing" + (f": {error}" if error else ".")) + else: # error / timeout / failed + lines.append( + f"The subagent did not complete successfully (status={status})." + (f"\n{error}" if error else "")) + if summary: + lines += ["Partial output:", summary] + return "\n".join(lines) + + +def async_delegation_display_text(evt: dict) -> str: + """Compact UI title; the separate model notification retains all task evidence.""" + raw_results = evt.get("results") + results = [r for r in raw_results if isinstance(r, dict)] if isinstance(raw_results, list) else [] + results = results or [evt] + goals = evt.get("goals") or [] + labels, titles = [], [] + status_labels = {"failed": "Failed", "error": "Failed", "cancelled": "Cancelled", + "interrupted": "Interrupted", "timeout": "Timed Out", "stalled": "Stalled", + "unknown": "Unknown", "rejected": "Failed"} + for result in results: + status = result.get("status") or ("failed" if result.get("error") else "completed") + label = ("Incomplete" if _is_truncated(result) else "Completed") if status in _DONE else ( + status_labels.get(status, "Incomplete")) + labels.append(label) + index = result.get("task_index", 0) + goal = goals[index] if 0 <= index < len(goals) else result.get("goal", "") + titles.append(" ".join(str(goal or "Background task").split())) + if len(results) == 1: + return f"Subagent Task {labels[0]}: {titles[0]}" + outcome = labels[0] if len(set(labels)) == 1 else "Finished with Issues" + title = " ".join(str(evt.get("group") or "").split()) or "; ".join(titles) + return f"Subagent Tasks {outcome}: {title} ({len(results)} tasks)" + + +PROCESS_COMPLETE_DISPLAY_KIND = "process_complete" + + +def _short_command(command) -> str: + cmd = " ".join(str(command or "").split()) + return cmd[:77] + "..." if len(cmd) > 80 else cmd + + +def process_completion_display_text(events: list) -> str: + """Compact UI title for one or more process completions; the model text keeps the full output.""" + if len(events) != 1: + return f"{len(events)} Background Processes Finished" + evt = events[0] + reason, exit_code = evt.get("completion_reason") or "exited", evt.get("exit_code", "?") + if reason == "killed": + outcome = "Terminated" + elif reason in _REASON_STATUS: + outcome = "Lost" if reason == "lost" else "Failed to Start" + else: + outcome = "Finished" if exit_code == 0 else "Failed" + cmd = _short_command(evt.get("command")) + detail = f" (exit {exit_code})" if reason not in ("killed", *_REASON_STATUS) and exit_code != 0 else "" + return f"Background Process {outcome}{detail}: {cmd}" if cmd else f"Background Process {outcome}{detail}" + + +class TimelineNotification(str): + """Queued model text that stays string-compatible, plus the display kind and compact human + title the surface paints instead of the raw notification wall.""" + + display_text: str + display_kind: str + + def __new__(cls, text: str, display_text: str, display_kind: str): + instance = super().__new__(cls, text) + instance.display_text = display_text + instance.display_kind = display_kind + return instance + + @classmethod + def for_delegation(cls, text: str, event: dict) -> "TimelineNotification": + return cls(text, async_delegation_display_text(event), "async_delegation_complete") + + +def _delegation_attribution_line(evt: dict) -> "str | None": + """One-line provenance for a subagent-owned process event, else None. Such a process + outlives the child and lands in the PARENT conversation, which would otherwise see an + anonymous output wall. Keyed on ``owner_task_id`` — ``task_id`` may be the session key.""" + task_id = str(evt.get("owner_task_id") or evt.get("task_id") or "") + if not task_id.startswith("sa-"): + return None + info = None + with suppress(Exception): + from tools.delegate_tool import get_subagent_attribution + info = get_subagent_attribution(task_id) + if not info: + # Registry entry aged out — still attribute generically, not anonymously. + return f"Started by subagent {task_id} (delegate_task)." + goal, deleg = str(info.get("goal") or "").strip(), info.get("delegation_id") + goal = goal[:117] + "..." if len(goal) > 120 else goal + return (f"Started by subagent {task_id}" + (f" of delegation {deleg}" if deleg else "") + "." + + (f' Task: "{goal}"' if goal else "")) + + +def _completion_status(evt: dict) -> str: + reason = evt.get("completion_reason") or "exited" + if reason == "killed": + return f"terminated by {evt.get('termination_source') or 'Hermes'}" + return _REASON_STATUS.get(reason) or ("completed normally" if evt.get("exit_code", "?") == 0 else "exited") + + +def format_process_notification(evt: dict) -> "str | None": + """Format a completion_queue event into an ``[IMPORTANT: ...]`` message.""" + evt_type = evt.get("type", "completion") + # watch_disabled and overflow events carry their own human-readable `message`; + # otherwise overflow events would fall through to the completion formatter as a + # phantom "process exited (exit code ?)". + if evt_type in ("watch_disabled", "watch_overflow_tripped", "watch_overflow_released"): + return f"[IMPORTANT: {evt.get('message', '')}]" + if evt_type == "async_delegation": + return _format_async_delegation(evt) + _sid, _cmd = evt.get("session_id", "unknown"), evt.get("command", "unknown") + _attribution = _delegation_attribution_line(evt) + if evt.get("handoff_note"): + _attribution = f"Handed off to you by a subagent before it finished. Purpose: {evt['handoff_note']}" + attribution = f"{_attribution}\n" if _attribution else "" + if evt_type == "watch_match": + _sup = evt.get("suppressed", 0) + return ( + f"[IMPORTANT: Background process {_sid} matched watch pattern \"{evt.get('pattern', '?')}\".\n" + f"{attribution}Command: {_cmd}\nMatched output:\n{evt.get('output', '')}" + + (f"\n({_sup} earlier matches were suppressed by rate limit)" if _sup else "") + "]") + _exit = evt.get("exit_code", "?") + _out = evt.get("output", "") + _signal = ", SIGTERM" if _exit in {-15, 143, "-15", "143"} else "" + # A subagent-owned process's full output belongs in the child's transcript, not as + # a raw wall in the parent — trim hard but keep enough tail to recognise failures. + if _attribution and isinstance(_out, str) and len(_out) > 600: + _out = ( + "...(output trimmed — subagent-owned process; see the " + "delegation's live transcript for full output)\n" + + _out[-600:]) + return ( + f"[IMPORTANT: Background process {_sid} {_completion_status(evt)} (exit code {_exit}{_signal}).\n" + f"{attribution}Command: {_cmd}\nOutput:\n{_out}]") diff --git a/tools/pty_query_responder.py b/tools/pty_query_responder.py new file mode 100644 index 0000000000000000000000000000000000000000..28cccc4ec69407da0fe993d048f43fa31f39aa5a --- /dev/null +++ b/tools/pty_query_responder.py @@ -0,0 +1,118 @@ +"""Answer a bounded set of blocking terminal queries from PTY subprocesses. + +Programs running inside a background PTY session (``terminal(background=true, +pty=true)``) sometimes probe their "terminal" with ANSI queries — device +status reports (``ESC[5n``), window-size queries (``ESC[18t``), cursor +position reports (``ESC[6n``), or DEC private-mode queries +(``ESC[?$p``). A real terminal emulator answers these on stdin; Hermes' +PTY has no emulator on the master side, so the subprocess either blocks +forever waiting for a reply or the raw query bytes leak into the captured +output as garbage. + +This module ports openai/codex#41436 (``terminal_queries.rs``): a tiny +byte-level state machine that scans PTY output for the handled queries, +strips them from the output stream (queries split across read chunks +included), and produces the bounded responses to write back to the +subprocess. Everything else — colors, other escape sequences, partial +UTF-8 — passes through untouched. + +Only the POSIX ``ptyprocess`` path uses this. On Windows, ConPTY is a real +console host that answers queries itself. +""" + +from __future__ import annotations + +_ESC = 0x1B + +# DEC private-mode queries carry a numeric mode of bounded length; anything +# longer is not a query we answer (and is passed through untouched). +_MAX_MODE_DIGITS = 10 +# Longest handled sequence: ESC [ ? $ p +_MAX_QUERY_BYTES = _MAX_MODE_DIGITS + 5 + + +class PtyQueryResponder: + """Incremental scanner for terminal queries in a PTY output stream. + + Feed raw output chunks through :meth:`process`; it returns the chunk with + any handled queries removed, plus the response bytes to write to the + subprocess's stdin. Call :meth:`flush` at end-of-stream to recover any + trailing partial escape sequence that never completed. + """ + + def __init__(self, rows: int = 24, cols: int = 80): + # Exact-match queries and their responses. Window size reports the + # PTY's actual spawn dimensions; cursor position reports home (1;1) — + # we don't emulate a screen, a bounded answer just unblocks the + # subprocess (same policy as openai/codex#41436). + self._query_responses: tuple[tuple[bytes, bytes], ...] = ( + # Device status report: terminal operating normally. + (b"\x1b[5n", b"\x1b[0n"), + # Window-size query: report the PTY's row/col text area. + (b"\x1b[18t", b"\x1b[8;%d;%dt" % (rows, cols)), + # Cursor-position report: row 1, column 1. + (b"\x1b[6n", b"\x1b[1;1R"), + ) + self._pending = bytearray() + + def process(self, data: bytes) -> tuple[bytes, bytes]: + """Scan ``data``; return ``(output_bytes, response_bytes)``.""" + if not self._pending and _ESC not in data: + return data, b"" + + output = bytearray() + responses = bytearray() + pending = self._pending + + for byte in data: + if not pending and byte != _ESC: + output.append(byte) + continue + + if byte == _ESC: + # A fresh ESC aborts any partial sequence — flush it through. + output += pending + pending.clear() + pending.append(byte) + + if ( + len(pending) == 1 + or bytes(pending) == b"\x1b[" + or ( + pending[1] == ord("[") + and not (0x40 <= byte <= 0x7E) + and len(pending) < _MAX_QUERY_BYTES + ) + ): + # Still accumulating a possible query. + continue + + seq = bytes(pending) + matched = False + for query, response in self._query_responses: + if seq == query: + responses += response + matched = True + break + if not matched: + mode = seq[3:-2] + if ( + seq.startswith(b"\x1b[?") + and seq.endswith(b"$p") + and 0 < len(mode) <= _MAX_MODE_DIGITS + and mode.isdigit() + ): + # DEC private-mode query: report mode as unrecognized. + responses += b"\x1b[?" + mode + b";0$y" + else: + # Not a handled query — pass the sequence through. + output += pending + pending.clear() + + return bytes(output), bytes(responses) + + def flush(self) -> bytes: + """Return any incomplete trailing sequence held back by the scanner.""" + tail = bytes(self._pending) + self._pending.clear() + return tail diff --git a/tools/read_window_tool.py b/tools/read_window_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..267ff6ad6f8fe03c00704e15dfe8a0086469319f --- /dev/null +++ b/tools/read_window_tool.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""Read which OS window sits directly underneath the Hermes desktop window. + +The window list lives with the OS, so this round-trips through the gateway's +blocking-prompt bridge like `read_terminal`: ``window.read.request`` -> the renderer's +main process (native window enumeration) -> ``window.read.respond``. +""" + +from typing import Callable, Optional + +from tools.read_terminal_tool import read_pane +from tools.registry import registry + + +def read_window_below_tool(callback: Optional[Callable] = None) -> str: + """Return the window underneath the Hermes window as a JSON string.""" + return read_pane(callback, (), ( + "read_window_below is only available in the Hermes desktop app.", + "", + "Failed to read the window below: ", + "Could not determine the window underneath (the desktop app did " + "not answer, or window enumeration is unavailable on this system).", + )) + + +READ_WINDOW_BELOW_SCHEMA = { + "name": "read_window_below", + "description": ( + "Identify the app window directly behind the Hermes desktop window " + "(what the user is working in). JSON: {window: {app, title, bounds, " + "id}, frontmost, platform}. title may be empty when the OS withholds " + "it (noted in `note`); where windows cannot be enumerated at all, " + "{error, platform} says what would fix it — relay that instead of " + "retrying. Metadata only; never captures pixels." + ), + "parameters": { + "type": "object", "properties": {} + }, +} + + +registry.register( + name="read_window_below", + toolset="desktop_ui", + schema=READ_WINDOW_BELOW_SCHEMA, + handler=lambda args, **kw: read_window_below_tool(callback=kw.get("callback")), + emoji="🪟", +) + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. +import json # noqa: F401,E402 + + +_PLUGIN_COMPAT_LAZY = { + 'tool_error': ('tools.registry', 'tool_error'), +} + + +def __getattr__(name): # PEP 562 — lazy so no import cycles + target = _PLUGIN_COMPAT_LAZY.get(name) + if target is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + import importlib + from hermes_cli.plugin_compat import warn_once + warn_once(__name__, name, *target) + return getattr(importlib.import_module(target[0]), target[1]) +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/registry.py b/tools/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..26257fccc25aaf04707b8f6d46ac83fd1e8704ab --- /dev/null +++ b/tools/registry.py @@ -0,0 +1,975 @@ +"""Central registry for all hermes-agent tools: each tool file calls ``registry.register()`` +at import to declare schema, handler, toolset membership and availability check; +``model_tools.py`` queries the registry instead of keeping parallel data structures. +Cycle-safe import chain: this module imports nothing from model_tools or tool files; +tools/*.py import it at module level; model_tools.py imports both; run_agent/cli import +model_tools.""" + +import ast +import functools +import importlib +import json +import logging +import sys +import threading +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Callable, Dict, List, Optional, Set + +from hermes_constants import hermes_home_key + +logger = logging.getLogger(__name__) + +# Cap on a tool error body; only trims runaway interpolated exceptions (static msgs are ~115 chars). +_MAX_TOOL_ERROR_CHARS = 2048 +_TOOL_ERROR_TRUNCATION_MARKER = "… [truncated]" +# Logs keep more of the body than the model sees, but still a bounded amount. +_MAX_LOGGED_ERROR_CHARS = 8192 + + +def _bound_error_text(text: str) -> str: + """Bound an error body destined for model context; logs keep a longer prefix.""" + if len(text) <= _MAX_TOOL_ERROR_CHARS: + return text + logger.debug( + "tool error body truncated for context (%d chars): %s", + len(text), text[:_MAX_LOGGED_ERROR_CHARS]) + return text[:_MAX_TOOL_ERROR_CHARS] + _TOOL_ERROR_TRUNCATION_MARKER + + +def _bound_json_error_result(result: str) -> str: + """Trim an oversized ``error`` field in a JSON string result: handlers that + ``json.dumps({"error": str(exc)})`` directly bypass ``tool_error``'s cap, so this runs + at the dispatch boundary to stop unbounded errors stacking across retries.""" + if len(result) <= _MAX_TOOL_ERROR_CHARS or '"error"' not in result: + return result + try: + payload = json.loads(result) + except ValueError: + return result + error = payload.get("error") if isinstance(payload, dict) else None + if not isinstance(error, str) or len(error) <= _MAX_TOOL_ERROR_CHARS: + return result + payload["error"] = _bound_error_text(error) + return json.dumps(payload, ensure_ascii=False) + + +def _is_registry_register_call(node: ast.AST) -> bool: + """True when *node* is a ``registry.register(...)`` call expression.""" + if not isinstance(node, ast.Expr) or not isinstance(node.value, ast.Call): + return False + func = node.value.func + return ( + isinstance(func, ast.Attribute) and func.attr == "register" + and isinstance(func.value, ast.Name) and func.value.id == "registry") + + +def _module_registers_tools(module_path: Path) -> bool: + """True when the module body (or a module-level ``for``) calls ``registry.register(...)``. + Only module-body statements count, so helpers registering inside a function are skipped; + a text prefilter avoids ``ast.parse`` for files lacking both words.""" + try: + source = module_path.read_text(encoding="utf-8") + if "registry" not in source or "register" not in source: + return False + tree = ast.parse(source, filename=str(module_path)) + except (OSError, SyntaxError): + return False + # Table-driven modules register several tools from one loop, still at import time. + return any( + _is_registry_register_call(stmt) + or (isinstance(stmt, ast.For) and any(_is_registry_register_call(s) for s in stmt.body)) + for stmt in tree.body) + + +def _tool_module_candidates(tools_path: Path) -> List[Path]: + """Flat ``tools/*.py`` modules plus the package entry point ``tools//tool.py``, in one + sorted list. Only ``tool.py`` is scanned in a package, so every other file in it is a library + by construction. Sorted after merging: ``register()`` lets a same-name, same-toolset duplicate + overwrite silently, so the import order must not depend on file depth.""" + candidates = list(tools_path.glob("*.py")) + list(tools_path.glob("*/tool.py")) + return sorted(candidates) + + +def discover_builtin_tools(tools_dir: Optional[Path] = None) -> List[str]: + """Import built-in self-registering tool modules and return their module names. The + per-file AST scan costs ~145 ms over ~100 files, so verdicts are memoized on disk keyed + by ``(mtime_ns, size)``; a mismatch or corrupt cache re-scans that file. The write is + best-effort and atomic, so concurrent processes race harmlessly.""" + tools_path = (Path(tools_dir) if tools_dir is not None else Path(__file__).resolve().parent).resolve() + cache = _load_discovery_cache() + fresh_cache: Dict[str, list] = {} + cache_dirty = False + module_names: List[str] = [] + for path in _tool_module_candidates(tools_path): + if path.name in {"__init__.py", "registry.py", "mcp_tool.py"}: + continue + rel_parts = path.relative_to(tools_path).with_suffix("").parts + if len(rel_parts) > 1 and not (path.parent / "__init__.py").exists(): + # setuptools' package finder drops a directory without __init__.py, so this tool would + # register from a checkout and vanish from an installed wheel. + logger.warning("Skipping %s: package %s has no __init__.py", path, path.parent.name) + continue + abs_path = str(path.resolve()) + try: + st = path.stat() + stat_key = (st.st_mtime_ns, st.st_size) + except OSError: + continue + cached = cache.get(abs_path) + if isinstance(cached, (list, tuple)) and len(cached) == 3 and tuple(cached[:2]) == stat_key: + registers = bool(cached[2]) + else: + registers = _module_registers_tools(path) + cache_dirty = True + fresh_cache[abs_path] = [stat_key[0], stat_key[1], registers] + if registers: + module_names.append(".".join(("tools", *rel_parts))) + + # Drop entries for files that no longer exist; rewrite only when changed. + if cache_dirty or set(fresh_cache) != set(cache): + _save_discovery_cache(fresh_cache) + imported: List[str] = [] + for mod_name in module_names: + try: + importlib.import_module(mod_name) + imported.append(mod_name) + except Exception as e: + logger.warning("Could not import tool module %s: %s", mod_name, e) + return imported + + +def _discovery_cache_path() -> Optional[Path]: + """Path of the tool-discovery verdict cache, or None if unresolvable.""" + try: + # Deferred import keeps tools/registry.py a no-deps leaf at import time. + from hermes_constants import get_hermes_home + return Path(get_hermes_home()) / "cache" / "tool_discovery_cache.json" + except Exception: + return None + + +def _load_discovery_cache() -> Dict[str, list]: + """Read the discovery cache; any error → empty dict (full scan).""" + path = _discovery_cache_path() + if path is None: + return {} + try: + with open(path, "r", encoding="utf-8") as fh: + data = json.load(fh) + return data if isinstance(data, dict) else {} + except (OSError, ValueError): + return {} + + +def _save_discovery_cache(cache: Dict[str, list]) -> None: + """Best-effort atomic write of the discovery cache. Never raises.""" + path = _discovery_cache_path() + if path is None: + return + try: + from utils import atomic_json_write # stdlib+yaml only; no cycle + path.parent.mkdir(parents=True, exist_ok=True) + atomic_json_write(path, cache, indent=0) + except Exception as e: + logger.debug("Could not write tool discovery cache %s: %s", path, e) + + +@dataclass(eq=False, slots=True) +class ToolEntry: + """Metadata for one registered tool (identity semantics: restore/CAS paths compare ``is``).""" + + name: str + toolset: str + schema: dict + handler: Callable + check_fn: Optional[Callable] + requires_env: list + is_async: bool + description: str + emoji: str + max_result_size_chars: int | float | None = None + # Zero-arg callable whose dict is shallow-merged onto the schema at every get_definitions() + # — for fields tracking runtime config (delegate_task's description reflects limits). + dynamic_schema_overrides: Optional[Callable] = None + + +class _PluginOverridePolicy: + """Identity-bearing authorization record for one plugin generation.""" + + __slots__ = ("allowed",) + + def __init__(self, allowed: bool) -> None: + self.allowed = bool(allowed) + + +_OVERRIDE_DENIED_MSG = ( + "Plugin module {owner!r} cannot override built-in tool {name!r} " + "without operator opt-in (allow_tool_override).") + + +# ---- check_fn TTL cache ---------------------------------------------------- +# check_fns probe external state (Docker, Modal SDK, playwright) that changes on human +# timescales, so results are cached ~30 s: env-var flips via ``hermes tools`` still land +# within a turn or two. Transient-failure suppression: a flapping probe (``docker version`` +# timing out under load) would silently strip a whole toolset from the agent being built — +# most visibly a subagent reporting "Tool read_file does not exist" — so a failure within a +# short grace window of the last success serves the last-good True WITHOUT caching it; a +# failure persisting past the window is honored so a dead backend stops advertising tools. + +_CHECK_FN_TTL_SECONDS = 30.0 +# Grace window after a success in which a failure counts as a flake; kept short +# so a genuinely-down backend is reflected within a couple of turns. +_CHECK_FN_FAILURE_GRACE_SECONDS = 60.0 +_CHECK_FN_CACHE_MAX = 512 +_check_fn_cache: Dict[tuple[Callable, Optional[str]], tuple[float, bool]] = {} +_check_fn_last_good: Dict[tuple[Callable, Optional[str]], float] = {} +_check_fn_cache_lock = threading.Lock() +CHECK_FN_CACHE_BYPASS = "" +_NO_CACHE_CHECK_FNS: Set[Callable] = set() +_BROWSER_IDENTITY_KEYS = ( + "HERMES_SESSION_ID", + "HERMES_BROWSER_CONTROL_PRINCIPAL", + "HERMES_BROWSER_CONTROL_TRANSPORT_FAMILY") + + +def no_cache_check_fn(fn: Callable) -> Callable: + """Mark a local, config-backed availability check as uncached.""" + _NO_CACHE_CHECK_FNS.add(fn) + return fn + + +def _fn_label(fn: Callable) -> object: + return getattr(fn, "__qualname__", fn) + + +def _prune_check_fn_caches(now: float) -> None: + """Expire stale entries and cap profile-dimensional cache growth. Caller holds the lock.""" + for cache, ttl, stamp in ( + (_check_fn_cache, _CHECK_FN_TTL_SECONDS, lambda v: v[0]), + (_check_fn_last_good, _CHECK_FN_FAILURE_GRACE_SECONDS, lambda v: v)): + for key, value in list(cache.items()): + if now - stamp(value) >= ttl: + cache.pop(key, None) + while len(cache) >= _CHECK_FN_CACHE_MAX: + cache.pop(next(iter(cache))) + + +def check_fn_cache_scope() -> Optional[str]: + """Return the active profile key when availability is profile-scoped. Browser-controller + availability is request-bound (changes on every attach/detach), so a fully bound + browser-control request bypasses this cache AND model_tools' outer definition cache (same + sentinel) — one Browser session's live tools must not leak into another. Single-profile + processes keep the process-wide cache; a multiplex gateway installs a Hermes-home override + per profile turn, so the canonical profile key is the boundary.""" + try: + from gateway.session_context import get_session_env + if all(str(get_session_env(k, "") or "").strip() for k in _BROWSER_IDENTITY_KEYS): + return CHECK_FN_CACHE_BYPASS + except Exception: + pass + try: + from agent.secret_scope import is_multiplex_active + from hermes_constants import get_hermes_home_override + if not is_multiplex_active(): + return None + override = get_hermes_home_override() + return str(Path(override).expanduser().resolve()) if override else CHECK_FN_CACHE_BYPASS + except Exception: + # Fail closed: bypass both cache layers rather than aliasing requests + # whose multiplex profile identity could not be resolved. + return CHECK_FN_CACHE_BYPASS + + +def _run_check_fn_uncached(fn: Callable) -> bool: + """Run an availability check without cache/grace handling.""" + from agent.secret_scope import UnscopedSecretError, current_secret_scope + try: + return bool(fn()) + except UnscopedSecretError: + # The verdict comes from the LIVE scope at the catch site, not from which registry branch + # ran the probe: ``no_cache_check_fn`` probes skip the cache-scope lookup entirely, so a + # branch-derived hint misreported every boot-time uncached probe as a lost scope (#110635). + if current_secret_scope() is None: + # Expected fail-closed probe: with multiplexing on, boot-time check_fns run before any + # profile secret scope exists, so get_secret raises by design. No traceback, so this + # cannot be mistaken for a crashed check_fn (#100697). + logger.debug( + "check_fn %s hit the multiplex fail-closed path with no " + "profile secret scope active; dependent tools re-probe on the first scoped turn", + _fn_label(fn)) + else: + # The caller IS scoped but the read still failed closed: the probe dropped the scope on + # the way to get_secret (a bare thread/executor hop) — a spawn-site bug, kept loud. + logger.warning( + "check_fn %s raised UnscopedSecretError while the profile cache " + "scope was resolved; dependent tools will be unavailable this turn", + _fn_label(fn), exc_info=True) + except Exception: + logger.warning( + "check_fn %s raised; dependent tools will be unavailable this turn", + _fn_label(fn), exc_info=True) + return False + + +def _check_fn_cached(fn: Callable) -> bool: + """Return bool(fn()), TTL-cached across calls.""" + now = time.monotonic() + if fn in _NO_CACHE_CHECK_FNS: + return _run_check_fn_uncached(fn) + scope = check_fn_cache_scope() + if scope == CHECK_FN_CACHE_BYPASS: + return _run_check_fn_uncached(fn) + cache_key = (fn, scope) + with _check_fn_cache_lock: + _prune_check_fn_caches(now) # leaves only entries within TTL + cached = _check_fn_cache.get(cache_key) + if cached is not None: + return cached[1] + exc_info = None + try: + value, outcome = bool(fn()), "returned False" + except Exception as exc: + # Keep the exception for the verdict log below (emitted outside this block, where + # ``exc_info=True`` would resolve to nothing): a check_fn that raises is a bug in the probe + # or its resolver, and a bare "raised" verdict reads as "nothing configured" (#87950). + value, outcome, exc_info = False, "raised", exc + with _check_fn_cache_lock: + _prune_check_fn_caches(now) + if value: + _check_fn_last_good[cache_key] = now + _check_fn_cache[cache_key] = (now, True) + return True + last_good = _check_fn_last_good.get(cache_key) + if last_good is not None and now - last_good < _CHECK_FN_FAILURE_GRACE_SECONDS: + # Recent success → flake: serve last-good True, do NOT cache (next call re-probes). + logger.warning( + "check_fn %s failed (%s) within %.0fs of last success; " + "treating as transient and keeping tool(s) available", + _fn_label(fn), outcome, _CHECK_FN_FAILURE_GRACE_SECONDS) + return True + + # No recent success (or grace expired) — honor the failure; logged so silent tool + # loss in quiet mode (subagents) is diagnosable. + logger.warning( + "check_fn %s %s; dependent tools will be unavailable this turn", _fn_label(fn), outcome, + exc_info=exc_info) + _check_fn_cache[cache_key] = (now, False) + return False + + +def _memo_check(fn: Callable, memo: Dict[Callable, bool]) -> bool: + """Per-pass memo on top of the TTL cache: one probe per distinct check_fn.""" + if fn not in memo: + memo[fn] = _check_fn_cached(fn) + return memo[fn] + + +def invalidate_check_fn_cache() -> None: + """Drop all cached ``check_fn`` results (after config changes like ``hermes tools enable``).""" + with _check_fn_cache_lock: + _check_fn_cache.clear() + _check_fn_last_good.clear() + + +def get_cached_check_fn_result(fn: Callable) -> Optional[bool]: + """Cached verdict for *fn* if its TTL is still valid, else None. NEVER runs the probe: + for read-only surfaces (dashboard panels) that must not do network/auth/SDK work.""" + now = time.monotonic() + scope = check_fn_cache_scope() + if scope == CHECK_FN_CACHE_BYPASS: + # Unresolved profile identity bypasses the cache; nothing trustworthy to report. + return None + with _check_fn_cache_lock: + cached = _check_fn_cache.get((fn, scope)) + return cached[1] if cached is not None and now - cached[0] < _CHECK_FN_TTL_SECONDS else None + + +class ToolRegistry: + """Singleton registry that collects tool schemas + handlers from tool files.""" + + def __init__(self): + self._tools: Dict[str, ToolEntry] = {} # built-in / process-global registrations + # Plugin overlays keyed by resolved HERMES_HOME; a profile sees its overlay first. + self._scoped_tools: Dict[str, Dict[str, ToolEntry]] = {} + # Plugin namespace -> operator opt-in for built-in override (lifecycle-managed); + # scope attribution stays durable after policy removal so delayed callbacks + # remain confined to the profile that loaded them. + self._plugin_override_policy: Dict[tuple[Optional[str], str], _PluginOverridePolicy] = {} + self._plugin_module_scopes: Dict[str, Set[Optional[str]]] = {} + self._toolset_checks: Dict[str, Callable] = {} + self._toolset_aliases: Dict[str, str] = {} + # MCP refresh mutates while other threads read: serialize writes, snapshot reads. + self._lock = threading.RLock() + # Bumped on every mutation; get_tool_definitions memoizes against it. + self._generation: int = 0 + + @staticmethod + def current_scope_key() -> str: + return hermes_home_key() + + @staticmethod + def _grouped(entries: List[ToolEntry]) -> Dict[str, List[ToolEntry]]: + """``{toolset: entries}`` in first-appearance order.""" + groups: Dict[str, List[ToolEntry]] = {} + for entry in entries: + groups.setdefault(entry.toolset, []).append(entry) + return groups + + def _slot(self, scope: Optional[str], *, create: bool = False) -> Dict[str, ToolEntry]: + """The registration map for *scope*: global when None, else that profile's overlay.""" + if scope is None: + return self._tools + if create: + return self._scoped_tools.setdefault(scope, {}) + return self._scoped_tools.get(scope, {}) + + def _drop_toolset_aliases(self, toolset: str) -> None: + self._toolset_aliases = { + alias: target for alias, target in self._toolset_aliases.items() if target != toolset} + + def _merged_tools(self, scope: Optional[str] = None) -> Dict[str, ToolEntry]: + """Return global tools overlaid with one profile's plugin tools.""" + return {**self._tools, **self._scoped_tools.get(scope or self.current_scope_key(), {})} + + def _toolset_entries(self, toolset: str, scope: Optional[str]) -> List[ToolEntry]: + return self._grouped(self._merged_tools(scope).values()).get(toolset, []) + + def _snapshot_state( + self, scope: Optional[str] = None) -> tuple[List[ToolEntry], Dict[str, Callable]]: + """Return a coherent snapshot of registry entries and toolset checks.""" + with self._lock: + entries = list(self._merged_tools(scope).values()) + checks = dict(self._toolset_checks) + checks.update({e.toolset: e.check_fn for e in entries if e.check_fn is not None}) + return entries, checks + + def _snapshot_entries(self) -> List[ToolEntry]: + return self._snapshot_state()[0] + + def _toolset_has_exposable_tools(self, toolset: str, entries: List[ToolEntry]) -> bool: + """True when at least one tool in *toolset* would be exposed. Mirrors + :meth:`get_definitions` per-tool filtering so doctor/banners agree with runtime: + mixed toolsets (``terminal`` + desktop-only ``read_terminal``) must not be gated + by the first ``check_fn``.""" + memo: Dict[Callable, bool] = {} + members = (e for e in entries if e.toolset == toolset) + return any(not e.check_fn or _memo_check(e.check_fn, memo) for e in members) + + def get_entry(self, name: str, *, scope: Optional[str] = None) -> Optional[ToolEntry]: + """Active profile's entry by name, falling back to global.""" + with self._lock: + return self._merged_tools(scope).get(name) + + def snapshot_registration( + self, name: str, *, scope: Optional[str] = None) -> Optional[ToolEntry]: + """Local slot state only — no global fallback.""" + with self._lock: + return self._slot(scope).get(name) + + def get_registered_toolset_names(self) -> List[str]: + return sorted(self._grouped(self._snapshot_entries())) + + def get_all_entries(self) -> List[ToolEntry]: + return self._snapshot_entries() + + def get_tool_names_for_toolset(self, toolset: str) -> List[str]: + return sorted(e.name for e in self._grouped(self._snapshot_entries()).get(toolset, [])) + + def register_toolset_alias(self, alias: str, toolset: str) -> None: + """Register an explicit alias for a canonical toolset name.""" + with self._lock: + existing = self._toolset_aliases.get(alias) + if existing and existing != toolset: + logger.warning( + "Toolset alias collision: '%s' (%s) overwritten by %s", alias, existing, toolset + ) + self._toolset_aliases[alias] = toolset + self._generation += 1 + + def get_registered_toolset_aliases(self) -> Dict[str, str]: + with self._lock: + return dict(self._toolset_aliases) + + def get_toolset_alias_target(self, alias: str) -> Optional[str]: + with self._lock: + return self._toolset_aliases.get(alias) + + # ---- Registration ------------------------------------------------ + + def register_plugin_override_policy( + self, module_namespace: str, allowed: bool, *, scope: Optional[str] = None, + ) -> _PluginOverridePolicy: + """Bind a plugin module namespace to its current operator opt-in. The identity-bearing + result lets unload/reload revoke a stale authorization without losing attribution.""" + with self._lock: + policy = _PluginOverridePolicy(allowed) + self._plugin_override_policy[(scope, module_namespace)] = policy + self._plugin_module_scopes.setdefault(module_namespace, set()).add(scope) + return policy + + def snapshot_plugin_override_policy( + self, module_namespace: str, *, scope: Optional[str] = None, + ) -> Optional[_PluginOverridePolicy]: + """Return one local authorization generation without fallback.""" + with self._lock: + return self._plugin_override_policy.get((scope, module_namespace)) + + def restore_plugin_override_policy( + self, module_namespace: str, current: _PluginOverridePolicy, + previous: Optional[_PluginOverridePolicy], *, scope: Optional[str] = None) -> bool: + """CAS-restore policy state while retaining durable scope attribution.""" + with self._lock: + key = (scope, module_namespace) + if self._plugin_override_policy.get(key) is not current: + return False + if previous is None: + self._plugin_override_policy.pop(key, None) + else: + self._plugin_override_policy[key] = previous + return True + + def _plugin_override_allowed(self, scope: Optional[str], module_namespace: str) -> bool: + policy = self._plugin_override_policy.get((scope, module_namespace)) + if policy is None and scope is not None: + policy = self._plugin_override_policy.get((None, module_namespace)) + return bool(policy and policy.allowed) + + def _plugin_owner_of(self, handler: Callable) -> Optional[str]: + """Plugin namespace that DEFINED *handler* (None for built-in/MCP handlers). Bound to + ``handler.__globals__["__name__"]``, fixed at definition time so it cannot drift with + call site/thread/timing; lambdas and nested functions inherit it, so a plugin cannot + launder an override via a callback.""" + mod = self._callable_module(handler) + return self._plugin_namespace_of_module(mod) if mod else None + + @staticmethod + def _callable_module(handler: Callable) -> str: + """Resolve defining module through wrappers, partials, and objects.""" + current = handler + seen: Set[int] = set() + while id(current) not in seen: + seen.add(id(current)) + globals_dict = getattr(current, "__globals__", None) + if isinstance(current, functools.partial): + current = current.func + elif getattr(current, "__func__", None) is not None: + current = current.__func__ + elif isinstance(globals_dict, dict) and globals_dict.get("__name__", ""): + return str(globals_dict["__name__"]) + elif getattr(current, "__wrapped__", None) is not None: + current = current.__wrapped__ + else: + break + module_name = getattr(current, "__module__", "") + return str(module_name or getattr(type(current), "__module__", "") or "") + + def _plugin_namespace_of_module(self, module_namespace: str) -> Optional[str]: + """Resolve a module/submodule to its durable plugin namespace.""" + with self._lock: + matches = [ + namespace for namespace in self._plugin_module_scopes + if module_namespace == namespace or module_namespace.startswith(f"{namespace}.")] + if matches: + return max(matches, key=len) + # Also gate plugin modules currently loading but not yet policy-recorded + # (defensive: a handler defined in the plugin namespace is plugin code). + if module_namespace.startswith("hermes_plugins."): + return ".".join(module_namespace.split(".")[:2]) + return None + + def _plugin_scope_of(self, module_namespace: str) -> Optional[str]: + """Return the profile scope bound to a loaded plugin module.""" + with self._lock: + scopes = self._plugin_module_scopes.get(module_namespace) + if not scopes: + return None + active_scope = self.current_scope_key() + if active_scope in scopes: + return active_scope + if len(scopes) == 1: + return next(iter(scopes)) + raise PermissionError( + f"Plugin module {module_namespace!r} is active in multiple profiles and cannot " + "register outside one of those scopes.") + + def plugin_scope_for_module(self, module_namespace: str) -> Optional[str]: + """Public host lookup for a loaded plugin module's immutable scope.""" + owner = self._plugin_namespace_of_module(module_namespace) + return self._plugin_scope_of(owner or module_namespace) + + def plugin_scope_for_callable(self, callback: Callable) -> Optional[str]: + """Return the durable plugin scope for any supported callable shape.""" + module_name = self._callable_module(callback) + return self.plugin_scope_for_module(module_name) if module_name else None + + @staticmethod + def _caller_module() -> str: + """Best-effort module name of the registry method's caller (two frames up). + ``deregister()`` takes only a tool name — no handler for ``_plugin_owner_of`` — + so frame inspection is the only way to know who is asking.""" + try: + return sys._getframe(2).f_globals.get("__name__", "") or "" + except Exception: + return "" + + def register( + self, name: str, toolset: str, schema: dict, handler: Callable, + check_fn: Callable = None, requires_env: list = None, is_async: bool = False, + description: str = "", emoji: str = "", max_result_size_chars: int | float | None = None, + dynamic_schema_overrides: Callable = None, override: bool = False, + scope: Optional[str] = None): + """Register a tool (called at import time by each tool file). ``override=True`` is an + explicit opt-in for plugins replacing a built-in implementation (e.g. a headed-Chrome + browser backend); without it, cross-toolset shadowing is rejected.""" + # Reject malformed schemas at registration, not at request time: a non-dict + # ``parameters`` (e.g. a list) serializes into every provider request and 400s the + # whole turn far from the offending plugin. Failing here names the culprit instead. + if not isinstance(schema, dict): + raise ValueError( + f"Tool {name!r}: schema must be a dict, got {type(schema).__name__}") + params = schema.get("parameters") + if params is not None and not isinstance(params, dict): + raise ValueError( + f"Tool {name!r}: schema['parameters'] must be an object (JSON Schema dict), " + f"got {type(params).__name__}") + handler_owner = self._plugin_owner_of(handler) + caller_owner = self._plugin_namespace_of_module(self._caller_module()) + owner = caller_owner or handler_owner + if scope is None and owner is not None: + scope = self._plugin_scope_of(owner) + with self._lock: + target = self._slot(scope, create=True) + existing = (self._tools if scope is None else self._merged_tools(scope)).get(name) + plugin_override_denied = ( + owner is not None and not self._plugin_override_allowed(scope, owner)) + shadows_global = ( + owner is not None and scope is not None + and name not in target and name in self._tools) + if shadows_global: + if not override: + logger.error( + "Tool registration REJECTED: plugin %r attempted to shadow global tool %r " + "without override=True", owner, name) + return + if plugin_override_denied: + raise PermissionError(_OVERRIDE_DENIED_MSG.format(owner=owner, name=name)) + if existing and existing.toolset != toolset: + if override: + if plugin_override_denied: + logger.error( + "Tool registration REJECTED: plugin %r attempted to override built-in " + "tool %r (existing toolset %r) without operator opt-in. Set " + "plugins.entries..allow_tool_override: true in config.yaml " + "to allow it.", + owner, name, existing.toolset) + raise PermissionError(_OVERRIDE_DENIED_MSG.format(owner=owner, name=name)) + # Explicit opt-in (or non-plugin caller): INFO so the override is auditable. + logger.info( + "Tool '%s': toolset '%s' overriding existing toolset '%s' " + "(override=True opt-in)", name, toolset, existing.toolset) + else: + # Reject every cross-toolset shadow (incl. MCP-to-MCP); same-toolset + # re-registration (MCP reconnect/refresh) stays allowed. + logger.error( + "Tool registration REJECTED: '%s' (toolset '%s') would shadow existing " + "tool from toolset '%s'. Pass override=True to register() if the " + "replacement is intentional, or deregister the existing tool first.", + name, toolset, existing.toolset) + return + target[name] = ToolEntry( + name=name, toolset=toolset, schema=schema, handler=handler, check_fn=check_fn, + requires_env=requires_env or [], is_async=is_async, + description=description or schema.get("description", ""), emoji=emoji, + max_result_size_chars=max_result_size_chars, + dynamic_schema_overrides=dynamic_schema_overrides) + # Availability is derived per-tool (_toolset_has_exposable_tools), so this map no + # longer gates a toolset; it still feeds get_toolset_requirements -> + # TOOLSET_REQUIREMENTS["check_fn"], which banner.py reads (presence only, + # never called) to classify an unavailable toolset as lazy-init vs disabled. + if scope is None and check_fn and toolset not in self._toolset_checks: + self._toolset_checks[toolset] = check_fn + self._generation += 1 + + def deregister(self, name: str, *, scope: Optional[str] = None) -> None: + """Remove a tool; drops the toolset check/aliases if it was the last in its toolset. + + ``scope`` selects a profile overlay explicitly (multiplexed MCP tools live in the + owning profile's overlay); plugin callers may not name another scope, non-plugin + callers default to the process-global map. Gated by the same opt-in as + ``register(override=True)``, else a plugin could deregister a tool it doesn't own + and re-register over the empty slot (the override check only runs when an entry + exists). ``mcp-*`` toolsets are exempt — discovery repaves its own tools per refresh.""" + with self._lock: + caller_mod = self._caller_module() + caller_owner = self._plugin_namespace_of_module(caller_mod) + caller_scope = self._plugin_scope_of(caller_owner) if caller_owner is not None else None + if caller_owner is not None and scope is not None and scope != caller_scope: + raise PermissionError( + f"Plugin module {caller_mod!r} cannot deregister tools " + "outside its own profile scope.") + if scope is None: + scope = caller_scope + target = self._slot(scope) + entry = target.get(name) + if entry is None: + if scope is not None and caller_owner is not None and name in self._tools: + raise PermissionError( + f"Scoped plugin module {caller_mod!r} cannot deregister process-global " + f"tool {name!r}; register a scoped override instead.") + return + if not entry.toolset.startswith("mcp-"): + owner = self._plugin_owner_of(entry.handler) + # Ownership binds to the plugin package root (``hermes_plugins.{name}``), not + # the exact module: a submodule's handler is still the package's to remove. + # A handler defined in ``hermes_plugins.pkg.handlers`` is still owned by the + # ``hermes_plugins.pkg`` package — exact string equality would wrongly block root-module + # cleanup code from removing tools registered by a submodule of the same plugin (egilewski + # review on #55840). + same_plugin = bool(owner and caller_owner == owner) + if ( + caller_owner is not None + and not same_plugin + and not self._plugin_override_allowed(caller_scope, caller_owner)): + logger.error( + "Tool deregistration REJECTED: plugin %r attempted to " + "remove tool %r (toolset %r) it does not own, without operator opt-in. Set " + "plugins.entries.%s.allow_tool_override: true in config.yaml to allow it.", + caller_mod, name, entry.toolset, caller_mod) + raise PermissionError( + f"Plugin module {caller_mod!r} cannot deregister tool {name!r} (toolset " + f"{entry.toolset!r}) without operator opt-in (allow_tool_override).") + del target[name] + if scope is not None and not target: + self._scoped_tools.pop(scope, None) + if not self._toolset_entries(entry.toolset, scope): + self._toolset_checks.pop(entry.toolset, None) + self._drop_toolset_aliases(entry.toolset) + self._generation += 1 + logger.debug("Deregistered tool: %s", name) + + def restore_registration( + self, name: str, current: ToolEntry, previous: Optional[ToolEntry], *, + scope: Optional[str] = None) -> bool: + """Restore a host-owned registration if it is still current (plugin ownership ledger). + The identity check is deliberate: another plugin (or ``PluginManager`` in a + multi-profile process) may have registered a newer entry under the same name, and + unloading this entry must leave that newer one untouched.""" + with self._lock: + target = self._slot(scope, create=True) + if target.get(name) is not current: + return False + if previous is None: + target.pop(name, None) + else: + target[name] = previous + if scope is not None and not target: + self._scoped_tools.pop(scope, None) + + # Rebuild affected toolset checks from survivors: a plugin may have replaced an + # entry in the same toolset, so its check_fn would otherwise linger after restore. + affected_toolsets = {current.toolset} + if previous is not None: + affected_toolsets.add(previous.toolset) + for toolset in affected_toolsets: + surviving = self._toolset_entries(toolset, scope) + check_fn = next((entry.check_fn for entry in surviving if entry.check_fn), None) + if scope is None: + if check_fn is None: + self._toolset_checks.pop(toolset, None) + else: + self._toolset_checks[toolset] = check_fn + in_overlays = (e for m in self._scoped_tools.values() for e in m.values()) + if not surviving and not any(e.toolset == toolset for e in in_overlays): + self._drop_toolset_aliases(toolset) + self._generation += 1 + logger.debug("Restored tool registration: %s", name) + return True + + # ---- Schema retrieval -------------------------------------------- + + def get_definitions(self, tool_names: Set[str], quiet: bool = False) -> List[dict]: + """OpenAI-format schemas for the requested tools whose ``check_fn`` passes (or is + absent). Probes use the ~30 s TTL cache so ``hermes tools enable`` lands quickly.""" + result = [] + check_results: Dict[Callable, bool] = {} + entries_by_name = {entry.name: entry for entry in self._snapshot_entries()} + for name in sorted(tool_names): + entry = entries_by_name.get(name) + if not entry: + continue + if entry.check_fn and not _memo_check(entry.check_fn, check_results): + if not quiet: + logger.debug("Tool %s unavailable (check failed)", name) + continue + schema_with_name = {**entry.schema, "name": entry.name} + # Runtime-dynamic overrides (e.g. delegate_task limits); the caller's memo is + # keyed on config.yaml mtime+size, so config changes invalidate it automatically. + if entry.dynamic_schema_overrides is not None: + try: + overrides = entry.dynamic_schema_overrides() + except Exception as exc: + overrides = None + logger.warning( + "dynamic_schema_overrides for tool %s raised %s; using static schema", + name, exc) + if isinstance(overrides, dict): + schema_with_name.update(overrides) + result.append({"type": "function", "function": schema_with_name}) + return result + + # ---- Dispatch ---------------------------------------------------- + + @staticmethod + def _normalize_handler_result(name: str, result): + """Results must be a string or the multimodal envelope; anything else becomes a + string error so logging/hooks/budgeting/persistence never receive values they + cannot slice or size.""" + if isinstance(result, str): + return _bound_json_error_result(result) + if ( + isinstance(result, dict) + and result.get("_multimodal") is True + and isinstance(result.get("content"), list)): + return result + result_type = type(result).__name__ + logger.error("Tool %s handler returned unsupported result type: %s", name, result_type) + return tool_error( + f"Tool handler returned unsupported result type: {result_type}", + error_type="tool_result_contract", tool=name, result_type=result_type) + + def dispatch( + self, name: str, args: dict, *, scope: Optional[str] = None, **kwargs) -> str | dict: + """Execute a tool handler by name: async handlers bridged via ``_run_async()``, + results normalized, every exception returned as ``{"error": ...}``.""" + entry = self.get_entry(name, scope=scope) + if not entry: + return tool_error(f"Unknown tool: {name}") + try: + if entry.is_async: + from model_tools import _run_async + result = _run_async(entry.handler(args, **kwargs)) + else: + result = entry.handler(args, **kwargs) + return self._normalize_handler_result(name, result) + except Exception as e: + # exc_info already renders the exception, so keep the message copy bounded. + logger.exception("Tool %s dispatch error: %s", name, _bound_error_text(str(e))) + # Sanitize so framing tokens/CDATA/fences in exception text aren't structural noise. + raw = f"Tool execution failed: {type(e).__name__}: {e}" + try: + from model_tools import _sanitize_tool_error + sanitized = _sanitize_tool_error(raw) + except Exception: + sanitized = raw # defensive: never let the sanitizer block error propagation + return tool_error(sanitized) + + # ---- Query helpers ----------------------------------------------- + + def _attr(self, name: str, attr: str): + return getattr(self.get_entry(name), attr, None) + + def get_max_result_size(self, name: str, default: int | float | None = None) -> int | float: + """Return per-tool max result size, or *default* (or global default).""" + size = self._attr(name, "max_result_size_chars") + if size is not None: + return size + if default is not None: + return default + from tools.budget_config import DEFAULT_RESULT_SIZE_CHARS + return DEFAULT_RESULT_SIZE_CHARS + + def get_all_tool_names(self) -> List[str]: + return sorted(entry.name for entry in self._snapshot_entries()) + + def get_schema(self, name: str) -> Optional[dict]: + """Raw schema dict, bypassing check_fn filtering (token estimates, introspection).""" + return self._attr(name, "schema") + + def get_toolset_for_tool(self, name: str) -> Optional[str]: + return self._attr(name, "toolset") + + def get_emoji(self, name: str, default: str = "⚡") -> str: + """Return the emoji for a tool, or *default* if unset.""" + return self._attr(name, "emoji") or default + + def get_tool_to_toolset_map(self) -> Dict[str, str]: + return {entry.name: entry.toolset for entry in self._snapshot_entries()} + + def is_toolset_available(self, toolset: str) -> bool: + """True when a toolset has at least one exposable tool (never raises).""" + return self._toolset_has_exposable_tools(toolset, self._snapshot_entries()) + + + def check_toolset_requirements(self) -> Dict[str, bool]: + entries = self._snapshot_entries() + return { + toolset: self._toolset_has_exposable_tools(toolset, entries) + for toolset in sorted(self._grouped(entries))} + + def get_available_toolsets(self) -> Dict[str, dict]: + """Return toolset metadata for UI display.""" + entries = self._snapshot_entries() + toolsets: Dict[str, dict] = {} + for toolset, members in self._grouped(entries).items(): + toolsets[toolset] = { + "available": self._toolset_has_exposable_tools(toolset, entries), + "tools": [entry.name for entry in members], + "description": "", + "requirements": _unique_env(members)} + return toolsets + + def get_toolset_requirements(self) -> Dict[str, dict]: + """Build a TOOLSET_REQUIREMENTS-compatible dict for backward compat.""" + entries, toolset_checks = self._snapshot_state() + result: Dict[str, dict] = {} + for toolset, members in self._grouped(entries).items(): + result[toolset] = { + "name": toolset, + "env_vars": _unique_env(members), + "check_fn": toolset_checks.get(toolset), + "setup_url": None, + "tools": [entry.name for entry in members]} + return result + + def check_tool_availability(self, quiet: bool = False): + """Return (available_toolsets, unavailable_info) like the old function.""" + available, unavailable = [], [] + entries = self._snapshot_entries() + groups = self._grouped(entries) + for ts in sorted(groups): + if self._toolset_has_exposable_tools(ts, entries): + available.append(ts) + else: + unavailable.append({ + "name": ts, "env_vars": groups[ts][0].requires_env, + "tools": [entry.name for entry in groups[ts]]}) + return available, unavailable + + +def _unique_env(entries: List[ToolEntry]) -> list: + """Union of ``requires_env`` across *entries*, first-seen order, no duplicates.""" + out: list = [] + for entry in entries: + out.extend(v for v in (entry.requires_env or []) if v not in out) + return out + + +# Module-level singleton +registry = ToolRegistry() + + +# Tool handlers must return JSON strings; these replace the ubiquitous +# ``json.dumps({"error": msg}, ensure_ascii=False)`` boilerplate. + + +def tool_error(message, **extra) -> str: + """``'{"error": "", **extra}'`` — the error body is bounded so a raw + exception can't bloat history across retries.""" + return json.dumps({"error": _bound_error_text(str(message)), **extra}, ensure_ascii=False) + + +def tool_result(data=None, **kwargs) -> str: + """JSON-encode a dict positional arg *or* keyword arguments (not both).""" + return json.dumps(data if data is not None else kwargs, ensure_ascii=False) diff --git a/tools/schema_sanitizer.py b/tools/schema_sanitizer.py new file mode 100644 index 0000000000000000000000000000000000000000..644232882ee803b696356fcaf9d74adf87feae72 --- /dev/null +++ b/tools/schema_sanitizer.py @@ -0,0 +1,386 @@ +"""Sanitize tool JSON schemas for strict LLM backends. llama.cpp's grammar converter fails on +``{"type": "object"}`` without ``properties``, bare-string schemas and ``type`` arrays; Anthropic +rejects nullable ``anyOf`` at the top of ``input_schema``; Fireworks rejects ``default`` beside +``$ref``; Codex rejects top-level combinators. Walks a deep copy and fixes only those shapes. +Legacy boolean ``required`` flags are removed from schema positions, lifting property-level +``true`` flags into the parent's required-name list; literal defaults/consts are not schemas.""" + +from __future__ import annotations + +import copy +import logging +import re +from typing import Any, Callable + +logger = logging.getLogger(__name__) + +# Anthropic (and Bedrock/Vertex/Azure fronting it) reject property keys not matching this; one bad +# key anywhere in the tools array 400s the request (Cloudflare's MCP ships 61). +_PROP_KEY_RE = re.compile(r"^[a-zA-Z0-9_.-]{1,64}$") +_PROP_KEY_BAD_CHARS = re.compile(r"[^a-zA-Z0-9_.-]") +_UNION_KEYS = ("anyOf", "oneOf") +_UNION_META_KEYS = ("title", "description", "default", "examples") # copied onto replacements + + +def _empty_object() -> dict: + return {"type": "object", "properties": {}} + + +def _rewrite(schema: Any, fn: Callable[[dict], Any]) -> Any: + """Bottom-up map over a schema tree: lists/dicts recurse, then *fn* sees each dict.""" + if isinstance(schema, list): + return [_rewrite(item, fn) for item in schema] + if not isinstance(schema, dict): + return schema + return fn({k: _rewrite(v, fn) for k, v in schema.items()}) + + +def sanitize_property_key(key: str) -> str: + """Deterministically map an arbitrary property key to a conforming one.""" + return _PROP_KEY_BAD_CHARS.sub("_", key)[:64] or "param" + + +def _rename_property_keys(props: dict, path: str) -> dict[str, str]: + """{original_key: conforming_key} for one properties dict (identity entries omitted). + Deterministic (insertion order, numeric suffixes on collision) so the model-visible schema + and the dispatch-time reverse map from the registry's original schema agree.""" + renames: dict[str, str] = {} + taken = {k for k in props if _PROP_KEY_RE.match(k)} + for key in (k for k in props if not _PROP_KEY_RE.match(k)): + base = sanitize_property_key(key) + candidate, i = base, 2 + while candidate in taken: + candidate, i = base[: 64 - len(f"_{i}")] + f"_{i}", i + 1 + taken.add(candidate) + renames[key] = candidate + logger.debug("schema_sanitizer[%s]: renamed property key %r -> %r " + "(provider key-pattern compat)", path, key, candidate) + return renames + + +def unrename_tool_args(params_schema: Any, args: Any) -> Any: + """Map sanitized keys in model-emitted args back to wire names. ``params_schema`` is the + ORIGINAL registry schema; recurses into objects/array items; unknown keys pass through.""" + props = params_schema.get("properties") if isinstance(params_schema, dict) else None + if not isinstance(props, dict) or not isinstance(args, dict): + return args + reverse = {v: k for k, v in _rename_property_keys(props, "").items()} + out = {} + for key, value in args.items(): + orig = reverse.get(key, key) + sub = props.get(orig) if isinstance(props.get(orig), dict) else {} + if isinstance(value, dict) and sub: + value = unrename_tool_args(sub, value) + elif isinstance(value, list) and isinstance(sub.get("items"), dict): + value = [unrename_tool_args(sub["items"], item) if isinstance(item, dict) else item + for item in value] + out[orig] = value + return out + + +def sanitize_tool_schemas(tools: list[dict]) -> list[dict]: + """Deep-copied ``tools`` (OpenAI format) with sanitized parameter schemas; safe to mutate.""" + return [_sanitize_single_tool(tool) for tool in tools] if tools else tools + + +def _sanitize_single_tool(tool: dict) -> dict: + out = copy.deepcopy(tool) + fn = out.get("function") if isinstance(out, dict) else None + if not isinstance(fn, dict): + return out + params = fn.get("parameters") + if not isinstance(params, dict): # missing / non-dict → minimal valid shape + fn["parameters"] = _empty_object() + return out + name = fn.get("name", "") + top = _sanitize_node(params, path=name) + top = top if isinstance(top, dict) else {} # guarantee an object with properties on top + top["type"] = "object" + if not isinstance(top.get("properties"), dict): + top["properties"] = {} + # The recursive pass only handles array-form ``type: [X, "null"]``; collapse anyOf unions + # here, keeping ``nullable: true`` so ``tools.arg_coercion._schema_allows_null`` still coerces. + top = strip_nullable_unions(top, keep_nullable_hint=True) + top = _strip_top_level_combinators(top, path=name) + fn["parameters"] = _strip_ref_siblings(top) + return out + + +_REF_FORBIDDEN_SIBLINGS = frozenset({"default"}) # strict validators reject these beside ``$ref`` + + +def _strip_ref_siblings(node: Any) -> Any: + """Recursively drop forbidden siblings of ``$ref`` (Fireworks rejects ``default`` there).""" + def strip(out: dict) -> dict: + for key in _REF_FORBIDDEN_SIBLINGS if "$ref" in out else (): + out.pop(key, None) + return out + return _rewrite(node, strip) + + +_TOP_LEVEL_FORBIDDEN_KEYS = ("allOf", "anyOf", "oneOf", "enum", "not") + + +def _strip_top_level_combinators(params: dict, *, path: str = "") -> dict: + """Drop combinators from the TOP level only (Codex rejects them there). They are usually + conditional-required hints, so validity is unchanged (handlers re-validate); nested ones + stay.""" + if not isinstance(params, dict): + return params + out = dict(params) + for key in [k for k in _TOP_LEVEL_FORBIDDEN_KEYS if k in out]: + logger.debug("schema_sanitizer[%s]: stripped top-level %r combinator " + "from tool parameters (strict-backend compat)", path, key) + del out[key] + return out + + +def _is_null_branch(item: Any) -> bool: + return isinstance(item, dict) and item.get("type") == "null" + + +def _carry_union_meta(outer: dict, replacement: dict, *, skip_default_on_ref: bool) -> None: + """Copy outer-union metadata onto *replacement* where absent (``default`` is illegal beside + ``$ref`` on strict backends, hence ``skip_default_on_ref``).""" + for meta_key in _UNION_META_KEYS: + if meta_key in outer and meta_key not in replacement and not ( + skip_default_on_ref and meta_key == "default" and "$ref" in replacement): + replacement[meta_key] = outer[meta_key] + + +def strip_nullable_unions(schema: Any, *, keep_nullable_hint: bool = True) -> Any: + """Collapse ``anyOf``/``oneOf`` nullable unions (MCP/Pydantic optional fields) to the single + non-null branch: Anthropic rejects the null branch and optionality already lives in the parent's + ``required``. Only when a null branch was dropped AND exactly one non-null branch survives. + ``keep_nullable_hint`` sets ``nullable: true`` for runtime ``"null"`` → ``None`` coercion.""" + def collapse(stripped: dict) -> Any: + for key in _UNION_KEYS: + variants = stripped.get(key) + if not isinstance(variants, list): + continue + non_null = [item for item in variants if not _is_null_branch(item)] + if len(non_null) == 1 and len(non_null) != len(variants): + replacement = dict(non_null[0]) if isinstance(non_null[0], dict) else {} + if keep_nullable_hint: + replacement.setdefault("nullable", True) + _carry_union_meta(stripped, replacement, skip_default_on_ref=True) + return _rewrite(replacement, collapse) # the survivor may itself be a union + return stripped + return _rewrite(schema, collapse) + + +_CONST_PRIMITIVE_TYPES: dict[type, str] = { + bool: "boolean", int: "integer", float: "number", str: "string"} + + +def _const_branch_type(branch: Any) -> str | None: + """Primitive JSON-Schema type of a pure ``const`` branch (declared ``type``, if any, must match; + only ``title``/``description`` may accompany it), else None.""" + if not isinstance(branch, dict) or "const" not in branch \ + or set(branch) - {"const", "type", "title", "description"}: + return None + # ``type(value)`` lookup (not isinstance): bool is a subclass of int. + json_type = _CONST_PRIMITIVE_TYPES.get(type(branch["const"])) + return json_type if branch.get("type") in (None, json_type) else None + + +def collapse_const_unions(schema: Any) -> Any: + """Collapse ``anyOf``/``oneOf`` unions of same-typed consts (Rust/TS MCP servers emit + ``{"anyOf": [{"const": "red"}, {"const": "green"}]}``) to ``enum``; ported from block/goose + ``tool_schema_normalize.rs`` (Apache-2.0). Only when EVERY non-null branch is a pure ``const`` + of one primitive type (``bool`` never merges with ``integer``); one ``{"type": "null"}`` branch + is tolerated as ``nullable: true``. Branch order kept; outer metadata carried; input never + mutated.""" + def collapse(out: dict) -> Any: + for key in _UNION_KEYS: + variants = out.get(key) + if not isinstance(variants, list) or not variants: + continue + null_branches = [i for i in variants if _is_null_branch(i) and "const" not in i] + const_branches = [item for item in variants if item not in null_branches] + if len(null_branches) > 1 or not const_branches: + continue + branch_types = {_const_branch_type(item) for item in const_branches} + if len(branch_types) != 1 or None in branch_types: + continue + replacement: dict = { + "type": branch_types.pop(), "enum": [item["const"] for item in const_branches]} + if null_branches: + replacement["nullable"] = True + _carry_union_meta(out, replacement, skip_default_on_ref=False) + return replacement + return out + return _rewrite(schema, collapse) + + +_BARE_TYPE_NAMES = frozenset({"object", "string", "number", "integer", "boolean", "array", "null"}) +# Values that are NOT schemas (recursing would treat a required name like "path" as a bare schema). +_NON_SCHEMA_LIST_KEYS = frozenset({"required", "enum", "examples", "dependentRequired"}) +_SCHEMA_MAP_KEYS = frozenset({"properties", "$defs", "definitions", "patternProperties", "dependentSchemas"}) +_SCHEMA_CHILD_KEYS = frozenset({ + "items", "additionalItems", "additionalProperties", "unevaluatedItems", "unevaluatedProperties", + "contains", "propertyNames", "not", "if", "then", "else", "anyOf", "oneOf", "allOf", "prefixItems", +}) + + +def _normalize_type_array(value: list, out: dict) -> None: + """Normalize a ``type: [...]`` array into *out* (llama.cpp and Gemini-via-OpenAI reject arrays). + Per AI-SDK: one non-null type → ``type: X`` (+ ``nullable`` if ``null`` present); several → + ``anyOf`` of single-type schemas so EVERY branch survives; none → ``null``/object fallback.""" + has_null = "null" in value + non_null = [t for t in value if isinstance(t, str) and t != "null"] + if not non_null: + out["type"] = "null" if has_null else "object" + return + if len(non_null) == 1: + out["type"] = non_null[0] + else: + out["anyOf"] = [{"type": t} for t in non_null] + if has_null: + out.setdefault("nullable", True) + + +def _sanitize_node(node: Any, path: str) -> Any: + """Recursively sanitize a JSON-Schema fragment: bare-string schemas → ``{"type": }`` + (unknown strings → permissive object); object nodes gain ``properties: {}``; ``type`` arrays + are normalized; property keys are renamed to the provider-safe pattern and ``required`` + follows, with entries missing from ``properties`` pruned. + + - Normalizes ``type: [X, "null"]`` arrays to single ``type: X`` (keeping ``nullable: true`` as a hint), + and multi-type arrays like ``["number", "string"]`` to an ``anyOf`` of single-type schemas so no branch + is dropped (ported from anomalyco/opencode#31877). - Recurses into ``properties``, ``items``, + ``additionalProperties``, ``anyOf``, ``oneOf``, ``allOf``, and ``$defs`` / ``definitions``. + """ + if isinstance(node, str): + if node in _BARE_TYPE_NAMES: + logger.debug("schema_sanitizer[%s]: replacing bare-string schema %r with {'type': %r}", + path, node, node) + return _empty_object() if node == "object" else {"type": node} + logger.debug("schema_sanitizer[%s]: replacing non-schema string %r " + "with empty object schema", path, node) + return _empty_object() + if isinstance(node, list): + return [_sanitize_node(item, f"{path}[{i}]") for i, item in enumerate(node)] + if not isinstance(node, dict): + return node + # Renames computed up front so ``required`` remaps even when it precedes ``properties``. + props_in = node.get("properties") + prop_renames = (_rename_property_keys(props_in, f"{path}.properties") + if isinstance(props_in, dict) else {}) + out: dict = {} + for key, value in node.items(): + # JSON Schema ``type`` arrays (e.g. ``["number", "string"]``, common in MCP tool schemas) are + # rejected by several tool-call backends: * llama.cpp's grammar generator only accepts a singular + # string type. * Gemini (including OpenAI-compatible transports such as GitHub Copilot proxying to + # Gemini) rejects the array form outright — plain @ai-sdk/google rewrites it, but the + # OpenAI-compatible path forwards it verbatim and the backend 400s. Normalize per the SDK's + # behavior: * single non-null type → ``type: X`` (+ ``nullable: true`` if the array also contained + # "null"). No data lost. * multiple non-null types → ``anyOf`` of single-type schemas, so EVERY + # branch survives instead of silently dropping all but the first. ``null`` is lifted into + # ``nullable: true``. * all-null / empty → ``type: "null"`` (or object fallback). Ported from + # anomalyco/opencode#31877. + if key == "type" and isinstance(value, list): + _normalize_type_array(value, out) + elif key in _SCHEMA_MAP_KEYS and isinstance(value, dict): + renames = prop_renames if key == "properties" else {} + out[key] = { + renames.get(k, k): _sanitize_node(v, f"{path}.{key}.{renames.get(k, k)}") + for k, v in value.items()} + elif key == "dependencies" and isinstance(value, dict): + out[key] = {k: _sanitize_node(v, f"{path}.{key}.{k}") if isinstance(v, dict) + else copy.deepcopy(v) for k, v in value.items()} + elif key in {"items", "additionalProperties"}: + # Bool ``additionalProperties`` is valid; bool ``items`` is non-standard but preserved. + out[key] = value if isinstance(value, bool) else _sanitize_node(value, f"{path}.{key}") + elif key in _NON_SCHEMA_LIST_KEYS: + if key == "required" and isinstance(value, bool): + continue # Legacy property flags are lifted by the parent below. + if key == "required" and prop_renames and isinstance(value, list): + out[key] = [prop_renames.get(r, r) if isinstance(r, str) else r for r in value] + else: + out[key] = copy.deepcopy(value) if isinstance(value, (list, dict)) else value + elif key in _SCHEMA_CHILD_KEYS: + out[key] = _sanitize_node(value, f"{path}.{key}") + else: + # Defaults, consts and extension metadata are literal data, not schemas. + out[key] = copy.deepcopy(value) + if isinstance(props_in, dict): + lifted = [prop_renames.get(k, k) for k, v in props_in.items() + if isinstance(v, dict) and v.get("required") is True] + if lifted: + required = out.get("required", []) + required = required if isinstance(required, list) else [] + out["required"] = required + [key for key in lifted if key not in required] + if out.get("type") == "object": + if not isinstance(out.get("properties"), dict): + out["properties"] = {} + if isinstance(out.get("required"), list): + valid = [r for r in out["required"] if isinstance(r, str) and r in out["properties"]] + if valid: + out["required"] = valid + else: + del out["required"] + return out + + +# ---- Reactive strips — only invoked after a backend rejects a schema ---- +_STRIP_ON_RECOVERY_KEYS = frozenset({"pattern", "format"}) +_SCHEMA_MARKERS = frozenset({"type", "anyOf", "oneOf", "allOf"}) # a node with one IS a schema + + +def _dict_nodes(node: Any): + """Pre-order walk over every dict node (yielded before its values, so it may be mutated).""" + if isinstance(node, dict): + yield node + children = node.values() if isinstance(node, dict) else node if isinstance(node, list) else () + for child in children: + yield from _dict_nodes(child) + + +def _reactive_strip( + tools: list[dict], strip_node: Callable[[dict], int], log_msg: str) -> tuple[list[dict], int]: + """Apply *strip_node* (-> keywords removed) to every dict node of each tool's parameters, in + place; OpenAI (``{"function": {"parameters"}}``) and Responses (``{"parameters"}``) formats.""" + stripped = 0 + for tool in tools or (): + if not isinstance(tool, dict): + continue + fn = tool.get("function") + params = fn.get("parameters") if isinstance(fn, dict) else None + params = params if isinstance(params, dict) else tool.get("parameters") + if isinstance(params, dict): + stripped += sum(strip_node(node) for node in _dict_nodes(params)) + if stripped: + logger.info(log_msg, stripped) + return tools, stripped + + +def strip_pattern_and_format(tools: list[dict]) -> tuple[list[dict], int]: + """Strip ``pattern``/``format`` in place — reactive, only after llama.cpp's grammar converter + rejected a schema (its regex engine is a small ECMAScript subset); cloud providers use these as + prompting hints. Only beside ``type``/combinators, so a property *named* ``pattern`` stays.""" + def _strip(node: dict) -> int: + is_schema = bool(node.keys() & _SCHEMA_MARKERS) + hits = [k for k in node if k in _STRIP_ON_RECOVERY_KEYS] if is_schema else [] + for k in hits: + del node[k] + return len(hits) + return _reactive_strip( + tools, _strip, + "schema_sanitizer: stripped %d pattern/format keyword(s) from " + "tool schemas (llama.cpp grammar-parse recovery)") + + +def strip_slash_enum(tools: list[dict]) -> tuple[list[dict], int]: + """Strip ``enum`` keywords whose string values contain ``/``, in place: xAI's grammar compiler + rejects them (HTTP 400 before any token) — typically MCP enums of HuggingFace model IDs.""" + def _strip(node: dict) -> int: + enum_val = node.get("enum") + if isinstance(enum_val, list) and any(isinstance(v, str) and "/" in v for v in enum_val): + del node["enum"] + return 1 + return 0 + return _reactive_strip( + tools, _strip, + "schema_sanitizer: stripped %d enum keyword(s) containing '/' " + "from tool schemas (xAI Responses grammar-compile recovery)") diff --git a/tools/send_message_senders.py b/tools/send_message_senders.py new file mode 100644 index 0000000000000000000000000000000000000000..1e1e3530172704d7bd463d7ca5240c834186f324 --- /dev/null +++ b/tools/send_message_senders.py @@ -0,0 +1,650 @@ +"""Standalone per-platform senders and error helpers for send_message.""" + +import asyncio +import contextlib +import logging +import os +import re +import time + +from agent.redact import redact_sensitive_text + +logger = logging.getLogger("tools.send_message_tool") + +_IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".gif"} +_VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm", ".3gp"} +_AUDIO_EXTS = {".ogg", ".opus", ".mp3", ".m2a", ".wav", ".m4a", ".flac"} +_VOICE_EXTS = {".ogg", ".opus"} +_TELEGRAM_SEND_AUDIO_EXTS = {".mp3", ".m4a"} # sendAudio accepts only these; other audio -> sendVoice / document +# Captionable on the media bubble; voice/audio notes excluded (a caption there reads as a separate label). +_CAPTIONABLE_EXTS = _IMAGE_EXTS | _VIDEO_EXTS | {".pdf", ".doc", ".docx", ".txt", ".md", ".csv", ".xlsx", ".zip"} +# Native caption limits (chars): Telegram caps photo/video at 1024; one conservative shared ceiling elsewhere. +_TELEGRAM_CAPTION_LIMIT = 1024 +_DEFAULT_CAPTION_LIMIT = 4096 + + +def _media_caption_split(text, media_files, *, max_caption_len): + """Single chokepoint deciding whether text rides on the media bubble as its caption: + ``(caption, "")`` only for exactly one captionable file (not a voice/audio note) whose + text fits ``max_caption_len``, else ``(None, text)`` — multi-file caption→file association + is ambiguous. Length is codepoints (never under-counts Telegram's UTF-16 units for BMP + text); the Telegram sender re-checks the *formatted* caption since escaping inflates it.""" + stripped = (text or "").strip() + media = media_files or [] + if (not stripped or len(media) != 1 or len(stripped) > max_caption_len or media[0][1] + or os.path.splitext(media[0][0])[1].lower() not in _CAPTIONABLE_EXTS): + return None, text + return stripped, "" + + +_URL_SECRET_QUERY_RE = re.compile( + r"([?&](?:access_token|api[_-]?key|auth[_-]?token|token|signature|sig)=)([^&#\s]+)", re.IGNORECASE) +_GENERIC_SECRET_ASSIGN_RE = re.compile( + r"\b(access_token|api[_-]?key|auth[_-]?token|signature|sig)\s*=\s*([^\s,;]+)", re.IGNORECASE) + + +def _sanitize_error_text(text) -> str: + """Redact secrets from error text before surfacing it to users/models.""" + redacted = _URL_SECRET_QUERY_RE.sub(lambda m: f"{m.group(1)}***", redact_sensitive_text(text)) + return _GENERIC_SECRET_ASSIGN_RE.sub(lambda m: f"{m.group(1)}=***", redacted) + + +def _error(message: str) -> dict: + """Build a standardized error payload with redacted content.""" + return {"error": _sanitize_error_text(message)} + + +def _success(platform: str, chat_id, warnings=None, **fields) -> dict: + """Standard success payload; ``warnings`` is only included when non-empty.""" + return {"success": True, "platform": platform, "chat_id": chat_id, **fields, + **({"warnings": warnings} if warnings else {})} + + +_NO_DELIVERABLE = "No deliverable text or media remained after processing MEDIA tags" + +_TELEGRAM_TRANSIENT_MARKERS = ("bad gateway", "502", "too many requests", "429", "service unavailable", "503", + "gateway timeout", "504") + + +def _telegram_retry_delay(exc: Exception, attempt: int) -> float | None: + """Retry delay in seconds, or None when final: honours ``retry_after``; timeouts are + never retried (the send may have gone through); 5xx/429 back off exponentially.""" + retry_after = getattr(exc, "retry_after", None) + if retry_after is not None: + try: + return max(float(retry_after), 0.0) + except (TypeError, ValueError): + return 1.0 + text = str(exc).lower() + if "timed out" in text or "timeout" in text: + return None + return float(2 ** attempt) if any(marker in text for marker in _TELEGRAM_TRANSIENT_MARKERS) else None + + +async def _send_telegram_message_with_retry(bot, *, attempts: int = 3, **kwargs): + """``bot.send_message`` with bounded retries on transient failures.""" + for attempt in range(attempts): + try: + return await bot.send_message(**kwargs) + except Exception as exc: + delay = _telegram_retry_delay(exc, attempt) + if delay is None or attempt >= attempts - 1: + raise + logger.warning("Transient Telegram send failure (attempt %d/%d), retrying in %.1fs: %s", + attempt + 1, attempts, delay, _sanitize_error_text(exc)) + await asyncio.sleep(delay) + + +def _is_telegram_thread_not_found(error: Exception) -> bool: + """Mirror of the gateway adapter's ``_is_thread_not_found_error``. + + Matches the gateway adapter's ``_is_thread_not_found_error`` for the standalone ``_send_telegram`` path + (issue #27012). + """ + return "thread not found" in str(error).lower() + + +def _telegram_bot(token): + """Bot honouring TELEGRAM_PROXY (standalone sends time out where api.telegram.org is + blocked); falls back to a direct connection.""" + from telegram import Bot + try: + from gateway.platforms.base import resolve_proxy_url + proxy = resolve_proxy_url("TELEGRAM_PROXY", target_hosts=["api.telegram.org"]) + if not proxy: + return Bot(token=token) + from telegram.request import HTTPXRequest + logger.info("send_message: standalone Telegram send routed through proxy %s", proxy) + return Bot(token=token, request=HTTPXRequest(proxy=proxy), get_updates_request=HTTPXRequest(proxy=proxy)) + except Exception as proxy_err: + logger.warning("send_message: failed to attach Telegram proxy (%s), falling back to direct connection", proxy_err) + return Bot(token=token) + + +def _telegram_thread_kwargs(thread_id): + """Topic id -> ``message_thread_id`` kwargs. Forum "General" is thread "1" inbound but + the Bot API rejects message_thread_id=1, so it maps to no thread — same as the adapter.""" + if thread_id is None: + return {} + try: + from plugins.platforms.telegram.adapter import TelegramAdapter + effective = TelegramAdapter._message_thread_id_for_send(str(thread_id)) + except Exception: # adapter import failed (python-telegram-bot missing): explicit mapping + effective = None if str(thread_id) == "1" else int(thread_id) + return {} if effective is None else {"message_thread_id": effective} + + +def _strip_mdv2_safe(text): + """Strip MarkdownV2 escapes for the plain-text fallback; identity if unavailable.""" + try: + from plugins.platforms.telegram.adapter import _strip_mdv2 + return _strip_mdv2(text) + except Exception: + return text + + +def _adapter_media_method(ext, voice, force_document=False): + """``(adapter method, kind)``: document when forced, else image / video / voice by + extension (``voice`` already folds in the caller's audio rule).""" + if force_document: + return "send_document", "document" + if ext in _IMAGE_EXTS: + return "send_image_file", "image" + if ext in _VIDEO_EXTS: + return "send_video", "video" + return ("send_voice", "audio") if voice else ("send_document", "document") + + +async def _telegram_send_media(bot, chat_id, f, ext, is_voice, force_document, **kwargs): + """Bot API media method by extension: photo (unless forced document), video, voice note, + sendAudio (MP3/M4A only), else document.""" + kind = next((k for exts, k in ((() if force_document else _IMAGE_EXTS, "photo"), (_VIDEO_EXTS, "video"), + (_VOICE_EXTS if is_voice else (), "voice"), (_TELEGRAM_SEND_AUDIO_EXTS, "audio")) + if ext in exts), "document") + return await getattr(bot, f"send_{kind}")(chat_id=chat_id, **{kind: f}, **kwargs) + + +async def _telegram_send_text_chunk(bot, chat_id, chunk, parse_mode, has_html, text_kwargs): + """One text chunk with adapter-matching fallbacks: thread-not-found -> retry without + ``message_thread_id`` (dropped from ``text_kwargs`` for later chunks too); parse failure + -> plain text.""" + async def send(text, mode): + return await _send_telegram_message_with_retry(bot, chat_id=chat_id, text=text, parse_mode=mode, **text_kwargs) + try: + return await send(chunk, parse_mode) + except Exception as md_error: + # Thread not found — retry without message_thread_id so the message still delivers (matching the + # gateway adapter's fallback behaviour, issue #27012). + if _is_telegram_thread_not_found(md_error) and text_kwargs.get("message_thread_id") is not None: + logger.warning("Thread %s not found in _send_telegram, retrying without message_thread_id", + text_kwargs.pop("message_thread_id")) + return await send(chunk, parse_mode) + err_text = str(md_error).lower() + if "parse" in err_text or "markdown" in err_text or "html" in err_text: + logger.warning("Parse mode %s failed in _send_telegram, falling back to plain text: %s", + parse_mode, _sanitize_error_text(md_error)) + return await send(chunk if has_html else _strip_mdv2_safe(chunk), None) + raise + + +async def _telegram_send_one_media(bot, chat_id, media_path, is_voice, *, caption, parse_mode, has_html, + thread_kwargs, force_document): + """Upload one file with adapter-matching fallbacks (thread-not-found -> no + ``message_thread_id``; caption parse failure -> plain caption); retries re-seek the file.""" + ext = os.path.splitext(media_path)[1].lower() + voice_note = ext in _VOICE_EXTS and is_voice + # ``caption`` is only set for a single captionable file, so this never double-captions + # a multi-file send or a voice note. + media_kwargs = {**thread_kwargs, **({"caption": caption, "parse_mode": parse_mode} + if caption is not None and not voice_note else {})} + if voice_note or ext in _TELEGRAM_SEND_AUDIO_EXTS: + with contextlib.suppress(Exception): + from plugins.platforms.telegram.adapter import _probe_voice_duration_seconds + duration = await asyncio.to_thread(_probe_voice_duration_seconds, media_path) + if duration is not None: + media_kwargs["duration"] = duration + with open(media_path, "rb") as f: + try: + return await _telegram_send_media(bot, chat_id, f, ext, is_voice, force_document, **media_kwargs) + except Exception as media_err: + err_text = str(media_err).lower() + if _is_telegram_thread_not_found(media_err) and media_kwargs.get("message_thread_id"): + logger.warning("Thread %s not found for media send, retrying without message_thread_id", + media_kwargs.pop("message_thread_id")) + elif media_kwargs.get("parse_mode") and ("parse" in err_text or "caption" in err_text): + logger.warning("Caption parse failed for media send, retrying plain: %s", + _sanitize_error_text(media_err)) + media_kwargs.pop("parse_mode", None) + if not has_html and media_kwargs.get("caption"): + media_kwargs["caption"] = _strip_mdv2_safe(media_kwargs["caption"]) + else: + raise + f.seek(0) + return await _telegram_send_media(bot, chat_id, f, ext, is_voice, force_document, **media_kwargs) + + +def _telegram_format(message): + """``(formatted, parse_mode, has_html)``: text already containing HTML tags is sent as + HTML; otherwise Markdown -> MarkdownV2 via the adapter's ``format_message``.""" + from telegram.constants import ParseMode + if re.search(r'<[a-zA-Z/][^>]*>', message): + return message, ParseMode.HTML, True + try: + from plugins.platforms.telegram.adapter import TelegramAdapter + return TelegramAdapter.__new__(TelegramAdapter).format_message(message), ParseMode.MARKDOWN_V2, False + except Exception: + return message, ParseMode.MARKDOWN_V2, False # formatting unavailable: send as-is + + +async def _send_telegram(token, chat_id, message, media_files=None, thread_id=None, disable_link_previews=False, force_document=False): + """One-shot Telegram Bot API send; parse failures fall back to plain text.""" + try: + formatted, send_parse_mode, _has_html = _telegram_format(message) + bot = _telegram_bot(token) + from plugins.platforms.telegram.telegram_ids import normalize_telegram_chat_id + from gateway.platforms.base import BasePlatformAdapter, utf16_len + # Telegram accepts a numeric chat_id OR an @username string; never force-int. + # See #13206. + int_chat_id = normalize_telegram_chat_id(chat_id) + media_files = media_files or [] + thread_kwargs = _telegram_thread_kwargs(thread_id) + # disable_web_page_preview is only valid for send_message, not media sends. + text_kwargs = {**thread_kwargs, **({"disable_web_page_preview": True} if disable_link_previews else {})} + last_msg, warnings, _tg_caption = None, [], None + # MEDIA caption rides on the bubble as its *formatted* caption; formatting can inflate a + # raw <1024 string past Telegram's cap, so re-check in UTF-16 units. + _cap, _ = _media_caption_split(message, media_files, max_caption_len=_TELEGRAM_CAPTION_LIMIT) + if _cap is not None and utf16_len(formatted) <= _TELEGRAM_CAPTION_LIMIT: + _tg_caption, formatted = formatted, "" # suppress the separate text send below + # Chunk *after* formatting, in UTF-16 units: escaping can push a raw-<4096 message over. + for chunk in BasePlatformAdapter.truncate_message(formatted, 4096, len_fn=utf16_len) if formatted.strip() else (): + last_msg = await _telegram_send_text_chunk(bot, int_chat_id, chunk, send_parse_mode, _has_html, text_kwargs) + for media_path, is_voice in media_files: + if not os.path.exists(media_path): + warnings.append(f"Media file not found, skipping: {media_path}") + logger.warning(warnings[-1]) + # Caption mode suppressed the text send; the file is gone, so deliver the words alone. + if _tg_caption is not None and last_msg is None: + try: + last_msg = await _send_telegram_message_with_retry( + bot, chat_id=int_chat_id, text=_tg_caption, parse_mode=send_parse_mode, **text_kwargs) + _tg_caption = None # delivered — don't re-caption a later file + except Exception as _cap_err: + logger.warning("Telegram caption-fallback send failed for missing media: %s", + _sanitize_error_text(_cap_err)) + continue + try: + last_msg = await _telegram_send_one_media( + bot, int_chat_id, media_path, is_voice, caption=_tg_caption, parse_mode=send_parse_mode, + has_html=_has_html, thread_kwargs=thread_kwargs, force_document=force_document) + except Exception as e: + warnings.append(_sanitize_error_text(f"Failed to send media {media_path}: {e}")) + logger.error(warnings[-1]) + if last_msg is None: + return {"error": _NO_DELIVERABLE, **({"warnings": warnings} if warnings else {})} + return _success("telegram", chat_id, warnings, message_id=str(last_msg.message_id)) + except ImportError: + return {"error": "python-telegram-bot not installed. Run: pip install python-telegram-bot"} + except Exception as e: + return _error(f"Telegram send failed: {e}") + + +def _live_adapter(platform, *, lookup_failed_warning=None): + """``(runner, adapter)`` for the in-process gateway; ``(None, None)`` standalone (cron); + ``(runner, None)`` when the lookup fails — logged when a warning is given, never silently + swallowed (a silent fall-through could recreate a reconnect storm). + + Multiplex: the adapter is the ACTIVE PROFILE's (``_profile_adapters[profile]``), never a bare + ``runner.adapters`` hit — that map holds the default profile's bots, so a secondary profile's turn + would post/react with the default bot's identity. A profile with no adapter for the platform + yields ``None`` (fail closed → the caller's scoped standalone sender or an error), never the + default bot. Same resolver shape as ``hermes_cli/platform_actions.py::_resolve_adapter``.""" + try: + from gateway.run import _gateway_runner_ref + runner = _gateway_runner_ref() + except Exception: + runner = None + if runner is None: + return None, None + try: + resolve = getattr(runner, "_authorization_adapter", None) + if not callable(resolve): # bare runner stubs without the authz mixin + return runner, runner.adapters.get(platform) + from hermes_cli.profiles import get_active_profile_name + return runner, resolve(platform, get_active_profile_name()) + except Exception: + if lookup_failed_warning: + logger.warning(lookup_failed_warning, exc_info=True) + return runner, None + + +def _plugin_standalone_sender(platform_name, *, label=None, discover=True): + """``(standalone_sender_fn, None)`` for a registered plugin or ``(None, error_dict)``; + ``discover`` runs the idempotent plugin scan first.""" + from gateway.platform_registry import platform_registry + if discover: + from hermes_cli.plugins import discover_plugins + discover_plugins() + entry = platform_registry.get(platform_name) + if entry is None or entry.standalone_sender_fn is None: + return None, {"error": f"{label or platform_name} plugin not registered or missing standalone_sender_fn"} + return entry.standalone_sender_fn, None + + +async def _registry_standalone_send(platform_name, pconfig, chat_id, message, thread_id=None): + """One-shot text send through a plugin's ``standalone_sender_fn``.""" + sender, err = _plugin_standalone_sender(platform_name) + return err or await sender(pconfig, chat_id, message, thread_id=thread_id) + + +async def _resolve_slack_user_target(token, chat_id): + """Resolve ``user:U...`` / ``user_name:`` to a D... DM conversation (chat.postMessage + needs a conversation ID); ``user_name:`` goes through users.list first (stable handle match + only); other ids pass through. ``(chat_id, None)`` or ``(None, error_dict)``.""" + if not (chat_id.startswith("user:") or chat_id.startswith("user_name:")): + return chat_id, None + try: + import aiohttp + except ImportError: + return None, {"error": "aiohttp not installed. Run: pip install aiohttp"} + try: + from gateway.platforms.base import resolve_proxy_url, proxy_kwargs_for_aiohttp + _sess_kw, _req_kw = proxy_kwargs_for_aiohttp(resolve_proxy_url()) + headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} + async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30), **_sess_kw) as session: + async def post_api(method, payload): + async with session.post(f"https://slack.com/api/{method}", headers=headers, json=payload, + **_req_kw) as resp: + return await resp.json() + + if chat_id.startswith("user_name:"): + name = chat_id[len("user_name:"):] + query = name.strip().lstrip("@").lower() + matches, cursor = [], None + for _page in range(20): + data = await post_api("users.list", {"limit": 200, **({"cursor": cursor} if cursor else {})}) + if not data.get("ok"): + return None, _error(f"Slack users.list error: {data.get('error', 'unknown')}") + # Stable handle only: display/real names are mutable and non-unique. + matches += [m for m in data.get("members", []) if not (m.get("deleted") or m.get("is_bot")) + and str(m.get("name", "")).strip().lower() == query] + cursor = (data.get("response_metadata") or {}).get("next_cursor") + if not cursor: + break + if not matches: + return None, _error(f"Could not resolve Slack user '@{name}'.") + if len(matches) > 1: + return None, _error(f"Slack user '@{name}' matched multiple Slack users. Use a Slack user ID instead.") + chat_id = f"user:{matches[0].get('id')}" + opened = await post_api("conversations.open", {"users": chat_id[len("user:"):]}) + if not opened.get("ok"): + return None, _error(f"Slack conversations.open error: {opened.get('error', 'unknown')}. " + "Check bot permissions (im:write).") + dm_id = (opened.get("channel") or {}).get("id") + return (dm_id, None) if dm_id else (None, _error("Slack conversations.open did not return a DM channel ID")) + except Exception as e: + return None, _error(f"Slack DM resolution failed: {e}") + + +async def _signal_send_batch(post, scheduler, rl, idx, n_batches, att_batch, batch_message): + """One Signal batch under the scheduler with rate-limit retries: None on success, False when + retries were exhausted (batch lost), error dict for a non-rate-limit RPC error.""" + n, max_attempts = len(att_batch), rl.SIGNAL_RATE_LIMIT_MAX_ATTEMPTS + for attempt in range(1, max_attempts + 1): + try: + await scheduler.acquire(n) + _rpc_t0 = time.monotonic() + data = await post(att_batch, batch_message) + if "error" not in data: + await scheduler.report_rpc_duration(time.monotonic() - _rpc_t0, n) + return None + err = data["error"] + if not rl._is_signal_rate_limit_error(err): + return _error(f"Signal RPC error on batch {idx + 1}/{n_batches}: {err}") + server_retry_after = rl._extract_retry_after_seconds(err) + scheduler.feedback(server_retry_after, n) + retry_after_label = f"{server_retry_after:.0f}s" if server_retry_after else "unknown" + if attempt >= max_attempts: + logger.error("Signal: rate-limit retries exhausted on batch %d/%d (%d attachments lost, " + "server retry_after=%s)", idx + 1, n_batches, n, retry_after_label) + return False + logger.warning("Signal: rate-limited on batch %d/%d (attempt %d/%d, server retry_after=%s); " + "scheduler will pace the retry", + idx + 1, n_batches, attempt, max_attempts, retry_after_label) + except Exception as e: + if attempt >= max_attempts: + logger.error("Signal: send error on batch %d/%d after %d attempts: %s", + idx + 1, n_batches, attempt, str(e)) + return False + logger.warning("Signal: transient error on batch %d/%d (attempt %d/%d): %s; will retry", + idx + 1, n_batches, attempt, max_attempts, str(e)) + + +async def _send_signal(extra, chat_id, message, media_files=None): + """signal-cli JSON-RPC send; attachments go in SIGNAL_MAX_ATTACHMENTS_PER_MSG batches metered + by the process-wide SignalAttachmentScheduler (shared with the gateway adapter's rate-limit state).""" + try: + import httpx + except ImportError: + return {"error": "httpx not installed"} + from gateway.platforms import signal_rate_limit as rl + from gateway.platforms.signal_format import markdown_to_signal + try: + http_url, account = extra.get("http_url", "http://127.0.0.1:8080").rstrip("/"), extra.get("account", "") + if not account: + return {"error": "Signal account not configured"} + valid_media = media_files or [] + attachment_paths = [] + for media_path, _is_voice in valid_media: + if os.path.exists(media_path): + attachment_paths.append(media_path) + else: + logger.warning("Signal media file not found, skipping: %s", media_path) + # No attachments still means one (text-only) batch; text rides on batch #0 only. + per_batch = rl.SIGNAL_MAX_ATTACHMENTS_PER_MSG + att_batches = [attachment_paths[i:i + per_batch] for i in range(0, len(attachment_paths), per_batch)] or [[]] + n_batches, (plain_text, text_styles) = len(att_batches), markdown_to_signal(message) + recipient = {"groupId": chat_id[6:]} if chat_id.startswith("group:") else {"recipient": [chat_id]} + + async def _rpc_send(text, *, id_prefix, timeout, attachments=None, styled=False): + params = {"account": account, "message": text, **recipient} + if styled and text and text_styles: + params["textStyle" if len(text_styles) == 1 else "textStyles"] = ( + text_styles[0] if len(text_styles) == 1 else text_styles) + if attachments: + params["attachments"] = attachments + payload = {"jsonrpc": "2.0", "method": "send", "params": params, + "id": f"{id_prefix}_{int(time.time() * 1000)}"} + async with httpx.AsyncClient(timeout=timeout) as client: + return await client.post(f"{http_url}/api/v1/rpc", json=payload) + + async def _post(batch_attachments, batch_message): + resp = await _rpc_send(batch_message, id_prefix="send", attachments=batch_attachments, styled=True, + timeout=rl._signal_send_timeout(len(batch_attachments))) + resp.raise_for_status() + return resp.json() + scheduler = rl.get_scheduler() + logger.info("send_message Signal: scheduler state=%s, %d attachment(s) in %d batch(es)", + scheduler.state(), len(attachment_paths), n_batches) + failed_batches: list[int] = [] + for idx, att_batch in enumerate(att_batches): + n = len(att_batch) + if n > 0 and (estimated := scheduler.estimate_wait(n)) >= rl.SIGNAL_BATCH_PACING_NOTICE_THRESHOLD: + # Best-effort one-shot RPC for a user-facing pacing notice. + try: + await _rpc_send(f"(More images coming — pausing ~{rl._format_wait(estimated)} " + f"for Signal rate limit, batch {idx + 1}/{n_batches}.)", id_prefix="notice", timeout=30.0) + except Exception as _e: + logger.warning("Signal: inline notice failed: %s", _e) + outcome = await _signal_send_batch(_post, scheduler, rl, idx, n_batches, att_batch, + plain_text if idx == 0 else "") + if outcome is False: + failed_batches.append(idx + 1) + elif outcome is not None: + return outcome + warnings = [] + if len(attachment_paths) < len(valid_media): + warnings.append("Some media files were skipped (not found on disk)") + if failed_batches: + warnings.append(f"Signal rate-limited {len(failed_batches)} batch(es) " + f"(#{', #'.join(str(b) for b in failed_batches)})") + if failed_batches and len(failed_batches) == n_batches: + return _error(f"Signal: every batch ({n_batches}) hit rate limit; no attachments delivered") + # Result-safe chat identifier for tool transcripts/log consumers. + return _success("signal", "group:***" if str(chat_id).startswith("group:") else chat_id, warnings) + except Exception as e: + return _error(f"Signal send failed: {e}") + + +# "ephemeral connect (may re-init E2EE per send, see #46310)", +async def _send_matrix_via_adapter(pconfig, chat_id, message, media_files=None, thread_id=None): + """Matrix adapter send (native media preserved). Prefer the live gateway adapter's persistent + olm/megolm session: ephemeral per-send connects re-init E2EE and claim one-time keys, which + under bursts exhausts recipient OTKs and silently drops messages — ephemeral is cron-only. + + When a live gateway adapter is available (i.e. the tool runs inside a running gateway), the persistent + connection is reused — one olm/megolm session for all sends. This avoids per-message E2EE re-init storms + that exhaust recipient OTKs and silently drop messages (issue #46310). + """ + media_files = media_files or [] + metadata = {"thread_id": thread_id} if thread_id else None + from gateway.config import Platform + _, live_adapter = _live_adapter(Platform.MATRIX, lookup_failed_warning=( + "Matrix: live gateway adapter lookup failed; falling back to an " + "ephemeral connect (may re-init E2EE per send)")) + if live_adapter is not None: + # Owned by the gateway — must NOT be disconnected (return before the ephemeral ``finally``). + return await _matrix_send_core(live_adapter, chat_id, message, media_files, metadata) + try: + from plugins.platforms.matrix.adapter import MatrixAdapter + except ImportError: + return {"error": "Matrix dependencies not installed. Run: pip install 'mautrix[encryption]'"} + adapter = MatrixAdapter(pconfig) + try: + if not await adapter.connect(): + return _error("Matrix connect failed") + return await _matrix_send_core(adapter, chat_id, message, media_files, metadata) + except Exception as e: + return _error(f"Matrix send failed: {e}") + finally: + with contextlib.suppress(Exception): + await adapter.disconnect() + + +async def _matrix_send_core(adapter, chat_id, message, media_files, metadata): + """Core send logic shared by live and ephemeral Matrix adapters.""" + last_result = None + if message.strip(): + last_result = await adapter.send(chat_id, message, metadata=metadata) + if not last_result.success: + return _error(f"Matrix send failed: {last_result.error}") + for media_path, is_voice in media_files: + if not os.path.exists(media_path): + return _error(f"Media file not found: {media_path}") + ext = os.path.splitext(media_path)[1].lower() + method, _ = _adapter_media_method(ext, (ext in _VOICE_EXTS and is_voice) or ext in _AUDIO_EXTS) + last_result = await getattr(adapter, method)(chat_id, media_path, metadata=metadata) + if not last_result.success: + return _error(f"Matrix media send failed: {last_result.error}") + return {"error": _NO_DELIVERABLE} if last_result is None else _success("matrix", chat_id, message_id=last_result.message_id) + + +def _gateway_platform_module(name, *, unavailable, unmet): + """``(gateway.platforms., None)`` once its ``check__requirements`` passes, else ``(None, error)``.""" + import importlib + try: + module = importlib.import_module(f"gateway.platforms.{name}") + except ImportError: + return None, {"error": unavailable} + return (module, None) if getattr(module, f"check_{name}_requirements")() else (None, {"error": unmet}) + + +async def _send_weixin(pconfig, chat_id, message, media_files=None): + """Send via Weixin iLink using the native adapter helper.""" + wx, err = _gateway_platform_module("weixin", unavailable="Weixin adapter not available.", + unmet="Weixin requirements not met. Need aiohttp + cryptography.") + if err: + return err + try: + return await wx.send_weixin_direct(extra=pconfig.extra, token=pconfig.token, chat_id=chat_id, + message=message, media_files=media_files) + except Exception as e: + return _error(f"Weixin send failed: {e}") + + +async def _send_bluebubbles(extra, chat_id, message): + """Send via BlueBubbles iMessage server using the adapter's REST API.""" + bb, err = _gateway_platform_module("bluebubbles", unavailable="BlueBubbles adapter not available.", + unmet="BlueBubbles requirements not met (need aiohttp + httpx).") + if err: + return err + try: + from gateway.config import PlatformConfig + adapter = bb.BlueBubblesAdapter(PlatformConfig(extra=extra)) + if not await adapter.connect(): + return _error("BlueBubbles: failed to connect to server") + try: + result = await adapter.send(chat_id, message) + finally: + await adapter.disconnect() + if not result.success: + return _error(f"BlueBubbles send failed: {result.error}") + return _success("bluebubbles", chat_id, message_id=result.message_id) + except Exception as e: + return _error(f"BlueBubbles send failed: {e}") + + +async def _send_qqbot(pconfig, chat_id, message): + """Send via the QQ Bot Open Platform REST API (no WebSocket needed).""" + try: + import httpx + except ImportError: + return _error("QQBot direct send requires httpx. Run: pip install httpx") + + # Profile-scoped lookup so a multiplex profile never borrows another's QQ credentials. + from gateway.config import _getenv + extra = pconfig.extra or {} + appid = extra.get("app_id") or _getenv("QQ_APP_ID", "") + secret = pconfig.token or extra.get("client_secret") or _getenv("QQ_CLIENT_SECRET", "") + if not appid or not secret: + return _error("QQBot: QQ_APP_ID / QQ_CLIENT_SECRET not configured.") + try: + async with httpx.AsyncClient(timeout=15) as client: + token_resp = await client.post("https://bots.qq.com/app/getAppAccessToken", + json={"appId": str(appid), "clientSecret": str(secret)}) + if token_resp.status_code != 200: + return _error(f"QQBot token request failed: {token_resp.status_code}") + access_token = token_resp.json().get("access_token") + if not access_token: + return _error("QQBot: no access_token in response") + + # Separate endpoints for guild channels, C2C (private) and groups; first 2xx wins. + headers = {"Authorization": f"QQBot {access_token}", "Content-Type": "application/json"} + payload = {"content": message[:4000], "msg_type": 0} + endpoints = (("channel", f"https://api.sgroup.qq.com/channels/{chat_id}/messages"), + ("c2c", f"https://api.sgroup.qq.com/v2/users/{chat_id}/messages"), + ("group", f"https://api.sgroup.qq.com/v2/groups/{chat_id}/messages")) + statuses = [] + for kind, url in endpoints: + resp = await client.post(url, json=payload, headers=headers) + if resp.status_code in {200, 201}: + return _success("qqbot", chat_id, message_id=resp.json().get("id")) + statuses.append(f"{kind}={resp.status_code}") + return _error(f"QQBot send failed: {' '.join(statuses)}") + except Exception as e: + return _error(f"QQBot send failed: {e}") + + +async def _send_yuanbao(chat_id, message, media_files=None): + """Send via the running Yuanbao adapter's persistent WebSocket (no throwaway client possible).""" + try: + from gateway.platforms.yuanbao import YuanbaoAdapter + except ImportError: + return _error("Yuanbao adapter module not available.") + adapter = YuanbaoAdapter.get_active() + if adapter is None: + return _error("Yuanbao adapter is not running. Start the gateway with yuanbao platform enabled first.") + try: + return await adapter._outbound.sender.send_direct(chat_id, message, media_files) + except Exception as e: + return _error(f"Yuanbao send failed: {e}") diff --git a/tools/session_search_tool.py b/tools/session_search_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..14ec9edc20d194ec4ad101af3956507f0e3281ba --- /dev/null +++ b/tools/session_search_tool.py @@ -0,0 +1,654 @@ +#!/usr/bin/env python3 +"""Session Search Tool - long-term conversation recall over the SQLite session DB. + +Single-shape tool; the mode is inferred from the args: DISCOVERY (``query``; +FTS5 deduped by lineage, adaptive detail hydrates only the top result), +SCROLL (``session_id`` + ``around_message_id``; ±window around the anchor), +READ (``session_id`` alone; whole session or head/tail), BROWSE (no args). +No LLM calls — every shape returns actual DB messages. +""" + +import json +import logging +from datetime import datetime +from typing import Any, Dict, List, Optional, Union + +from hermes_state_common import _BOUNDARY_END_REASONS + +# Hidden from browsing/searching — integrations (HERMES_SESSION_SOURCE=tool), delegate +# subagent runs, kanban workers are not the user's history. +_HIDDEN_SESSION_SOURCES = ("kanban", "subagent", "tool") +# Searchable but DEMOTED below interactive sessions: cron vocabulary dominates bare +# BM25 and starves out the user's own sessions ("recall blindness"). +# Automation sources that are kept searchable but DEMOTED below interactive sessions in discover ranking. +# Cron jobs run on a schedule and accumulate large volumes of repetitive vocabulary (recurring project +# names, dates, "session", summaries); under bare BM25 they dominate the top-N FTS rows and starve out the +# user's own interactive sessions, producing "recall blindness" where only cron sessions surface (#19434). +# Demoting — not excluding — keeps cron content reachable when it's the only match, while interactive +# sessions always win when both match. +_DEMOTED_SESSION_SOURCES = ("cron",) +# FTS rows scanned before dedup-by-lineage — well above the distinct sessions a query +# returns, so interactive matches buried under cron hits survive the demotion pass. +_DISCOVER_SCAN_LIMIT = 300 +# Raw FTS rows are only a plan input; the response hydrates its own window/bookends. +_DISCOVER_SEARCH_FIELDS = ("id", "session_id", "role", "snippet", "source", "model", "session_started") +# Compaction handoff summaries (agent/context_compressor.py); excluded from bookends. +_COMPACTION_PREFIXES = ("[CONTEXT COMPACTION", "[CONTEXT SUMMARY]:") +# /new, /reset, idle/daily expiry and CLI /new ("new_session") end the predecessor WITHOUT +# carrying its transcript forward — unlike compression continuations and live delegation +# children. The store's boundary set, so the two cannot drift. +_FRESH_RESET_END_REASONS = _BOUNDARY_END_REASONS + + +def _quiet(fn, default, msg, *log_args, with_exc: bool = False): + """``fn()``, or *default* after debug-logging *msg* (+ the exception when *with_exc*).""" + try: + return fn() + except Exception as e: + logging.debug(msg, *(log_args + (e,) if with_exc else log_args), exc_info=True) + return default + + +def _loud(fn, log_msg, error_prefix, *log_args): + """``(fn(), None)``, or ``(None, tool_error_json)`` after an error-level log — for DB + calls whose failure the model must see.""" + try: + return fn(), None + except Exception as e: + logging.error(log_msg, *log_args, e, exc_info=True) + return None, tool_error(f"{error_prefix}: {e}", success=False) + + +def _format_timestamp(ts: Union[int, float, str, None]) -> str: + """Unix timestamp -> readable date; ISO strings pass through; "unknown" for None.""" + if ts is None: + return "unknown" + if isinstance(ts, str) and not ts.replace(".", "").replace("-", "").isdigit(): + return ts + return _quiet(lambda: datetime.fromtimestamp(float(ts)).strftime("%B %d, %Y at %I:%M %p"), str(ts), + "Failed to format timestamp %s: %s", ts, with_exc=True) + + +def _get_session_meta(db, session_id: str) -> dict: + """``db.get_session`` that degrades to ``{}`` on error.""" + return _quiet(lambda: db.get_session(session_id), None, + "get_session failed for %s: %s", session_id, with_exc=True) or {} + + +def _session_meta_block(meta: Dict[str, Any]) -> Dict[str, Any]: + return {"when": _format_timestamp(meta.get("started_at")), "source": meta.get("source"), + "model": meta.get("model"), "title": meta.get("title")} + + +def _ok(**payload) -> str: + return json.dumps({"success": True, **payload}, ensure_ascii=False) + + +def _is_compaction_summary(content: str) -> bool: + return bool(content) and content.lstrip().startswith(_COMPACTION_PREFIXES) + + +def _resolve_to_parent(db, session_id: str) -> tuple[str, bool]: + """Walk parent_session_id to the root -> ``(root_id, has_compression_hop)``; the flag + separates a compression-split lineage (parent summarised away) from a delegation + lineage (child still visible to the parent).""" + visited: set[str] = set() + cur, has_compression = session_id, False + while cur and cur not in visited: + visited.add(cur) + s = _get_session_meta(db, cur) + has_compression = has_compression or s.get("end_reason") == "compression" + if not s.get("parent_session_id"): + break + cur = s["parent_session_id"] + return cur, has_compression + + +def _resolve_lineage(db, session_id: str) -> str: + return _resolve_to_parent(db, session_id)[0] + + +def _same_lineage(db, a: str, b: str) -> bool: + a_root = _resolve_lineage(db, a) + return bool(a_root and a_root == _resolve_lineage(db, b)) + + +def _session_left_live_context(db, session_id: str) -> bool: + """True when the transcript left everyone's live context: ``compression`` + (summarised into the child) or a fresh reset (child starts empty). Live delegation + children (``end_reason is None``) and ``branched`` parents (copied verbatim into + the branch) ARE the current context, so they stay excluded from recall.""" + end_reason = (session_id and _get_session_meta(db, session_id).get("end_reason")) or None + return end_reason == "compression" or end_reason in _FRESH_RESET_END_REASONS + + +def _get_message_storage_state(db, message_id) -> Optional[Dict[str, Any]]: + """Owning session and visibility flags for *message_id* (None if missing/error).""" + def _lookup(): + with db._lock: + return db._conn.execute( + "SELECT session_id, active, compacted FROM messages WHERE id = ?", (message_id,)).fetchone() + row = message_id and _quiet(_lookup, None, "message storage-state lookup failed for %s", message_id) + return dict(row) if row else None + + +def _is_compacted_state(state: Optional[Dict[str, Any]]) -> bool: + """Compaction archives are ``active=0, compacted=1``; rewind/undo rows are + ``active=0, compacted=0`` and must stay hidden.""" + return state is not None and state["active"] == 0 and state["compacted"] == 1 + + +def _is_compacted_message(db, message_id) -> bool: + """True for a compaction-archived row: no longer in live context, so discoverable + even on the current session. False on any error.""" + return _is_compacted_state(_get_message_storage_state(db, message_id)) + + +def _shape_message(m: Dict[str, Any], anchor_id: Optional[int] = None, + max_content_len: Optional[int] = None) -> Dict[str, Any]: + """Slim a message row; keeps ``content`` even when empty (tool-call-only turns).""" + content = m.get("content") + if isinstance(content, str) and "\x1b" in content: # archived terminal output carries ANSI + from tools.ansi_strip import strip_ansi + content = strip_ansi(content) + entry = {"id": m.get("id"), "role": m.get("role"), "content": content, "timestamp": m.get("timestamp")} + entry.update({k: m.get(k) for k in ("tool_name", "tool_calls", "tool_call_id") if m.get(k)}) + if anchor_id is not None and m.get("id") == anchor_id: + entry["anchor"] = True + if max_content_len and content and len(content) > max_content_len: + entry.update(content=content[:max_content_len] + "…", content_truncated=True, + original_content_chars=len(content)) + return {k: v for k, v in entry.items() if v is not None or k == "content"} + + +def _session_link(session_id: str, profile: str = None) -> str: + """The reference the agent writes for a session — same value the desktop composer + emits, so it renders as a titled link. The profile segment is omitted when it + can't be named confidently (a bare id still resolves, just not across profiles).""" + def _active(): + from hermes_cli.profiles import get_active_profile_name + resolved = get_active_profile_name() + return "" if resolved == "custom" else resolved + name = (profile or "").strip() or _quiet(_active, "", "get_active_profile_name failed for session link") + return f"@session:{name}/{session_id}" if name else f"@session:{session_id}" + + +def _discovery_entry(lineage_root: Optional[str], **fields) -> Dict[str, Any]: + """Canonical key order; ``parent_session_id`` set when the hit lives in a child.""" + entry = {k: fields[k] for k in ( + "session_id", "when", "source", "model", "title", "matched_role", "match_message_id", "snippet", + "bookend_start", "messages", "bookend_end", "messages_before", "messages_after", "detail")} + if lineage_root and lineage_root != entry["session_id"]: + entry["parent_session_id"] = lineage_root + return entry + + +def _title_match_result(db, query: str, current_lineage_root: Optional[str]) -> Optional[Dict[str, Any]]: + """Discovery-shaped result when the query matches a session title, else None.""" + title_query = query.strip().strip("`'\"") # models often quote a remembered title + session_id = title_query and _quiet(lambda: db.resolve_session_by_title(title_query), None, + "resolve_session_by_title failed for %r", title_query) + if not session_id: + return None + lineage_root = _resolve_lineage(db, session_id) + # Same-lineage title hits are in-context only while the session is live; + # /new-reset and compression-ended parents are not. + if current_lineage_root and lineage_root == current_lineage_root and not _session_left_live_context(db, session_id): + return None + session_meta = _quiet(lambda: db.get_session(lineage_root) or db.get_session(session_id), None, + "get_session failed for title match %s", session_id) or {} + if session_meta.get("source") in _HIDDEN_SESSION_SOURCES: + return None + messages = _quiet(lambda: db.get_messages(session_id), [], "get_messages failed for title match %s", session_id) + anchor_id = messages[0].get("id") if messages else None + view = {} if anchor_id is None else _quiet( + lambda: db.get_anchored_view(session_id, anchor_id, window=5, bookend=3), {}, + "get_anchored_view failed for title match %s/%s", session_id, anchor_id) + title = session_meta.get("title") or title_query + def shape(key, fallback, anchor=None): + return [_shape_message(m, anchor_id=anchor) for m in (view.get(key) or fallback)] + return {**_discovery_entry( + lineage_root, session_id=session_id, when=_format_timestamp(session_meta.get("started_at")), + source=session_meta.get("source", "unknown"), model=session_meta.get("model") or "unknown", + title=title, matched_role="session_title", match_message_id=anchor_id, + snippet=f"Session title matched: {title}", + bookend_start=shape("bookend_start", messages[:3]), messages=shape("window", messages[:5], anchor_id), + bookend_end=shape("bookend_end", messages[-3:]), messages_before=view.get("messages_before", 0), + messages_after=view.get("messages_after", max(len(messages) - 5, 0)), detail="full"), + "_lineage_root": lineage_root} + + +def _discover_payload(db, query: str, detail: str, results: list, **extra) -> str: + """Discovery response; notes FTS backfill progress so the agent can explain thin + results instead of treating them as ground truth.""" + status = _quiet(db.fts_rebuild_status, None, "fts_rebuild_status failed") + rebuild = {} if status is None else {"index_rebuild": {"percent": status["percent"], "note": ( + f"The search index is rebuilding in the background ({status['percent']}% done, " + f"{status['indexed']:,} of {status['total']:,} messages). Results from older messages " + f"may be incomplete until it finishes.")}} + return _ok(mode="discover", query=query, detail=detail, results=results, count=len(results), **extra, **rebuild) + + +def _bookend(view: Dict[str, Any], key: str) -> List[Dict[str, Any]]: + return [_shape_message(m, max_content_len=1200) for m in (view.get(key) or []) + if not _is_compaction_summary(m.get("content", ""))] + + +def _hydrate_hit(db, lineage_root: str, match_info: Dict[str, Any], result_detail: str) -> Optional[Dict[str, Any]]: + """Discovery result from a surviving FTS row; None (dropped) if the view can't load.""" + hit_sid, msg_id = match_info.get("session_id") or lineage_root, match_info.get("id") + try: + view = db.get_anchored_view(hit_sid, msg_id, window=5, bookend=3) + except Exception as e: + logging.warning("get_anchored_view failed for %s/%s: %s", hit_sid, msg_id, e, exc_info=True) + return None + session_meta, full = _get_session_meta(db, lineage_root), result_detail == "full" + return _discovery_entry( + lineage_root, session_id=hit_sid, + when=_format_timestamp(session_meta.get("started_at") or match_info.get("session_started")), + source=session_meta.get("source") or match_info.get("source", "unknown"), + model=session_meta.get("model") or match_info.get("model") or "unknown", + title=session_meta.get("title") or None, matched_role=match_info.get("role"), + match_message_id=msg_id, snippet=match_info.get("snippet") or "", + bookend_start=_bookend(view, "bookend_start") if full else [], + messages=[_shape_message(m, anchor_id=msg_id, max_content_len=4000) + for m in (view.get("window") or []) if full or m.get("id") == msg_id], + bookend_end=_bookend(view, "bookend_end") if full else [], + messages_before=view.get("messages_before", 0), messages_after=view.get("messages_after", 0), + detail=result_detail) + + +def _discover(db, query: str, role_filter: Optional[List[str]], limit: int, sort: Optional[str], + detail: str, current_session_id: str = None, link_profile: str = None) -> str: + """Discovery shape: FTS5 plus adaptive or full result hydration.""" + current_lineage_root = _resolve_lineage(db, current_session_id) if current_session_id else None + title_result = _title_match_result(db, query, current_lineage_root) + raw_results, err = _loud(lambda: db.search_messages( + query=query, role_filter=role_filter or ["user", "assistant"], + exclude_sources=list(_HIDDEN_SESSION_SOURCES), limit=_DISCOVER_SCAN_LIMIT, offset=0, sort=sort, + fields=_DISCOVER_SEARCH_FIELDS), "FTS5 search failed: %s", "Search failed") + if err: + return err + # Demote cron rows below interactive ones BEFORE dedup so a high-volume cron corpus + # can't starve the user's own sessions out of the top `limit`; stable sort keeps BM25 + # order within each class. + raw_results = sorted(raw_results, key=lambda r: (r.get("source") or "") in _DEMOTED_SESSION_SOURCES) + # See #19434. + if not raw_results and not title_result: + return _discover_payload(db, query, detail, [], message=( + "No matching sessions found. FTS5 ANDs all terms by default — " + "broaden with OR (`alpha OR beta`), exact-match with quoted " + "phrases, exclude with NOT, or prefix-match with `deploy*`.")) + seen_sessions: Dict[str, Dict[str, Any]] = {} + results = [title_result] if title_result else [] + if title_result and (title_lineage := title_result.pop("_lineage_root", None)): + seen_sessions[title_lineage] = {"_title_only": True} + # Dedupe by lineage (lineage_root -> first surviving FTS row) up to `limit`. The raw + # owning session_id stays on the row — only it pairs validly with the FTS match id. + # Current-lineage hits are skipped UNLESS the transcript left live context + # (compression-ended, /new-reset predecessor, or an in-place compacted row on the + # SAME session); a live delegation child (end_reason=None) stays excluded. + for r in raw_results: + if len(seen_sessions) >= limit: + break + raw_sid, resolved_sid = r["session_id"], _resolve_lineage(db, r["session_id"]) + # Skip the current session lineage — UNLESS the hit's transcript has left live context. Three + # sub-cases: Legacy compression rotation: the FTS hit lives in a session that itself ended with + # end_reason='compression'. That session's content has been replaced by a summary in the + # continuation child, so it must stay discoverable. /new-reset (and idle/daily/CLI new_session): the + # predecessor was ended without carrying any transcript into the child. Same lineage root, but the + # prior conversation is NOT in the active context — hiding it made gateway recall go blind after + # every /new (#85756). A live delegation child has end_reason=None, so it stays excluded. In-place + # compaction: the FTS hit lives on the SAME session_id as the current session, but the matched + # message row is an archived (active=0, compacted=1) row. The live-context load filters active=1, so + # that content is no longer in context — let it through. + is_compacted_hit = _is_compacted_message(db, r.get("id")) + if current_lineage_root and resolved_sid == current_lineage_root and not ( + _session_left_live_context(db, raw_sid) or is_compacted_hit): + continue + if current_session_id and raw_sid == current_session_id and not is_compacted_hit: + continue + seen_sessions.setdefault(resolved_sid, {**r, "_lineage_root": resolved_sid}) + for lineage_root, match_info in seen_sessions.items(): + if match_info.get("_title_only"): + continue + # Adaptive: only the top-ranked result is fully hydrated. + entry = _hydrate_hit(db, lineage_root, match_info, "full" if detail == "full" or not results else "compact") + if entry is not None: + results.append(entry) + for entry in results: + entry["link"] = _session_link(entry["session_id"], link_profile) + return _discover_payload(db, query, detail, results, sessions_searched=len(seen_sessions), link_hint=( + "When referring the user to a session, write its `link` value " + "verbatim inline mid-sentence (it renders as a titled link) — never " + "as markdown, in backticks, on its own line, or next to the " + "title/id/date. To read more around a compact result, scroll: " + "session_search(session_id=..., around_message_id=match_message_id).")) + + +def _resolve_profile_db(profile: str): + """Another profile's ``state.db`` opened read-only (safe on a live DB); None = current.""" + if profile is None or not str(profile).strip(): + return None + from hermes_cli import profiles as profiles_mod + from hermes_state import SessionDB + canon = profiles_mod.normalize_profile_name(profile) + profiles_mod.validate_profile_name(canon) + if not profiles_mod.profile_exists(canon): + raise ValueError(f"profile '{canon}' does not exist") + return SessionDB(db_path=profiles_mod.get_profile_dir(canon) / "state.db", read_only=True) + + +def _read_session(db, session_id: str, head: int = 20, tail: int = 10, link_profile: str = None) -> str: + """Read shape: whole session, or ``head`` + ``tail`` messages with a scroll pointer.""" + meta = _get_session_meta(db, session_id) + if not meta: + return tool_error(f"session_id not found: {session_id}", success=False) + rows, err = _loud(lambda: db.get_messages(session_id), "get_messages failed for %s: %s", "failed to load session", + session_id) + if err: + return err + shaped = [_shape_message(m) for m in rows] + total, truncated = len(shaped), len(shaped) > head + tail + return _ok(mode="read", session_id=session_id, link=_session_link(session_id, link_profile), + session_meta=_session_meta_block(meta), message_count=total, truncated=truncated, + messages=shaped[:head] + shaped[-tail:] if truncated else shaped, + **({"message": (f"Session has {total} messages; showing first {head} + last {tail}. " + "Pass around_message_id (any id above) to scroll the middle.")} if truncated else {})) + + +def _read_scoped(db, sid: str, profile: Optional[str]) -> str: + """Read shape scoped to ONE store: the caller's profile, or the profile it named. + + A miss is a miss. Profiles are isolated islands, so a bare id never falls through to + a scan of every other profile's ``state.db`` — that returned another profile's full + transcript to any caller holding the id (#106761). The hint tells the model how to + ask properly: ``@session:/`` or ``profile=``. + """ + result = _read_session(db, sid, link_profile=profile) + if json.loads(result).get("success") is not False or profile: + return result + return tool_error(f"session_id not found in this profile: {sid}. If it belongs to another " + "profile, pass profile= (or the @session:/ link).", success=False) + + +def _list_recent_sessions(db, limit: int, current_session_id: str = None, link_profile: str = None) -> str: + """Browse shape: metadata for the most recent sessions (no LLM, no FTS5).""" + def _browse(): + # Never use list_sessions_rich(order_by_last_active=True) here: it walks every + # compression chain and derives activity/previews before LIMIT, which can + # monopolise a gateway callback for minutes on a multi-GB state.db. The + # bounded browse query preselects an indexed candidate set and carries a + # cooperative SQLite VM cancellation deadline. Fail closed rather than + # silently falling back to the whole-database query shape. + bounded_list = getattr(db, "list_recent_sessions_bounded", None) + if bounded_list is None: + raise RuntimeError("session database does not support bounded recent-session browse") + sessions = bounded_list( + limit=limit + 15, # extra so we can skip current / compression roots + exclude_sources=list(_HIDDEN_SESSION_SOURCES), timeout_seconds=3.0) + current_root, has_compression_hop = ( + _resolve_to_parent(db, current_session_id) if current_session_id else (None, False)) + # Compression continuation: the root was summarised into the live child, so hide + # it. /new-reset children carry no transcript — keep that root browsable. + hidden = {current_session_id, current_root if has_compression_hop and current_root else None} + results = [{ + "session_id": s.get("id", ""), "link": _session_link(s.get("id", ""), link_profile), + "title": s.get("title") or None, **{k: s.get(k, "") for k in ("source", "started_at", "last_active")}, + "message_count": s.get("message_count", 0), "preview": s.get("preview", "")} + for s in [x for x in sessions if x.get("id", "") not in hidden][:limit]] + return _ok(mode="browse", results=results, count=len(results), message=( + f"Showing {len(results)} most recent sessions. Pass a query= to search, " + "or session_id+around_message_id to scroll.")) + + out, err = _loud(_browse, "Error listing recent sessions: %s", "Failed to list recent sessions") + return err or out + + +def _clamp_int(value, default: int, lo: int, hi: int) -> int: + try: + value = int(value) + except (TypeError, ValueError): + value = default + return max(lo, min(value, hi)) + + +def _anchor_in_live_context(db, anchor_state, anchor_sid: str, current_session_id: str) -> bool: + """True when the scroll anchor is still in the caller's active context (reject). + Same-lineage history that LEFT live context (compacted rows, compression-ended + parents, /new-reset predecessors) passes, so scroll never rejects a discovery result. + Rewind/undo rows (active=0, compacted!=1) never count as out-of-context history.""" + if not _same_lineage(db, anchor_sid, current_session_id) or _is_compacted_state(anchor_state): + return False + return (anchor_state is not None and anchor_state["active"] == 0) or not _session_left_live_context(db, anchor_sid) + + +def _scroll(db, session_id: str, around_message_id: int, window: int = 5, + current_session_id: str = None) -> str: + """Scroll shape: a window centered on an anchor (no FTS5, no bookends).""" + try: + around_message_id = int(around_message_id) + except (TypeError, ValueError): + return tool_error("scroll requires integer around_message_id", success=False) + window = _clamp_int(window, 5, 1, 20) + # Locate the anchor BEFORE the current-lineage guard (see _anchor_in_live_context). + anchor_state = _get_message_storage_state(db, around_message_id) + owning = (anchor_state or {}).get("session_id") + if current_session_id and _anchor_in_live_context(db, anchor_state, owning or session_id, current_session_id): + return tool_error("scroll rejected: anchor lives in the current session lineage (already in your active context)", success=False) + session_meta = _get_session_meta(db, session_id) + if not session_meta: + return tool_error(f"session_id not found: {session_id}", success=False) + view, err = _loud(lambda: db.get_messages_around(session_id, around_message_id, window=window), + "get_messages_around failed: %s", "failed to load messages") + if err: + return err + messages = view.get("window") or [] + extra = {} + if not messages and owning and owning != session_id: + # Lineage rebind: the caller paired a parent session_id with a message id + # living in a descendant — serve the owner's window transparently. + rebind_view = _same_lineage(db, session_id, owning) and _quiet( + lambda: db.get_messages_around(owning, around_message_id, window=window), + None, "rebind get_messages_around failed: %s", with_exc=True) + if rebind_view and rebind_view.get("window"): + extra["warning"] = (f"around_message_id {around_message_id} lives in {owning} " + f"(child of {session_id}); rebound transparently") + view, messages, session_id = rebind_view, rebind_view["window"], owning + session_meta = _get_session_meta(db, owning) or session_meta + if not messages: + return tool_error(f"around_message_id {around_message_id} not in session_id {session_id}", success=False) + return _ok( + mode="scroll", session_id=session_id, around_message_id=around_message_id, + session_meta=_session_meta_block(session_meta), window=window, + messages=[_shape_message(m, anchor_id=around_message_id) for m in messages], + messages_before=view.get("messages_before", 0), messages_after=view.get("messages_after", 0), + hint=("Scroll forward: re-call with around_message_id = the LAST message's " + "id; backward: the FIRST message's id (the boundary message repeats " + "as an orientation marker). messages_before/messages_after < window " + "means you've hit that end of the session."), **extra) + + +def _dispatch(query, role_filter, limit, db, current_session_id, session_id, + around_message_id, window, sort, profile, detail, owned_dbs) -> str: + """Mode dispatch (see module docstring); scroll wins when an anchor is set. + Profile DBs opened here are appended to *owned_dbs* for the caller to close.""" + # A raw `@session:/` link as session_id: ids never contain "/", so + # split on it and adopt the embedded profile only when none was passed. + if isinstance(session_id, str) and "/" in session_id: + emb_profile, _, emb_id = session_id.partition("/") + if emb_id: + session_id = emb_id + if emb_profile and (profile is None or not str(profile).strip()): + profile = emb_profile + # Cross-profile: swap in the named profile's DB (read-only) for every shape; + # current-lineage guards key off ids that won't collide, so they stay inert. + try: + profile_db = _resolve_profile_db(profile) + except Exception as e: + return tool_error(f"profile '{profile}': {e}", success=False) + if profile_db is not None: + db, current_session_id = profile_db, None + owned_dbs.append(profile_db) + if isinstance(session_id, str) and session_id.strip(): + if around_message_id is not None: + return _scroll(db, session_id.strip(), around_message_id, window, current_session_id) + return _read_scoped(db, session_id.strip(), profile) + limit = _clamp_int(limit, 3, 1, 10) + if not query or not isinstance(query, str) or not query.strip(): + return _list_recent_sessions(db, limit, current_session_id, link_profile=profile) + sort_norm = sort.strip().lower() if isinstance(sort, str) else None + return _discover( + db=db, query=query.strip(), limit=limit, sort=sort_norm if sort_norm in ("newest", "oldest") else None, + role_filter=([r.strip() for r in role_filter.split(",") if r.strip()] or None) if isinstance(role_filter, str) else None, + detail="full" if isinstance(detail, str) and detail.strip().lower() == "full" else "adaptive", + current_session_id=current_session_id, link_profile=profile) + + +def session_search(query: str = "", role_filter: str = None, limit: int = 3, db=None, + current_session_id: str = None, session_id: str = None, around_message_id: int = None, + window: int = 5, sort: str = None, profile: str = None, detail: str = "adaptive") -> str: + """Run session search, closing DBs opened here. Positional order is frozen for old callers.""" + from hermes_state import format_session_db_unavailable + from hermes_state_registry import acquire, release_or_close + owned_dbs: List[Any] = [] + if db is None: + db = _quiet(acquire, None, "SessionDB unavailable for session_search") + if db is None: + return tool_error(format_session_db_unavailable(), success=False) + owned_dbs.append(db) + try: + return _dispatch(query, role_filter, limit, db, current_session_id, session_id, + around_message_id, window, sort, profile, detail, owned_dbs) + finally: + for owned_db in reversed(owned_dbs): + _quiet(lambda: release_or_close(owned_db), None, "Failed to close session_search SessionDB") + + +def check_session_search_requirements() -> bool: + """Requires the SQLite state database.""" + try: + from hermes_state import _default_db_path + return _default_db_path().parent.exists() + except ImportError: + return False + + +SESSION_SEARCH_SCHEMA = { + "name": "session_search", + "description": ( + "Recall past conversations: search or read old Hermes sessions (FTS5), or " + "scroll inside one. Four shapes, picked by args: `query` = discovery " + "(top-N matching sessions, top result fully hydrated); `session_id` + " + "`around_message_id` = scroll (window of messages around an anchor); " + "`session_id` alone = read a whole session — how you resolve an " + "`@session:/` link (split on '/' into profile + id); no " + "args = browse recent sessions. Results are actual DB messages, no LLM. " + "Searches conversation history ONLY — when the user gave a direct " + "source (URL, file, contact, live system), inspect that first; never " + "conclude 'not found' from history alone. Use for questions about past " + "conversations: 'what did we do about X', 'where did we leave Y'. When " + "referring the user to a session, write its `link` value verbatim " + "inline (it renders as a titled link)." + ), + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": ( + "Search query (discovery shape). Keywords, phrases, or boolean " + "expressions to find in past sessions. Omit to browse recent " + "sessions. Ignored when session_id + around_message_id are set " + "(scroll shape)." + ), + }, + "limit": { + "type": "integer", + "description": ( + "Discovery shape only. Max sessions to return (default 3, max 10). " + "Bump to 5–10 when the topic likely spans several sessions and you " + "want to pick the right one to scroll into." + ), + "default": 3, + }, + "sort": { + "type": "string", + "enum": ["newest", "oldest"], + "description": ( + "Discovery shape only. Temporal bias on top of FTS5 ranking: omit " + "for relevance-only (exploratory recall), 'newest' for " + "\"where did we leave X\", 'oldest' for \"how did X start\"." + ), + }, + "detail": { + "type": "string", + "enum": ["adaptive", "full"], + "description": ( + "Discovery shape only. 'adaptive' (default) fully hydrates the " + "top-ranked result and returns only the exact anchor message for " + "lower-ranked results. 'full' returns bookends and the complete " + "anchored window for every result." + ), + "default": "adaptive", + }, + "session_id": { + "type": "string", + "description": ( + "Scroll shape. Session to read inside. Use the session_id returned " + "from a prior discovery call. Must be paired with " + "around_message_id." + ), + }, + "around_message_id": { + "type": "integer", + "description": ( + "Scroll shape. Message id to center the window on — use " + "match_message_id from a discovery result, or any id from a " + "prior window." + ), + }, + "window": { + "type": "integer", + "description": ( + "Scroll shape only. Messages to return on each side of the anchor " + "(anchor itself always included). Clamped to [1, 20]. Default 5." + ), + "default": 5, + }, + "role_filter": { + "type": "string", + "description": ( + "Optional. Comma-separated roles to include. Discovery defaults to " + "'user,assistant' (tool output is usually noise). Pass " + "'user,assistant,tool' to include tool output (debugging tool " + "behaviour) or 'tool' to search tool output only." + ), + }, + "profile": { + "type": "string", + "description": ( + "Optional. Read sessions from another Hermes profile's database " + "(read-only). Use when resolving an `@session:/` link: " + "pass the profile segment here with session_id as the id segment. " + "Omit to use the current profile." + ), + }, + }, + "required": [], + }, +} + + +from tools.registry import registry, tool_error # noqa: E402 (registration at import time) + +registry.register( + name="session_search", + toolset="session_search", + schema=SESSION_SEARCH_SCHEMA, + handler=lambda args, **kw: session_search( + query=args.get("query") or "", limit=args.get("limit", 3), window=args.get("window", 5), + detail=args.get("detail", "adaptive"), db=kw.get("db"), current_session_id=kw.get("current_session_id"), + **{k: args.get(k) for k in ("role_filter", "session_id", "around_message_id", "sort", "profile")}), + check_fn=check_session_search_requirements, + emoji="🔍") diff --git a/tools/shell_heredoc.py b/tools/shell_heredoc.py new file mode 100644 index 0000000000000000000000000000000000000000..7c0b6a1ae6bf3e029d53cff7bfe961be78e94a30 --- /dev/null +++ b/tools/shell_heredoc.py @@ -0,0 +1,202 @@ +"""Conservative heredoc masking for shell-command scanners ('&' guard, blocked-command checks, +cron lifecycle_guard) that false-positive on heredoc *bodies*. Stripping every body is unsafe the +other way (a fake ``<<`` in quotes can swallow an operator; unquoted bodies expand; ``bash <<'EOF'`` +executes), so a body is masked ONLY when every delimiter is quoted, every heredoc has an exact +terminator line, the opener is a single command (no ``;|&``, ``$(...)``, backticks, process +substitution) and the consumer is an allowlisted non-shell interpreter. Otherwise the command is +returned untouched: a false positive is acceptable, hiding shell syntax from a guard is not. +Masked bodies keep their newline count (re.MULTILINE).""" + +from __future__ import annotations + +import re + +# Non-shell interpreters whose quoted heredoc bodies are data for THAT interpreter; optional +# VAR=... assignments, ``env`` and a path prefix allowed. Narrow on purpose: unmatched = visible. +_INERT_HEREDOC_CONSUMER_RE = re.compile( + r"^\s*(?:[A-Z_][A-Z0-9_]*=\S+\s+)*(?:env\s+)?(?:[A-Za-z0-9_./-]+/)?" + r"(?:python(?:3(?:\.\d+)*)?|osascript|cat)(?=\s|$)", + re.IGNORECASE) + + +def _span_end(command: str, cursor: int, closer: str) -> int: + """Index just past the backslash-aware span opened at ``cursor``.""" + end = cursor + 1 + while end < len(command): + if command[end] == closer: + return end + 1 + end += 2 if command[end] == "\\" and end + 1 < len(command) else 1 + return end + + +def _mask_simple_quotes(command: str) -> str: + """Blank inert quoted spans; keep ``$(``/backtick-bearing ones visible.""" + result = [] + cursor = 0 + while cursor < len(command): + char = command[cursor] + if char in "'\"": # single quotes have no escapes; double quotes are backslash-aware + end = (command.find("'", cursor + 1) + 1 if char == "'" + else _span_end(command, cursor, '"')) + segment = command[cursor:end] + if not segment.endswith(char): + result.append(command[cursor:]) + break + keep = char == '"' and ("$(" in segment or "`" in segment) + result.append(segment if keep else char * 2) + cursor = end + elif char == "`": + end = _span_end(command, cursor, "`") + result.append(command[cursor:end]) + cursor = end + else: + result.append(char) + cursor += 1 + return "".join(result) + + +def _parse_heredoc_operator(command: str, index: int): + """Parse one ``<<`` opener -> ``(end_index, delimiter, strip_tabs, quoted)`` or None.""" + if not command.startswith("<<", index) or command.startswith("<<<", index): + return None + strip_tabs = command.startswith("-", index + 2) + cursor = index + 3 if strip_tabs else index + 2 + while cursor < len(command) and command[cursor] in " \t": + cursor += 1 + if cursor >= len(command) or command[cursor] in "\r\n": + return None + delimiter: list[str] = [] + quoted = False + while cursor < len(command) and not (command[cursor].isspace() or command[cursor] in ";&|<>()"): + char = command[cursor] + if char == "\\": # backslash-escaped char: quoted, literal + if cursor + 1 >= len(command) or command[cursor + 1] in "\r\n": + return None + quoted = True + delimiter.append(command[cursor + 1]) + cursor += 2 + elif char in "'\"": + quoted = True + cursor += 1 + while cursor < len(command) and command[cursor] != char: + current = command[cursor] + if current in "\r\n": + return None + if char == '"' and current == "\\": + if cursor + 1 >= len(command): + return None + if command[cursor + 1] in '$`"\\\n': # else backslash is literal in dquotes + cursor += 1 + current = command[cursor] + delimiter.append(current) + cursor += 1 + if cursor >= len(command): # unterminated quote + return None + cursor += 1 + else: + delimiter.append(char) + cursor += 1 + if not delimiter and not quoted: + return None + return cursor, "".join(delimiter), strip_tabs, quoted + + +def _scan_heredoc_command_unit(command: str, start: int): + """Scan one logical command -> ``(end, specs, unknown_operator, has_list_operator)``: an + unparseable ``<<`` (caller must fail closed) / an unquoted ``;|&`` on the opener line.""" + cursor = start + quote = None + comment = False + specs = [] + unknown_operator = False + has_list_operator = False + while cursor < len(command): + char = command[cursor] + if char == "\n" and (comment or quote is None): + break + # Backslash escapes (incl. line continuations) outside single quotes skip the next char. + escaped = char == "\\" and quote != "'" and not comment and cursor + 1 < len(command) + if comment or quote is not None or escaped: + if char == quote: + quote = None + cursor += 2 if escaped else 1 + elif char in "'\"`": + quote = char + cursor += 1 + elif char == "#" and (cursor == start or command[cursor - 1].isspace() + or command[cursor - 1] in ";&|()"): + comment = True + cursor += 1 + elif command.startswith("<<<", cursor): + cursor += 3 + elif command.startswith("<<", cursor): + parsed = _parse_heredoc_operator(command, cursor) + if parsed is None: + unknown_operator = True + cursor += 2 + else: + cursor, delimiter, strip_tabs, quoted = parsed + specs.append((delimiter, strip_tabs, quoted)) + else: + has_list_operator = has_list_operator or char in ";|&" + cursor += 1 + return cursor, specs, unknown_operator, has_list_operator + + +def _find_heredoc_close( + command: str, body_start: int, delimiter: str, strip_tabs: bool) -> int | None: + """Return the position after an exact shell heredoc terminator line.""" + cursor = body_start + while True: + newline = command.find("\n", cursor) + after = len(command) if newline == -1 else newline + 1 + line = command[cursor:after].removesuffix("\n").removesuffix("\r") + candidate = line.lstrip("\t") if strip_tabs else line + if candidate == delimiter: + return after + if newline == -1: + return None + cursor = after + + +def strip_inert_heredoc_bodies(command: str) -> str: + """Mask heredoc bodies that are provably inert data (see module docstring).""" + # Runs on every terminal call: skip the state machine when no '<<' exists; stop past the last. + if "<<" not in command: + return command + last_opener_index = command.rfind("<<") + ranges: list[tuple[int, int]] = [] + command_start = 0 + while command_start <= last_opener_index: + command_end, specs, unknown_operator, has_list_operator = ( + _scan_heredoc_command_unit(command, command_start)) + if unknown_operator: + return command + if not specs: + if command_end >= len(command): + break + command_start = command_end + 1 + continue + if command_end >= len(command): + return command # opener with no body line: unterminated — leave visible + body_cursor = command_end + 1 + body_ranges: list[tuple[int, int]] = [] + for delimiter, strip_tabs, _quoted in specs: + close_end = _find_heredoc_close(command, body_cursor, delimiter, strip_tabs) + if close_end is None: + return command # unterminated + body_ranges.append((body_cursor, close_end)) + body_cursor = close_end + if all(quoted for _delimiter, _strip_tabs, quoted in specs) and not has_list_operator: + masked_opener = _mask_simple_quotes(command[command_start:command_end]) + if (not any(m in masked_opener for m in ("$(", "`", "<(", ">(")) + and _INERT_HEREDOC_CONSUMER_RE.search(masked_opener)): + ranges.extend(body_ranges) + command_start = body_cursor + # Single-pass rebuild (ranges are sorted and non-overlapping), bodies -> their newlines only. + parts: list[str] = [] + previous = 0 + for start, end in ranges: + parts += [command[previous:start], "\n" * command.count("\n", start, end)] + previous = end + return "".join(parts) + command[previous:] diff --git a/tools/skill_ledger.py b/tools/skill_ledger.py new file mode 100644 index 0000000000000000000000000000000000000000..cbe041ddff3629bdccd6c18aeb69a3abb4d76d52 --- /dev/null +++ b/tools/skill_ledger.py @@ -0,0 +1,415 @@ +"""Per-mutation skill audit ledger + single-edit rollback. + +Every skill mutation (any actor) appends one JSONL entry to +``~/.hermes/skills/.curator_ledger.jsonl`` with before/after file manifests whose +contents are stored content-addressed (sha256-deduped) under +``~/.hermes/.curator_backups/blobs/``. JSONL, not the state DB: durable, greppable, +survives DB resets. TELEMETRY, NOT A GATE: every public write path swallows and +logs — except ``rollback_entry``, which FAILS CLOSED when its safety capture fails. +""" + +from __future__ import annotations + +import contextvars +import hashlib +from contextlib import suppress +import json +import logging +import os +import re +import tarfile +import uuid +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple + +from hermes_constants import get_hermes_home + +logger = logging.getLogger(__name__) + +# Snapshot-id shape of agent.curator_backup (duplicated to avoid importing the backup stack). +_BACKUP_ID_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}Z(-\d{2})?$") +# ".archive/-YYYYMMDDHHMMSS" collision suffix added by archive_skill. +_ARCHIVE_TS_SUFFIX_RE = re.compile(r"^(.+)-\d{14}$") +# Rollback of these must restore a COMPLETE package: consolidation may have re-homed +# support files first, so a disk-only capture would restore a hollow skill. +_PACKAGE_RESTORE_ACTIONS = frozenset({"delete", "archive", "purge"}) +_VALID_ACTORS = {"curator", "agent", "user"} +_NON_PACKAGE_TOPS = {".curator_backups", ".hub", ".archive"} + +# Explicit actor override: the CLI sets "user", the curator walk sets "curator". +_actor_override: contextvars.ContextVar[Optional[str]] = contextvars.ContextVar( + "skill_ledger_actor", default=None) + + +def set_ledger_actor(actor: Optional[str]) -> contextvars.Token: + """Bind an explicit actor for this context; reset_ledger_actor(token) in a finally.""" + return _actor_override.set(actor) + + +def reset_ledger_actor(token: contextvars.Token) -> None: + _actor_override.reset(token) + + +def derive_actor() -> str: + """Explicit override, else background-review provenance -> curator, else agent.""" + override = _actor_override.get() + if override in _VALID_ACTORS: + return override + with suppress(Exception): + from tools.skill_provenance import is_background_review + if is_background_review(): + return "curator" + return "agent" + + +def _skills_dir() -> Path: + return get_hermes_home() / "skills" + + +def ledger_path() -> Path: + return _skills_dir() / ".curator_ledger.jsonl" + + +def blobs_dir() -> Path: + return get_hermes_home() / ".curator_backups" / "blobs" + + +def ledger_enabled() -> bool: + """Config gate ``skills.ledger`` (default True); lazy import keeps this importable without the CLI.""" + try: + from hermes_cli.config import cfg_get, load_config + return bool(cfg_get(load_config(), "skills", "ledger", default=True)) + except Exception as e: # pragma: no cover — best-effort config read + logger.debug("skill_ledger: config read failed (%s); defaulting on", e) + return True + + +def _rel_posix(path: Path | str, root: Path) -> Optional[str]: + """POSIX path of ``path`` relative to ``root`` (both normalized), or None when outside.""" + try: + return Path(os.path.normpath(str(path))).relative_to(os.path.normpath(str(root))).as_posix() + except (ValueError, TypeError): + return None + + +def _is_within(root: Path, path: Path) -> bool: + """True when *path* (normalized, no symlink resolution) sits under *root*.""" + return _rel_posix(path, root) is not None + + +def _store_blob(data: bytes) -> str: + """Write *data* keyed by sha256 (existing blob left alone). Returns the hash.""" + digest = hashlib.sha256(data).hexdigest() + dest = blobs_dir() / digest + if not dest.exists(): + dest.parent.mkdir(parents=True, exist_ok=True) + tmp = dest.with_name(f".tmp-{uuid.uuid4().hex[:8]}-{digest}") + tmp.write_bytes(data) + os.replace(tmp, dest) + return digest + + +def read_blob(sha256: str) -> Optional[bytes]: + """Return blob content or None when missing/invalid.""" + if not sha256 or not all(c in "0123456789abcdef" for c in sha256): + return None + with suppress(OSError): + return (blobs_dir() / sha256).read_bytes() if (blobs_dir() / sha256).exists() else None + return None + + +def snapshot_paths(root: Optional[Path], *, complete_package: bool = False) -> List[Dict[str, str]]: + """{path, sha256} for every file under *root*, each stored as a blob; [] when root is + None/missing. Raises on I/O failure — callers decide whether that is fatal (rollback safety + capture) or swallowed (telemetry). ``complete_package`` unions in the newest curator + tarball's files (disk hashes win).""" + if root is None: + return [] + root = Path(root) # gone from disk -> []; the complete_package fill may still recover it + files = ([root] if root.is_file() + else sorted(p for p in root.rglob("*") if p.is_file()) if root.is_dir() else []) + out = [{"path": str(f), "sha256": _store_blob(f.read_bytes())} for f in files] + return fill_snapshot_from_curator_backup(root, out) if complete_package else out + + +def _package_rel(root: Path) -> Optional[str]: + """Relative POSIX path of a skill dir under ``skills/``; None when outside it + or under backup/hub/archive metadata roots (never a package).""" + posix = (_rel_posix(root, _skills_dir()) or "").strip("/") + if not posix or posix.split("/", 1)[0] in _NON_PACKAGE_TOPS: + return None + return posix + + +def _strip_archive_timestamp(name: str) -> str: + match = _ARCHIVE_TS_SUFFIX_RE.match(name) + return match.group(1) if match else name + + +def _skill_md_parents(items: Optional[List[Dict[str, str]]]) -> List[Path]: + return [p.parent for p in (Path(str(i.get("path", ""))) for i in items or []) if p.name == "SKILL.md"] + + +def package_prefixes( + root: Optional[Path] = None, skill: Optional[str] = None, + before: Optional[List[Dict[str, str]]] = None) -> List[str]: + """Tar member prefixes of this skill's package: live location under ``skills/``, + the package parent from the before-state SKILL.md path (rollback fills where + *root* is gone), the bare skill name, and the name minus an archive suffix.""" + candidates = [_package_rel(Path(root)) if root is not None else None] + candidates += [_package_rel(p) for p in _skill_md_parents(before)] + candidates += [skill, _strip_archive_timestamp(skill) if skill else None] + return list(dict.fromkeys(p for p in ((c or "").strip("/") for c in candidates) if p)) + + +def _read_package_files_from_latest_backup(prefixes: List[str]) -> Dict[str, bytes]: + """``{posix-relpath: bytes}`` under *prefixes* in the newest ``skills/.curator_backups/*/ + skills.tar.gz``; malicious member names (absolute, ``..`` traversal) are rejected.""" + backups = _skills_dir() / ".curator_backups" + try: + children = list(backups.iterdir()) if prefixes and backups.is_dir() else [] + except OSError: + return {} + candidates = [ + child / "skills.tar.gz" for child in children + if child.is_dir() and _BACKUP_ID_RE.match(child.name) and (child / "skills.tar.gz").is_file()] + if not candidates: + return {} + # Parent dirs sort lexicographically == chronologically for the id shape. + archive = max(candidates, key=lambda p: p.parent.name) + prefixed = tuple(p if p.endswith("/") else p + "/" for p in prefixes) + exact = set(prefixes) + out: Dict[str, bytes] = {} + try: + with tarfile.open(archive, "r:gz") as tf: + for member in tf.getmembers(): + name = member.name.replace("\\", "/").lstrip("./") + if (not member.isfile() or not name or name.startswith("/") + or ".." in Path(name).parts + or (name not in exact and not name.startswith(prefixed))): + continue + extracted = tf.extractfile(member) + if extracted is not None: + out[name] = extracted.read() + except (OSError, tarfile.TarError) as exc: + logger.debug("skill_ledger: could not read curator backup package: %s", exc) + return {} + return out + + +def fill_snapshot_from_curator_backup( + root: Optional[Path], existing: Optional[List[Dict[str, str]]] = None, *, + skill: Optional[str] = None) -> List[Dict[str, str]]: + """Union missing skill-package files from the newest curator snapshot. Completeness fill, not + a gate: failures return *existing* unchanged, and only ABSENT paths are filled. Fill targets go + where rollback must restore them: under *root* when known (for purge that is + ``.archive//``, NOT the live tree), else the live skills dir; the tar's leading + package-dir segment is stripped when *root* already names the package. Every target must stay + under ``skills/`` and HERMES_HOME.""" + out = list(existing or []) + prefixes = package_prefixes(root, skill, out) + if not prefixes: + return out + try: + extra = _read_package_files_from_latest_backup(prefixes) + except Exception as exc: + logger.debug("skill_ledger: backup package fill failed: %s", exc) + return out + if not extra: + return out + skills = _skills_dir() + dest_root = Path(root) if root is not None else None + pkg_names = {dest_root.name, _strip_archive_timestamp(dest_root.name)} if dest_root else set() + have = {rel for rel in (_rel_posix(str(i.get("path", "")), skills) for i in out) if rel is not None} + for rel, data in extra.items(): + parts = rel.split("/") + if dest_root is not None and parts and parts[0] in pkg_names: + parts = parts[1:] + if not parts: + continue + dest = (dest_root if dest_root is not None else skills).joinpath(*parts) + if not _is_within(skills, dest) or not _is_within(get_hermes_home(), dest): + continue + rel_key = _rel_posix(dest, skills) + if rel_key is None or rel_key in have: + continue + try: + out.append({"path": str(dest), "sha256": _store_blob(data)}) + except Exception as exc: + logger.debug("skill_ledger: backup blob store failed for %s: %s", rel, exc) + continue + have.add(rel_key) + return out + + +def append_entry( + action: str, skill: str, before: Optional[List[Dict[str, str]]] = None, + after: Optional[List[Dict[str, str]]] = None, actor: Optional[str] = None, + evidence: Optional[Dict[str, Any]] = None) -> Optional[str]: + """Append one entry -> id, or None when disabled / write failed (never raises).""" + if not ledger_enabled(): + return None + try: + entry = { + "id": uuid.uuid4().hex[:12], "ts": datetime.now(timezone.utc).isoformat(), + "actor": actor if actor in _VALID_ACTORS else derive_actor(), + "action": action, "skill": skill, "evidence": evidence or {}, + "before": before or [], "after": after or []} + path = ledger_path() + path.parent.mkdir(parents=True, exist_ok=True) + with open(path, "a", encoding="utf-8") as fh: + fh.write(json.dumps(entry, ensure_ascii=False) + "\n") + return entry["id"] + except Exception as e: + logger.warning("skill_ledger: failed to append entry (%s) — mutation unaffected", e) + return None + + +def record_mutation( + action: str, skill: str, before_root: Optional[Path] = None, + before: Optional[List[Dict[str, str]]] = None, after_root: Optional[Path] = None, + actor: Optional[str] = None, evidence: Optional[Dict[str, Any]] = None) -> Optional[str]: + """Mutation hook: after-state from *after_root* (before = pre-captured list or captured from + *before_root*), then append. NEVER raises. delete/archive/purge capture a COMPLETE package + (filled from the newest curator backup) so rollback never restores a shell.""" + if not ledger_enabled(): + return None + try: + _complete = action in _PACKAGE_RESTORE_ACTIONS + if before is None: + before = snapshot_paths(before_root, complete_package=_complete) + elif _complete: + before = fill_snapshot_from_curator_backup(before_root, before, skill=skill) + return append_entry(action, skill, before=before, after=snapshot_paths(after_root), + actor=actor, evidence=evidence) + except Exception as e: + logger.warning("skill_ledger: record_mutation failed (%s) — mutation unaffected", e) + return None + + +def capture_before( + root: Optional[Path], *, complete_package: bool = False, skill: Optional[str] = None, +) -> Optional[List[Dict[str, str]]]: + """Best-effort pre-mutation capture; None on failure/disabled (pass straight to + record_mutation). ``complete_package=True`` for delete/archive/purge.""" + if not ledger_enabled(): + return None + try: + captured = snapshot_paths(root) + return fill_snapshot_from_curator_backup(root, captured, skill=skill) if complete_package else captured + except Exception as e: + logger.warning("skill_ledger: before-capture failed (%s) — mutation unaffected", e) + return None + + +def list_entries(skill: Optional[str] = None, limit: Optional[int] = None) -> List[Dict[str, Any]]: + """Read the ledger, newest first. Malformed lines are skipped.""" + try: + lines = ledger_path().read_text(encoding="utf-8").splitlines() + except OSError: # missing or unreadable ledger == empty + return [] + rows: List[Dict[str, Any]] = [] + for line in lines: + with suppress(json.JSONDecodeError): + row = json.loads(line) if line.strip() else None + if isinstance(row, dict) and (not skill or row.get("skill") == skill): + rows.append(row) + rows.reverse() + return rows[:limit] if limit is not None and limit >= 0 else rows + + +def get_entry(entry_id: str) -> Optional[Dict[str, Any]]: + return next((r for r in list_entries() if r.get("id") == entry_id), None) if entry_id else None + + +def _validate_entry_paths(entry: Dict[str, Any]) -> Optional[str]: + """Every entry path must be under HERMES_HOME — a hand-edited ledger must not + become a write-anywhere primitive.""" + home = get_hermes_home() + for section in ("before", "after"): + for item in entry.get(section) or []: + p = Path(str(item.get("path", ""))) + if not _is_within(home, p): + return f"entry references a path outside {home}: {p}" + return None + + +def rollback_entry(entry_id: str) -> Tuple[bool, str]: + """Restore the before-state of mutation *entry_id*. Fail-closed (mirrors + agent/curator_backup.rollback): every before-blob must exist BEFORE any change, and a + pre-rollback safety entry of every touched path's CURRENT state is appended first. + + 1. 2. See #63366. + """ + entry = get_entry(entry_id) + if entry is None: + return False, f"no ledger entry with id '{entry_id}'" + if path_err := _validate_entry_paths(entry): + return False, f"refusing rollback: {path_err}" + before = list(entry.get("before") or []) + after = list(entry.get("after") or []) + # Historical hollow delete/archive/purge entries (SKILL.md only): fill from the + # newest curator backup so the complete package is restored. Entry hashes win; + # only missing paths are added, and the filled set is re-validated. + if entry.get("action") in _PACKAGE_RESTORE_ACTIONS: + before = fill_snapshot_from_curator_backup( + next(iter(_skill_md_parents(before)), None), before, + skill=str(entry.get("skill") or "") or None) + if path_err := _validate_entry_paths({**entry, "before": before, "after": after}): + return False, f"refusing rollback: {path_err}" + # Pre-check every blob we need so we never fail mid-restore. + for item in before: + if read_blob(str(item.get("sha256", ""))) is None: + return False, (f"missing blob {item.get('sha256')} for {item.get('path')}; " + "rollback aborted, nothing was changed") + # Safety entry: CURRENT state of every touched path, so the rollback itself is undoable. + touched = {str(i["path"]) for i in before + after if i.get("path")} + try: + safety_before = [{"path": p, "sha256": _store_blob(Path(p).read_bytes())} + for p in sorted(touched) if Path(p).is_file()] + safety_id = append_entry( + "pre-rollback", entry.get("skill", "?"), before=safety_before, after=safety_before, + evidence={"rollback_target": entry_id}) + except Exception as e: + return False, (f"pre-rollback safety capture failed ({e}); rollback aborted and " + "current skills were not changed") + if safety_id is None: + return False, ("pre-rollback safety capture failed (ledger disabled or " + "unwritable); rollback aborted and current skills were not changed") + # Restore: write every before-file, remove files the mutation created. + before_paths = {str(i["path"]) for i in before} + for item in before: + fp = Path(str(item["path"])) + fp.parent.mkdir(parents=True, exist_ok=True) + fp.write_bytes(read_blob(str(item["sha256"]))) # pre-checked above + restored, removed = len(before), 0 + for item in after: + p = str(item.get("path", "")) + if p and p not in before_paths: + try: + if Path(p).is_file(): + Path(p).unlink() + removed += 1 + except OSError as e: + logger.warning("skill_ledger: could not remove %s during rollback: %s", p, e) + append_entry( + "rollback", entry.get("skill", "?"), before=safety_before, after=before, + evidence={"rollback_target": entry_id, "restored": restored, "removed": removed}) + return True, ( + f"rolled back entry {entry_id} ({entry.get('action')} on " + f"'{entry.get('skill')}'): {restored} file(s) restored, {removed} removed. " + f"Safety entry {safety_id} captured the pre-rollback state.") + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. + +ACTOR_AGENT = "agent" + +ACTOR_CURATOR = "curator" + +ACTOR_USER = "user" +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/skill_manager_tool.py b/tools/skill_manager_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..00a7ce8c0bffa826ec0c6a0172e0ae0fdff283a7 --- /dev/null +++ b/tools/skill_manager_tool.py @@ -0,0 +1,925 @@ +#!/usr/bin/env python3 +"""Skill Manager Tool — agent-managed skill creation & editing. + +Skills are the agent's procedural memory (narrow "how to do X"; MEMORY.md/USER.md are +broad, declarative). New skills land in ~/.hermes/skills/ (or ``skills.create_dir``); +existing skills (bundled, hub, user) are modified in place. Layout: +``/[category/]/SKILL.md`` + optional ``references/ templates/ scripts/ assets/``. +""" + +import contextvars as _ctxvars +import json +from contextlib import suppress +import logging +import re +import shutil +import threading +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple + +import yaml + +from hermes_constants import get_hermes_home, display_hermes_home +from utils import atomic_write_text, is_truthy_value +from hermes_cli.config import cfg_get +from agent.skill_utils import ( + extract_skill_description, + is_skill_description_truncated_for_prompt, + parse_frontmatter as _parse_frontmatter, + SKILL_PROMPT_DESC_LIMIT) +from tools.skill_manager_guards import ( + _background_review_preflight, _background_review_read_before_write_guard, _background_review_write_guard, + _containing_skills_root, _curator_consolidation_delete_guard, _maybe_auto_propose_org_edit, + _org_mirror_write_guard, _pinned_guard, _validate_delete_target, _is_background_review, _refusal as _err) +from tools.skill_manager_batch import _skill_manage_batch +from tools.skills_guard import scan_skill, should_allow_install, format_scan_report + +logger = logging.getLogger(__name__) + + +def _guard_agent_created_enabled() -> bool: + """skills.guard_agent_created (default False): opt-in — terminal() runs the same code ungated.""" + try: + from hermes_cli.config import load_config + return is_truthy_value(cfg_get(load_config(), "skills", "guard_agent_created"), default=False) + except Exception: + return False + + +def _security_scan_skill(skill_dir: Path) -> Optional[str]: + """Post-write scan (opt-in); error string if blocked, else None. An "ask" verdict + (dangerous findings) is surfaced as an error so the agent can retry without them.""" + if not _guard_agent_created_enabled(): + return None + try: + result = scan_skill(skill_dir, source="agent-created") + allowed, reason = should_allow_install(result) + if allowed is None: + logger.warning("Agent-created skill blocked (dangerous findings): %s", reason) + if allowed is not True: + return f"Security scan blocked this skill ({reason}):\n{format_scan_report(result)}" + except Exception as e: + logger.warning("Security scan failed for %s: %s", skill_dir, e, exc_info=True) + return None + + +# All skills live in ~/.hermes/skills/ (single source of truth) +HERMES_HOME = get_hermes_home() +SKILLS_DIR = HERMES_HOME / "skills" +_SKILLS_DIR_AT_IMPORT = SKILLS_DIR + + +def _skills_dir() -> Path: + """Active profile's skills dir at call time (multi-profile runtimes rebind per session). + An explicitly patched module-level ``SKILLS_DIR`` (tests) wins over the live HERMES_HOME. + + Long-lived multi-profile runtimes (Dashboard/TUI/Desktop backend, cron, kanban workers) import this + module once under the launch HERMES_HOME and later bind a different profile per session (#40677). + """ + configured = Path(SKILLS_DIR) + return configured if configured != _SKILLS_DIR_AT_IMPORT else get_hermes_home() / "skills" + + +MAX_NAME_LENGTH = 64 +MAX_DESCRIPTION_LENGTH = 1024 +MAX_SKILL_CONTENT_CHARS = 100_000 # ~36k tokens at 2.75 chars/token +MAX_SKILL_FILE_BYTES = 1_048_576 # 1 MiB per supporting file +VALID_NAME_RE = re.compile(r'^[a-z0-9][a-z0-9._-]*$') # filesystem-safe, URL-friendly +ALLOWED_SUBDIRS = {"references", "templates", "scripts", "assets"} # for write_file/remove_file +_FRONTMATTER_END_RE = re.compile(r'\n---\s*\n') +_NAME_RULE = "Use lowercase letters, numbers, hyphens, dots, and underscores." + + +def _display_create_dir() -> str: + """Skill-creation dir for schema/instruction text; follows ``skills.create_dir``.""" + try: + from agent.skill_utils import display_skill_create_dir + return display_skill_create_dir() + except Exception: + return f"{display_hermes_home()}/skills/" + + +# --- Validation helpers ------------------------------------------------------- + +def _check_identifier(value: str, label: str, invalid: str) -> Optional[str]: + if len(value) > MAX_NAME_LENGTH: + return f"{label} exceeds {MAX_NAME_LENGTH} characters." + return None if VALID_NAME_RE.match(value) else invalid + + +def _validate_name(name: str) -> Optional[str]: + if not name: + return "Skill name is required." + return _check_identifier( + name, "Skill name", f"Invalid skill name '{name}'. {_NAME_RULE} Must start with a letter or digit.") + + +def _validate_category(category: Optional[str]) -> Optional[str]: + if category is None or (isinstance(category, str) and not category.strip()): + return None + if not isinstance(category, str): + return "Category must be a string." + category = category.strip() + invalid = (f"Invalid category '{category}'. {_NAME_RULE} " + "Categories must be a single directory name.") + if "/" in category or "\\" in category: + return invalid + return _check_identifier(category, "Category", invalid) + + +def _validate_frontmatter(content: str, *, new_skill: bool = False) -> Optional[str]: + """Validate frontmatter (name + description) and a non-empty body. ``new_skill`` (create + only) also enforces SKILL_PROMPT_DESC_LIMIT so new skills never lose routing signal to + index truncation; edit/patch skip it so existing over-limit skills stay maintainable.""" + if not content.strip(): + return "Content cannot be empty." + content = content.lstrip("\ufeff") # tolerate a Windows UTF-8 BOM + if not content.startswith("---"): + return "SKILL.md must start with YAML frontmatter (---). See existing skills for format." + end_match = _FRONTMATTER_END_RE.search(content[3:]) + if not end_match: + return "SKILL.md frontmatter is not closed. Ensure you have a closing '---' line." + try: + parsed = yaml.safe_load(content[3:end_match.start() + 3]) + except yaml.YAMLError as e: + return f"YAML frontmatter parse error: {e}" + if not isinstance(parsed, dict): + return "Frontmatter must be a YAML mapping (key: value pairs)." + for field in ("name", "description"): + if field not in parsed: + return f"Frontmatter must include '{field}' field." + desc = str(parsed["description"]) + if len(desc) > MAX_DESCRIPTION_LENGTH: + return f"Description exceeds {MAX_DESCRIPTION_LENGTH} characters." + if new_skill and len(desc.strip().strip("'\"")) > SKILL_PROMPT_DESC_LIMIT: + return ( + f"Description is {len(desc.strip())} chars — new skills must fit the " + f"{SKILL_PROMPT_DESC_LIMIT}-char system-prompt budget (one sentence, trigger first, " + f"ends with a period). The skill index truncates longer descriptions to " + f"{SKILL_PROMPT_DESC_LIMIT - 3} chars + '...', destroying the routing signal. " + f"Move detail into the skill body.") + if not content[end_match.end() + 3:].strip(): + return "SKILL.md must have content after the frontmatter (instructions, procedures, etc.)." + return None + + +def _validate_content_size(content: str, label: str = "SKILL.md") -> Optional[str]: + if len(content) > MAX_SKILL_CONTENT_CHARS: + return ( + f"{label} content is {len(content):,} characters (limit: {MAX_SKILL_CONTENT_CHARS:,}). " + f"Consider splitting into a smaller SKILL.md with supporting files in references/ " + f"or templates/.") + return None + + +def _description_preview(content: str) -> str: + """First 120 chars of the frontmatter description; '' on any failure.""" + with suppress(Exception): + fm_end = _FRONTMATTER_END_RE.search(content[3:]) + if fm_end: + return str(yaml.safe_load(content[3:fm_end.start() + 3]).get("description", ""))[:120] + return "" + + +def _resolve_skill_dir(name: str, category: str = None) -> Path: + """New-skill dir; honors ``skills.create_dir`` (e.g. a shared fleet dir).""" + base = _skills_dir() + try: + from agent.skill_utils import get_skill_create_dir + base = get_skill_create_dir() or base + except Exception: + logger.debug("skills.create_dir lookup failed", exc_info=True) + return base / (category or "") / name + + +def _iter_skill_dirs(root: Path): + from agent.skill_utils import is_excluded_skill_path + for skill_md in root.rglob("SKILL.md"): + if not is_excluded_skill_path(skill_md): + yield skill_md.parent + + +def _find_skill(name: str) -> Optional[Dict[str, Any]]: + """Find a skill (local skills dir, then skills.external_dirs) -> ``{"path": Path}`` | None. + + Accepts the bare dir name (``axolotl``; matches category-nested skills too) and the + categorized relative path (``mlops/axolotl``) — the two forms skill_view resolves. The + categorized form matches RELATIVE to the local root only (relative_to raises for external dirs).""" + from agent.skill_utils import get_all_skills_dirs + local_root = None + if "/" in name or "\\" in name: + try: + local_root = _skills_dir().resolve() + except OSError: + logger.debug( + "skills dir resolve failed; categorized lookups fall back to the unresolved path", + exc_info=True) + local_root = _skills_dir() + for skills_dir in get_all_skills_dirs(): + if not skills_dir.exists(): + continue + for skill_dir in _iter_skill_dirs(skills_dir): + if skill_dir.name == name: + return {"path": skill_dir} + if local_root is not None: + resolved = skill_dir.resolve() + if (resolved.is_relative_to(local_root) + and resolved.relative_to(local_root).as_posix() == name): # POSIX form + return {"path": skill_dir} + return None + + +def _find_skill_in_other_profiles(name: str) -> List[Tuple[str, Path]]: + """``(profile, skill_dir)`` pairs for OTHER profiles holding ``name`` (so the not-found + error can explain a wrong-profile mistake). Fail-quiet.""" + matches: List[Tuple[str, Path]] = [] + try: + from hermes_constants import get_default_hermes_root + root = get_default_hermes_root() + except Exception: + return matches + _active = _skills_dir() + active_dir = _active.resolve() if _active.exists() else _active + # Every profile's skills dir EXCEPT the active one (already searched). A candidate whose + # path cannot be resolved is skipped (not a fatal error); is_dir() checks stay unguarded. + candidates: List[Tuple[str, Path]] = [] + with suppress(OSError, RuntimeError): + if (root / "skills").resolve() != active_dir: + candidates.append(("default", root / "skills")) + if (root / "profiles").is_dir(): + with suppress(OSError): + for entry in (root / "profiles").iterdir(): + if not entry.is_dir(): + continue + try: + if (entry / "skills").resolve() == active_dir: + continue + except (OSError, RuntimeError): + continue + candidates.append((entry.name, entry / "skills")) + for profile_name, skills_dir in candidates: + if not skills_dir.is_dir(): + continue + with suppress(OSError): + hit = next((d for d in _iter_skill_dirs(skills_dir) if d.name == name), None) + if hit is not None: + matches.append((profile_name, hit)) # one match per profile is enough + return matches + + +def _skill_not_found_error(name: str, suffix: str = "") -> str: + """Not-found error naming other profiles that hold the skill, plus ``suffix``.""" + from agent.file_safety import _resolve_active_profile_name + base = f"Skill '{name}' not found in active profile '{_resolve_active_profile_name()}'." + others = _find_skill_in_other_profiles(name) + if len(others) == 1: + other_profile, other_path = others[0] + base += ( + f" A skill by that name exists in profile '{other_profile}' ({other_path}). To edit " + f"it, switch profiles (`hermes -p {other_profile}`) or edit the file directly " + f"(file tools / terminal).") + elif others: + names = ", ".join(f"'{p}'" for p, _ in others) + base += ( + f" Skills by that name exist in other profiles: {names}. Switch profiles (`hermes -p " + f"`) to edit there, or edit the files directly (file tools / terminal).") + else: + base += " Use skills_list() to see available skills." + return base + suffix + + +def _validate_file_path(file_path: str) -> Optional[str]: + """Validate a write_file/remove_file path: under an allowed subdir, no escape.""" + from tools.path_security import has_traversal_component + if not file_path: + return "file_path is required." + parts = Path(file_path).parts + # Traversal first, so the SKILL.md exception is unreachable by a traversal-laden path. + if has_traversal_component(file_path): + return "Path traversal ('..') is not allowed." + # SKILL.md lives at the skill root; accept 'SKILL.md' and '/SKILL.md'. + if parts and parts[-1] == "SKILL.md" and len(parts) in (1, 2): + return None + if not parts or parts[0] not in ALLOWED_SUBDIRS: + allowed = ", ".join(sorted(ALLOWED_SUBDIRS)) + return f"File must be under one of: {allowed}. Got: '{file_path}'" + if len(parts) < 2: + return f"Provide a file path, not just a directory. Example: '{parts[0]}/myfile.md'" + return None + + +def _resolve_supporting_file(skill_dir: Path, file_path: str): + """Validate ``file_path`` and resolve it inside ``skill_dir`` + -> ``(target, None)`` | ``(None, error_dict)``.""" + from tools.path_security import validate_within_dir + target = skill_dir / (file_path or "") + err = _validate_file_path(file_path) or validate_within_dir(target, skill_dir) + return (None, _err(err)) if err else (target, None) + + +def _locate_for_write(name: str, action: str, not_found_suffix: str = "", *, + org_guard: bool = True): + """Find the skill; run the org-mirror (unless ``org_guard=False``) and background-review + write guards -> ``(skill_dir, None)`` | ``(None, error_dict)``.""" + existing = _find_skill(name) + if not existing: + return None, _err(_skill_not_found_error(name, not_found_suffix)) + skill_dir = existing["path"] + guard = ((org_guard and _org_mirror_write_guard(name, skill_dir, action)) + or _background_review_write_guard(name, skill_dir, action)) + return (None, guard) if guard else (skill_dir, None) + + +def _guarded_write(name: str, skill_dir: Path, target: Path, action: str, label: str, + content: str) -> Optional[Dict[str, Any]]: + """Read-before-write guard (existing targets only), atomic write, then the security scan; + a blocked scan restores the original (or unlinks a new file). Error dict or None.""" + original = None + if target.exists(): + if read_guard := _background_review_read_before_write_guard(name, target, action, label): + return read_guard + original = target.read_text(encoding="utf-8") + target.parent.mkdir(parents=True, exist_ok=True) + atomic_write_text(target, content, preserve_mode=True, create_mode=0o644) + scan_error = _security_scan_skill(skill_dir) + if not scan_error: + return None + if original is not None: + atomic_write_text(target, original, preserve_mode=True) + else: + target.unlink(missing_ok=True) + return _err(scan_error) + + +def _attach_org_note(result: Dict[str, Any], name: str, skill_dir: Path) -> Dict[str, Any]: + if org_note := _maybe_auto_propose_org_edit(name, skill_dir): + result["org_sharing"] = org_note + result["message"] = f"{result['message']} {org_note}" + return result + + +def _add_description_prompt_preview(result: Dict[str, Any], content: str) -> Dict[str, Any]: + fm, _ = _parse_frontmatter(content) + if is_skill_description_truncated_for_prompt(fm): + result["system_prompt_preview"] = ( + f"System prompt will show: \"{extract_skill_description(fm)}\" — keep the trigger " + f"self-contained in the first {SKILL_PROMPT_DESC_LIMIT - 3} chars.") + return result + + +def _attach_lint_findings(result: Dict[str, Any], skill_md: Path) -> None: + """Attach ADVISORY authoring findings (hard rejects already ran in _validate_frontmatter).""" + try: + from tools.skill_linter import lint_skill # local import: optional path + findings = lint_skill(skill_md) + except Exception: + findings = None + if not findings: + return + result["lint_warnings"] = [ + {"severity": f.severity, "rule": f.rule, "message": f.message} for f in findings] + result["lint_hint"] = ( + "The skill was created. These are advisory authoring-convention findings (not blockers) " + "— fix them with skill_manage(action='patch') to match Hermes skill standards.") + + +def _clip(text: str, n: int, ellipsis: str) -> str: + return text[:n] + (ellipsis if len(text) > n else "") + + +# --- Core actions ------------------------------------------------------------- + +def _create_skill(name: str, content: str, category: str = None) -> Dict[str, Any]: + if err := (_validate_name(name) or _validate_category(category) + or _validate_frontmatter(content, new_skill=True) or _validate_content_size(content)): + return _err(err) + if existing := _find_skill(name): + return _err(f"A skill named '{name}' already exists at {existing['path']}.") + skill_dir = _resolve_skill_dir(name, category) + skill_dir.mkdir(parents=True, exist_ok=True) + skill_md = skill_dir / "SKILL.md" + atomic_write_text(skill_md, content, preserve_mode=True, create_mode=0o644) + if scan_error := _security_scan_skill(skill_dir): + shutil.rmtree(skill_dir, ignore_errors=True) + return _err(scan_error) + root = _skills_dir() # display relative under the profile dir; absolute under skills.create_dir + display = skill_dir.relative_to(root) if skill_dir.is_relative_to(root) else skill_dir + result = { + "success": True, "message": f"Skill '{name}' created.", "path": str(display), + "skill_md": str(skill_md), "_change": {"description": _description_preview(content)}, + **({"category": category} if category else {}), + "hint": "To add reference files, templates, or scripts, use " + f"skill_manage(action='write_file', name='{name}', file_path='references/example.md', " + "file_content='...')"} + _attach_lint_findings(_add_description_prompt_preview(result, content), skill_md) + return result + + +def _edit_skill(name: str, content: str) -> Dict[str, Any]: + """Replace the SKILL.md of any existing skill (full rewrite).""" + if err := _validate_frontmatter(content) or _validate_content_size(content): + return _err(err) + skill_dir, guard = _locate_for_write(name, "edit") + # SKILL.md always exists here (_find_skill requires it), so a blocked scan restores it. + if guard := guard or _guarded_write(name, skill_dir, skill_dir / "SKILL.md", "edit", "SKILL.md", content): + return guard + result = { + "success": True, "message": f"Skill '{name}' updated (full rewrite).", + "path": str(skill_dir), "_change": {"description": _description_preview(content)}} + return _add_description_prompt_preview(_attach_org_note(result, name, skill_dir), content) + + +def _patch_skill(name: str, old_string: str, new_string: str, file_path: str = None, + replace_all: bool = False) -> Dict[str, Any]: + """Targeted find-and-replace in SKILL.md (default) or a supporting file; unique match unless replace_all.""" + if not old_string: + # A bare "required" error is a dead end: the model retries blindly and often + # escapes to action='write_file', clobbering the whole file. + return _err( + "old_string is required for 'patch' and must be the EXACT text currently in the file. " + "Read the target file first (read_file on the skill's SKILL.md, or the file named by " + "file_path) and copy the snippet verbatim, then retry 'patch'. Do NOT fall back to " + "action='write_file' — that rewrites the entire file and destroys unrelated content.") + if new_string is None: + return _err("new_string is required for 'patch'. Use an empty string to delete matched text.") + # No old_string == new_string guard here: fuzzy_find_and_replace rejects that with a + # richer error (file_preview) this layer cannot produce. + skill_dir, guard = _locate_for_write(name, "patch") + if guard: + return guard + target_label = file_path or "SKILL.md" + if file_path: + target, err = _resolve_supporting_file(skill_dir, file_path) + if err: + return err + else: + target = skill_dir / "SKILL.md" + if not target.exists(): + return _err(f"File not found: {target.relative_to(skill_dir)}") + if read_guard := _background_review_read_before_write_guard(name, target, "patch", target_label): + return read_guard + content = target.read_text(encoding="utf-8") + # Same fuzzy engine as the file patch tool (whitespace/indent/escape normalization, + # block anchors) so minor formatting mismatches don't fail. + from tools.fuzzy_match import fuzzy_find_and_replace + new_content, match_count, _strategy, match_error = fuzzy_find_and_replace( + content, old_string, new_string, replace_all) + if match_error: + with suppress(Exception): + from tools.fuzzy_match import format_no_match_hint + match_error += format_no_match_hint(match_error, match_count, old_string, content) + return _err(match_error) | {"file_preview": _clip(content, 500, "...")} + if err := _validate_content_size(new_content, label=target_label): + return _err(err) + if not file_path and (err := _validate_frontmatter(new_content)): + return _err(f"Patch would break SKILL.md structure: {err}") + if guard := _guarded_write(name, skill_dir, target, "patch", target_label, new_content): + return guard + result = { + "success": True, + "message": f"Patched {target_label} in skill '{name}' ({match_count} replacement{'s' if match_count > 1 else ''}).", + "_change": {"old": _clip(old_string, 200, "…"), "new": _clip(new_string, 200, "…")}} + return _attach_org_note(result, name, skill_dir) + + +def _delete_skill(name: str, absorbed_into: Optional[str] = None) -> Dict[str, Any]: + """Delete a skill. ``absorbed_into``: None = undeclared (legacy, accepted); "" = explicit prune; + "" = absorbed into that umbrella, which must exist (so the model can't claim one).""" + skill_dir, guard = _locate_for_write(name, "delete") + if guard := guard or _curator_consolidation_delete_guard(name, absorbed_into): + return guard + if pinned_err := _pinned_guard(name): + return _err(pinned_err) + absorbed_target = absorbed_into.strip() if isinstance(absorbed_into, str) else "" + if absorbed_target: + if absorbed_target == name: + return _err(f"absorbed_into='{absorbed_target}' cannot equal the skill being deleted.") + if not _find_skill(absorbed_target): + return _err(f"absorbed_into='{absorbed_target}' does not exist. " + f"Create or patch the umbrella skill first, then retry the delete.") + skills_root = _containing_skills_root(skill_dir) + if unsafe := _validate_delete_target(skill_dir): # defense-in-depth before rmtree + return _err(unsafe) + # Curator consolidations must be RECOVERABLE (`hermes curator restore`): archive instead + # of rmtree. Foreground deletes keep hard-delete semantics. + absorbed_note = f" Content absorbed into '{absorbed_target}'." if absorbed_target else "" + if _is_background_review(): + try: + from tools.skill_usage import archive_skill + ok, archive_msg = archive_skill(name) + except Exception as e: + return _err(f"failed to archive '{name}': {e}") + if not ok: + return _err(archive_msg) + return {"success": True, + "message": f"Skill '{name}' archived ({archive_msg}).{absorbed_note}", + "_archived": True} + shutil.rmtree(skill_dir) + _rmdir_if_empty(skill_dir.parent, skills_root) # empty category dir, never the root + return {"success": True, "message": f"Skill '{name}' deleted.{absorbed_note}"} + + +def _rmdir_if_empty(parent: Path, stop: Path) -> None: + if parent != stop and parent.exists() and not any(parent.iterdir()): + parent.rmdir() + + +def _write_file(name: str, file_path: str, file_content: str) -> Dict[str, Any]: + """Add or overwrite a supporting file within any skill directory.""" + if err := _validate_file_path(file_path): + return _err(err) + if not file_content and file_content != "": + return _err("file_content is required.") + if (content_bytes := len(file_content.encode("utf-8"))) > MAX_SKILL_FILE_BYTES: + return _err(f"File content is {content_bytes:,} bytes (limit: {MAX_SKILL_FILE_BYTES:,} " + f"bytes / 1 MiB). Consider splitting into smaller files.") + if err := _validate_content_size(file_content, label=file_path): + return _err(err) + skill_dir, guard = _locate_for_write(name, "write_file", " Create it first with action='create'.") + if guard: + return guard + target, err = _resolve_supporting_file(skill_dir, file_path) + if guard := err or _guarded_write(name, skill_dir, target, "write_file", file_path, file_content): + return guard + result = _attach_org_note({"success": True, "message": f"File '{file_path}' written to skill '{name}'.", + "path": str(target)}, name, skill_dir) + # references/ is where per-session hoarding shows up; surface the sprawl finding on the write + # that crosses the line so the review fork sees it in the same turn. + if file_path.startswith("references/") and (skill_dir / "SKILL.md").exists(): + _attach_lint_findings(result, skill_dir / "SKILL.md") + return result + + +def _remove_file(name: str, file_path: str) -> Dict[str, Any]: + """Remove a supporting file from any skill directory.""" + if err := _validate_file_path(file_path): + return _err(err) + skill_dir, guard = _locate_for_write(name, "remove_file", org_guard=False) + if guard: + return guard + target, err = _resolve_supporting_file(skill_dir, file_path) + if err: + return err + if not target.exists(): # list what IS there so the model can pick the right path + available = [str(f.relative_to(skill_dir)) for subdir in ALLOWED_SUBDIRS + if (skill_dir / subdir).exists() for f in (skill_dir / subdir).rglob("*") if f.is_file()] + return _err(f"File '{file_path}' not found in skill '{name}'.", available_files=available or None) + if read_guard := _background_review_read_before_write_guard(name, target, "remove_file", file_path): + return read_guard + target.unlink() + _rmdir_if_empty(target.parent, skill_dir) + return {"success": True, "message": f"File '{file_path}' removed from skill '{name}'."} + + +# --- Main entry point --------------------------------------------------------- + +# Set while replaying an approved staged skill write so skill_manage() does not re-gate it. +_skill_gate_bypass: "_ctxvars.ContextVar[bool]" = _ctxvars.ContextVar( + "skill_gate_bypass", default=False) + + +def _run_write_gate(build_staging): + """Shared write gate: None to proceed, else a JSON tool result (blocked/staged). + ``build_staging(wa) -> (payload, gist)`` runs only when staging. Fails open if + write_approval cannot be imported.""" + try: + from tools import write_approval as wa + except Exception: + return None # fail open + decision = wa.evaluate_gate(wa.SKILLS) + if decision.allow: + return None + if decision.blocked: + return tool_error(decision.message, success=False) + payload, gist = build_staging(wa) + record = wa.stage_write(wa.SKILLS, payload, summary=gist, origin=wa.current_origin()) + return json.dumps({"success": True, "staged": True, "pending_id": record["id"], + "gist": gist, "message": decision.message}, ensure_ascii=False) + + +def _apply_skill_write_gate(action, name, **payload_kwargs): + """Flat-shape gate: stage the full kwargs so approval can replay them; bypassed during replay.""" + if action not in _ACTION_HANDLERS or _skill_gate_bypass.get(): + return None + def _staging(wa): + payload = {"action": action, "name": name, + **{k: v for k, v in payload_kwargs.items() if v is not None}} + gist_kw = {k: payload_kwargs.get(k) or "" + for k in ("content", "file_path", "old_string", "new_string")} + return payload, wa.skill_gist(action, name, **gist_kw) + return _run_write_gate(_staging) + + +_FLAT_OP_KEYS = ("content", "category", "file_path", "file_content", "old_string", "new_string", + "absorbed_into", "operations") + + +def _skill_manage_from(payload: Dict[str, Any], **extra) -> str: + """Call ``skill_manage`` with the flat-shape fields (and absorbed_into/operations) of ``payload``.""" + return skill_manage( + action=payload.get("action", ""), name=payload.get("name", ""), + replace_all=payload.get("replace_all", False), + **{k: payload.get(k) for k in _FLAT_OP_KEYS}, **extra) + + +def apply_skill_pending(payload: Dict[str, Any]) -> str: + """Replay a staged skill write, bypassing the gate (the /skills approve handler).""" + token = _skill_gate_bypass.set(True) + try: + return _skill_manage_from(payload) + finally: + _skill_gate_bypass.reset(token) + + +# Sync push debounce: a burst of skill_manage writes collapses into one push on a daemon timer. +# One timer per profile home: in a multiplexed process B's write must not cancel A's pending push. +_sync_push_timers: Dict[str, threading.Timer] = {} +_sync_push_lock = threading.Lock() +_SYNC_PUSH_DEBOUNCE_S = 5.0 + + +def _maybe_debounced_sync_push(skill_name: str) -> None: + """Debounced best-effort sync push after a skill write; never blocks the caller. Skills not + opted into sync do nothing (no auth/network); ``maybe_push_skills`` enforces the access gate.""" + try: + from tools.skill_usage import is_sync_enabled + if not is_sync_enabled(skill_name): + return + except Exception: + return + from hermes_constants import hermes_home_key + home_key = hermes_home_key() + # Timer threads start with empty ContextVars; without the scheduling turn's context the push would + # resolve the launch profile's home and credentials instead of the writing profile's. + ctx = _ctxvars.copy_context() + def _fire(): + with suppress(Exception): + from tools.skills_sync_client import maybe_push_skills + maybe_push_skills(message=f"sync: {skill_name}") + with _sync_push_lock: + pending = _sync_push_timers.get(home_key) + if pending is not None: + pending.cancel() # only sets an Event; never raises + timer = threading.Timer(_SYNC_PUSH_DEBOUNCE_S, ctx.run, args=(_fire,)) + timer.daemon = True + _sync_push_timers[home_key] = timer + timer.start() + + +def _act_patch(a): + """Two shapes: old_string/new_string = targeted replacement (validated in _patch_skill so the + tool and the helper give the same guidance); content alone = full rewrite (the old 'edit').""" + if a["content"] and (a["old_string"] or a["new_string"] is not None): + return tool_error("Pass EITHER content (full SKILL.md rewrite) OR " + "old_string/new_string (targeted replacement), not both.", success=False) + if a["content"]: + return _edit_skill(a["name"], a["content"]) + return _patch_skill(a["name"], a["old_string"], a["new_string"], a["file_path"], a["replace_all"]) + + +# action -> handler(args dict) returning a result dict, or a tool_error JSON string for +# argument-shape errors. "edit" is a legacy alias for a full rewrite (not in the schema). +_ACTION_HANDLERS = { + "create": lambda a: _create_skill(a["name"], a["content"], a["category"]), + "edit": lambda a: _edit_skill(a["name"], a["content"]), + "patch": _act_patch, + "delete": lambda a: _delete_skill(a["name"], absorbed_into=a["absorbed_into"]), + "write_file": lambda a: _write_file(a["name"], a["file_path"], a["file_content"]), + "remove_file": lambda a: _remove_file(a["name"], a["file_path"])} +# action -> (arg, is_missing, error) argument-shape checks run before the handler. +_MISSING, _IS_NONE = (lambda v: not v), (lambda v: v is None) +_REQUIRED_ARGS = { + "create": [("content", _MISSING, + "content is required for 'create'. Provide the full SKILL.md text (frontmatter + body).")], + "edit": [("content", _MISSING, + "content is required for a full rewrite. Provide the full updated SKILL.md text.")], + "write_file": [ + ("file_path", _MISSING, "file_path is required for 'write_file'. Example: 'references/api-guide.md'"), + ("file_content", _IS_NONE, "file_content is required for 'write_file'.")], + "remove_file": [("file_path", _MISSING, "file_path is required for 'remove_file'.")]} + + +def _record_success(action, name, result, *, file_path, absorbed_into, task_id, + session_id, ledger_before) -> None: + """Best-effort post-mutation side effects (never break the tool): ledger, prompt-cache + clear, curator telemetry, debounced sync push.""" + with suppress(Exception): + from tools import skill_ledger as _ledger + _post = _find_skill(name) + # delete: consolidation vs prune, and whether the recoverable archive handled it + _evidence = ({"absorbed_into": absorbed_into, "archived": bool(result.get("_archived"))} + if action == "delete" else {}) + _evidence.update({k: v for k, v in (("session_id", session_id), ("file_path", file_path)) if v}) + _ledger.record_mutation( + action, name, before=ledger_before if ledger_before is not None else [], + after_root=_post["path"] if _post else None, evidence=_evidence) + with suppress(Exception): + from agent.prompt_builder import clear_skills_system_prompt_cache + clear_skills_system_prompt_cache(clear_snapshot=True) + # Curator telemetry: only the background review fork marks a skill agent-created + # (foreground creates belong to the user). A recoverable curator archive keeps its + # record as STATE_ARCHIVED (`hermes curator status`/`restore`); only a hard delete forgets. + with suppress(Exception): + from tools.skill_usage import bump_patch, forget, record_created + # During the curator consolidation pass, a verified consolidation must be RECOVERABLE: archival into + # ~/.hermes/skills/.archive/ is documented as the maximum destructive action the curator may take, + # and `hermes curator restore` promises the skill can be brought back. Route through the recoverable + # archive primitive instead of permanent rmtree so a misjudged consolidation can be undone (#29912). + # Foreground, user-directed deletes keep their existing hard-delete semantics. + from tools.skill_provenance import is_background_review + if action == "create": + record_created(name, agent_created=is_background_review(), + task_id=task_id, session_id=session_id) + elif action in {"patch", "edit", "write_file", "remove_file"}: + bump_patch(name, action=action, task_id=task_id, session_id=session_id) + elif action == "delete" and not result.get("_archived"): + forget(name) + # Only AFTER the write gate passed (staged writes returned early): never push un-reviewed content. + with suppress(Exception): + _maybe_debounced_sync_push(name) + + +def skill_manage( + action: str, name: str, content: str = None, category: str = None, file_path: str = None, + file_content: str = None, old_string: str = None, new_string: str = None, + replace_all: bool = False, absorbed_into: str = None, task_id: str = None, + session_id: str = None, operations=None) -> str: + """Dispatch to the action handler -> JSON string. ``operations`` (atomic batch shape, + see _skill_manage_batch) overrides the flat fields.""" + if operations is not None: + return _skill_manage_batch( + operations, default_name=name or None, task_id=task_id, session_id=session_id) + if (preflight := _background_review_preflight(action, name)) is not None: + return json.dumps(preflight, ensure_ascii=False) + # Approval gate: skills are too large to review inline, so they always stage regardless + # of origin; bypassed when replaying an approved staged write. + args = dict(content=content, category=category, file_path=file_path, file_content=file_content, + old_string=old_string, new_string=new_string, replace_all=replace_all, + absorbed_into=absorbed_into) + if (gate_result := _apply_skill_write_gate(action, name, **args)) is not None: + return gate_result + # Ledger pre-capture: telemetry, not a gate — failures must NEVER block the mutation. delete + # destroys the whole package (consolidation may have re-homed support files first), so + # complete it from the newest curator backup or a restore is hollow. + # Audit ledger (tracker #79686 P3): capture the pre-mutation state of the skill directory so every + # mutation — any actor — lands in the append-only JSONL ledger with before/after blobs. + _ledger_before = None + with suppress(Exception): + from tools import skill_ledger as _ledger + _pre = _find_skill(name) + _ledger_before = _ledger.capture_before( + _pre["path"] if _pre else None, complete_package=(action == "delete"), skill=name) + for arg, missing, message in _REQUIRED_ARGS.get(action, ()): + if missing(args[arg]): + return tool_error(message, success=False) + handler = _ACTION_HANDLERS.get(action, lambda a: _err( + f"Unknown action '{action}'. Use: create, edit, patch, delete, write_file, remove_file")) + result = handler({"name": name, **args}) + if isinstance(result, str): + return result # tool_error JSON for argument-shape problems (patch) + if result.get("success"): + _record_success( + action, name, result, file_path=file_path, absorbed_into=absorbed_into, + task_id=task_id, session_id=session_id, ledger_before=_ledger_before) + return json.dumps(result, ensure_ascii=False) + + +# --- OpenAI Function-Calling Schema ------------------------------------------- + +def _skill_manage_description(create_dir: str) -> str: + return ( + "Create, update, or delete skills — your procedural memory for " + "recurring task types. The call is an operations array (a single " + "edit is a list of one); it applies atomically — any failure rolls " + "every touched skill back. Ops: create (full SKILL.md; lands in " + f"{create_dir}; must precede that skill's other " + "ops), patch (targeted old_string/new_string fix — preferred; " + "content alone REPLACES the whole file, read it via skill_view() " + "first), write_file/remove_file (supporting files), delete (sole " + "op only). Existing skills are modified wherever they live. Keep " + "the description's first 57 chars a self-contained trigger: 'Use " + "when . .' Write lessons, not logs: " + "imperative rule + why, no PR numbers/dates/incident narration, one " + "rule per lesson, references/ named by topic (extend before adding). " + "skill_view() shows format conventions." + ) + + +def _skill_manage_schema_overrides() -> dict: + """Rebuild the create-dir hint from the ACTIVE profile at every get_definitions(): the + multiplexed gateway serves every profile from one process, so a path baked in at import + would name the launch profile's skills dir for everyone else (#95685).""" + return {"description": _skill_manage_description(_display_create_dir())} + + +SKILL_MANAGE_SCHEMA = { + "name": "skill_manage", + # ONE advertised call shape (memory-tool pattern): the call IS an operations + # array. The legacy flat shape (top-level action/name/content/...) is still + # ACCEPTED for old transcripts and staged-write replay, but not advertised. + "description": _skill_manage_description("the profile's skills.create_dir"), + "parameters": { + "type": "object", + "properties": { + "operations": { + "type": "array", + "description": "Ordered ops; each names its target skill.", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": ( + "Skill name (lowercase, hyphens/underscores, " + "max 64 chars); an existing skill's name " + "unless creating." + ) + }, + "action": { + "type": "string", + "enum": ["create", "patch", "delete", "write_file", "remove_file"] + }, + "content": { + "type": "string", + "description": ( + "Full SKILL.md text (YAML frontmatter + " + "markdown body) for create, or a full " + "rewrite on patch." + ) + }, + "category": { + "type": "string", + "description": "Optional category subdir for create (e.g. 'devops')." + }, + # patch args: same fuzzy-matching semantics as the + # `patch` tool — teach only skill-specific facts here. + "old_string": { + "type": "string", + "description": "Text to find (patch; same matching semantics as the patch tool)." + }, + "new_string": { + "type": "string", + "description": "Replacement (patch); empty string deletes the match." + }, + "replace_all": { + "type": "boolean", + "description": "patch: replace all occurrences (default false)." + }, + "file_path": { + "type": "string", + "description": ( + "Path RELATIVE to the skill's own directory, " + "e.g. 'references/api.md' — no leading slash, " + "never absolute. write_file/remove_file: " + "required; first segment references/, " + "templates/, scripts/, or assets/. patch: " + "optional (default SKILL.md)." + ) + }, + "file_content": { + "type": "string", + "description": "Content for write_file." + } + }, + "required": ["name", "action"] + } + }, + # Also accepted, never advertised: the legacy flat single-op fields, and + # `absorbed_into` on delete ops (curator-only vocabulary; the curator's + # prompt documents it and the delete guard's error re-teaches it). + }, + "required": ["operations"], + }, +} + + +# --- Registry --- +from tools.registry import registry, tool_error + +registry.register( + name="skill_manage", toolset="skills", schema=SKILL_MANAGE_SCHEMA, emoji="📝", + handler=lambda args, **kw: _skill_manage_from( + args, task_id=kw.get("task_id"), session_id=kw.get("session_id")), + dynamic_schema_overrides=_skill_manage_schema_overrides) + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. + + +_PLUGIN_COMPAT_LAZY = { + 'mark_background_review_skill_read': ('tools.skill_manager_guards', 'mark_background_review_skill_read'), +} + + +def __getattr__(name): # PEP 562 — lazy so no import cycles + target = _PLUGIN_COMPAT_LAZY.get(name) + if target is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + import importlib + from hermes_cli.plugin_compat import warn_once + warn_once(__name__, name, *target) + return getattr(importlib.import_module(target[0]), target[1]) +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/skillevaluator_scan.py b/tools/skillevaluator_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..f48142c20a229dafaa0975f866e06e24c2229288 --- /dev/null +++ b/tools/skillevaluator_scan.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Advisory NVIDIA SkillEvaluator Tier 1 scan for skill installs — alongside (never instead of) skills_guard, +the enforcement layer. Contract: warn, don't block (the upstream PII scanner false-positives on +``git@github.com`` / ``op://``); prompt only for secrets-class criticals (``--force`` / non-interactive proceed +with a loud warning); a missing/crashing/timed-out/unparseable scanner is a no-op. Toggle +``skills.tier1_advisory`` (default on). Binary: ``uv tool install --python 3.13 +"skillevaluator @ git+https://github.com/NVIDIA/SkillEvaluator.git@v0.1.0"``.""" + +from __future__ import annotations + +import json +import logging +import shutil +import subprocess +import tempfile +from dataclasses import dataclass, field +from pathlib import Path +from typing import List + +logger = logging.getLogger(__name__) + +SCANNER_BIN = "skillevaluator" +# Keyless, deterministic checks (schema/quality are index-pipeline hygiene, not install-time signal). `security` +# invokes NVIDIA SkillSpector (static rules, no LLM); when absent it reports status="incomplete". +TIER1_CHECKS = "pii,unicode,lint,license,security" +SCAN_TIMEOUT_SECONDS = 120 + +# pii_patterns.yaml categories indicating a possible REAL credential (not PII hygiene) — the only prompt-worthy ones. +SECRETS_CLASS_CHECKS = frozenset({"database_credentials", "hardcoded_secrets", "jwt_tokens", "webhook_urls", + "aws_identifiers", "github_tokens", "private_keys"}) + + +@dataclass +class Tier1Finding: + check: str # e.g. "emails", "database_credentials" + validator: str # e.g. "PII Scan" + severity: str # "critical" | "high" | "medium" | "low" | "info" + message: str + file: str = "" + line: int = 0 + suggestion: str = "" + + @property + def is_secrets_class(self) -> bool: + return self.check in SECRETS_CLASS_CHECKS + + def location(self) -> str: + return f"{self.file}:{self.line}" if self.file and self.line else self.file or "?" + + +@dataclass +class Tier1Report: + available: bool # scanner ran and produced a report + passed: bool = True + findings: List[Tier1Finding] = field(default_factory=list) + incomplete_checks: List[str] = field(default_factory=list) + error: str = "" # why the scan is unavailable (debug only) + + @property + def advisory_findings(self) -> List[Tier1Finding]: + return [f for f in self.findings if not f.is_secrets_class] + + @property + def secrets_findings(self) -> List[Tier1Finding]: + return [f for f in self.findings if f.is_secrets_class] + + +def tier1_advisory_enabled() -> bool: + """``skills.tier1_advisory`` (default True; safe because the scan is a no-op without the binary).""" + try: + from hermes_cli.config import load_config + skills_cfg = load_config().get("skills") or {} + value = skills_cfg.get("tier1_advisory", True) if isinstance(skills_cfg, dict) else True + return value.strip().lower() not in ("false", "0", "no", "off") if isinstance(value, str) else bool(value) + except Exception: + return True + + +def _parse_report(report: dict) -> Tier1Report: + """Reduce a SkillEvaluator JSON report to install-relevant findings. Findings from ``status == "incomplete"`` + validators are kept (partial evidence is evidence) but excluded from the pass/fail signal.""" + findings: List[Tier1Finding] = [] + incomplete: List[str] = [] + failed = False + for res in report.get("results", []) or []: + validator = str(res.get("validator", "unknown")) + if str(res.get("status", "")).lower() == "incomplete": + incomplete.append(validator) + else: + failed = failed or not res.get("passed", True) + findings.extend(Tier1Finding( + check=str(f.get("check_name", "")), validator=validator, severity=str(f.get("severity", "info")).lower(), + message=str(f.get("message", ""))[:200], file=str(f.get("file_path", "")), + line=int(f.get("line_number") or 0), suggestion=str(f.get("suggestion", ""))[:200]) + for f in res.get("findings", []) or [] if isinstance(f, dict)) + return Tier1Report(available=True, passed=not failed and not findings, findings=findings, + incomplete_checks=incomplete) + + +def run_tier1_scan(skill_dir: Path, timeout: int = SCAN_TIMEOUT_SECONDS) -> Tier1Report: + """Run SkillEvaluator Tier 1 over one skill dir; any failure returns ``available=False``, never raises.""" + unavailable = lambda why: Tier1Report(available=False, error=why) # noqa: E731 + if shutil.which(SCANNER_BIN) is None: + return unavailable("scanner not on PATH") + with tempfile.TemporaryDirectory(prefix="se-tier1-") as outdir: + try: + subprocess.run([SCANNER_BIN, "validate", str(skill_dir), "--checks", TIER1_CHECKS, "--no-dedup", + "-r", "json", "-o", outdir], capture_output=True, text=True, encoding="utf-8", errors="replace", + stdin=subprocess.DEVNULL, timeout=timeout) + except subprocess.TimeoutExpired: + return unavailable(f"scan timed out after {timeout}s") + except OSError as exc: + return unavailable(f"scanner failed to launch: {exc}") + if not (reports := sorted(Path(outdir).glob("skillevaluator-output-*.json"))): + return unavailable("scanner produced no JSON report") + try: + parsed = json.loads(reports[-1].read_text(encoding="utf-8")) + except (json.JSONDecodeError, OSError) as exc: + return unavailable(f"unparseable report: {exc}") + return _parse_report(parsed) if isinstance(parsed, dict) else unavailable("unexpected report shape") + + +def format_tier1_report(report: Tier1Report, limit: int = 10) -> str: + """Plain-text advisory summary for console display ("" when unavailable).""" + if not report.available: + return "" + lines: List[str] = [] + if not report.findings: + lines.append("SkillEvaluator Tier 1: no findings from completed checks." if report.incomplete_checks + else "SkillEvaluator Tier 1: no findings.") + else: + lines.append(f"SkillEvaluator Tier 1 (advisory): {len(report.findings)} finding(s) — informational, " + "verify before relying on this skill.") + shown = report.secrets_findings + report.advisory_findings + lines.extend(f" [{'SECRETS' if f.is_secrets_class else f.severity.upper()}] {f.location()} — {f.message}" + for f in shown[:limit]) + if len(shown) > limit: + lines.append(f" … and {len(shown) - limit} more") + if report.incomplete_checks: + lines.append(f" (not run: {', '.join(report.incomplete_checks)} — no opinion from these checks)") + return "\n".join(lines) + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. +from typing import Optional # noqa: F401,E402 + +SCANNER_NAME = "skillevaluator-tier1" + +def scanner_available() -> bool: + return shutil.which(SCANNER_BIN) is not None +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/skills_ast_audit.py b/tools/skills_ast_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..ddc09004ee21fc6222157bd4e5c643401e645e7f --- /dev/null +++ b/tools/skills_ast_audit.py @@ -0,0 +1,92 @@ +"""AST-level deep audit for skill Python files — opt-in diagnostic (``hermes skills audit --deep``), not a +security gate (SECURITY.md §2.4). Flags dynamic import / attribute access for human review; every pattern has +legitimate uses, so findings are hints, not verdicts.""" + +from __future__ import annotations + +import ast +from contextlib import suppress +from pathlib import Path +from typing import List, Tuple + +# (file, line, pattern_id, description) +Finding = Tuple[str, int, str, str] + +_IGNORED_DIRS = {"__pycache__", ".venv", "venv", "node_modules"} +# builtin name -> (index of the argument that must be a literal, pattern_id, description) +_DYNAMIC_CALLS = {"__import__": (0, "dynamic_import_computed", "__import__ with non-literal module name"), + "getattr": (1, "dynamic_getattr", "getattr with non-literal attribute name")} + + +def _is_importlib(name: str) -> bool: + return name == "importlib" or name.startswith("importlib.") + + +def _scan_source(content: str, rel_path: str) -> List[Finding]: + try: + tree = ast.parse(content) + except (SyntaxError, ValueError, RecursionError): + return [] + findings: List[Finding] = [] + hit = lambda node, pid, desc: findings.append((rel_path, node.lineno, pid, desc)) # noqa: E731 + + class V(ast.NodeVisitor): + def visit_Call(self, node): + f = node.func + if isinstance(f, ast.Attribute) and f.attr == "import_module": + hit(node, "dynamic_import", "importlib.import_module() — loads arbitrary modules at runtime") + elif isinstance(f, ast.Name) and f.id in _DYNAMIC_CALLS: + arg_index, pid, desc = _DYNAMIC_CALLS[f.id] + if len(node.args) > arg_index and not isinstance(node.args[arg_index], ast.Constant): + hit(node, pid, desc) + self.generic_visit(node) + + def visit_Subscript(self, node): + if (isinstance(node.value, ast.Attribute) and node.value.attr == "__dict__" + and not isinstance(node.slice, ast.Constant)): + hit(node, "dict_access", "__dict__[] — dynamic attribute access") + self.generic_visit(node) + + def visit_Import(self, node): + for a in node.names: + if _is_importlib(a.name): + hit(node, "importlib_import", f"import {a.name} — enables dynamic module loading") + self.generic_visit(node) + + def visit_ImportFrom(self, node): + if _is_importlib(node.module or ""): + hit(node, "importlib_import", f"from {node.module} import ... — enables dynamic module loading") + self.generic_visit(node) + + with suppress(RecursionError, ValueError, RuntimeError): # hostile input: keep what was collected so far + V().visit(tree) + return findings + + +def _scan_file(py: Path, rel: str) -> List[Finding]: + try: + return _scan_source(py.read_text(encoding="utf-8", errors="replace"), rel) + except OSError: + return [] + + +def ast_scan_path(path: Path) -> List[Finding]: + """Scan one .py file or every .py under a directory; [] for non-Python/missing paths.""" + if path.is_file(): + return _scan_file(path, path.name) if path.suffix.lower() == ".py" else [] + return [f for py in sorted(path.rglob("*.py")) if not set(py.parent.parts) & _IGNORED_DIRS + for f in _scan_file(py, py.relative_to(path).as_posix())] if path.is_dir() else [] + + +def format_ast_report(findings: List[Finding], skill_name: str = "") -> str: + """Plain-text (Rich-markup-free) report grouped by file.""" + header = f"AST deep scan: {skill_name}" if skill_name else "AST deep scan" + if not findings: + return f"{header}\n No dynamic import/access patterns detected." + lines, current = [header, f" {len(findings)} finding(s):"], None + for f, line, pid, desc in sorted(findings): + if f != current: + current = f + lines.append(f" {f}") + lines.append(f" L{line} {pid} — {desc}") + return "\n".join(lines + ["", " Note: diagnostic hints for human review, not security verdicts."]) diff --git a/tools/skills_hub.py b/tools/skills_hub.py new file mode 100644 index 0000000000000000000000000000000000000000..6fafdddabdbcfcd12208e062dc74ca45cb53f8d8 --- /dev/null +++ b/tools/skills_hub.py @@ -0,0 +1,454 @@ +#!/usr/bin/env python3 +""" +Skills Hub — hub state management and the public facade for the source adapters. + +Library module (not an agent tool). Owns the hub paths, guarded HTTP, index +cache, lock file, taps and audit log. Install/uninstall/update live in +``skills_hub_install``, the index fetch/source router/search in +``skills_hub_search``, and the adapters in the other ``tools.skills_hub_*`` +siblings; import each name from its defining module. + +Used by hermes_cli/skills_hub.py for CLI commands and the /skills slash command. +""" + +import json +import logging +import time +from contextlib import ExitStack, contextmanager +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Dict, Iterator, List, Optional +from urllib.parse import urljoin + +import httpx + +from hermes_constants import get_hermes_home +from tools.url_safety import is_safe_url +from tools.website_policy import check_website_access +from tools.skills_hub_models import _normalize_lock_install_path, _validate_skill_name + +logger = logging.getLogger(__name__) + + +# --------------------------------------------------------------------------- +# Paths +# --------------------------------------------------------------------------- +# Resolved per-call (not frozen at import) so the profile override is honored; +# import-time constants leaked across profiles in single-process multi-profile +# runtimes. The path names (SKILLS_DIR, ...) resolve live via __getattr__ below. + +INDEX_CACHE_TTL = 3600 # 1 hour + + +def _path_resolver(name: str, parent: str, leaf: str): + """Resolver for hub path ``/``: a test-injected real module attribute + (patch.object/monkeypatch on SKILLS_DIR etc.) wins over live resolution.""" + def resolve() -> Path: + forced = globals().get(name) + return Path(forced) if forced is not None else _DYNAMIC_PATH_RESOLVERS[parent]() / leaf + resolve.__name__ = f"_{name.lower()}" + return resolve + + +def _hermes_home() -> Path: + return get_hermes_home() + + +_skills_dir = _path_resolver("SKILLS_DIR", "HERMES_HOME", "skills") +_hub_dir = _path_resolver("HUB_DIR", "SKILLS_DIR", ".hub") +_lock_file = _path_resolver("LOCK_FILE", "HUB_DIR", "lock.json") +_quarantine_dir = _path_resolver("QUARANTINE_DIR", "HUB_DIR", "quarantine") +_audit_log = _path_resolver("AUDIT_LOG", "HUB_DIR", "audit.log") +_taps_file = _path_resolver("TAPS_FILE", "HUB_DIR", "taps.json") +_index_cache_dir = _path_resolver("INDEX_CACHE_DIR", "HUB_DIR", "index-cache") +_DYNAMIC_PATH_RESOLVERS = {"HERMES_HOME": _hermes_home, **{ + r.__name__[1:].upper(): r + for r in (_skills_dir, _hub_dir, _lock_file, _quarantine_dir, _audit_log, _taps_file, _index_cache_dir) +}} + + +def __getattr__(name: str): + """Resolve legacy path constants dynamically (PEP 562) so they reflect the + active profile override; a test's patch.object-set real attribute shadows it.""" + resolver = _DYNAMIC_PATH_RESOLVERS.get(name) + if resolver is not None: + return resolver() + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +# --------------------------------------------------------------------------- +# Install-path safety + guarded HTTP +# --------------------------------------------------------------------------- + +_REDIRECT_STATUS_CODES = {301, 302, 303, 307, 308} +_MAX_SKILL_FETCH_REDIRECTS = 5 + + +def _ssrf_safe_http_get(url: str, *, timeout: int = 20) -> httpx.Response: + """Fetch one URL with connect-time SSRF validation and no automatic redirects.""" + from tools.url_safety import create_ssrf_safe_client + + with create_ssrf_safe_client(timeout=timeout, follow_redirects=False) as client: + return client.get(url) + + +def _guarded_http_get(url: str, *, timeout: int = 20) -> Optional[httpx.Response]: + """Fetch a URL with SSRF and redirect-target validation (each hop re-checked).""" + from tools.url_safety import SSRFConnectionBlocked + + current_url = url + + for _ in range(_MAX_SKILL_FETCH_REDIRECTS + 1): + if not is_safe_url(current_url): + logger.warning("Blocked unsafe Skills Hub URL: %s", current_url) + return None + + blocked = check_website_access(current_url) + if blocked: + logger.info( + "Blocked Skills Hub fetch for %s by rule %s", + blocked["host"], + blocked["rule"], + ) + return None + + try: + resp = _ssrf_safe_http_get(current_url, timeout=timeout) + except (SSRFConnectionBlocked, httpx.HTTPError) as exc: + logger.debug("Skills Hub fetch failed for %s: %s", current_url, exc) + return None + + if resp.status_code in _REDIRECT_STATUS_CODES: + location = getattr(resp, "headers", {}).get("location") + if not location: + return None + current_url = urljoin(current_url, location) + continue + + return resp + + logger.warning("Skills Hub fetch exceeded redirect limit for %s", url) + return None + + +@contextmanager +def _guarded_http_stream( + url: str, + *, + params: Optional[Dict[str, str]] = None, + timeout: int = 20, +) -> Iterator[Optional[httpx.Response]]: + """Stream one response with bounded, policy-checked redirects.""" + from tools.url_safety import SSRFConnectionBlocked, create_ssrf_safe_client + + current_url = url + current_params = params + response: Optional[httpx.Response] = None + stack = ExitStack() + + try: + for _ in range(_MAX_SKILL_FETCH_REDIRECTS + 1): + if not is_safe_url(current_url): + logger.warning("Blocked unsafe Skills Hub URL: %s", current_url) + response = None + break + + blocked = check_website_access(current_url) + if blocked: + logger.info( + "Blocked Skills Hub fetch for %s by rule %s", + blocked["host"], + blocked["rule"], + ) + response = None + break + + stack.close() + stack = ExitStack() + try: + client = stack.enter_context( + create_ssrf_safe_client(timeout=timeout, follow_redirects=False) + ) + response = stack.enter_context( + client.stream("GET", current_url, params=current_params) + ) + except (SSRFConnectionBlocked, httpx.HTTPError) as exc: + logger.debug("Skills Hub stream failed for %s: %s", current_url, exc) + response = None + break + + if response.status_code not in _REDIRECT_STATUS_CODES: + break + + location = response.headers.get("location") + if not location: + response = None + break + current_url = urljoin(current_url, location) + current_params = None + else: + logger.warning("Skills Hub fetch exceeded redirect limit for %s", url) + response = None + + yield response + finally: + stack.close() + + +# --------------------------------------------------------------------------- +# Shared index cache (used by every adapter) +# --------------------------------------------------------------------------- + +def _read_json_if_fresh(path: Path, ttl: float) -> Optional[Any]: + """Parsed JSON from ``path`` when it exists and is younger than ``ttl`` seconds.""" + try: + if time.time() - path.stat().st_mtime > ttl: + return None + return json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return None + + +def _read_index_cache(key: str) -> Optional[Any]: + return _read_json_if_fresh(_index_cache_dir() / f"{key}.json", INDEX_CACHE_TTL) + + +def _write_index_cache(key: str, data: Any) -> None: + index_cache_dir = _index_cache_dir() + index_cache_dir.mkdir(parents=True, exist_ok=True) + # Cache files hold unvetted community text (possible prompt injection); + # a .ignore keeps ripgrep and .ignore-aware tools out of the hub dir. + ignore_file = _hub_dir() / ".ignore" + if not ignore_file.exists(): + try: + ignore_file.write_text("# Exclude hub internals from search tools\n*\n", encoding="utf-8") + except OSError: + pass + try: + (index_cache_dir / f"{key}.json").write_text( + json.dumps(data, ensure_ascii=False, default=str), encoding="utf-8" + ) + except OSError as e: + logger.debug("Could not write cache: %s", e) + + +# --------------------------------------------------------------------------- +# Hub state files: lock.json, taps.json, audit.log +# --------------------------------------------------------------------------- + +class _JsonStateFile: + """A JSON file under the hub dir with a fixed empty shape (``EMPTY``, deep-copied + on every miss/corrupt read); ``DEFAULT_PATH`` is the hub path resolver.""" + + EMPTY: dict = {} + DEFAULT_PATH: Any = None + + def __init__(self, path: Optional[Path] = None): + self.path = path if path is not None else type(self).DEFAULT_PATH() + + def _read(self) -> dict: + try: + return json.loads(self.path.read_text(encoding="utf-8")) + except (json.JSONDecodeError, OSError): + return json.loads(json.dumps(self.EMPTY)) + + def _write(self, data: dict, **dumps_kwargs) -> None: + self.path.parent.mkdir(parents=True, exist_ok=True) + self.path.write_text(json.dumps(data, indent=2, **dumps_kwargs) + "\n", encoding="utf-8") + + +class HubLockFile(_JsonStateFile): + """skills/.hub/lock.json — provenance of installed hub skills.""" + + EMPTY = {"version": 1, "installed": {}} + DEFAULT_PATH = staticmethod(_lock_file) + + def load(self) -> dict: + return self._read() + + def save(self, data: dict) -> None: + self._write(data, ensure_ascii=False) + + def record_install( + self, + name: str, + source: str, + identifier: str, + trust_level: str, + scan_verdict: str, + skill_hash: str, + install_path: str, + files: List[str], + metadata: Optional[Dict[str, Any]] = None, + scan_provenance: Optional[Dict[str, Any]] = None, + ) -> None: + # Validate name and install-path SHAPE at write time: a poisoned lock + # entry is the precondition for the uninstall_skill rmtree-escape. + safe_name = _validate_skill_name(name) + safe_install_path = _normalize_lock_install_path(install_path, safe_name) + data = self.load() + now = datetime.now(timezone.utc).isoformat() + data["installed"][safe_name] = { + "source": source, + "identifier": identifier, + "trust_level": trust_level, + "scan_verdict": scan_verdict, + "content_hash": skill_hash, + "install_path": safe_install_path, + "files": files, + "metadata": metadata or {}, + "scan_provenance": scan_provenance or {}, + "installed_at": now, + "updated_at": now, + } + self.save(data) + + def record_uninstall(self, name: str) -> None: + data = self.load() + data["installed"].pop(name, None) + self.save(data) + + def get_installed(self, name: str) -> Optional[dict]: + return self.load()["installed"].get(name) + + def list_installed(self) -> List[dict]: + return [{"name": name, **entry} for name, entry in self.load()["installed"].items()] + + +class TapsManager(_JsonStateFile): + """skills/.hub/taps.json — custom GitHub repo sources.""" + + EMPTY = {"taps": []} + DEFAULT_PATH = staticmethod(_taps_file) + + def load(self) -> List[dict]: + return self._read().get("taps", []) + + def save(self, taps: List[dict]) -> None: + self._write({"taps": taps}) + + def add(self, repo: str, path: str = "skills/") -> bool: + """Add a tap. Returns False if already exists.""" + taps = self.load() + if any(t["repo"] == repo for t in taps): + return False + taps.append({"repo": repo, "path": path}) + self.save(taps) + return True + + def remove(self, repo: str) -> bool: + """Remove a tap by repo name. Returns False if not found.""" + taps = self.load() + new_taps = [t for t in taps if t["repo"] != repo] + if len(new_taps) == len(taps): + return False + self.save(new_taps) + return True + + list_taps = load + + +def append_audit_log(action: str, skill_name: str, source: str, + trust_level: str, verdict: str, extra: str = "") -> None: + """Append one space-separated line to the audit log (best-effort).""" + audit_log = _audit_log() + audit_log.parent.mkdir(parents=True, exist_ok=True) + timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + parts = [timestamp, action, skill_name, f"{source}:{trust_level}", verdict] + if extra: + parts.append(extra) + try: + with open(audit_log, "a", encoding="utf-8") as f: + f.write(" ".join(parts) + "\n") + except OSError as e: + logger.debug("Could not write audit log: %s", e) + + +# --------------------------------------------------------------------------- +# Hub operations (high-level) +# --------------------------------------------------------------------------- + +def ensure_hub_dirs() -> None: + """Create the .hub directory structure if it doesn't exist.""" + _hub_dir().mkdir(parents=True, exist_ok=True) + _quarantine_dir().mkdir(exist_ok=True) + _index_cache_dir().mkdir(exist_ok=True) + for path, initial in ( + (_lock_file(), '{"version": 1, "installed": {}}\n'), + (_audit_log(), ""), + (_taps_file(), '{"taps": []}\n'), + ): + if not path.exists(): + path.write_text(initial, encoding="utf-8") + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. +from abc import ABC # noqa: F401,E402 +from pathlib import PurePosixPath # noqa: F401,E402 +from typing import Tuple # noqa: F401,E402 +from typing import Union # noqa: F401,E402 +from abc import abstractmethod # noqa: F401,E402 +from dataclasses import dataclass # noqa: F401,E402 +from dataclasses import field # noqa: F401,E402 +import hashlib # noqa: F401,E402 +import os # noqa: F401,E402 +from urllib.parse import quote # noqa: F401,E402 +import re # noqa: F401,E402 +import shutil # noqa: F401,E402 +import subprocess # noqa: F401,E402 +from urllib.parse import unquote # noqa: F401,E402 +from urllib.parse import urlparse # noqa: F401,E402 +from urllib.parse import urlsplit # noqa: F401,E402 +from urllib.parse import urlunparse # noqa: F401,E402 +import yaml # noqa: F401,E402 + + +_PLUGIN_COMPAT_LAZY = { + 'BrowseShSource': ('tools.skills_hub_sources', 'BrowseShSource'), + 'ClawHubSource': ('tools.skills_hub_clawhub', 'ClawHubSource'), + 'GITHUB_TAP_PROVIDERS': ('tools.skills_hub_github', 'GITHUB_TAP_PROVIDERS'), + 'GitHubAuth': ('tools.skills_hub_github', 'GitHubAuth'), + 'GitHubSource': ('tools.skills_hub_github', 'GitHubSource'), + 'HERMES_INDEX_TTL': ('tools.skills_hub_search', 'HERMES_INDEX_TTL'), + 'HERMES_INDEX_URL': ('tools.skills_hub_search', 'HERMES_INDEX_URL'), + 'HermesIndexSource': ('tools.skills_hub_official', 'HermesIndexSource'), + 'LobeHubSource': ('tools.skills_hub_sources', 'LobeHubSource'), + 'OptionalSkillSource': ('tools.skills_hub_official', 'OptionalSkillSource'), + 'ScanResult': ('tools.skills_guard', 'ScanResult'), + 'SkillBundle': ('tools.skills_hub_models', 'SkillBundle'), + 'SkillMeta': ('tools.skills_hub_models', 'SkillMeta'), + 'SkillSource': ('tools.skills_hub_models', 'SkillSource'), + 'SkillsShSource': ('tools.skills_hub_skillssh', 'SkillsShSource'), + 'TRUSTED_REPOS': ('tools.skills_guard', 'TRUSTED_REPOS'), + 'UrlSource': ('tools.skills_hub_sources', 'UrlSource'), + 'WellKnownSkillSource': ('tools.skills_hub_sources', 'WellKnownSkillSource'), + 'bundle_content_hash': ('tools.skills_hub_install', 'bundle_content_hash'), + 'check_for_skill_updates': ('tools.skills_hub_install', 'check_for_skill_updates'), + 'content_hash': ('tools.skills_guard', 'content_hash'), + 'create_source_router': ('tools.skills_hub_search', 'create_source_router'), + 'github_provider_for': ('tools.skills_hub_github', 'github_provider_for'), + 'install_from_quarantine': ('tools.skills_hub_install', 'install_from_quarantine'), + 'is_excluded_skill_path': ('agent.skill_utils', 'is_excluded_skill_path'), + 'parallel_search_sources': ('tools.skills_hub_search', 'parallel_search_sources'), + 'quarantine_bundle': ('tools.skills_hub_install', 'quarantine_bundle'), + 'source_url_for_bundle': ('tools.skills_hub_models', 'source_url_for_bundle'), + 'unified_search': ('tools.skills_hub_search', 'unified_search'), + 'uninstall_skill': ('tools.skills_hub_install', 'uninstall_skill'), + 'windows_hide_flags': ('hermes_cli._subprocess_compat', 'windows_hide_flags'), +} + +_plugin_compat_prev_getattr = __getattr__ + + +def __getattr__(name): # PEP 562 — chained onto the module's own __getattr__ + target = _PLUGIN_COMPAT_LAZY.get(name) + if target is None: + return _plugin_compat_prev_getattr(name) + import importlib + from hermes_cli.plugin_compat import warn_once + warn_once(__name__, name, *target) + return getattr(importlib.import_module(target[0]), target[1]) +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/skills_hub_install.py b/tools/skills_hub_install.py new file mode 100644 index 0000000000000000000000000000000000000000..0272e51ac406f531fe1a65269624b83657d993be --- /dev/null +++ b/tools/skills_hub_install.py @@ -0,0 +1,304 @@ +"""Skills Hub install/uninstall/update operations: quarantine staging, install- +target safety (symlink/junction, category-bucket and nested-skill checks), +lock-file-backed uninstall, bundle hashing and upstream update checks. + +Split out of ``tools/skills_hub.py``; hub state (paths, ``HubLockFile``, audit log) +is still read from there at call time. +""" + +from __future__ import annotations + +import logging +import hashlib +import shutil +from pathlib import Path +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple +from agent.skill_utils import is_excluded_skill_path +from tools.skills_guard import ScanResult, content_hash +from tools.skills_hub_github import GitHubAuth +from tools.skills_hub_models import ( + SkillBundle, SkillSource, _normalize_lock_install_path, _validate_bundle_rel_path, + _validate_install_parent_path, _validate_skill_name, +) + +if TYPE_CHECKING: # origin class; runtime use is via the lazy origin import + from tools.skills_hub import HubLockFile + +# Log-record parity with the origin module. +logger = logging.getLogger("tools.skills_hub") + + +def _is_path_redirect(path: Path) -> bool: + """True when ``path`` is a symlink or (on Windows) a directory junction — + either lets a writer in ``skills/`` redirect a later ``rmtree`` outside it. + ``is_junction`` only exists on Python 3.12+ Windows; gate with ``hasattr``.""" + return path.is_symlink() or (hasattr(path, "is_junction") and path.is_junction()) + + +def _resolve_lock_install_path(install_path: str, skill_name: str) -> Path: + """Resolve a lock-file install path without allowing escapes from ``SKILLS_DIR``. + + Walks component-by-component refusing symlink/junction redirects (which + ``Path.resolve`` would silently follow), then rejects both escape-out and + ``resolved == SKILLS_DIR`` — an empty/``"."`` install_path resolves to the + skills root and ``rmtree`` there would wipe every installed skill. + """ + from tools.skills_hub import _skills_dir + normalized = _normalize_lock_install_path(install_path, skill_name) + target = skills_dir = _skills_dir() + skills_root = skills_dir.resolve() + for part in normalized.split("/"): + target = target / part + if _is_path_redirect(target): + raise ValueError(f"Unsafe install path: {install_path}") + target = target.resolve() + if target == skills_root or not target.is_relative_to(skills_root): + raise ValueError(f"Unsafe install path: {install_path}") + return target + + +def quarantine_bundle(bundle: SkillBundle) -> Path: + """Write a skill bundle to the quarantine directory for scanning.""" + from tools.skills_hub import _quarantine_dir, ensure_hub_dirs + ensure_hub_dirs() + skill_name = _validate_skill_name(bundle.name) + # Validate every path before touching disk so a bad member aborts cleanly. + validated_files = [(_validate_bundle_rel_path(rel_path), content) for rel_path, content in bundle.files.items()] + dest = _quarantine_dir() / skill_name + if dest.exists(): + shutil.rmtree(dest) + dest.mkdir(parents=True) + for rel_path, file_content in validated_files: + file_dest = dest.joinpath(*rel_path.split("/")) + file_dest.parent.mkdir(parents=True, exist_ok=True) + if isinstance(file_content, bytes): + file_dest.write_bytes(file_content) + else: + file_dest.write_text(file_content, encoding="utf-8") + return dest + + +def _category_skill_dirs(directory: Path) -> List[str]: + """Names of non-hidden child dirs holding at least one active SKILL.md + anywhere below (nested layouts like ``mlops/training/`` count). + + Vendored/cache/progressive-disclosure paths are pruned via + :func:`is_excluded_skill_path` so a lone ``node_modules`` or + ``references/pkg/SKILL.md`` does not make the directory a category. + Shared with ``hermes_cli.skills_hub._existing_categories``. + """ + return [ + entry.name for entry in directory.iterdir() + if entry.is_dir() and not entry.name.startswith(".") and any( + not is_excluded_skill_path(skill_md.relative_to(directory), root=directory) + for skill_md in entry.rglob("SKILL.md") + ) + ] + + +def _check_install_target(install_dir: Path) -> None: + """Raise ValueError when installing at ``install_dir`` would destroy other skills. + + - Nesting inside an existing skill dir (``--category ``) + would make a later update/uninstall of the outer skill rmtree the inner one. + - A stray regular file at the target: rmtree would raise NotADirectoryError. + - A category bucket (dir without SKILL.md that holds other skills) must never + be silently wiped; a dir that directly contains SKILL.md is an existing + install and stays overwritable (hub installs are lock-guarded in do_install). + """ + from tools.skills_hub import _skills_dir + # Refuse to nest a skill inside an existing skill directory. Installing with ``--category + # `` would create a hybrid skill-plus-category directory; a later update or + # uninstall of the outer skill would then rmtree the inner one — the sibling case of the category-bucket + # wipe reported in issue #75983. + skills_root = _skills_dir().resolve() + ancestor = install_dir.parent + while ancestor != skills_root and ancestor.is_relative_to(skills_root): + if (ancestor / "SKILL.md").is_file(): + raise ValueError(f"Refusing to install into '{ancestor.name}': it is an " + f"existing skill directory, not a category. Choose a different category.") + ancestor = ancestor.parent + if not install_dir.exists(): + return + if not install_dir.is_dir(): + raise ValueError(f"Refusing to install: '{install_dir.name}' already exists " + f"and is not a directory. Remove it or choose a different skill name.") + # Guard against silent data loss when the install target collides with an existing category bucket (a + # directory that holds other skills). This was reported as GitHub issue #75983: installing a skill with + # --name matching an existing category directory caused rmtree to wipe all sibling skills. A directory + # that directly contains SKILL.md is an existing skill installation and stays overwritable + # (hub-installed skills are additionally guarded by the lock-file check in do_install()). But a + # directory that contains *other* skill directories is a category bucket and must NOT be silently + # deleted. + if not (install_dir / "SKILL.md").exists(): + skill_dirs_in = _category_skill_dirs(install_dir) + if skill_dirs_in: + raise ValueError(f"Refusing to overwrite category directory '{install_dir}' " + f"which contains {len(skill_dirs_in)} skill(s): {', '.join(sorted(skill_dirs_in))}. " + f"Use a different --name or install into a subcategory.") + + +def install_from_quarantine( + quarantine_path: Path, skill_name: str, category: str, bundle: SkillBundle, scan_result: ScanResult, + scan_provenance: Optional[Dict[str, Any]] = None, +) -> Path: + """Move a scanned skill from quarantine into the skills directory.""" + from tools.skills_hub import HubLockFile, _quarantine_dir, _skills_dir, append_audit_log + safe_skill_name = _validate_skill_name(skill_name) + safe_category = _validate_install_parent_path(category) if category else "" + quarantine_resolved = quarantine_path.resolve() + if not quarantine_resolved.is_relative_to(_quarantine_dir().resolve()): + raise ValueError(f"Unsafe quarantine path: {quarantine_path}") + + install_rel_path = f"{safe_category}/{safe_skill_name}" if safe_category else safe_skill_name + # Same validator the uninstaller uses, so a lock entry can never point at a + # symlink-redirected target. + install_dir = _resolve_lock_install_path(install_rel_path, safe_skill_name) + _check_install_target(install_dir) + if install_dir.exists(): + shutil.rmtree(install_dir) + + try: + skill_size = (quarantine_path / "SKILL.md").stat().st_size + except OSError: + skill_size = 0 + if skill_size > 100_000: + logger.warning( + "Skill '%s' has a large SKILL.md (%s chars). " + "Large skills consume significant context when loaded. " + "Consider asking the author to split it into smaller files.", + safe_skill_name, f"{skill_size:,}", + ) + + # A symlink in the bundle would copy its target into skills/ and leak it + # to the agent on the next skill_view. + for entry in quarantine_path.rglob("*"): + if _is_path_redirect(entry): + try: + rel = entry.relative_to(quarantine_resolved) + except ValueError: + rel = entry + raise ValueError(f"Installed skill contains symlinks, which is not allowed: {rel}") + + install_dir.parent.mkdir(parents=True, exist_ok=True) + shutil.move(str(quarantine_path), str(install_dir)) + installed_hash = content_hash(install_dir) + HubLockFile().record_install( + name=safe_skill_name, source=bundle.source, identifier=bundle.identifier, trust_level=bundle.trust_level, + scan_verdict=scan_result.verdict, skill_hash=installed_hash, + install_path=install_dir.resolve().relative_to(_skills_dir().resolve()).as_posix(), + files=list(bundle.files.keys()), metadata=bundle.metadata, + scan_provenance=scan_provenance or getattr(scan_result, "scan_provenance", None), + ) + append_audit_log("INSTALL", safe_skill_name, bundle.source, bundle.trust_level, scan_result.verdict, + installed_hash) + try: + from tools.skill_usage import record_installed + record_installed(safe_skill_name) + except Exception: + logger.debug("Unable to record skill install lifecycle for %s", safe_skill_name, exc_info=True) + return install_dir + + +def uninstall_skill(skill_name: str) -> Tuple[bool, str]: + """Remove a hub-installed skill. Refuses to remove builtins.""" + from tools.skills_hub import HubLockFile, append_audit_log + lock = HubLockFile() + entry = lock.get_installed(skill_name) + if not entry: + return False, f"'{skill_name}' is not a hub-installed skill (may be a builtin)" + # The destructive boundary: whatever reaches rmtree MUST be inside + # SKILLS_DIR and MUST NOT be SKILLS_DIR itself (see _resolve_lock_install_path). + try: + install_path = _resolve_lock_install_path(entry.get("install_path", ""), skill_name) + except ValueError as exc: + return False, f"Refusing to uninstall '{skill_name}': {exc}" + if install_path.exists(): + shutil.rmtree(install_path) + lock.record_uninstall(skill_name) + append_audit_log("UNINSTALL", skill_name, entry["source"], entry["trust_level"], "n/a", "user_request") + return True, f"Uninstalled '{skill_name}' from {entry['install_path']}" + + +def bundle_content_hash(bundle: SkillBundle) -> str: + """Deterministic hash of an in-memory bundle. + + MUST stay symmetric with ``tools.skills_guard.content_hash`` (same skill + from disk), which keys files by POSIX relative path. Windows bundle keys + carry backslashes, which changed both bytes and sort order and made every + skill report ``update_available`` forever — normalize before hashing. The + path is hashed too so swapping contents between two files changes the hash. + + That function keys files by ``relative_to(...).as_posix()`` — forward slashes on every OS. See #62310. + """ + h = hashlib.sha256() + normalized = {rel_path.replace("\\", "/"): content for rel_path, content in bundle.files.items()} + for rel_path in sorted(normalized): + h.update(rel_path.encode("utf-8")) + h.update(b"\x00") + content = normalized[rel_path] + h.update(content if isinstance(content, bytes) else content.encode("utf-8")) + return f"sha256:{h.hexdigest()[:16]}" + + +_SOURCE_ID_ALIASES = {"skills.sh": "skills-sh"} + + +def _source_matches(source: SkillSource, source_name: str) -> bool: + return source.source_id() == _SOURCE_ID_ALIASES.get(source_name, source_name) + + +def check_for_skill_updates( + name: Optional[str] = None, *, lock: Optional[HubLockFile] = None, + sources: Optional[List[SkillSource]] = None, auth: Optional[GitHubAuth] = None, +) -> List[dict]: + """Check installed hub skills for upstream changes. + + Each entry is fetched ONLY from adapters matching its recorded source. + Falling back to all sources let a same-named skill in a different registry + satisfy the fetch and silently reassign provenance (names are not + namespaced across registries), so a missing adapter reports "unavailable". + """ + from tools.skills_hub import HubLockFile + from tools.skills_hub_search import create_source_router + lock = lock or HubLockFile() + installed = lock.list_installed() + if name: + installed = [entry for entry in installed if entry.get("name") == name] + if sources is None: + sources = create_source_router(auth=auth) + + results: List[dict] = [] + for entry in installed: + identifier, source_name = entry.get("identifier", ""), entry.get("source", "") + row = {"name": entry.get("name", ""), "identifier": identifier, "source": source_name} + try: + install_dir = _resolve_lock_install_path( + entry.get("install_path", ""), entry.get("name", "skill")) + orphaned = not install_dir.is_dir() + except (ValueError, OSError, RuntimeError): + results.append({**row, "status": "invalid_install"}) + continue + if orphaned: + # The lock-file entry points at a directory that is gone: the fetched + # bundle could never be applied, so skip the network cost entirely + # instead of re-paying it on every update run (#104291). + results.append({**row, "status": "orphaned"}) + continue + bundle = None + for src in filter(lambda s: _source_matches(s, source_name), sources): + try: + bundle = src.fetch(identifier) + except Exception: + bundle = None + if bundle: + break + if not bundle: + results.append({**row, "status": "unavailable"}) + continue + current_hash, latest_hash = entry.get("content_hash", ""), bundle_content_hash(bundle) + results.append({ + **row, "status": "up_to_date" if current_hash == latest_hash else "update_available", + "current_hash": current_hash, "latest_hash": latest_hash, "bundle": bundle, + }) + return results diff --git a/tools/skills_hub_skillssh.py b/tools/skills_hub_skillssh.py new file mode 100644 index 0000000000000000000000000000000000000000..606aa701b900f1c5bd6f4fe8540e7ee710b97cb5 --- /dev/null +++ b/tools/skills_hub_skillssh.py @@ -0,0 +1,361 @@ +"""Skills Hub skills.sh adapter: catalog discovery via skills.sh, content via GitHub.""" + +import hashlib +import logging +import re +from typing import Any, Dict, List, Optional + +from tools.skills_hub_github import GitHubAuth, GitHubSource, _split_repo_id +from tools.skills_hub_models import ( + SkillBundle, SkillMeta, SkillSource, _cache_metas, _cached_metas, _get_json, _get_text, _memo_json, +) + +logger = logging.getLogger("tools.skills_hub") + + +def _strip_html(value: str) -> str: + return re.sub(r'<[^>]+>', '', value) + + +class SkillsShSource(SkillSource): + """Discover skills via skills.sh and fetch content from the underlying GitHub repo.""" + + BASE_URL = "https://skills.sh" + SEARCH_URL = f"{BASE_URL}/api/search" + # The sitemap is the real catalog source: the homepage only exposes a + # ~200-entry featured strip; sitemap.xml points at sitemap-skills-N.xml + # files (10k URLs each) covering the full ~20k+ catalog. + SITEMAP_INDEX_URL = "https://www.skills.sh/sitemap.xml" + # skills.sh serves per-skill sitemaps brotli-compressed and httpx's optional + # brotlicffi backend has a streaming-decode bug on them; asking for gzip + # only makes the server fall back to gzip/identity on every httpx install. + _SITEMAP_HEADERS = {"Accept-Encoding": "gzip"} + _SITEMAP_LOC_RE = re.compile(r"([^<]+)", re.IGNORECASE) + _SITEMAP_SKILL_RE = re.compile( + r"^https?://(?:www\.)?skills\.sh/(?P[^/]+)/(?P[^/]+)/(?P[^/]+)/?$", re.IGNORECASE, + ) + _SKILL_LINK_RE = re.compile(r'href=["\']/(?P(?!agents/|_next/|api/)[^"\'/]+/[^"\'/]+/[^"\'/]+)["\']') + _INSTALL_CMD_RE = re.compile( + r'npx\s+skills\s+add\s+(?Phttps?://github\.com/[^\s<]+|[^\s<]+)' + r'(?:\s+--skill\s+(?P[^\s<]+))?', + re.IGNORECASE, + ) + _PAGE_H1_RE = re.compile(r']*>(?P.*?)</h1>', re.IGNORECASE | re.DOTALL) + _PROSE_H1_RE = re.compile( + r'<div[^>]*class=["\'][^"\']*prose[^"\']*["\'][^>]*>.*?<h1[^>]*>(?P<title>.*?)</h1>', + re.IGNORECASE | re.DOTALL, + ) + _PROSE_P_RE = re.compile( + r'<div[^>]*class=["\'][^"\']*prose[^"\']*["\'][^>]*>.*?<p[^>]*>(?P<body>.*?)</p>', + re.IGNORECASE | re.DOTALL, + ) + _WEEKLY_INSTALLS_RE = re.compile(r'Weekly Installs.*?children\\":\\"(?P<count>[0-9.,Kk]+)\\"', re.DOTALL) + _ID_PREFIX_ALIASES = ("skills-sh/", "skills.sh/", "skils-sh/", "skils.sh/") + # Standard skill sub-paths tried before any tree/discovery walk. + _STANDARD_BASE_PATHS = ("skills/", ".agents/skills/", ".claude/skills/") + + _strip_html = staticmethod(_strip_html) + SOURCE_ID = "skills-sh" + + def __init__(self, auth: GitHubAuth): + self.auth, self.github = auth, GitHubSource(auth=auth) + + def trust_level_for(self, identifier: str) -> str: + return self.github.trust_level_for(self._normalize_identifier(identifier)) + + def _meta(self, canonical: str, *, name: str, description: str, path: str, + extra: Optional[Dict[str, Any]] = None) -> SkillMeta: + return SkillMeta( + name=name, description=description, source="skills.sh", identifier=self._wrap_identifier(canonical), + trust_level=self.github.trust_level_for(canonical), repo="/".join(canonical.split("/", 2)[:2]), + path=path, extra=extra if extra is not None else {}, + ) + + def _urls_for(self, canonical: str, repo: str) -> Dict[str, str]: + return {"detail_url": f"{self.BASE_URL}/{canonical}", "repo_url": f"https://github.com/{repo}"} + + def search(self, query: str, limit: int = 10) -> List[SkillMeta]: + if not query.strip(): + # Empty query = bulk catalog dump (build_skills_index.py) — walk the sitemap. + return self._sitemap_catalog(limit) + cache_key = f"skills_sh_search_{hashlib.md5(f'{query}|{limit}'.encode()).hexdigest()}" + cached = _cached_metas(cache_key) + if cached is not None: + return cached[:limit] + data = _get_json(self.SEARCH_URL, params={"q": query, "limit": limit}) + if data is None: + return [] + items = data.get("skills", []) if isinstance(data, dict) else [] + if not isinstance(items, list): + return [] + results = [m for m in map(self._meta_from_search_item, items[:limit]) if m] + _cache_metas(cache_key, results) + return results + + def fetch(self, identifier: str) -> Optional[SkillBundle]: + canonical = self._normalize_identifier(identifier) + detail = self._fetch_detail_page(canonical) + + def _relabel(github_id: Optional[str]) -> Optional[SkillBundle]: + bundle = self.github.fetch(github_id) if github_id else None + if bundle: + bundle.source, bundle.identifier = "skills.sh", self._wrap_identifier(canonical) + bundle.metadata.update(self._detail_to_metadata(canonical, detail)) + return bundle or None + + for candidate in self._candidate_identifiers(canonical): + bundle = _relabel(candidate) + if bundle: + return bundle + return _relabel(self._discover_identifier(canonical, detail=detail)) + + def inspect(self, identifier: str) -> Optional[SkillMeta]: + canonical = self._normalize_identifier(identifier) + detail = self._fetch_detail_page(canonical) + meta = self._resolve_github_meta(canonical, detail=detail) + return self._finalize_inspect_meta(meta, canonical, detail) if meta else None + + def _sitemap_catalog(self, limit: int) -> List[SkillMeta]: + """Enumerate the full catalog via the sitemap (cached for the index TTL — + ~2 MB of XML). Falls back to ``_featured_skills`` when unreachable/empty.""" + cache_key = "skills_sh_sitemap_v1" + cached = _cached_metas(cache_key) + if cached is not None: + return cached[:limit] if limit > 0 else cached + + # Step 1: sitemap index -> per-skill sitemap URLs. + index_xml = _get_text(self.SITEMAP_INDEX_URL, follow_redirects=True, headers=self._SITEMAP_HEADERS) + skill_sitemap_urls = [m.group(1).strip() for m in self._SITEMAP_LOC_RE.finditer(index_xml or "") + if "sitemap-skills" in m.group(1)] + if not skill_sitemap_urls: + return self._featured_skills(limit) + + # Step 2: collect canonical "owner/repo/skill" IDs from each sitemap. + seen, results = set(), [] + for sitemap_url in skill_sitemap_urls: + xml = _get_text(sitemap_url, timeout=30, follow_redirects=True, headers=self._SITEMAP_HEADERS) + for loc_match in self._SITEMAP_LOC_RE.finditer(xml or ""): + m = self._SITEMAP_SKILL_RE.match(loc_match.group(1).strip()) + if not m: + continue + repo, skill = f"{m.group('owner')}/{m.group('repo')}", m.group("skill") + canonical = f"{repo}/{skill}" + if canonical not in seen: + seen.add(canonical) + results.append(self._meta(canonical, name=skill, description=f"Indexed by skills.sh from {repo}", + path=skill, extra=self._urls_for(canonical, repo))) + if not results: + return self._featured_skills(limit) + _cache_metas(cache_key, results) + return results[:limit] if limit > 0 else results + + def _featured_skills(self, limit: int) -> List[SkillMeta]: + cache_key = "skills_sh_featured" + cached = _cached_metas(cache_key) + if cached is not None: + return cached[:limit] + html = _get_text(self.BASE_URL) + if html is None: + return [] + seen, results = set(), [] + for match in self._SKILL_LINK_RE.finditer(html): + canonical = match.group("id") + split = None if canonical in seen else _split_repo_id(canonical) + seen.add(canonical) + if split is None: + continue + repo, skill_path = split + results.append(self._meta(canonical, name=skill_path.split("/")[-1], + description=f"Featured on skills.sh from {repo}", path=skill_path)) + if len(results) >= limit: + break + _cache_metas(cache_key, results) + return results + + def _meta_from_search_item(self, item: dict) -> Optional[SkillMeta]: + if not isinstance(item, dict): + return None + canonical, repo, skill_path = item.get("id"), item.get("source"), item.get("skillId") + if not isinstance(canonical, str) or canonical.count("/") < 2: + if not (isinstance(repo, str) and isinstance(skill_path, str)): + return None + canonical = f"{repo}/{skill_path}" + split = _split_repo_id(canonical) + if split is None: + return None + repo, skill_path = split + installs = item.get("installs") + installs_label = f" · {int(installs):,} installs" if isinstance(installs, int) else "" + return self._meta( + canonical, name=str(item.get("name") or skill_path.split("/")[-1]), + description=f"Indexed by skills.sh from {repo}{installs_label}", path=skill_path, + extra={"installs": installs, **self._urls_for(canonical, repo)}, + ) + + def _fetch_detail_page(self, identifier: str) -> Optional[dict]: + def compute(): + html = _get_text(f"{self.BASE_URL}/{identifier}") + return None if html is None else self._parse_detail_page(identifier, html) or None + key = f"skills_sh_detail_{hashlib.md5(identifier.encode()).hexdigest()}" + return _memo_json(key, compute, valid=lambda c: isinstance(c, dict)) + + def _parse_detail_page(self, identifier: str, html: str) -> Optional[dict]: + split = _split_repo_id(identifier) + if split is None: + return None + repo, install_skill = split + install_command, install_match = None, self._INSTALL_CMD_RE.search(html) + if install_match: + install_command = install_match.group(0).strip() + install_skill = (install_match.group("skill") or install_skill).strip() + repo = self._extract_repo_slug((install_match.group("repo") or "").strip()) or repo + return { + "repo": repo, "install_skill": install_skill, + "page_title": self._extract_first_match(self._PAGE_H1_RE, html), + "body_title": self._extract_first_match(self._PROSE_H1_RE, html), + "body_summary": self._extract_first_match(self._PROSE_P_RE, html), + "weekly_installs": self._extract_weekly_installs(html), + "install_command": install_command, + **self._urls_for(identifier, repo), + "security_audits": self._extract_security_audits(html, identifier), + } + + def _discover_identifier(self, identifier: str, detail: Optional[dict] = None) -> Optional[str]: + split = _split_repo_id(identifier) + if split is None: + return None + default_repo, skill_path = split + repo = detail.get("repo", default_repo) if isinstance(detail, dict) else default_repo + skill_token = skill_path.split("/")[-1] + tokens = [skill_token] + if isinstance(detail, dict): + tokens.extend(detail.get(k, "") for k in ("install_skill", "page_title", "body_title")) + + def _match_in(base_path: str) -> Optional[str]: + try: + skills = self.github._list_skills_in_repo(repo, base_path) + except Exception: + return None + return next((m.identifier for m in skills if self._matches_skill_tokens(m, tokens)), None) + + # One recursive tree lookup before brute-forcing every top-level dir + # (avoids request bursts on categorized repos like borghei/claude-skills). + found = (next((f for f in map(_match_in, self._STANDARD_BASE_PATHS) if f), None) + or self.github._find_skill_in_repo_tree(repo, skill_token)) + if found: + return found + + # Fallback: scan repo root for directories that might contain skills. + try: + entries = _get_json(f"https://api.github.com/repos/{repo}/contents/", + headers=self.github.auth.get_headers(), timeout=15, follow_redirects=True) + for entry in entries if isinstance(entries, list) else []: + if entry.get("type") != "dir": + continue + dir_name = entry["name"] + if dir_name.startswith((".", "_")) or dir_name in {"skills", ".agents", ".claude"}: + continue + meta = self.github.inspect(f"{repo}/{dir_name}/{skill_token}") + if meta: + return meta.identifier + found = _match_in(dir_name + "/") + if found: + return found + except Exception: + pass + return None + + def _resolve_github_meta(self, identifier: str, detail: Optional[dict] = None) -> Optional[SkillMeta]: + for candidate in self._candidate_identifiers(identifier): + meta = self.github.inspect(candidate) + if meta: + return meta + resolved = self._discover_identifier(identifier, detail=detail) + return self.github.inspect(resolved) if resolved else None + + def _finalize_inspect_meta(self, meta: SkillMeta, canonical: str, detail: Optional[dict]) -> SkillMeta: + meta.source, meta.identifier = "skills.sh", self._wrap_identifier(canonical) + meta.trust_level = self.trust_level_for(canonical) + meta.extra = {**meta.extra, **self._detail_to_metadata(canonical, detail)} + if isinstance(detail, dict): + body_summary, weekly_installs = detail.get("body_summary"), detail.get("weekly_installs") + if body_summary: + meta.description = body_summary + elif meta.description and weekly_installs: + meta.description = f"{meta.description} · {weekly_installs} weekly installs on skills.sh" + return meta + + @classmethod + def _matches_skill_tokens(cls, meta: SkillMeta, skill_tokens: List[str]) -> bool: + candidates = (cls._token_variants(meta.name) | cls._token_variants(meta.path) + | cls._token_variants(meta.identifier.split("/", 2)[-1] if meta.identifier else None)) + return any(cls._token_variants(token) & candidates for token in skill_tokens) + + @staticmethod + def _token_variants(value: Optional[str]) -> set[str]: + if not value: + return set() + plain = _strip_html(str(value)).strip().strip("/").lower() + if not plain: + return set() + base, sanitized = plain.split("/")[-1], re.sub(r'[^a-z0-9/_-]+', '-', plain).strip('-') + tail = base.lstrip('@') + variants = { + plain, plain.replace("_", "-"), plain.replace("/", "-"), base, base.replace("_", "-"), + sanitized, sanitized.replace("/", "-"), sanitized.split("/")[-1], tail, tail.replace("_", "-"), + } + return {v for v in variants if v} + + @staticmethod + def _extract_repo_slug(repo_value: str) -> Optional[str]: + parts = repo_value.strip().removeprefix("https://github.com/").strip("/").split("/") + return f"{parts[0]}/{parts[1]}" if len(parts) >= 2 else None + + @staticmethod + def _extract_first_match(pattern: re.Pattern, text: str) -> Optional[str]: + match = pattern.search(text) + value = next((group for group in match.groups() if group), None) if match else None + return (_strip_html(value).strip() or None) if value is not None else None + + def _detail_to_metadata(self, canonical: str, detail: Optional[dict]) -> Dict[str, Any]: + parts = canonical.split("/", 2) + metadata = {"detail_url": f"{self.BASE_URL}/{canonical}"} + if len(parts) >= 2: + metadata["repo_url"] = f"https://github.com/{parts[0]}/{parts[1]}" + if isinstance(detail, dict): + for key in ("weekly_installs", "install_command", "repo_url", "detail_url", "security_audits"): + if detail.get(key): + metadata[key] = detail[key] + return metadata + + @classmethod + def _extract_weekly_installs(cls, html: str) -> Optional[str]: + match = cls._WEEKLY_INSTALLS_RE.search(html) + return match.group("count") if match else None + + @staticmethod + def _extract_security_audits(html: str, identifier: str) -> Dict[str, str]: + audits: Dict[str, str] = {} + for audit in ("agent-trust-hub", "socket", "snyk"): + idx = html.find(f"/security/{audit}") + match = re.search(r'(Pass|Warn|Fail)', html[idx:idx + 500], re.IGNORECASE) if idx != -1 else None + if match: + audits[audit] = match.group(1).title() + return audits + + @classmethod + def _normalize_identifier(cls, identifier: str) -> str: + prefix = next((p for p in cls._ID_PREFIX_ALIASES if identifier.startswith(p)), "") + return identifier[len(prefix):] + + @classmethod + def _candidate_identifiers(cls, identifier: str) -> List[str]: + split = _split_repo_id(identifier) + if split is None: + return [identifier] + repo, path = split[0], split[1].lstrip("/") + return list(dict.fromkeys([f"{repo}/{path}"] + [f"{repo}/{b}{path}" for b in cls._STANDARD_BASE_PATHS])) + + @staticmethod + def _wrap_identifier(identifier: str) -> str: + return f"skills-sh/{identifier}" diff --git a/tools/skills_sync_client_org.py b/tools/skills_sync_client_org.py new file mode 100644 index 0000000000000000000000000000000000000000..936d91569344476a02506c7e0f85e8ed5e66a557 --- /dev/null +++ b/tools/skills_sync_client_org.py @@ -0,0 +1,298 @@ +"""Org-shared skills: org pull + propose (``~/.hermes/skills/_org/<org_id>/``). +Org skills live in a DISTINCT local namespace (read-only to the runtime; a local edit is a personal +fork until proposed); the canonical set is ``refs/org/<org_id>/HEAD`` with the SAME object model. +PERSONAL-ORG GATE: NAS stamps ``org_role`` ONLY for multi-member orgs; no claim => pull/propose +raise SyncInertError and personal sync is untouched. ``propose_skill`` must stay non-interactive. +Module state (``_skills_dir``, ``_org_dir``, base URL, device id) stays in ``tools.skills_sync_client`` +and is read lazily so tests can monkeypatch it.""" + +from __future__ import annotations + +import hashlib +import json +import logging +import shutil +from contextlib import suppress +from pathlib import Path, PurePosixPath +from typing import Any, Callable, Dict, List, Optional + +from tools.skills_sync_client_wire import ( + ObjectSet, SyncClient, SyncConflict, SyncError, assemble_root_from_skill_trees, build_commit, build_tree, + checked_capabilities, materialize_tree, read_ref_hash, root_tree_of_commit, skill_trees_of_root) + +logger = logging.getLogger("tools.skills_sync_client") +ORG_DIR_NAME = "_org" +# Propose re-splices onto a moved org HEAD at most this many times. Small: contention means +# other members are actively proposing; unbounded would spin. +_ORG_CAS_MAX_ATTEMPTS = 5 + + +def _ssc(): + from tools import skills_sync_client + return skills_sync_client + + +def org_head_ref(org_id: str) -> str: + return f"refs/org/{org_id}/HEAD" + + +def resolve_org_identity() -> Dict[str, Any]: + """``resolve_identity()`` + ``org_id``/``org_role``; SyncInertError without an ``org_role`` claim + (personal org / old issuer): org sync unavailable, NOT an error.""" + ssc = _ssc() + identity = ssc.resolve_identity() + claims = identity.get("claims") or {} + org_id, org_role = claims.get("org_id"), claims.get("org_role") + if not org_id: + raise ssc.SyncInertError("no organisation associated with this account") + if not isinstance(org_role, str) or not org_role: + raise ssc.SyncInertError("this account isn't a member of a shared organisation") + identity.update(org_id=str(org_id), org_role=org_role) + return identity + + +def _org_client(identity: Optional[Dict[str, Any]], client: Optional[SyncClient]): + """(identity, client, max_object_bytes) for an org operation; SyncInertError when the base URL is + missing or the server lacks the ``org`` feature.""" + ssc = _ssc() + identity = identity or resolve_org_identity() + if client is None: + if not (base_url := ssc.resolve_sync_base_url()): + raise ssc.SyncInertError("no sync base URL configured") + client = SyncClient(base_url, identity["api_key"]) + caps, max_bytes = checked_capabilities(client) + if "org" not in (caps.get("features") or []): + raise ssc.SyncInertError("this server does not support org-shared skills") + return identity, client, max_bytes + + +def _read_org_head(client: SyncClient, org_id: str) -> Optional[str]: + """Current org HEAD, or None. MUST read through the ORG endpoint.""" + return read_ref_hash(client, org_head_ref(org_id), org_scope=True) + + +# Local mirror sidecars +def _mirror_root(org_id: Optional[str]) -> Path: + """``<_org_dir>/<org_id>``; the org-level ``_org/`` root itself when *org_id* is None.""" + return _ssc()._org_dir() / org_id if org_id else _ssc()._org_dir() + + +def _write_sidecar(what: str, path_fn: Callable[[], Path], text: str) -> None: + """Best-effort sidecar write (path resolution included); never raises.""" + try: + path = path_fn() + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + except Exception as e: + logger.debug("skills_sync_client: %s write failed: %s", what, e) + + +def _skill_dir_fingerprint(path: Path) -> str: + """Content hash of a skill dir (sorted relative path + bytes; mtime-independent). "" on read failure.""" + h = hashlib.sha256() + try: + for f in sorted(p for p in path.rglob("*") if p.is_file()): + h.update(str(f.relative_to(path)).replace("\\", "/").encode("utf-8")) + h.update(b"\0") + h.update(f.read_bytes()) + h.update(b"\0") + except OSError as e: + logger.debug("skills_sync_client: fingerprint failed for %s: %s", path, e) + return "" + return h.hexdigest() + + +def _sidecar_path(org_id: Optional[str], const: str) -> Path: + """``<mirror>/<agent.skill_utils.<const>>`` (org-level when org_id is None).""" + import agent.skill_utils as sku + return _mirror_root(org_id) / getattr(sku, const) + + +def _read_org_baseline(org_id: str) -> Dict[str, Any]: + """The baseline sidecar: upstream fingerprint + tree of each mirrored skill ({} if absent).""" + try: + return json.loads(_sidecar_path(org_id, "ORG_BASELINE_FILE").read_text(encoding="utf-8")) + except Exception: + return {} + + +def _write_org_baseline(org_id: str, baseline: Dict[str, Any]) -> None: + _write_sidecar("baseline", lambda: _sidecar_path(org_id, "ORG_BASELINE_FILE"), + json.dumps(baseline, indent=2, sort_keys=True)) + + +def _write_org_provenance(org_id: str, data: Dict[str, Any]) -> None: + _write_sidecar("org provenance", lambda: _sidecar_path(org_id, "ORG_PROVENANCE_FILE"), + json.dumps(data, indent=2)) + + +def _write_active_org_marker(org_id: str) -> None: + """Record which org's mirror may resolve (agent/skill_utils.read_active_org_id).""" + _write_sidecar("active-org marker", lambda: _sidecar_path(None, "ORG_ACTIVE_MARKER"), org_id) + + +def _clear_active_org_marker() -> None: + """Remove the active-org marker so org skills stop resolving.""" + try: + marker = _sidecar_path(None, "ORG_ACTIVE_MARKER") + if marker.exists(): + marker.unlink() + logger.info("skills_sync_client: cleared active-org marker " + "(token has no org workflow); org skills no longer resolve") + except Exception as e: + logger.debug("skills_sync_client: marker clear failed: %s", e) + + +def org_skill_is_locally_modified(skill_rel_path: str, org_id: str) -> bool: + """Local copy differs from upstream's fingerprint. No baseline (pre-existing mirror) => unmodified.""" + dest = _mirror_root(org_id) / PurePosixPath(skill_rel_path) + entry = _read_org_baseline(org_id).get(skill_rel_path) or {} + recorded = entry.get("fingerprint") if isinstance(entry, dict) else entry + return dest.is_dir() and bool(recorded) and _skill_dir_fingerprint(dest) != recorded + + +def _active_org_id() -> Optional[str]: + from agent.skill_utils import read_active_org_id + return read_active_org_id(_ssc()._skills_dir()) + + +def list_locally_modified_org_skills(org_id: Optional[str] = None) -> List[str]: + """Org skills with local edits that upstream has not seen.""" + try: + org_id = org_id or _active_org_id() + if not org_id: + return [] + return sorted(rel for rel in _read_org_baseline(org_id) if org_skill_is_locally_modified(rel, org_id)) + except Exception as e: + logger.debug("skills_sync_client: modified-scan failed: %s", e) + return [] + + +def list_org_skill_names() -> List[str]: + """Skill names present in the local org mirror (empty when none pulled).""" + names: List[str] = [] + try: + org_id = _active_org_id() + root = _mirror_root(org_id) if org_id else None + if root and root.is_dir(): + names = [str(rel).replace("\\", "/") for rel in (p.parent.relative_to(root) for p in root.rglob("SKILL.md")) + if rel.parts] + except Exception as e: + logger.debug("skills_sync_client: org skill listing failed: %s", e) + return sorted(names) + + +# Pull / propose +def pull_org_skills(client: Optional[SyncClient] = None, *, identity: Optional[Dict[str, Any]] = None, + ) -> Dict[str, Any]: + """Pull the org canonical set into the mirror (fast-forward only, no client merge). A skill with + LOCAL edits is never clobbered: skipped, and in ``conflicted`` when upstream also moved. + Returns ``{ok, org_id, head, updated, conflicted}``.""" + identity = identity or resolve_org_identity() + if "org_id" not in identity: + raise _ssc().SyncInertError("no organisation context available") + identity, client, _ = _org_client(identity, client) + org_id = identity["org_id"] + head = _read_org_head(client, org_id) + # Marker written HERE: only after the token's org_id + org_role were verified, so a stale mirror + # from a previous org stops resolving on a pull under another org. + _write_active_org_marker(org_id) + if not head: + return {"ok": True, "org_id": org_id, "head": None, "updated": []} + head_commit = client.get_commit_json(head, org_scope=True) + updated, conflicted = [], [] + baseline = _read_org_baseline(org_id) + for rel_path, tree_hash in sorted(skill_trees_of_root(client, head_commit["tree"], org_scope=True).items()): + dest = _mirror_root(org_id) / PurePosixPath(rel_path) + try: + if dest.exists(): + if org_skill_is_locally_modified(rel_path, org_id): + if (baseline.get(rel_path) or {}).get("tree") != tree_hash: + conflicted.append(rel_path) + continue + shutil.rmtree(dest) + materialize_tree(client, tree_hash, dest, org_scope=True) # creates dest + baseline[rel_path] = {"fingerprint": _skill_dir_fingerprint(dest), "tree": tree_hash} + updated.append(rel_path) + except Exception as e: + logger.warning("skills_sync_client: org skill materialize failed for %s: %s", rel_path, e) + # Provenance for the skill_view header: the HEAD author is token-verified by the plane at + # push time, so it is trustworthy to display. + author = head_commit.get("author") or {} + _write_org_provenance(org_id, {"org_id": org_id, "head": head, "author_user_id": author.get("owner", ""), + "author_device": author.get("device", ""), "ts": head_commit.get("ts", ""), + "skills": updated}) + _write_org_baseline(org_id, baseline) + if conflicted: + logger.warning("skills_sync_client: %d org skill(s) have local edits AND upstream " + "changes; left untouched: %s", len(conflicted), ", ".join(conflicted)) + return {"ok": True, "org_id": org_id, "head": head, "updated": updated, "conflicted": conflicted} + + +def propose_skill(skill_name: str, client: Optional[SyncClient] = None, *, + identity: Optional[Dict[str, Any]] = None, message: Optional[str] = None) -> Dict[str, Any]: + """Propose a local skill to the org canonical set: an org-scoped commit splicing that ONE skill + subtree into the current org HEAD (per-skill deltas, never a wholesale replace), uploaded with + ``?scope=org``, then CAS. ADMIN/OWNER -> ``{ok, merged: True}``; MEMBER -> 202 -> ``{ok, + proposal_pending: True, proposal_id, ref}`` (never presented as live). If HEAD moves before the + CAS the skill is re-spliced onto the NEW head (replaying the old root would drop others' skills).""" + ssc = _ssc() + identity, client, max_bytes = _org_client(identity, client) + org_id = identity["org_id"] + rel = ssc._skill_rel_path(skill_name) + if rel is None: + raise SyncError(f"skill '{skill_name}' not found under the skills dir") + skill_dir = ssc._skills_dir() / rel + if not (skill_dir / "SKILL.md").exists(): + raise SyncError(f"skill '{skill_name}' has no SKILL.md") + objects = ObjectSet() + skill_tree = build_tree(skill_dir, objects, max_object_bytes=max_bytes) + for attempt in range(1, _ORG_CAS_MAX_ATTEMPTS + 1): + base_head = _read_org_head(client, org_id) + skill_map = {} if not base_head else skill_trees_of_root( + client, root_tree_of_commit(client, base_head, org_scope=True), org_scope=True) + skill_map[str(rel)] = skill_tree + root_hash = assemble_root_from_skill_trees(skill_map, objects) + commit_hash = build_commit(root_hash, [base_head] if base_head else [], owner=identity["owner"], + device=ssc.stable_device_id(), message=message or f"propose {skill_name}", + objects=objects) + client.put_objects(objects.objects, org_scope=True) + try: + result = client.cas_ref(org_head_ref(org_id), base_head, commit_hash) + break + except SyncConflict as conflict: + if attempt >= _ORG_CAS_MAX_ATTEMPTS: + raise SyncError("the organisation's skills changed while this was being " + f"proposed, and {attempt} attempts to catch up all lost " + "the race — run the command again", status=409) from conflict + logger.debug("propose_skill: org HEAD moved (actual=%r), re-splicing (attempt %d)", + conflict.actual, attempt) + if result.get("proposal_pending"): + return {"ok": True, "proposal_pending": True, "proposal_id": result.get("proposal_id"), + "ref": result.get("ref"), "commit": commit_hash, "org_id": org_id} + return {"ok": True, "merged": True, "head": result.get("hash", commit_hash), + "commit": commit_hash, "org_id": org_id} + + +def maybe_pull_org_skills() -> Optional[Dict[str, Any]]: + """Best-effort org pull if all gates hold; never raises, None when inert. Marker hygiene: a token + that VERIFIABLY lacks the org claim clears the active-org marker (org skills stop resolving); an + unresolvable identity (offline, logged out) leaves it alone so pulled org skills keep working.""" + ssc = _ssc() + try: + identity = resolve_org_identity() + except ssc.SyncInertError: + with suppress(Exception): + if not (ssc.resolve_identity().get("claims") or {}).get("org_role"): + _clear_active_org_marker() + return None + except Exception as e: + logger.debug("skills_sync_client: maybe_pull_org_skills inert/failed: %s", e) + return None + try: + if not ssc.sync_feature_enabled() or not ssc.resolve_sync_base_url(): + return None + return pull_org_skills(identity=identity) + except Exception as e: + logger.debug("skills_sync_client: maybe_pull_org_skills inert/failed: %s", e) + return None diff --git a/tools/skills_sync_client_wire.py b/tools/skills_sync_client_wire.py new file mode 100644 index 0000000000000000000000000000000000000000..ce29b13c589063eb4cea08236388277dbc987073 --- /dev/null +++ b/tools/skills_sync_client_wire.py @@ -0,0 +1,343 @@ +"""Skill Sync wire model: content-addressed objects, the HTTP client, tree walks. + +Independent of local skill state (no ``~/.hermes`` reads); ``tools/skills_sync_client.py`` +orchestrates push/pull on top of it and re-exports these names. Wire contract version 1: +``hsp_version`` / ``X-HSP-Object-Type`` are deployed protocol identifiers and are NOT +renamed with the product name "Skill Sync". +""" + +from __future__ import annotations + +import hashlib +import json +import logging +import stat as _stat +from contextlib import suppress +from datetime import datetime, timezone +from pathlib import Path, PurePosixPath +from typing import Any, Dict, List, Optional, Tuple + +logger = logging.getLogger("tools.skills_sync_client") +WIRE_VERSION = "1" +DEFAULT_MAX_OBJECT_BYTES = 26214400 # 25 MiB, mirrors capabilities default +KIND_BLOB, KIND_TREE, KIND_COMMIT = "blob", "tree", "commit" +MODE_FILE, MODE_EXEC, MODE_DIR = "file", "exec", "dir" +ARTIFACT_TYPE_SKILL = "skill" +_EXEC_BITS = _stat.S_IXUSR | _stat.S_IXGRP | _stat.S_IXOTH + +# `sync-manifest`: per-skill opt-in is CONTENT in the object model, not a device-local flag -- +# a root-level blob in the tree at refs/user/<owner>/HEAD recording {name, enabled}. The plane +# manifest is authoritative; the local `.usage.json` `sync` flag is only the editable intent +# (reconciled FROM it on pull, TO it on push). Shape MUST match gateway-gateway src/sync/manifest.ts. +SYNC_MANIFEST_ENTRY_NAME = SYNC_MANIFEST_TYPE = "sync-manifest" +SYNC_MANIFEST_VERSION = 1 + + +# Content addressing: the wire uses the FULL 64-hex sha256 -- a different namespace from the +# truncated 16-hex local `content_hash` (skills_guard.py). +def wire_address(data: bytes) -> str: + return "sha256:" + hashlib.sha256(data).hexdigest() + + +def canonical_json_bytes(obj: Dict[str, Any]) -> bytes: + """Canonical JSON for hashing: UTF-8, sorted keys, no whitespace/trailing newline; arrays already in + contract order. Client and server MUST agree byte-for-byte or a push fails ``422 hash_mismatch``.""" + return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8") + + +def build_sync_manifest_bytes(skills: Dict[str, bool]) -> bytes: + """Canonical ``sync-manifest`` bytes for ``{name: enabled}`` (sorted by name for a stable address).""" + return canonical_json_bytes({ + "type": SYNC_MANIFEST_TYPE, "version": SYNC_MANIFEST_VERSION, + "skills": [{"name": name, "enabled": bool(enabled)} for name, enabled in sorted(skills.items())], + }) + + +def parse_sync_manifest(data: bytes) -> Optional[Dict[str, bool]]: + """``{name: enabled}`` from ``sync-manifest`` bytes, or None if malformed. Strict (mirrors gateway + ``parseSyncManifest``): a bad manifest must not read as "nothing opted in".""" + try: + value = json.loads(data.decode("utf-8")) + except Exception: + return None + if (not isinstance(value, dict) or value.get("type") != SYNC_MANIFEST_TYPE + or value.get("version") != SYNC_MANIFEST_VERSION or not isinstance(value.get("skills"), list)): + return None + out: Dict[str, bool] = {} + for raw in value["skills"]: + name, enabled = (raw.get("name"), raw.get("enabled")) if isinstance(raw, dict) else (None, None) + if not isinstance(name, str) or not name or not isinstance(enabled, bool): + return None + out[name] = enabled + return out + + +# Object building +class ObjectSet: + """Objects to push, ``hash -> (kind, bytes)``, deduped by content address.""" + + def __init__(self) -> None: + self.objects: Dict[str, Tuple[str, bytes]] = {} + + def add(self, kind: str, data: bytes) -> str: + addr = wire_address(data) + self.objects.setdefault(addr, (kind, data)) + return addr + + def __len__(self) -> int: + return len(self.objects) + + +def _entry(name: str, kind: str, hash_: str, mode: str) -> Dict[str, str]: + return {"name": name, "kind": kind, "hash": hash_, "mode": mode} + + +def _add_tree(entries: List[Dict[str, str]], objects: ObjectSet) -> str: + """Canonicalize *entries* (sorted by name, byte order) into a tree object.""" + entries.sort(key=lambda e: e["name"]) + return objects.add(KIND_TREE, canonical_json_bytes({"type": KIND_TREE, "entries": entries})) + + +def _file_mode(path: Path) -> str: + """``exec`` if +x else ``file``. No symlink / other modes are emitted.""" + with suppress(OSError): + if path.stat().st_mode & _EXEC_BITS: + return MODE_EXEC + return MODE_FILE + + +def build_tree(dir_path: Path, objects: ObjectSet, *, max_object_bytes: int) -> str: + """Build objects for *dir_path* recursively; return the tree address. Symlinks/special files are + skipped (contract). A blob over *max_object_bytes* raises ValueError (server would 413).""" + entries: List[Dict[str, str]] = [] + for child in sorted(dir_path.iterdir(), key=lambda p: p.name): + if child.is_symlink(): + logger.debug("skills_sync_client: skipping symlink %s", child) + elif child.is_dir(): + entries.append(_entry(child.name, KIND_TREE, build_tree(child, objects, max_object_bytes=max_object_bytes), + MODE_DIR)) + elif child.is_file(): + data = child.read_bytes() + if len(data) > max_object_bytes: + raise ValueError(f"file {child} is {len(data)} bytes > max_object_bytes {max_object_bytes}") + entries.append(_entry(child.name, KIND_BLOB, objects.add(KIND_BLOB, data), _file_mode(child))) + return _add_tree(entries, objects) + + +def build_commit(tree_hash: str, parents: List[str], *, owner: str, device: str, message: str, + objects: ObjectSet, ts: Optional[str] = None) -> str: + """Commit object address. ``parents``: 0 first commit, 1 edit, 2 merge (base first, other head second).""" + return objects.add(KIND_COMMIT, canonical_json_bytes({ + "type": KIND_COMMIT, "tree": tree_hash, "parents": list(parents), + "author": {"owner": owner, "device": device}, + "ts": ts or datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "message": message, "artifact_type": ARTIFACT_TYPE_SKILL})) + + +def build_root_tree(node: Dict[str, Any], objects: ObjectSet, *, manifest_hash: Optional[str] = None) -> str: + """Canonicalize a nested ``{name: {"__tree__": hash} | subdict}`` root into trees. ``manifest_hash`` + adds the root ``sync-manifest`` BLOB entry (cannot collide with a skill dir: those are trees).""" + entries: List[Dict[str, str]] = [] + for name, child in node.items(): + leaf = isinstance(child, dict) and "__tree__" in child and len(child) == 1 + entries.append(_entry(name, KIND_TREE, child["__tree__"] if leaf else build_root_tree(child, objects), + MODE_DIR)) + if manifest_hash is not None: + entries.append(_entry(SYNC_MANIFEST_ENTRY_NAME, KIND_BLOB, manifest_hash, MODE_FILE)) + return _add_tree(entries, objects) + + +def nest_skill_tree(root: Dict[str, Any], rel_parts: Tuple[str, ...], tree_hash: str) -> None: + """Insert a skill tree leaf into the nested root structure by path parts.""" + node = root + for part in rel_parts[:-1]: + node = node.setdefault(part, {}) + node[rel_parts[-1]] = {"__tree__": tree_hash} + + +def assemble_root_from_skill_trees(skill_trees: Dict[str, str], objects: ObjectSet) -> str: + """Profile-root tree from ``{posix_rel_path: tree_hash}``; skill trees are assumed durable, only + the new intermediate/root trees are added.""" + root: Dict[str, Any] = {} + for path, tree_hash in skill_trees.items(): + nest_skill_tree(root, PurePosixPath(path).parts, tree_hash) + return build_root_tree(root, objects) + + +# HTTP client (routes under /v1/sync/) +class SyncError(RuntimeError): + """A non-recoverable wire error (4xx the client can't retry).""" + + def __init__(self, message: str, *, status: Optional[int] = None): + super().__init__(message) + self.status = status + + +class SyncConflict(RuntimeError): + """CAS lost (409); NOT a rejection, pushed objects are durable. ``actual`` = head to merge against, + or None when the ref does not exist (server sends ""): retry as a create, never fetch it.""" + + def __init__(self, actual: Optional[str]): + self.actual: Optional[str] = actual or None + super().__init__(f"CAS conflict; actual head {self.actual}" if self.actual + else "CAS conflict; the ref does not exist yet") + + +def _check_version(caps: Dict[str, Any]) -> None: + """Reject an incompatible server major version.""" + ver = str(caps.get("hsp_version") or "") # wire field name + if ver.split(".", 1)[0] != WIRE_VERSION: + raise SyncError(f"this server speaks sync version {ver!r}, but this Hermes speaks " + f"{WIRE_VERSION} — update Hermes to sync with it") + + +def _body(r) -> Dict[str, Any]: + return r.json() if r.content else {} + + +def checked_capabilities(client: "SyncClient") -> Tuple[Dict[str, Any], int]: + """Version-checked ``(caps, max_object_bytes)`` for a sync session.""" + caps = client.capabilities() + _check_version(caps) + return caps, int(caps.get("max_object_bytes") or DEFAULT_MAX_OBJECT_BYTES) + + +class SyncClient: + """Sync client bound to a base URL + Nous bearer. Org refs/objects live behind SEPARATE ``org/`` + routes: the personal routes are hard-scoped to the token's owner and would silently answer an + org query with personal data, so org readers MUST pass ``org_scope=True`` on every hop.""" + + def __init__(self, base_url: str, api_key: str, *, timeout: float = 30.0): + self.base = base_url.rstrip("/") + self.api_key = api_key + self.timeout = timeout + import requests # core dependency + self._session = requests.Session() + self._session.headers["Authorization"] = f"Bearer {api_key}" + + def _request(self, method: str, path: str, op: str, *, ok=(200,), errors: Optional[Dict[int, Any]] = None, **kw): + """One wire call to ``/v1/sync/<path>``; SyncError unless the status is in *ok*. *errors* maps a + status to a message (str or ``fn(response)``); anything else gets ``"<op> failed: <code>"``.""" + r = self._session.request(method, f"{self.base}/v1/sync/{path.lstrip('/')}", timeout=self.timeout, **kw) + if r.status_code in ok: + return r + msg = (errors or {}).get(r.status_code) + raise SyncError((msg(r) if callable(msg) else msg) or f"{op} failed: {r.status_code}", status=r.status_code) + + def capabilities(self) -> Dict[str, Any]: + """GET capabilities (no auth required).""" + return self._request("GET", "capabilities", "capabilities").json() + + def get_refs(self, prefix: str, *, org_scope: bool = False) -> List[Dict[str, str]]: + """GET refs?prefix=... (or org/refs, filtered client-side by *prefix*).""" + path, params = ("org/refs", None) if org_scope else ("refs", {"prefix": prefix}) + refs = (self._request("GET", path, "get_refs", params=params).json() or {}).get("refs", []) + return [r_ for r_ in refs if str(r_.get("name", "")).startswith(prefix)] if org_scope else refs + + def get_object(self, obj_hash: str, *, org_scope: bool = False) -> Tuple[str, bytes]: + """GET objects/:hash -> ``(kind, bytes)``; kind from the object-type header, blob default.""" + r = self._request("GET", f"{'org/' if org_scope else ''}objects/{obj_hash}", "get_object", + errors={404: f"object {obj_hash} not found", 403: f"object {obj_hash} not readable"}) + return r.headers.get("X-HSP-Object-Type") or KIND_BLOB, r.content + + def _get_json_of_kind(self, obj_hash: str, expected: str, org_scope: bool) -> Dict[str, Any]: + kind, data = self.get_object(obj_hash, org_scope=org_scope) + if kind != expected: + raise SyncError(f"{obj_hash} is {kind}, expected {expected}") + return json.loads(data.decode("utf-8")) + + def get_commit_json(self, commit_hash: str, *, org_scope: bool = False) -> Dict[str, Any]: + return self._get_json_of_kind(commit_hash, KIND_COMMIT, org_scope) + + def get_tree_json(self, tree_hash: str, *, org_scope: bool = False) -> Dict[str, Any]: + return self._get_json_of_kind(tree_hash, KIND_TREE, org_scope) + + def put_objects(self, objects: Dict[str, Tuple[str, bytes]], *, org_scope: bool = False) -> Dict[str, Any]: + """POST objects as multipart (field = claimed ``sha256:<hex>``, filename = kind, body = raw + bytes; no base64-in-JSON). The server rehashes and 422s the whole batch on mismatch; known + hashes are no-ops. ``org_scope`` adds ``?scope=org`` (required before an org CAS/propose).""" + files = [(h, (kind, data, "application/octet-stream")) for h, (kind, data) in objects.items()] + return _body(self._request( + "POST", "objects", "put_objects", ok=(200, 201), files=files, + params={"scope": "org"} if org_scope else None, + errors={413: "object too large (413)", 422: lambda r: f"hash_mismatch (422): {r.text}"})) + + def cas_ref(self, name: str, from_hash: Optional[str], to_hash: str) -> Dict[str, Any]: + """POST refs/:name -- atomic CAS; SyncConflict on 409. A member's CAS on an org HEAD becomes a + proposal (202) -> ``{"proposal_pending": True, ...}``: success-shaped, never present as live.""" + r = self._request("POST", f"refs/{name}", "cas_ref", ok=(200, 202, 409), + json={"from": from_hash, "to": to_hash}, errors={403: "forbidden (403) -- owner/permission"}) + if r.status_code == 202: + return {"proposal_pending": True, **_body(r)} + if r.status_code == 409: # "" actual = the ref does not exist server-side (-> None) + raise SyncConflict((r.json() or {}).get("actual", "")) + return _body(r) + + +# Reading remote trees +def read_ref_hash(client: SyncClient, ref: str, *, org_scope: bool = False) -> Optional[str]: + """Hash of *ref* (queried with itself as prefix), or None if absent.""" + refs = client.get_refs(ref, org_scope=org_scope) + return next((r.get("hash") for r in refs if r.get("name") == ref), None) + + +def root_tree_of_commit(client: SyncClient, commit_hash: str, *, org_scope: bool = False) -> str: + return client.get_commit_json(commit_hash, org_scope=org_scope)["tree"] + + +def skill_trees_of_root(client: SyncClient, root_tree_hash: str, *, org_scope: bool = False) -> Dict[str, str]: + """``{posix_rel_path: skill_tree_hash}`` for every subtree containing a ``SKILL.md`` blob.""" + result: Dict[str, str] = {} + def _walk(tree_hash: str, prefix: str) -> None: + entries = client.get_tree_json(tree_hash, org_scope=org_scope).get("entries", []) + if prefix and any(e.get("name") == "SKILL.md" and e.get("kind") == KIND_BLOB for e in entries): + result[prefix] = tree_hash + return + for e in entries: + if e.get("kind") == KIND_TREE: + _walk(e["hash"], f"{prefix}/{e['name']}" if prefix else e["name"]) + _walk(root_tree_hash, "") + return result + + +def read_manifest_of_root(client: SyncClient, root_tree_hash: str) -> Optional[Dict[str, bool]]: + """``{name: enabled}`` from the root ``sync-manifest`` blob (how a device learns another's opt-ins).""" + try: + for e in client.get_tree_json(root_tree_hash).get("entries", []): + if e.get("name") == SYNC_MANIFEST_ENTRY_NAME and e.get("kind") == KIND_BLOB: + return parse_sync_manifest(client.get_object(e["hash"])[1]) + except Exception as e: + logger.debug("skills_sync_client: manifest read failed: %s", e) + return None + + +def materialize_tree(client: SyncClient, tree_hash: str, dest: Path, *, org_scope: bool = False) -> None: + """Write the tree into *dest*: blobs -> files (+x for ``exec``), trees -> subdirs. Does NOT delete + files absent from the tree (caller decides). Refuses path traversal.""" + dest.mkdir(parents=True, exist_ok=True) + for entry in client.get_tree_json(tree_hash, org_scope=org_scope).get("entries", []): + name = entry.get("name", "") + if not name or "/" in name or name in (".", ".."): + logger.warning("skills_sync_client: skipping unsafe tree entry %r", name) + continue + target, kind = dest / name, entry.get("kind") + if kind == KIND_TREE: + materialize_tree(client, entry["hash"], target, org_scope=org_scope) + elif kind == KIND_BLOB: + _, data = client.get_object(entry["hash"], org_scope=org_scope) + target.write_bytes(data) + if entry.get("mode") == MODE_EXEC: + with suppress(OSError): + target.chmod(target.stat().st_mode | _EXEC_BITS) + + +def merge_skill(base: Optional[str], ours: Optional[str], theirs: Optional[str]) -> str: + """Three-way decision: ``ours``/``theirs``/``either``/``overlap``/``none``. A side "modified" the + skill when its hash differs from the base (same semantics as skills_sync.py).""" + if ours == theirs: + return "either" if ours is not None else "none" + if theirs == base: # only we moved + return "ours" + if ours == base: # only they moved + return "theirs" + return "overlap" diff --git a/tools/skills_sync_optional.py b/tools/skills_sync_optional.py new file mode 100644 index 0000000000000000000000000000000000000000..313de12c8805eb4c915ce27015eaae6ba6af6281 --- /dev/null +++ b/tools/skills_sync_optional.py @@ -0,0 +1,235 @@ +"""Official optional-skill provenance: hub-lock backfill and restore. Profile-scoped paths and +patchable helpers resolve through ``_ss()`` at call time so ``tools.skills_sync`` patches work.""" + +import json +import logging +from contextlib import suppress +from datetime import datetime, timezone +from pathlib import Path, PurePosixPath +from typing import Dict, Iterator, List, Optional, Set, Tuple + +from agent.skill_utils import is_excluded_skill_path +from utils import atomic_write_text + +logger = logging.getLogger("tools.skills_sync") + + +def _ss(): + """Live ``tools.skills_sync`` module (imported lazily: it imports helpers from this module).""" + from tools import skills_sync + return skills_sync + + +def _content_hash(directory: Path) -> str: + """Hub-lock hash style; provenance metadata only, so fall back to local MD5 sans guard deps.""" + try: + from tools.skills_guard import content_hash + return content_hash(directory) + except Exception: + return _ss()._dir_hash(directory) + + +def _safe_rel_install_path(path: Path, base: Path) -> str: + """Normalized relative POSIX path; rejects traversal/absolute paths.""" + pure = PurePosixPath(posix := path.relative_to(base).as_posix()) + parts = [part for part in pure.parts if part not in {"", "."}] + if pure.is_absolute() or not parts or ".." in parts: + raise ValueError(f"Unsafe optional skill path: {posix}") + return "/".join(parts) + + +# Only generated runtime state, never generic cache/ or arbitrary dotfiles. This +# is updater ownership, not the security scanner's content-integrity policy. +_RUNTIME_CACHE_DIRS = frozenset({"__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache"}) + + +def _is_runtime_cache(path: Path, skill_dir: Path) -> bool: + """Whether a skill-relative path is disposable Python/tool runtime state. + + Install prefixes may themselves contain a cache directory name. Legacy + sibling bytecode is ignored only alongside its source; source-less .pyc + files can be deliberately shipped or user-owned content. + """ + relative = path.relative_to(skill_dir) + if any(part in _RUNTIME_CACHE_DIRS for part in relative.parts[:-1]): + return True + if path.name in _RUNTIME_CACHE_DIRS and path.is_dir(): + return True + return path.suffix in {".pyc", ".pyo"} and path.with_suffix(".py").is_file() + + +def _ignore_runtime_cache(directory: str, names: List[str]) -> List[str]: + """copytree callback: don't seed generated caches into managed packages.""" + root = Path(directory) + return [name for name in names if _is_runtime_cache(root / name, root)] + + +def _skill_file_list(skill_dir: Path) -> List[str]: + """List package files for provenance/diff, excluding generated runtime caches.""" + return [f.relative_to(skill_dir).as_posix() for f in sorted(skill_dir.rglob("*")) + if not _is_runtime_cache(f, skill_dir) and f.is_file()] + + +def _load_hub_lock() -> Optional[dict]: + """Parse the skills-hub lock; None when missing or unreadable.""" + try: + return json.loads((_ss()._skills_dir() / ".hub" / "lock.json").read_text(encoding="utf-8")) + except (FileNotFoundError, json.JSONDecodeError, OSError): + return None + + +def _hub_lock_entries(data: Optional[dict]) -> List[dict]: + return [e for e in ((data or {}).get("installed") or {}).values() if isinstance(e, dict)] + + +def _read_hub_install_paths() -> Set[str]: + """Hub-lock install paths as POSIX strings. Hub-installed skills are owned by the hub: rename + recovery must not move them even when content matches a bundled origin hash (dangling lock).""" + return {str(e["install_path"]).strip("/") for e in _hub_lock_entries(_load_hub_lock()) if e.get("install_path")} + + +def _iter_optional_skills(optional_dir: Path, *, root_relative: bool) -> Iterator[Tuple[Path, Path, str]]: + """Yield ``(skill_md, src, install_path)`` for every safe official optional skill.""" + for skill_md in sorted(optional_dir.rglob("SKILL.md")): + if (is_excluded_skill_path(skill_md.relative_to(optional_dir), root=optional_dir) + if root_relative else is_excluded_skill_path(skill_md)): + continue + try: + yield skill_md, skill_md.parent, _safe_rel_install_path(skill_md.parent, optional_dir) + except ValueError as e: + logger.debug("Skipping optional skill with unsafe path %s: %s", skill_md.parent, e) + + +def _optional_skill_index() -> Dict[str, Tuple[str, str, Path]]: + """Official optional skills keyed by BOTH folder name and frontmatter name (hub-lock slug or + user-facing name). Values are ``(folder_name, install_path, source_dir)``.""" + ss = _ss() + optional_dir = ss._get_optional_dir() + index: Dict[str, Tuple[str, str, Path]] = {} + if optional_dir.exists(): + for skill_md, src, install_path in _iter_optional_skills(optional_dir, root_relative=True): + value = (src.name, install_path, src) + index[src.name] = index[ss._read_skill_name(skill_md, src.name)] = value + return index + + +def _move_to_restore_backup(path: Path, backup_root: Path) -> str: + """Move an existing skill directory into a restore backup, preserving rel path.""" + ss = _ss() + rel = path.relative_to(ss._skills_dir()) + target, suffix = backup_root / rel, 0 + while target.exists(): + suffix += 1 + target = (backup_root / rel).with_name(f"{rel.name}-{suffix}") + ss._move_dir(path, target) + return rel.as_posix() + + +def restore_official_optional_skill(name: str, *, restore: bool = False) -> dict: + """Restore one or all official optional skills from repo source. ``restore=False`` only + backfills exact-match provenance; ``restore=True`` also backs up matching active copies + and copies the official source into its canonical path.""" + ss = _ss() + index = _optional_skill_index() + if index and name in {"all", "*"}: + targets = sorted(set(index.values()), key=lambda item: item[1]) + elif name in index: + targets = [index[name]] + else: + message = f"Official optional skill not found: {name}" if index else "No official optional skills directory found." + return {"ok": False, "message": message, "restored": [], "backfilled": [], "backed_up": []} + restored: List[str] = [] + backed_up: List[str] = [] + timestamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S") + backup_root = ss._skills_dir() / ".restore-backups" / f"official-optional-{timestamp}" + for folder_name, install_path, src in targets if restore else []: + dest = ss._skills_dir() / Path(*install_path.split("/")) + canonical_ok = dest.exists() and ss._dir_hash(dest) == ss._dir_hash(src) + # Active copies by frontmatter name or folder slug (the curator may have moved the skill + # into another category); ``dest`` itself is handled below. + names = {folder_name, ss._read_skill_name(src / "SKILL.md", folder_name)} + for md in ss._iter_active_skill_mds(sort=True): + match = md.parent + if match != dest and match.exists() and ( + match.name == folder_name or ss._read_skill_name(md, match.name) in names): + backed_up.append(_move_to_restore_backup(match, backup_root)) + if dest.exists() and not canonical_ok: + backed_up.append(_move_to_restore_backup(dest, backup_root)) + if not dest.exists(): + ss._copy_dir(src, dest) + restored.append(folder_name) + return { + "ok": True, "message": "Official optional skill repair complete.", "restored": restored, + "backfilled": _backfill_optional_provenance(quiet=True), "backed_up": backed_up, + "backup_dir": str(backup_root) if backed_up else ""} + + +def _index_installed_skill_dirs_by_name() -> Dict[str, List[Path]]: + """Installed skills by directory name in one active-tree scan, skipping anything that + resolves outside the skills tree (symlinks/external).""" + ss = _ss() + index: Dict[str, List[Path]] = {} + root = ss._skills_dir().resolve() + for skill_md in ss._iter_active_skill_mds(): + with suppress(OSError, ValueError): + skill_md.parent.resolve().relative_to(root) + index.setdefault(skill_md.parent.name, []).append(skill_md.parent) + return index + + +def _relocated_dest(src_name: str, index: Dict[str, List[Path]]) -> Optional[Tuple[Path, str]]: + """``(dest, install_path)`` of a UNIQUE same-directory-name match, else None: the active + tree may hold a skill under a DIFFERENT category than the repo (upstream reorganized, + installed copy kept its place); ambiguity gives no basis to pick.""" + if len(candidates := index.get(src_name, [])) != 1: + return None + try: + return candidates[0], _safe_rel_install_path(candidates[0], _ss()._skills_dir()) + except ValueError as e: + logger.debug("Skipping relocated optional skill %s: %s", candidates[0], e) + return None + + +def _backfill_optional_provenance(quiet: bool = False) -> List[str]: + """Mark already-present official optional skills as hub-installed: formerly bundled (or + hand-copied) skills now under optional-skills/ get official provenance when byte-identical + to the source; modified/local skills are left alone.""" + ss = _ss() + optional_dir = ss._get_optional_dir() + if not optional_dir.exists(): + return [] + data = _load_hub_lock() + if data is None: + data = {"version": 1, "installed": {}} + installed = data.setdefault("installed", {}) + existing_paths = {entry.get("install_path") for entry in _hub_lock_entries(data)} + backfilled: List[str] = [] + installed_dir_index: Optional[Dict[str, List[Path]]] = None + for _skill_md, src, install_path in _iter_optional_skills(optional_dir, root_relative=False): + lock_name = src.name + if lock_name in installed or install_path in existing_paths: + continue + dest = ss._skills_dir() / Path(*install_path.split("/")) + if not dest.is_dir(): + if installed_dir_index is None: + installed_dir_index = _index_installed_skill_dirs_by_name() + if (found := _relocated_dest(src.name, installed_dir_index)) is None: + continue + dest, install_path = found # still requires a byte-identical hash below + if install_path in existing_paths or ss._dir_hash(dest) != ss._dir_hash(src): + continue + timestamp = datetime.now(timezone.utc).isoformat() + installed[lock_name] = { + "source": "official", "identifier": f"official/{install_path}", + "trust_level": "builtin", "scan_verdict": "backfilled", + "content_hash": _content_hash(dest), "install_path": install_path, + "files": _skill_file_list(dest), "metadata": {"backfilled_from": "optional-skills"}, + "installed_at": timestamp, "updated_at": timestamp} + existing_paths.add(install_path) + backfilled.append(lock_name) + if not quiet: + print(f" = {lock_name} (official optional provenance backfilled)") + if backfilled: # atomic: a mid-write crash must not wipe provenance (reader resets bad JSON) + atomic_write_text(ss._skills_dir() / ".hub" / "lock.json", tmp_prefix=".lock_", + content=json.dumps(data, indent=2, ensure_ascii=False) + "\n") + return backfilled diff --git a/tools/skills_tool_plugin.py b/tools/skills_tool_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..043c3b0cfbc0ff8db168cc873e456588aaa9b992 --- /dev/null +++ b/tools/skills_tool_plugin.py @@ -0,0 +1,172 @@ +"""Plugin-provided skill serving for ``skill_view`` (``plugin:skill`` names) plus the JSON / +file-serving helpers shared with the local-skill path. Helpers tests patch on the origin module +(``_is_skill_disabled``, ``_parse_frontmatter``, ``skill_matches_platform``) resolve lazily.""" + +import json +import logging +from contextlib import suppress +from pathlib import Path +from typing import Any, Dict, List + +from tools.skills_tool_setup import SkillReadinessStatus + +logger = logging.getLogger("tools.skills_tool") + +MAX_NAME_LENGTH = 64 # Anthropic-recommended progressive-disclosure limits +MAX_DESCRIPTION_LENGTH = 1024 +_INJECTION_PATTERNS: list = [ # shared by local-skill and plugin-skill paths + "ignore previous instructions", "ignore all previous", "you are now", + "disregard your", "forget your instructions", "new instructions:", + "system prompt:", "<system>", "]]>"] +_SUPPORT_DIRS = ("references", "templates", "assets", "scripts") +_SKILL_FILE_EXTS = {".md", ".py", ".yaml", ".yml", ".json", ".tex", ".sh"} + + +def _json(payload: dict) -> str: + return json.dumps(payload, ensure_ascii=False) + + +def _fail(error: str, **extra) -> str: + return _json({"success": False, "error": error, **extra}) + + +def _read_skill_text(path: Path) -> str: + """utf-8-sig + errors="replace": user-authored SKILL.md may carry a Notepad BOM or stray + bytes; pinning UTF-8 keeps skill_view deterministic across host locales.""" + return path.read_text(encoding="utf-8-sig", errors="replace") + + +def _truncate_description(description: str) -> str: + if len(description) <= MAX_DESCRIPTION_LENGTH: + return description + return description[: MAX_DESCRIPTION_LENGTH - 3] + "..." + + +def _safe_frontmatter(path: Path | None = None, *, content: str | None = None) -> Dict[str, Any]: + """Frontmatter of *path* (or of *content*), ``{}`` on any read/parse failure. + Parses via ``tools.skills_tool._parse_frontmatter`` so test patches are honored.""" + from tools import skills_tool as _st + with suppress(Exception): + return _st._parse_frontmatter(_read_skill_text(path) if content is None else content)[0] + return {} + + +def _available_skill_files(skill_dir: Path) -> Dict[str, List[str]]: + """Non-SKILL.md files grouped by support dir (+ "other" for known source extensions + elsewhere); empty groups dropped.""" + groups: Dict[str, List[str]] = {} + for f in skill_dir.rglob("*"): + if not f.is_file() or f.name == "SKILL.md": + continue + rel = str(f.relative_to(skill_dir)) + top = rel.split("/", 1)[0] if "/" in rel else None + if top in _SUPPORT_DIRS or f.suffix in _SKILL_FILE_EXTS: + groups.setdefault(top if top in _SUPPORT_DIRS else "other", []).append(rel) + return {k: groups[k] for k in (*_SUPPORT_DIRS, "other") if k in groups} + + +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: + """Serve one linked file from a skill directory as a skill_view JSON result. ``hint`` + decorates traversal/containment errors; ``list_available`` adds the available-files listing + on not-found (local); ``read_error_prefix`` wraps non-decode read errors (plugin) instead + of propagating to the caller's handler.""" + from tools.path_security import has_traversal_component, validate_within_dir + extra = {"hint": hint} if hint else {} + if has_traversal_component(file_path): + return _fail("Path traversal ('..') is not allowed.", **extra) + target = skill_root / file_path + if path_error := validate_within_dir(target, skill_root): + return _fail(path_error, **extra) + # is_file(), not exists(): a bare directory must take the not-found branch. + if not target.is_file(): + listing = {} if not list_available else { + "available_files": _available_skill_files(skill_root), + "hint": "Use one of the available file paths listed above"} + return _fail(f"File '{file_path}' not found in skill '{label}'.", **listing) + try: + content = _read_skill_text(target) + except UnicodeDecodeError: + return _json({ + "success": True, "name": label, "file": file_path, "is_binary": True, + "content": f"[Binary file: {target.name}, size: {target.stat().st_size} bytes]"}) + except Exception as exc: + if not read_error_prefix: + raise + return _fail(f"Failed to read '{file_path}': {exc}") + if mark_read: + _mark_background_review_read(target) + return _json({ # _source_path: internal, feeds the repeat-view dedup fingerprint + "success": True, "name": label, "file": file_path, "content": content, + "file_type": target.suffix, "_source_path": str(target)}) + + +def _mark_background_review_read(path: Path) -> None: + try: + from tools.skill_manager_guards import mark_background_review_skill_read + mark_background_review_skill_read(path) + except Exception: + logger.debug("Could not record background-review skill read for %s", path, exc_info=True) + + +def _preprocess_skill(content: str, skill_dir, session_id, debug_msg: str, *args) -> str: + """Apply the configured SKILL.md preprocessing; on failure log and serve raw.""" + try: + from agent.skill_preprocessing import preprocess_skill_content + return preprocess_skill_content(content, skill_dir, session_id=session_id) + except Exception: + logger.debug(debug_msg, *args, exc_info=True) + return content + + +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: + """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 + if namespace in _get_disabled_plugins(): + return _fail(f"Plugin '{namespace}' is disabled. Re-enable with: hermes plugins enable {namespace}") + qualified_name = f"{namespace}:{bare}" + try: + content = _read_skill_text(skill_md) + except Exception as e: + return _fail(f"Failed to read skill '{qualified_name}': {e}") + parsed_frontmatter = _safe_frontmatter(content=content) + if _st._is_skill_disabled(qualified_name): + return _fail(f"Skill '{qualified_name}' is disabled.") + if not _st.skill_matches_platform(parsed_frontmatter): + return _fail(f"Skill '{qualified_name}' is not supported on this platform.", + readiness_status=SkillReadinessStatus.UNSUPPORTED.value) + if file_path: + return _serve_skill_file(skill_md.parent, file_path, qualified_name, read_error_prefix=True) + if any(p in content.lower() for p in _INJECTION_PATTERNS): + logger.warning( + "Plugin skill '%s:%s' contains patterns that may indicate prompt injection", namespace, bare) + banner = "" + with suppress(Exception): # bundle-context banner: sibling skills of the same plugin + siblings = [s for s in get_plugin_manager().list_plugin_skills(namespace) if s != bare] + banner = f"[Bundle context: This skill is part of the '{namespace}' plugin." + ( + f"\nSibling skills: {', '.join(siblings)}.\nUse qualified form to invoke siblings " + f"(e.g. {namespace}:{siblings[0]})." if siblings else "") + "]\n\n" + rendered_content = content if not preprocess else _preprocess_skill( + content, skill_md.parent, session_id, "Could not preprocess plugin skill %s:%s", + namespace, bare) + return _json({ + "success": True, "name": qualified_name, "content": banner + rendered_content, + "description": _truncate_description(str(parsed_frontmatter.get("description", ""))), + "linked_files": _plugin_skill_linked_files(skill_md.parent), + "readiness_status": SkillReadinessStatus.AVAILABLE.value}) + + +def _plugin_skill_linked_files(skill_root: Path) -> Dict[str, List[str]] | None: + from tools.path_security import validate_within_dir + linked: Dict[str, List[str]] = {} + for category in _SUPPORT_DIRS: + files = [ + str(path.relative_to(skill_root)) for path in sorted((skill_root / category).rglob("*")) + if path.is_file() and validate_within_dir(path, skill_root) is None] + if files: + linked[category] = files + return linked or None diff --git a/tools/subagent_worktree.py b/tools/subagent_worktree.py new file mode 100644 index 0000000000000000000000000000000000000000..9b1e4add6a9fd898eb8707b0aa5b9a49a1bdd9e3 --- /dev/null +++ b/tools/subagent_worktree.py @@ -0,0 +1,193 @@ +"""Opt-in git worktree isolation for delegated subagents (``delegation.worktree_isolation``). + +Git-only (outside a repo children share the parent's cwd); local terminal backend only (on +docker/ssh/modal the host worktree is invisible in the sandbox, so isolation is skipped). One +worktree per child under ``<repo>/.worktrees/subagent-<id>``, branch ``hermes-subagent/<id>``; +pruned only on proof (zero commits AND clean, both probes ok), else kept + ``inspection_failed``. +""" + +from __future__ import annotations + +import logging +import os +import subprocess +import uuid +from pathlib import Path +from typing import Any, Dict, Optional + +from hermes_cli._subprocess_compat import harden_git_argv, noninteractive_git_env + +logger = logging.getLogger(__name__) + +_GIT_TIMEOUT = 30 + + +def _run_git(args, cwd: str, timeout: int = _GIT_TIMEOUT): + """Run git capturing output; never raises on non-zero exit. + + :func:`noninteractive_git_env` (GHSA-7x36-8jrh-v4pw): this runs unattended against whatever + repo the parent sits in and ``worktree add`` runs hooks, so a malicious ``.git/config`` must + not execute. + """ + return subprocess.run(["git", *harden_git_argv(args)], cwd=cwd, capture_output=True, + text=True, encoding="utf-8", errors="replace", timeout=timeout, + stdin=subprocess.DEVNULL, env=noninteractive_git_env()) + + +def local_backend_active() -> bool: + """True when the terminal backend is local (worktrees visible to tools).""" + try: + from hermes_cli.config import load_config_readonly + + backend = (load_config_readonly().get("terminal") or {}).get("backend") or "local" + return str(backend).strip().lower() in ("", "local") + except Exception: + # Legacy entry points without the shared loader default to local. + return True + + +def resolve_repo_root(path: Optional[str]) -> Optional[str]: + """Return the git toplevel for *path*, or None when not in a work tree.""" + candidate = os.path.abspath(os.path.expanduser(str(path))) if path else "" + if not candidate or not os.path.isdir(candidate): + return None + try: + result = _run_git(["rev-parse", "--show-toplevel"], cwd=candidate) + except Exception as exc: + logger.debug("subagent worktree: rev-parse failed: %s", exc) + return None + return (result.stdout.strip() or None) if result.returncode == 0 else None + + +def _ensure_gitignore_entry(repo_root: str) -> None: + """Best-effort: keep ``.worktrees/`` out of git status.""" + gitignore = Path(repo_root) / ".gitignore" + try: + existing = gitignore.read_text(encoding="utf-8-sig", errors="replace") if gitignore.exists() else "" + if ".worktrees/" not in existing.splitlines(): + with open(gitignore, "a", encoding="utf-8") as f: + sep = "\n" if existing and not existing.endswith("\n") else "" + f.write(f"{sep}.worktrees/\n") + except Exception as exc: + logger.debug("subagent worktree: could not update .gitignore: %s", exc) + + +def create_subagent_worktree(parent_cwd: Optional[str], subagent_id: Optional[str] = None) -> Optional[Dict[str, str]]: + """Create an isolated worktree for one child; None (silent downgrade) outside git/on failure.""" + repo_root = resolve_repo_root(parent_cwd) + if not repo_root: + return None + wt_name = f"subagent-{(subagent_id or uuid.uuid4().hex[:8]).replace('/', '-')}" + branch = f"hermes-subagent/{wt_name}" + wt_path = Path(repo_root) / ".worktrees" / wt_name + try: + wt_path.parent.mkdir(parents=True, exist_ok=True) + _ensure_gitignore_entry(repo_root) + base = _run_git(["rev-parse", "HEAD"], cwd=repo_root) + base_commit = base.stdout.strip() if base.returncode == 0 else "" + result = _run_git(["worktree", "add", str(wt_path), "-b", branch, "HEAD"], cwd=repo_root) + except Exception as exc: + logger.warning("subagent worktree: creation failed: %s", exc) + return None + if result.returncode != 0: + # Common on repos with zero commits (unborn HEAD) — degrade silently. + logger.warning("subagent worktree: git worktree add failed: %s", result.stderr.strip()) + return None + logger.info("subagent worktree created: %s (branch %s)", wt_path, branch) + return {"path": str(wt_path), "branch": branch, "repo_root": repo_root, "base_commit": base_commit} + + +def _base_payload(info: Dict[str, str]) -> Dict[str, Any]: + """Result-entry schema the parent expects (no creation-side internals).""" + return {"path": info.get("path", ""), "branch": info.get("branch", ""), + "commits": 0, "dirty": False, "pruned": False} + + +def mark_worktree_payload_unproven(payload: Dict[str, Any], reason: str, *, + unmeasured: str = "commits/dirty") -> Dict[str, Any]: + """Flag a worktree result payload as un-inspected, in place. + + The parent only sees this dict, so the uncertainty must travel in it or "0 commits, clean" + reads as "the child produced nothing". *unmeasured* names only the fields actually left + unproven (one probe can succeed while the other fails). + + See #88113. + """ + path, branch = payload.get("path", ""), payload.get("branch", "") + payload["inspection_failed"] = True + payload["note"] = (f"git inspection failed ({reason}): {unmeasured} UNKNOWN — not proven " + f"zero/clean. The worktree and branch were preserved — inspect {path} " + f"(branch {branch}) before assuming no work.") + logger.warning("subagent worktree: git inspection failed (%s) — keeping %s (branch %s) " + "for manual review", reason, path, branch) + return payload + + +def unproven_worktree_payload(info: Dict[str, str], reason: str) -> Dict[str, Any]: + """Complete un-inspected payload for ``delegate_tool`` when finalize raises.""" + return mark_worktree_payload_unproven(_base_payload(info), reason) + + +def finalize_subagent_worktree(info: Dict[str, str], *, prune: bool = True) -> Dict[str, Any]: + """Inspect (and possibly prune) a child worktree after the child finishes. + + Prunes only when *prune*, commits==0, clean tree AND both git probes succeeded; otherwise + keeps it with ``inspection_failed`` + ``note`` (``commits``/``dirty`` then are defaults). + """ + path, branch = info.get("path", ""), info.get("branch", "") + base_commit = info.get("base_commit", "") + payload = _base_payload(info) + if not path or not os.path.isdir(path): + payload["pruned"] = True # nothing on disk to review + return payload + # Without a base commit the count is an unproven default, and the prune + # condition reads payload["commits"] — so it must not prune either. + # See #88113. + if not base_commit: + return mark_worktree_payload_unproven( + payload, "no base_commit recorded — commit count unmeasurable", unmeasured="commits") + failed, unmeasured = [], [] + probes = (("commits", "rev-list", ["rev-list", "--count", f"{base_commit}..HEAD"], + lambda s: int(s or 0)), + ("dirty", "status", ["status", "--porcelain"], bool)) + try: + for field, label, args, parse in probes: + res = _run_git(args, cwd=path) + if res.returncode == 0: + payload[field] = parse(res.stdout.strip()) + else: + failed.append(f"{label} exit {res.returncode}: {res.stderr.strip()[:200]}") + unmeasured.append(field) + except Exception as exc: + # Timeout, OSError or non-numeric rev-list stdout: which probe raised is + # unknowable, so neither value is trustworthy — keep the worktree. + return mark_worktree_payload_unproven(payload, f"inspection raised: {exc}") + if failed: + # Destructive cleanup requires affirmative proof; defaults prove nothing. + return mark_worktree_payload_unproven(payload, "; ".join(failed), unmeasured="/".join(unmeasured)) + if prune and payload["commits"] == 0 and not payload["dirty"]: + cwd = info.get("repo_root", "") or path + try: + removed = _run_git(["worktree", "remove", "--force", path], cwd=cwd) + if removed.returncode == 0: + _run_git(["branch", "-D", branch], cwd=cwd) + payload["pruned"] = True + logger.info("subagent worktree pruned (no work): %s", path) + else: + logger.debug("subagent worktree: prune failed: %s", removed.stderr.strip()) + except Exception as exc: + logger.debug("subagent worktree: prune failed: %s", exc) + return payload + + +def build_worktree_context_note(info: Dict[str, str]) -> str: + """Context block telling the child to work inside its isolated worktree.""" + return ( + "\n\n[WORKTREE ISOLATION] You are working in an isolated git worktree " + f"at: {info.get('path')}\n" + f"Your dedicated branch is: {info.get('branch')}\n" + "All file edits and shell commands must happen inside this worktree directory (your " + "terminal already starts there). Do NOT cd to the main repository checkout. Commit your " + "changes to your branch when done; the parent agent will review and merge your branch. If " + "you make no commits and leave the tree clean, the worktree is discarded automatically." + ) diff --git a/tools/terminal_hints.py b/tools/terminal_hints.py new file mode 100644 index 0000000000000000000000000000000000000000..fe155df040a9118764b69aa8cb91654abc05c81b --- /dev/null +++ b/tools/terminal_hints.py @@ -0,0 +1,160 @@ +"""Output-pattern failure hints for the terminal tool. + +Extends the exit-code semantics table in ``terminal_tool`` with a bounded scan of failed-command +output mapped to ONE short, actionable recovery hint. Rules: only fires on non-zero exit; first +match wins, patterns ordered by observed production frequency; scans only the first +``_SCAN_CHARS`` so hints key on error headers, not deep context; hints state the *next action* +in 1-2 sentences; pure function, no I/O or config reads. +""" + +from __future__ import annotations + +import re +from typing import Callable, Optional + +_SCAN_CHARS = 4000 + + +def _regex_hint(pattern: str, message: str | Callable[[str], str], flags: int = 0) -> Callable[[str, str], Optional[str]]: + """Hint firing when ``pattern`` matches; ``{0}`` = first group, or ``message(group1)``.""" + rx = re.compile(pattern, flags) + + def hint(command: str, output: str) -> Optional[str]: + m = rx.search(output) + if m: + return message(m.group(1)) if callable(message) else message.format(*m.groups()) + return None + + return hint + + +# Most `command not found` hits are bare `python` on python3-only distros. +_MISSING_COMMAND_HINTS = { + "python": "This system has no bare `python` — use `python3`, or the project venv's " + "interpreter (e.g. .venv/bin/python).", + "pip": "This system has no bare `pip` — use `pip3`, `python3 -m pip`, or the project venv's " + "pip (e.g. .venv/bin/pip).", +} + + +def _missing_command_hint(missing: str) -> str: + return _MISSING_COMMAND_HINTS.get(missing) or ( + f"`{missing}` is not installed or not on PATH. Verify with `which {missing}`; install it " + "or use an absolute path instead of retrying the same command.") + + +# Ordered by production frequency — first match wins. +_OUTPUT_HINTS: list[Callable[[str, str], Optional[str]]] = [ + # gh version drift; gh already prints the valid field list. + _regex_hint(r'Unknown JSON field: "?(\w+)', + "The installed gh does not support the JSON field '{0}'. The valid field list is " + "printed in the output above — retry using only fields from that list."), + _regex_hint(r"^CONFLICT |Automatic merge failed|needs merge", + "Git merge conflict. Do not retry this command. Resolve the conflicted files " + "listed above (edit, then `git add`), then continue (`git rebase --continue` / " + "commit the merge) — or abort with `--abort`.", re.M), + _regex_hint(r"(?:bash: line \d+: |bash: |sh: \d*:? ?)?([\w.+-]+): command not found", + _missing_command_hint), + # Almost always a venv-activation slip, not a missing dependency. + _regex_hint(r"(?:ModuleNotFoundError|ImportError): No module named '?([\w.]+)", + "Python cannot import '{0}'. Most often the wrong interpreter is running: " + "activate the project venv (e.g. `source .venv/bin/activate`) or invoke its python " + "directly. Only pip install if the package is genuinely absent from that venv."), + _regex_hint(r"(?:fatal|error):.*?'([^']+)' already exists", + "'{0}' already exists — retrying unchanged will keep failing. Reuse it, choose " + "another name, or delete it first if it is genuinely stale."), + _regex_hint(r"API rate limit|was submitted too quickly", + "GitHub API rate limit hit — immediate retries will keep failing. Continue with " + "other work and retry this operation later."), + _regex_hint(r"Permission denied|EACCES", + "Permission denied. Check ownership/mode of the target path (`ls -la`); prefer a " + "user-writable location. Only escalate to sudo if the task genuinely requires it."), +] + +# Exit-code-only hints for codes the terminal_tool semantics table does not +# cover per-command. Checked after output patterns. +_EXIT_CODE_HINTS: dict[int, str] = { + 126: "Exit 126: the file was found but is not executable — `chmod +x` it or invoke it via its interpreter (e.g. `bash script.sh`).", + 137: "Exit 137: the process was SIGKILLed — usually out-of-memory or an external kill. Reduce memory use or check `dmesg | tail` before retrying.", + 124: "Exit 124: the command hit its timeout. Raise timeout= (foreground max 600s) or run it with background=true and notify_on_complete=true.", +} + + +# Masked-success detection: `cargo build 2>&1 | tail -20` exits with tail's 0 +# (no pipefail) and `cargo build || echo FAILED` with echo's 0, so the model can +# conclude a build passed while the output says it failed. Conservative: BOTH a +# masking command shape AND a strong tool-specific failure shape must hold, and +# read-only heads (`grep ... | head`) are excluded because their output +# legitimately contains error text. Advisory only — exit_code is never changed. + +# Consumers whose exit status says nothing about the upstream command. +_PASSTHROUGH_CONSUMERS = r"(?:tail|head|cat|tee|less|more|wc|sort|uniq)" + +# Command shapes that swallow an upstream status -> warning, checked in order. +_MASKING_SHAPES: list[tuple[re.Pattern[str], str]] = [ + # Top-level `... | tail -20` (not `||`); consumer must be the LAST segment. + (re.compile(r"(?<!\|)\|(?!\|)\s*" + _PASSTHROUGH_CONSUMERS + r"\b[^|]*$"), + "exit_code 0 here is the status of the last pipeline command (tail/head/cat/...), NOT of " + "the command before the pipe — and the output contains failure indicators. Treat this run " + "as FAILED until proven otherwise: re-run the command WITHOUT the pipe (output is " + "auto-truncated and the full text is saved to a file, so piping through tail/head is never " + "needed) to get the real exit code."), + # `cmd || echo ...` / `cmd || true` — fallback swallows the failure status. + (re.compile(r"\|\|\s*(?:echo\b|printf\b|true\b|:\s|:$)"), + "exit_code 0 here is the status of the `||` fallback (echo/true), NOT of the command before " + "it — and the output contains failure indicators. Treat this run as FAILED until proven " + "otherwise: re-run the command bare to get its real exit code."), +] + +_READONLY_HEADS = frozenset({ + "grep", "rg", "ag", "find", "ls", "cat", "head", "tail", "jq", "awk", + "sed", "strings", "zcat", "journalctl", "dmesg", "echo", "printf"}) + +# Strong failure shapes keyed to specific tools so that error-mentioning +# *content* (diffs, logs, commit messages) rarely matches. +_FAILURE_SHAPES = re.compile( + r"(?:" + r"error\[E\d+\]" # rustc + r"|error: could not compile" # cargo + r"|error: aborting due to" # rustc summary + r"|Traceback \(most recent call last\)" # python + r"|(?m:^(?:=+ )?\d+ failed)" # pytest summary + r"|(?m:^FAILED (?:\S+::|\S+\.py))" # pytest per-test lines + r"|compilation terminated\." # gcc/clang + r"|npm ERR!" # npm + r"|BUILD FAILED|Build FAILED" # gradle/msbuild/echoed fallbacks + r"|FAILED: " # ninja + r"|(?m:^make(?:\[\d+\])?: \*\*\*)" # make + r")") + + +def _first_token(command: str) -> str: + """Basename of the command head, skipping leading env-var assignments.""" + for tok in (command or "").strip().split(): + if "=" not in tok or tok.startswith(("=", "./", "/")): + return tok.rsplit("/", 1)[-1] + return "" + + +def annotate_masked_success(command: str, output: str) -> Optional[str]: + """Warning note when an exit-0 result likely masks a failure (caller gates on exit 0).""" + cmd = command or "" + window = (output or "")[:_SCAN_CHARS] + if (not cmd or not window or _first_token(cmd) in _READONLY_HEADS + or not _FAILURE_SHAPES.search(window)): + return None + return next((note for rx, note in _MASKING_SHAPES if rx.search(cmd)), None) + + +def annotate_failure(command: str, exit_code: int, output: str) -> Optional[str]: + """Return one short recovery hint for a failed command, or None (exit 0).""" + if exit_code == 0: + return None + window = (output or "")[:_SCAN_CHARS] + for fn in _OUTPUT_HINTS if window else (): + try: + if hint := fn(command or "", window): + return hint + except Exception: + continue + return _EXIT_CODE_HINTS.get(exit_code) diff --git a/tools/terminal_tool_backends.py b/tools/terminal_tool_backends.py new file mode 100644 index 0000000000000000000000000000000000000000..335bb1c30486d31a009c8dcba67f6ac6a923a6cd --- /dev/null +++ b/tools/terminal_tool_backends.py @@ -0,0 +1,325 @@ +"""Execution-environment backends for the terminal tool: per-backend builders, config-to-kwargs +shapers, and requirement checkers, routed by dispatch/spec tables. Split out of ``tools/terminal_tool.py``; +the terminal tool imports the builders/checkers it uses from here.""" + +import functools +import importlib.util +import inspect +import logging +import shutil +import subprocess +from typing import Any, Dict, Optional + +from tools.environments.docker import DockerEnvironment as _DockerEnvironment +from tools.environments.local import LocalEnvironment as _LocalEnvironment +from tools.environments.managed_modal import ManagedModalEnvironment as _ManagedModalEnvironment +from tools.environments.modal import ModalEnvironment as _ModalEnvironment +from tools.environments.singularity import SingularityEnvironment as _SingularityEnvironment +from tools.environments.ssh import SSHEnvironment as _SSHEnvironment +from tools.managed_tool_gateway import is_managed_tool_gateway_ready +from tools.terminal_tool_config import _get_plugin_env_provider +from tools.tool_backend_helpers import (has_direct_modal_credentials, managed_nous_tools_enabled, + nous_tool_gateway_unavailable_message, resolve_modal_backend_state) + +# Log-record parity with the origin module. +logger = logging.getLogger("tools.terminal_tool") + +_VERCEL_SANDBOX_DEFAULT_CWD = "/vercel/sandbox" +_SUPPORTED_VERCEL_RUNTIMES = ("node24", "node22", "python3.13") +_BUILTIN_BACKENDS = "local, docker, singularity, modal, daytona, vercel_sandbox, ssh" + +# Config -> kwargs shapers, driven by (out_key, config_key, default) tables. The container table's +# (key, default) literal is intentionally greppable; tools/terminal_tool.py keeps its own for the AST test. +_SSH_KEYS = (("host", "ssh_host", ""), ("user", "ssh_user", ""), ("port", "ssh_port", 22), + ("key", "ssh_key", ""), ("persistent", "ssh_persistent", False)) +_RESOURCE_KEYS = (("cpu", "container_cpu", 1), ("memory", "container_memory", 5120), + ("disk", "container_disk", 51200), ("persistent_filesystem", "container_persistent", True)) +_CONTAINER_KEYS = ( + ("container_cpu", 1), ("container_memory", 5120), ("container_disk", 51200), + ("container_persistent", True), ("modal_mode", "auto"), ("vercel_runtime", ""), + ("docker_volumes", []), ("docker_mount_cwd_to_workspace", False), ("docker_forward_env", []), + ("docker_env", {}), ("docker_run_as_host_user", False), ("docker_extra_args", []), + ("docker_shm_size", "1g"), ("docker_network", True), ("docker_persist_across_processes", True), + ("docker_shared_container_key", ""), ("docker_orphan_reaper", True), ("docker_snap_compat", False), +) +_DOCKER_KWARGS = ( + ("volumes", "docker_volumes", []), ("auto_mount_cwd", "docker_mount_cwd_to_workspace", False), + ("forward_env", "docker_forward_env", []), ("env", "docker_env", {}), + ("run_as_host_user", "docker_run_as_host_user", False), ("network", "docker_network", True), + ("extra_args", "docker_extra_args", []), ("persist_across_processes", "docker_persist_across_processes", True), + ("shared_container_key", "docker_shared_container_key", ""), ("shm_size", "docker_shm_size", "1g"), + ("snap_compat", "docker_snap_compat", False), +) + + +def _ssh_config_from_config(config: Dict[str, Any]) -> dict: + """``ssh_config`` for :func:`_create_environment` (shared with the lazy ``ensure_task_env``).""" + return {out: config.get(key, default) for out, key, default in _SSH_KEYS} + + +def _container_config_from_config(config: Dict[str, Any]) -> dict: + """``container_config`` for :func:`_create_environment` (shared with the lazy ``ensure_task_env``).""" + return {k: config.get(k, d) for k, d in _CONTAINER_KEYS} + + +def _resources(cc: Dict[str, Any]) -> dict: + """Common sandbox resource kwargs (cpu/memory in MB/disk in MB/persistence).""" + return {out: cc.get(key, default) for out, key, default in _RESOURCE_KEYS} + + +def _is_supported_vercel_runtime(runtime: str) -> bool: + return not runtime or runtime in _SUPPORTED_VERCEL_RUNTIMES + + +def _get_modal_backend_state(modal_mode: object | None) -> Dict[str, Any]: + """Resolve direct vs managed Modal backend selection.""" + return resolve_modal_backend_state(modal_mode, has_direct=has_direct_modal_credentials(), + managed_ready=is_managed_tool_gateway_ready("modal")) + + +def _modal_unavailable_reason(modal_state: Dict[str, Any]) -> tuple[str, str]: + """(log message, ValueError message) for a modal_state with no selected backend. + Single decision shared by the requirements checker and the env builder.""" + gateway = nous_tool_gateway_unavailable_message("managed Modal execution") + if modal_state["managed_mode_blocked"] or modal_state["mode"] == "managed": + tail = (("Nous Tool Gateway access is not currently available and no direct Modal credentials/config " + f"were found. {gateway} Choose TERMINAL_MODAL_MODE=direct/auto to use direct Modal credentials.") + if modal_state["managed_mode_blocked"] else f"the managed tool gateway is unavailable. {gateway}") + return (f"Modal backend selected with TERMINAL_MODAL_MODE=managed, but {tail}", + f"Modal backend is configured for managed mode, but {tail}") + managed = managed_nous_tools_enabled() + if modal_state["mode"] == "direct": + return ("Modal backend selected with TERMINAL_MODAL_MODE=direct, but no direct Modal credentials/config " + f"were found. Configure Modal or choose TERMINAL_MODAL_MODE={'managed/auto' if managed else 'auto'}.", + "Modal backend is configured for direct mode, but no direct Modal credentials/config were found.") + found = "or managed tool gateway was found" if managed else "was found" + fix = ", set up the managed gateway, or" if managed else " or" + return (f"Modal backend selected but no direct Modal credentials/config {found}. " + f"Configure Modal{fix} choose a different TERMINAL_ENV.", + f"Modal backend selected but no direct Modal credentials/config {found}.") + + +# --- Environment builders. Signature: (*, env_type, image, cwd, timeout, cc, task_id, ssh_config, host_cwd) +def _build_local_env(*, cwd, timeout, **_): + return _LocalEnvironment(cwd=cwd, timeout=timeout) + + +def _build_docker_env(*, image, cwd, timeout, cc, task_id, host_cwd, **_): + from tools.terminal_tool import (_docker_session_isolation_enabled, _has_isolation_overrides, + _maybe_reap_docker_orphans) + # One-shot reaper for labeled containers orphaned by prior Hermes processes that died before + # atexit (SIGKILL / OOM / closed terminal); ``terminal.docker_orphan_reaper: false`` disables it. + _maybe_reap_docker_orphans(cc) + # A session-keyed container must not outlive its session, so cross-process reuse/persist is + # disabled for it (cleanup_vm()/idle reaper stop+rm it). The shared "default" container and + # RL/benchmark override sandboxes keep their existing lifecycle. + session_scoped = (_docker_session_isolation_enabled() and task_id != "default" + and not _has_isolation_overrides(task_id)) + kwargs = {out: cc.get(key, default) for out, key, default in _DOCKER_KWARGS} + if session_scoped: + kwargs["persist_across_processes"] = False + docker_env_obj = _DockerEnvironment(image=image, cwd=cwd, timeout=timeout, task_id=task_id, host_cwd=host_cwd, + **_resources(cc), **kwargs) + # Marker read by is_persistent_env(): a session-scoped container survives BETWEEN turns (skip + # per-turn teardown) but is removed at session close / idle timeout. Test doubles may reject attrs. + if session_scoped: + try: + docker_env_obj._session_scoped = True + except AttributeError: + pass + return docker_env_obj + + +def _build_modal_env(*, image, cwd, timeout, cc, task_id, **_): + res = _resources(cc) + sandbox_kwargs = {k: res[k] for k in ("cpu", "memory") if res[k] > 0} + if res["disk"] > 0: + try: + import modal + if "ephemeral_disk" in inspect.signature(modal.Sandbox.create).parameters: + sandbox_kwargs["ephemeral_disk"] = res["disk"] + except Exception: + pass + modal_state = _get_modal_backend_state(cc.get("modal_mode")) + selected = modal_state["selected_backend"] + if selected not in ("managed", "direct"): + raise ValueError(_modal_unavailable_reason(modal_state)[1]) + cls = _ManagedModalEnvironment if selected == "managed" else _ModalEnvironment + return cls(image=image, cwd=cwd, timeout=timeout, modal_sandbox_kwargs=sandbox_kwargs, + persistent_filesystem=res["persistent_filesystem"], task_id=task_id) + + +# env_type -> (class getter, takes image, extra kwargs from (cc, resource kwargs)). SDK-backed modules +# (daytona/vercel) are imported lazily so they are only required when that backend is selected. +_SANDBOX_ROWS = { + "singularity": (lambda: _SingularityEnvironment, True, lambda cc, kw: {}), + "daytona": (lambda: importlib.import_module("tools.environments.daytona").DaytonaEnvironment, True, + lambda cc, kw: {"cpu": int(kw["cpu"])}), + "vercel_sandbox": (lambda: importlib.import_module("tools.environments.vercel_sandbox").VercelSandboxEnvironment, + False, lambda cc, kw: {"runtime": cc.get("vercel_runtime") or None}), +} + + +def _build_sandbox_env(env_type, *, image, cwd, timeout, cc, task_id, **_): + cls, with_image, extra = _SANDBOX_ROWS[env_type] + kwargs = dict(cwd=cwd, timeout=timeout, task_id=task_id, **_resources(cc), + **({"image": image} if with_image else {})) + kwargs.update(extra(cc, kwargs)) + return cls()(**kwargs) + + +_build_singularity_env = functools.partial(_build_sandbox_env, "singularity") +_build_daytona_env = functools.partial(_build_sandbox_env, "daytona") +_build_vercel_env = functools.partial(_build_sandbox_env, "vercel_sandbox") + + +def _build_ssh_env(*, cwd, timeout, ssh_config, probe_only=False, **_): + if not ssh_config or not ssh_config.get("host") or not ssh_config.get("user"): + raise ValueError("SSH environment requires ssh_host and ssh_user to be configured") + return _SSHEnvironment(host=ssh_config["host"], user=ssh_config["user"], port=ssh_config.get("port", 22), + key_path=ssh_config.get("key", ""), cwd=cwd, timeout=timeout, probe_only=probe_only) + + +def _build_plugin_env(*, env_type, image, cwd, timeout, cc, task_id, **_): + provider = _get_plugin_env_provider(env_type) + if provider is not None: + env_obj = provider.create_environment(cwd=cwd, timeout=timeout, task_id=task_id, image=image, + container_config=cc) + # Stamp the backend name so path-resolution and progress surfaces can identify plugin + # backends without class-name sniffing. Test doubles may reject attributes. + try: + env_obj._hermes_backend_name = provider.name.strip().lower() + except AttributeError: + pass + return env_obj + try: + from agent.terminal_env_registry import plugin_backend_names + plugin_names = plugin_backend_names() + except Exception: + plugin_names = [] + known = ", ".join(f"'{n}'" for n in _BUILTIN_BACKENDS.split(", ") + list(plugin_names)) + raise ValueError(f"Unknown environment type: {env_type}. Use {known}") + + +# Built-in backend -> builder. Anything else is looked up in the plugin registry. +_ENV_BUILDERS = {"local": _build_local_env, "docker": _build_docker_env, "singularity": _build_singularity_env, + "modal": _build_modal_env, "daytona": _build_daytona_env, "vercel_sandbox": _build_vercel_env, + "ssh": _build_ssh_env} + + +def _create_environment(env_type: str, image: str, cwd: str, timeout: int, + ssh_config: dict = None, container_config: dict = None, + local_config: dict = None, task_id: str = "default", + host_cwd: Optional[str] = None, probe_only: bool = False): + """Create an execution environment (instance with ``execute()``) for *env_type*. ``image`` is ignored + for local/ssh/vercel; ``container_config`` carries the container_*/docker_* resource keys; ``host_cwd`` is + the host dir bound into Docker when cwd mounting is enabled. ``probe_only`` asks ssh for a throwaway + connection with no remote setup/sync (the prompt-time probe). Unknown types fall through to plugin backends.""" + builder = _ENV_BUILDERS.get(env_type, _build_plugin_env) + return builder(env_type=env_type, image=image, cwd=cwd, timeout=timeout, cc=container_config or {}, + task_id=task_id, ssh_config=ssh_config, host_cwd=host_cwd, probe_only=probe_only) + + +# --- Requirement checkers: one generic path driven by _BACKEND_SPECS; optional fields, checked in order: +# pre(config) -> True (satisfied) / False (rejected, already logged) / None (continue); +# binary=(finder, version_arg, missing_log_or_None) runs ``<binary> <arg>``, ok iff rc == 0; +# module=(find_spec name, log message when absent); post(config) -> bool. +def _check_vercel(config: Dict[str, Any]) -> bool: + """Runtime -> disk -> SDK -> auth (OIDC token, else the full TOKEN/PROJECT_ID/TEAM_ID tuple).""" + runtime = (config.get("vercel_runtime") or "").strip() + disk = config.get("container_disk", 51200) + if not _is_supported_vercel_runtime(runtime): + logger.error("Vercel Sandbox runtime %r is not supported. Set TERMINAL_VERCEL_RUNTIME to one of: %s.", + runtime, ", ".join(_SUPPORTED_VERCEL_RUNTIMES)) + return False + if disk not in {0, 51200}: + logger.error("Vercel Sandbox does not support custom TERMINAL_CONTAINER_DISK=%s. " + "Use the default shared setting (51200 MB).", disk) + return False + if importlib.util.find_spec("vercel") is None: + logger.error("vercel is required for the Vercel Sandbox terminal backend: pip install vercel") + return False + from agent.secret_scope import get_secret + if get_secret("VERCEL_OIDC_TOKEN"): + return True + present = [bool(get_secret(k)) for k in ("VERCEL_TOKEN", "VERCEL_PROJECT_ID", "VERCEL_TEAM_ID")] + if all(present): + return True + head = ("selected with token auth, but VERCEL_TOKEN, VERCEL_PROJECT_ID, and VERCEL_TEAM_ID must all be " + "set together." if any(present) else + "selected but no supported auth configuration was found. Set VERCEL_TOKEN, VERCEL_PROJECT_ID, " + "and VERCEL_TEAM_ID for normal use.") + logger.error(f"Vercel Sandbox backend {head} VERCEL_OIDC_TOKEN is supported for one-off local development only.") + return False + + +def _modal_pre(config: Dict[str, Any]) -> Optional[bool]: + modal_state = _get_modal_backend_state(config.get("modal_mode")) + if modal_state["selected_backend"] == "managed": + return True + if modal_state["selected_backend"] != "direct": + logger.error(_modal_unavailable_reason(modal_state)[0]) + return False + return None + + +def _ssh_pre(config: Dict[str, Any]) -> bool: + if config.get("ssh_host") and config.get("ssh_user"): + return True + logger.error("SSH backend selected but TERMINAL_SSH_HOST and TERMINAL_SSH_USER " + "are not both set. Configure both or switch TERMINAL_ENV to 'local'.") + return False + + +def _daytona_post(config: Dict[str, Any]) -> bool: + from daytona import Daytona # noqa: F401 — SDK presence check (ImportError propagates) + from agent.secret_scope import get_secret + return get_secret("DAYTONA_API_KEY") is not None + + +_BACKEND_SPECS: Dict[str, Dict[str, Any]] = { + "local": {}, + "docker": {"binary": (lambda: importlib.import_module("tools.environments.docker").find_docker(), "version", + "Docker executable not found in PATH or common install locations")}, + "singularity": {"binary": (lambda: shutil.which("apptainer") or shutil.which("singularity"), "--version", None)}, + "ssh": {"pre": _ssh_pre}, + "modal": {"pre": _modal_pre, + "module": ("modal", "modal is required for direct modal terminal backend: pip install modal")}, + "vercel_sandbox": {"pre": _check_vercel}, + "daytona": {"post": _daytona_post}, +} + + +def _check_requirements(env_type: str, config: Dict[str, Any]) -> bool: + spec = _BACKEND_SPECS[env_type] + verdict = spec["pre"](config) if "pre" in spec else None + if verdict is not None: + return verdict + if "binary" in spec: + finder, arg, missing_msg = spec["binary"] + executable = finder() + if not executable: + if missing_msg: + logger.error(missing_msg) + return False + probe = subprocess.run([executable, arg], capture_output=True, timeout=5, stdin=subprocess.DEVNULL) + return probe.returncode == 0 + if "module" in spec and importlib.util.find_spec(spec["module"][0]) is None: + logger.error(spec["module"][1]) + return False + return spec["post"](config) if "post" in spec else True + + +def _check_plugin_requirements(config: Dict[str, Any]) -> bool: + env_type = config["env_type"] + provider = _get_plugin_env_provider(env_type) + if provider is not None: + return bool(provider.check_requirements(config)) + logger.error("Unknown TERMINAL_ENV '%s'. Use one of: %s, or a plugin-registered backend.", + env_type, _BUILTIN_BACKENDS) + return False + + +# Built-in backend -> requirements checker; unknown backends go to the plugin registry. +_REQUIREMENT_CHECKERS = {name: functools.partial(_check_requirements, name) for name in _BACKEND_SPECS} +_check_vercel_sandbox_requirements = _REQUIREMENT_CHECKERS["vercel_sandbox"] # used by code_execution_tool diff --git a/tools/terminal_tool_background.py b/tools/terminal_tool_background.py new file mode 100644 index 0000000000000000000000000000000000000000..3824a79544266648a0358f9be3384667c3722dae --- /dev/null +++ b/tools/terminal_tool_background.py @@ -0,0 +1,244 @@ +"""Background-process launch path: ``terminal(background=true)`` spawns a tracked +process via the process registry (Popen locally, ``env.execute`` in a sandbox), +stamps gateway routing metadata for completion / watch-pattern notifications and +returns the JSON result. Lazy ``tools.terminal_tool`` imports keep the origin's +monkeypatch points authoritative. +""" + +import json +import logging +from typing import Any, List, Optional + +logger = logging.getLogger("tools.terminal_tool") + +# A silent background process (no notify_on_complete / watch_patterns) is right +# only for servers/watchers; for bounded tasks the agent almost always wanted a +# notification and forgot the flag, so nudge it (cheap false positive). +_SILENT_BACKGROUND_HINT = ( + 'background=true without notify_on_complete=true means this process runs SILENTLY — you ' + 'will not be told when it exits. If this is a bounded task (test suite, build, CI poller, ' + 'deploy, anything with a defined end), you almost certainly wanted notify_on_complete=true ' + 'so the system pings you on exit. Re-launch with notify_on_complete=true, or call ' + "process(action='poll') / process(action='wait') yourself to learn the outcome. Only " + 'ignore this hint for genuine long-lived processes that never exit (servers, watchers, ' + 'daemons).' +) + +# Homebrewed CI pollers built on `gh pr view --json statusCheckRollup` or +# `gh pr checks | jq` fail silently in known ways (block-buffered stdout never +# reaches capture, jq null-key edge cases exit the loop, conclusion-vs-status +# confusion declares all-green early, TTY-only banners never appear piped). +# Detector is deliberately narrow: the canonical column-2 awk poller is fine. +_HOMEBREW_CI_POLLER_HINT = ( + 'This looks like a homebrewed CI poller built from `gh pr view --json statusCheckRollup` ' + 'and/or `gh pr checks | jq`. That shape has burned us repeatedly in hermes-agent dev work ' + '(PRs #31329, #31448, #31695, #31709, #31745, #32264, #33131) — stdout buffering kills ' + 'output capture, jq null-key edge cases silently exit the loop, conclusion-vs-status field ' + 'confusion exits early with bogus all-green verdicts, TTY-only summary banners never ' + 'appear when piped. Use the canonical snippets in the green-ci-policy skill instead: the ' + 'exit-code-driven `gh pr checks $PR >/dev/null` (rc 0 = green, 8 = pending, else fail) for ' + 'exit-on-first-fail behavior, or the column-2 awk-on-tabs poller (`awk -F"\\t" ' + '"$2==\\"pending\\""`) for sharded matrices. Load ' + "skill_view(name='github/hermes-agent-dev', file_path='references/green-ci-policy.md') for " + 'the verbatim snippets. If you must roll a custom loop with rich structured output, write ' + "each tick to a known file (`tee -a /tmp/ci.log`) and rely on `process(action='log')` to " + 'read THAT file — do not rely on background-process stdout capture for line-buffered shell ' + 'loops.' +) + +_ASYNC_UNSUPPORTED_NOTE = ( + 'notify_on_complete / watch_patterns are not available in this session — it cannot receive ' + 'an async completion after the turn ends (a one-shot runner such as `hermes -z`, a cron ' + 'job, a Kanban worker, or a stateless HTTP endpoint). The process is running in the ' + "background; retrieve its result with process(action='poll') or process(action='wait')." +) + +# proc_session attribute -> HERMES_SESSION_* env var carrying it. +_ROUTING_FIELDS = ( + ("watcher_chat_id", "HERMES_SESSION_CHAT_ID"), + ("watcher_user_id", "HERMES_SESSION_USER_ID"), + ("watcher_user_name", "HERMES_SESSION_USER_NAME"), + ("watcher_thread_id", "HERMES_SESSION_THREAD_ID"), + ("watcher_message_id", "HERMES_SESSION_MESSAGE_ID"), + # The spawning conversation's session-db id lets the gateway's completion + # pre-flight drop the notification if the user closed this session (/new) + # before the process finished, instead of injecting it into the NEW one. + ("parent_session_id", "HERMES_SESSION_ID"), +) + + +def _looks_like_homebrew_ci_poller(command: str) -> bool: + has_gh = "gh pr view" in command or "gh pr checks" in command + has_jq = " jq " in command or "| jq" in command or "$(jq" in command + # `gh pr checks` doesn't emit JSON, so piping it to jq is confused intent. + return "statusCheckRollup" in command or (has_gh and has_jq) + + +def _stamp_gateway_routing(proc_session, get_session_env) -> None: + """Copy the spawning chat's routing metadata onto the process session so + completion / watch notifications reach the right chat/thread.""" + platform = get_session_env("HERMES_SESSION_PLATFORM", "") + if not platform: + return + proc_session.watcher_platform = platform + for attr, var in _ROUTING_FIELDS: + setattr(proc_session, attr, get_session_env(var, "")) + + +def _spawn(process_registry, *, env, env_type, command, cwd, effective_task_id, task_id, + session_key, effective_pty): + common = dict(command=command, cwd=cwd, task_id=effective_task_id, + owner_task_id=task_id or effective_task_id, session_key=session_key) + if env_type == "local": + return process_registry.spawn_local( + env_vars=env.env if hasattr(env, 'env') else None, use_pty=effective_pty, **common) + return process_registry.spawn_via_env(env=env, **common) + + +def _apply_async_support(proc_session, result_data, notify_on_complete, watch_patterns): + """Finite sessions (stateless HTTP, one-shot Kanban workers) can't route a + completion back after the turn ends: drop the flags and tell the agent to + poll. Otherwise stamp gateway routing. Returns (notify, watch_patterns).""" + if not (notify_on_complete or watch_patterns): + return notify_on_complete, watch_patterns + from gateway.session_context import async_delivery_supported, get_session_env + + if async_delivery_supported(): + _stamp_gateway_routing(proc_session, get_session_env) + return notify_on_complete, watch_patterns + result_data["notify_on_complete"] = False + result_data["notify_unsupported"] = _ASYNC_UNSUPPORTED_NOTE + logger.info("background proc %s: async delivery unsupported on this " + "session; notify_on_complete/watch_patterns disabled", proc_session.id) + return False, None + + +def _register_completion_watcher(process_registry, proc_session, session_key) -> None: + """Gateway mode: register a fast watcher so completion triggers a new + agent turn (CLI mode uses the completion_queue directly).""" + proc_session.watcher_interval = 5 + process_registry.pending_watchers.append({ + "session_id": proc_session.id, "check_interval": 5, "session_key": session_key, + "platform": proc_session.watcher_platform, + **{attr.removeprefix("watcher_"): getattr(proc_session, attr) + for attr, _ in _ROUTING_FIELDS[:-1]}, + "notify_on_complete": True, "parent_session_id": proc_session.parent_session_id, + }) + + +def spawn_background_process( + *, command: str, env: Any, env_type: str, effective_task_id: str, task_id: Optional[str], + session_key: str, workdir: Optional[str], cwd: str, effective_pty: bool, + notify_on_complete: bool, watch_patterns: Optional[List[str]], approval_note: Optional[str], + pty_disabled_reason: Optional[str], +) -> str: + """Spawn *command* as a tracked background process and return the JSON result. + + Never inline-polls ``is_interrupted()``: the spawn detaches and returns + exit_code 0 immediately, so the stale-interrupt kill cannot occur here. + """ + from tools.process_registry import process_registry + from tools.terminal_tool import ( + _redact_terminal_error_text, _resolve_command_cwd, _resolve_notification_flag_conflict, + ) + + effective_cwd = _resolve_command_cwd( + workdir=workdir, default_cwd=cwd, session_key=session_key, env_type=env_type, + ) + try: + proc_session = _spawn( + process_registry, env=env, env_type=env_type, command=command, cwd=effective_cwd, + effective_task_id=effective_task_id, task_id=task_id, session_key=session_key, + effective_pty=effective_pty, + ) + result_data = {"output": "Background process started", "session_id": proc_session.id, + "pid": proc_session.pid, "exit_code": 0, "error": None} + if approval_note: + result_data["approval"] = approval_note + if pty_disabled_reason: + result_data["pty_note"] = pty_disabled_reason + if not notify_on_complete and not watch_patterns: + result_data["hint"] = _SILENT_BACKGROUND_HINT + if command and _looks_like_homebrew_ci_poller(command): + existing = result_data.get("hint", "") + result_data["hint"] = (existing + "\n\n" + _HOMEBREW_CI_POLLER_HINT if existing + else _HOMEBREW_CI_POLLER_HINT) + + notify_on_complete, watch_patterns = _apply_async_support( + proc_session, result_data, notify_on_complete, watch_patterns) + watch_patterns, conflict_note = _resolve_notification_flag_conflict( + notify_on_complete=bool(notify_on_complete), watch_patterns=watch_patterns, background=True, + ) + if conflict_note: + logger.warning("background proc %s: %s", proc_session.id, conflict_note) + result_data["watch_patterns_ignored"] = conflict_note + if notify_on_complete: + proc_session.notify_on_complete = True + result_data["notify_on_complete"] = True + if proc_session.watcher_platform: + _register_completion_watcher(process_registry, proc_session, session_key) + from agent.delegation_context import is_delegated_child_context + if is_delegated_child_context(): + result_data["notify_on_complete"] = False + result_data["subagent_note"] = _SUBAGENT_NOTIFY_NOTE + if watch_patterns: + proc_session.watch_patterns = list(watch_patterns) + result_data["watch_patterns"] = proc_session.watch_patterns + return json.dumps(result_data, ensure_ascii=False) + except Exception as e: + return json.dumps({ + "output": "", "exit_code": -1, + "error": _redact_terminal_error_text(f"Failed to start background process: {e}"), + }, ensure_ascii=False) + + +_SUBAGENT_NOTIFY_NOTE = ( + "You are a subagent: this process's completion notice will NOT reach your parent, and the process is killed when " + "you finish. Before you finish, either wait for it (process_manage wait), kill it, or hand it to your parent with " + "process_manage(action='handoff', session_id=..., data='<purpose>') so the parent receives its completion. For CI " + "watchers prefer returning the fact (PR number, SHA) and letting the parent watch." +) + +_YIELDED_NOTE = ( + "The user sent a message while this command was running, so it was moved to the " + "background WITHOUT being killed and is still running. You will be notified when it " + "exits (notify_on_complete). Read the user's message and respond to it now; use " + "process(action='poll'|'wait'|'log', session_id=...) to check on this command." +) + + +def yield_to_background_handler( + *, command: str, env_type: str, cwd: Optional[str], effective_task_id: str, + task_id: Optional[str], session_key: str, +): + """Build the ``yield_handler`` a foreground ``env.execute`` calls when the tool thread is + asked to yield (a user message arrived mid-command). Local backend only: the live Popen + is adopted by the process registry as a notify-on-complete background session and the + partial output is returned to the model right away. Other backends return None (no + adoptable host process) and the foreground wait continues.""" + if env_type != "local": + return None + + def _handler(proc, output_so_far: str) -> dict: + from tools.process_registry import process_registry + session = process_registry.adopt_local( + proc, command=command, cwd=cwd, task_id=effective_task_id, + owner_task_id=task_id or effective_task_id, session_key=session_key, + output_so_far=output_so_far) + _stamp_routing_if_gateway(process_registry, session, session_key) + logger.info("foreground command yielded to background as %s (pid %s)", session.id, session.pid) + return { + "output": output_so_far, "returncode": None, "yielded_session_id": session.id, "pid": session.pid, + } + return _handler + + +def _stamp_routing_if_gateway(process_registry, session, session_key) -> None: + """Route the adopted session's completion like a normal notify_on_complete spawn.""" + from gateway.session_context import async_delivery_supported, get_session_env + if not async_delivery_supported(): + session.notify_on_complete = False + return + _stamp_gateway_routing(session, get_session_env) + if session.watcher_platform: + _register_completion_watcher(process_registry, session, session_key) diff --git a/tools/terminal_tool_lifecycle.py b/tools/terminal_tool_lifecycle.py new file mode 100644 index 0000000000000000000000000000000000000000..ba2c2cc9e12e88d94192f1a1c4b9fe91c5308e5a --- /dev/null +++ b/tools/terminal_tool_lifecycle.py @@ -0,0 +1,328 @@ +"""Sandbox lifecycle for the terminal tool: idle reaping, teardown, manual/atexit +cleanup, and the lazy ensure_task_env bring-up. The env cache dicts and locks +stay in tools.terminal_tool (tests patch them there) and are read through it +at call time. + +Split out of ``tools/terminal_tool.py``; every public/patched name is re-imported there, +so ``tools.terminal_tool.<name>`` keeps resolving (and monkeypatching) as before. +""" + +import glob +import logging +import inspect +import shutil +import threading +import time +from pathlib import Path +from typing import Any, Dict, Optional +from tools.environments.singularity import _get_scratch_dir +from tools.terminal_tool_backends import ( + _container_config_from_config, + _ssh_config_from_config, +) +from tools.terminal_tool_config import _quiet + +# Log-record parity with the origin module. +logger = logging.getLogger("tools.terminal_tool") + + +# Advisory disk-usage check; cached so the recursive scan doesn't run on +# every command (a result up to 5 minutes stale is harmless). +_disk_usage_cache: dict = {"timestamp": 0.0, "result": False} + +_DISK_USAGE_CACHE_TTL = 300.0 # seconds + + +def _scratch_paths(): + return glob.glob(str(_get_scratch_dir() / "hermes-*")) + + +def _check_disk_usage_warning(): + """True when hermes scratch dirs exceed the warning threshold (cached, advisory).""" + from tools.terminal_tool import DISK_USAGE_WARNING_THRESHOLD_GB + if time.monotonic() - _disk_usage_cache["timestamp"] < _DISK_USAGE_CACHE_TTL: + return _disk_usage_cache["result"] + try: + total_bytes = 0 + for path in _scratch_paths(): + for f in Path(path).rglob('*'): + if f.is_file(): + with _quiet("Could not stat file %s", f, exc=OSError): + total_bytes += f.stat().st_size + total_gb = total_bytes / (1024 ** 3) + exceeded = total_gb > DISK_USAGE_WARNING_THRESHOLD_GB + if exceeded: + logger.warning("Disk usage (%.1fGB) exceeds threshold (%.0fGB). Consider running cleanup_all_environments().", + total_gb, DISK_USAGE_WARNING_THRESHOLD_GB) + _disk_usage_cache["timestamp"] = time.monotonic() + _disk_usage_cache["result"] = exceeded + return exceeded + except Exception: + # Don't update cache on error so the next call retries. + logger.debug("Disk usage warning check failed", exc_info=True) + return False + + +def _create_configured_env( + config: Dict[str, Any], env_type: str, *, image: str, cwd: str, timeout: int, + task_id: str, host_cwd: Optional[str], local_config: Optional[dict] = None, +): + """``_create_environment`` with the ssh/container kwargs shaped from *config* + (shared by the terminal tool and the lazy :func:`ensure_task_env` bring-up).""" + from tools.terminal_tool_backends import _create_environment + from tools.terminal_tool_config import _is_container_backend + return _create_environment( + env_type=env_type, image=image, cwd=cwd, timeout=timeout, + ssh_config=_ssh_config_from_config(config) if env_type == "ssh" else None, + container_config=( + _container_config_from_config(config) if _is_container_backend(env_type) else None + ), + local_config=local_config, task_id=task_id, host_cwd=host_cwd, + ) + + +def _cleanup_env(env: Any, *, force_remove: Optional[bool] = None) -> None: + """Tear down one environment via cleanup()/stop()/terminate(), whichever it has. + + ``force_remove`` is forwarded to ``cleanup()`` only when given and the backend's + signature accepts it (``DockerEnvironment``, issue #20561; other backends don't). + Shared by ``cleanup_vm``, the idle reaper and the prompt-time backend probe so + the signature check lives in one place. + """ + if hasattr(env, 'cleanup'): + if force_remove is not None and "force_remove" in inspect.signature(env.cleanup).parameters: + env.cleanup(force_remove=force_remove) + else: + env.cleanup() + elif hasattr(env, 'stop'): + env.stop() + elif hasattr(env, 'terminate'): + env.terminate() + + +def _teardown_env(env: Any, task_id: str, *, force_remove: Optional[bool] = None, done_msg: str = "Cleaned up inactive environment for task: %s") -> None: + """``_cleanup_env`` plus outcome logging. A 404/"not found" error means the + sandbox is already gone — logged at info.""" + try: + _cleanup_env(env, force_remove=force_remove) + logger.info(done_msg, task_id) + except Exception as e: + error_str = str(e) + if "404" in error_str or "not found" in error_str.lower(): + logger.info("Environment for task %s already cleaned up", task_id) + else: + logger.warning("Error cleaning up environment for task %s: %s", task_id, e) + + +def _clear_file_ops_cache(task_id: str) -> None: + """Invalidate the file_ops cache entry so ShellFileOperations can't reference a dead sandbox.""" + try: + from tools.file_tools import clear_file_ops_cache + clear_file_ops_cache(task_id) + except ImportError: + pass + + +def _unregister_env(task_id: str): + """Pop *task_id* from the env cache, activity map and creation locks; return + the env (or None). Callers run the (slow) teardown OUTSIDE the lock — + Modal/Docker teardown can block 10-15s and would stall every concurrent + terminal/file tool call.""" + from tools.terminal_tool import ( + _active_environments, _creation_locks, _creation_locks_lock, _env_lock, + _last_activity, + ) + with _env_lock: + env = _active_environments.pop(task_id, None) + _last_activity.pop(task_id, None) + with _creation_locks_lock: + _creation_locks.pop(task_id, None) + return env + + +def _cleanup_inactive_envs(lifetime_seconds: int = 300): + """Clean up environments that have been inactive for longer than lifetime_seconds.""" + from tools.terminal_tool import ( + _active_environments, _creation_locks, _creation_locks_lock, _env_lock, + _last_activity, + ) + current_time = time.time() + + # Sandboxes with active background processes stay alive (refresh activity). + try: + from tools.process_registry import process_registry + for task_id in list(_last_activity.keys()): + if process_registry.has_active_processes(task_id): + _last_activity[task_id] = current_time + except ImportError: + pass + + # Phase 1: unregister stale entries atomically under the lock; phase 2: + # stop them outside it (see _unregister_env for why). + with _env_lock: + stale = [t for t, last in list(_last_activity.items()) if current_time - last > lifetime_seconds] + envs_to_stop = [(t, _active_environments.pop(t, None)) for t in stale] + for t in stale: + _last_activity.pop(t, None) + with _creation_locks_lock: + for t in stale: + _creation_locks.pop(t, None) + for task_id, env in envs_to_stop: + if env is not None: + _clear_file_ops_cache(task_id) + _teardown_env(env, task_id) + + +def get_active_env(task_id: str): + """Return the active BaseEnvironment for *task_id*, or None.""" + from tools.terminal_tool import _active_environments, _env_lock, _resolve_container_task_id + lookup = _resolve_container_task_id(task_id) + with _env_lock: + return _active_environments.get(lookup) or _active_environments.get(task_id) + + +def ensure_task_env(task_id: Optional[str] = None): + """Lazily create and cache the sandbox env for *task_id* if none is active. + + Lets non-terminal callers (``tools.image_source`` reading container-only + paths) bring the sandbox up on demand with the same machinery as the + terminal tool. No-op on local. Returns the env, or ``None`` when local or + when creation fails (best-effort; the caller's fail-closed path stays intact). + + :func:`terminal_tool` creates the environment on the first terminal command, but nothing else did — so + under a non-local backend (ssh, docker, …) a session whose first action is ``vision_analyze`` on a + container-only path hit "no active sandbox session" because the SSH/Docker handshake never ran (issue + #62825). vision reads such paths inside the sandbox (see ``tools.image_source``), so it calls this to + bring the env up on demand, reusing the same creation machinery as the terminal tool. + """ + from tools.terminal_tool import ( + _active_environments, _creation_locks, _creation_locks_lock, _env_lock, + _get_env_config, _last_activity, _resolve_container_task_id, + _resolve_task_host_cwd, _select_image, _start_cleanup_thread, resolve_task_overrides, + ) + config = _get_env_config() + env_type = config["env_type"] + if env_type == "local": + return None + + effective_task_id = _resolve_container_task_id(task_id) + + existing = get_active_env(effective_task_id) + if existing is not None: + with _env_lock: + _last_activity[effective_task_id] = time.time() + return existing + + image = _select_image(env_type, resolve_task_overrides(task_id), config) + + _start_cleanup_thread() + + with _creation_locks_lock: + task_lock = _creation_locks.setdefault(effective_task_id, threading.Lock()) + + with task_lock: + existing = get_active_env(effective_task_id) + if existing is not None: + return existing + try: + new_env = _create_configured_env( + config, env_type, image=image, cwd=config["cwd"], + timeout=config["timeout"], task_id=effective_task_id, + host_cwd=_resolve_task_host_cwd(config, task_id), + ) + except Exception as exc: # noqa: BLE001 — best-effort bring-up + logger.warning( + "Lazy %s environment init failed for task %s: %s", + env_type, effective_task_id[:8], exc, + ) + return None + + with _env_lock: + _active_environments[effective_task_id] = new_env + _last_activity[effective_task_id] = time.time() + logger.info( + "%s environment lazily initialized for task %s", + env_type, effective_task_id[:8], + ) + return new_env + + +def is_persistent_env(task_id: str) -> bool: + """True if *task_id*'s active env persists across turns. + + The agent loop skips per-turn teardown for these (persistent docker, + daytona, modal, …); non-persistent backends are torn down at end of turn + to prevent leakage, and the idle reaper handles the rest. Session-scoped + docker containers count as persistent HERE: their lifetime is the session + (removed by ``AIAgent.close()`` → ``cleanup_vm`` and the idle reaper). + """ + env = get_active_env(task_id) + if env is None: + return False + return bool(getattr(env, "_session_scoped", False) or getattr(env, "_persistent", False)) + + +def cleanup_all_environments(): + """Clean up ALL active environments. Use with caution.""" + from tools.terminal_tool import _active_environments + cleaned = 0 + for task_id in list(_active_environments.keys()): + try: + cleanup_vm(task_id) + cleaned += 1 + except Exception as e: + logger.error("Error cleaning %s: %s", task_id, e, exc_info=True) + + # Also clean any orphaned directories + for path in _scratch_paths(): + with _quiet("Failed to remove orphaned path %s", path, exc=OSError): + shutil.rmtree(path, ignore_errors=True) + logger.info("Removed orphaned: %s", path) + + if cleaned > 0: + logger.info("Cleaned %d environments", cleaned) + return cleaned + + +def cleanup_vm(task_id: str, *, force_remove: bool = False): + """Manually clean up a specific environment by task_id. + + *force_remove* is forwarded to backends that accept it (currently only + ``DockerEnvironment``). Default False matches session-lifecycle semantics: + callers (``AIAgent.close()`` on TUI/gateway session teardown, the per-turn + cleanup of non-persistent envs) must honor the user's persist-mode + preference — stopping the container here would break the "ONE long-lived + container shared across sessions" contract. Pass ``force_remove=True`` + only for user-initiated teardown. The idle reaper calls ``env.cleanup()`` + directly, so persist-mode idle envs are likewise no-op'd; only the orphan + reaper at next startup reclaims them. + """ + env = _unregister_env(task_id) + _clear_file_ops_cache(task_id) + if env is None: + return + _teardown_env( + env, task_id, force_remove=force_remove, + done_msg="Manually cleaned up environment for task: %s", + ) + + +def _evict_environment_for_task(task_id: Optional[str]) -> None: + """Drop any cached env for *task_id* (and its collapsed key) after an + infrastructure failure, so later calls don't reuse a dead connection.""" + from tools.terminal_tool import ( + _active_environments, _env_lock, _last_activity, _resolve_container_task_id, + ) + keys = {_resolve_container_task_id(task_id)} + if task_id: + keys.add(task_id) + evicted = [] + with _env_lock: + for key in keys: + env = _active_environments.pop(key, None) + _last_activity.pop(key, None) + if env is not None: + evicted.append(env) + for env in evicted: + with _quiet("cleanup of degraded environment failed"): + env.cleanup() diff --git a/tools/terminal_tool_result.py b/tools/terminal_tool_result.py new file mode 100644 index 0000000000000000000000000000000000000000..681d1fb0c19f23563f42768bfe431d787e569631 --- /dev/null +++ b/tools/terminal_tool_result.py @@ -0,0 +1,277 @@ +"""Foreground result post-processing for the terminal tool (cwd dual-write, +sudo handling, transform hook, truncation, ANSI strip, redaction, exit-code +notes/hints, spill redaction, verification evidence) + exit-code tables. Lazy +``tools.terminal_tool`` lookups keep the origin's monkeypatch points authoritative. +""" + +import json +import logging +import os +import re +import signal +from contextlib import contextmanager +from pathlib import Path +from typing import Any, Optional + +logger = logging.getLogger("tools.terminal_tool") + + +@contextmanager +def _quiet(label: str): + """Best-effort block: swallow any exception, logging it at DEBUG.""" + try: + yield + except Exception: + logger.debug("%s failed", label, exc_info=True) + + +# Signal-death notes keyed by signum, used for both ``-signum`` (subprocess) +# and ``128+signum`` (shell) encodings. Curated, not exhaustive, so a +# legitimate application exit code is never mislabeled; 130/SIGINT is owned +# by the executor's interrupt-marker path and excluded. +_SIGNAL_EXIT_NOTES: dict[int, str] = { + 3: "SIGQUIT (quit from keyboard)", + 4: "SIGILL (illegal instruction — corrupt binary or wrong architecture)", + 6: "SIGABRT (abort — assertion failure, fatal runtime error, or glibc abort)", + 7: "SIGBUS (bus error — misaligned or unmapped memory access)", + 8: "SIGFPE (fatal arithmetic error, e.g. integer division by zero)", + 9: "SIGKILL — often the kernel OOM killer on memory exhaustion, or an explicit kill -9", + 11: "SIGSEGV (segmentation fault — the program crashed)", + 13: "SIGPIPE (wrote to a closed pipe — e.g. output piped to a reader that exited)", + 15: "SIGTERM (terminated — kill/timeout or shutdown requested it to stop)", + 24: "SIGXCPU (CPU time limit exceeded)", + 25: "SIGXFSZ (file size limit exceeded)", +} + + +def _interpret_signal_exit(exit_code: int) -> str | None: + """Note for a signal-termination exit code, or None. Negative codes are + definite (subprocess semantics); 128+signum is the shell convention and a + program *can* exit 139 itself, so those notes hedge with "usually".""" + if exit_code < 0: + signum = -exit_code + if signum == 2: # SIGINT — executor's interrupt-marker path owns it + return None + if note := _SIGNAL_EXIT_NOTES.get(signum): + return f"Command terminated by signal {signum}: {note}" + try: + name = signal.Signals(signum).name + except ValueError: + name = f"signal {signum}" + return f"Command terminated by {name} (signal {signum})" + if exit_code > 128 and (note := _SIGNAL_EXIT_NOTES.get(exit_code - 128)): + return (f"Exit code {exit_code} usually means the command was " + f"terminated by signal {exit_code - 128}: {note}") + return None + + +# Informational non-zero exit codes per base command. +_EXIT_CODE_SEMANTICS: dict[str, dict[int, str]] = { + **dict.fromkeys(("grep", "egrep", "fgrep", "rg", "ag", "ack"), {1: "No matches found (not an error)"}), + **dict.fromkeys(("diff", "colordiff"), {1: "Files differ (expected, not an error)"}), + **dict.fromkeys(("test", "["), {1: "Condition evaluated to false (expected, not an error)"}), + "find": {1: "Some directories were inaccessible (partial results may still be valid)"}, + "curl": {6: "Could not resolve host", 7: "Failed to connect to host", + 22: "HTTP response code indicated error (e.g. 404, 500)", 28: "Operation timed out"}, + "git": {1: "Non-zero exit (often normal — e.g. 'git diff' returns 1 when files differ)"}, +} + +# Model-facing warning attached when the backend replaced its container/sandbox +# mid-command (out-of-band removal, terminal sandbox state). Persistent-filesystem +# state was restored, but background processes and anything outside the synced +# paths are gone (ported from lobehub/lobehub#19329). +_ENV_RECREATED_NOTE = ( + "The execution environment was recreated while running this command " + "(the previous container/sandbox was gone). Persistent files were restored " + "where the backend supports it, but background processes and any files " + "outside persisted paths from earlier commands may be lost — verify state " + "before relying on prior work." +) + + +def _interpret_exit_code(command: str, exit_code: int) -> str | None: + """Note for a non-zero exit code that is informational rather than an + error (grep=1 "no matches", diff=1 "files differ", signal deaths), so the + model doesn't burn turns investigating it. None when 0 or a real error.""" + if exit_code == 0: + return None + if (signal_note := _interpret_signal_exit(exit_code)) is not None: + # Signal terminations (ported from Kilo-Org/kilocode#12698, adapted to Python semantics). Two shapes + # reach the model: * negative codes — subprocess.Popen reports a signal-killed process as + # ``-signum`` (definite signal death), and * 128+signum — the conventional shell encoding when bash + # reports a signal-killed child (heuristic: a program *can* ``exit 139``, so these notes say + # "usually"). Without a note the model sees a bare ``exit_code=-9`` or ``137`` and burns turns + # re-running or mis-diagnosing (137 = OOM kill is the big one). 130/SIGINT is deliberately absent: + # the executor has bespoke interrupt-marker handling for rc=130. + return signal_note + # The last command of a pipeline/chain determines the exit code; base + # command = its first word that isn't a VAR=val assignment, basename'd. + segments = re.split(r'\s*(?:\|\||&&|[|;])\s*', command) + last_segment = (segments[-1] if segments else command).strip() + base_cmd = next((w.split("/")[-1] for w in last_segment.split() + if "=" not in w or w.startswith("-")), "") + return _EXIT_CODE_SEMANTICS.get(base_cmd, {}).get(exit_code) + + +def _sudo_annotations(command: str, output: str, env_type: str) -> tuple[str, bool, bool]: + """Sudo failure handling -> (output, auth_failed, cache_cleared).""" + import tools.terminal_tool as tt + from tools.terminal_tool_sudo import ( + _handle_sudo_failure, _in_delegated_child_context, _invalidate_cached_sudo_on_auth_failure, + _sudo_wrong_password_failure, + ) + from utils import env_var_enabled + output = _handle_sudo_failure(output, env_type) + auth_failed = _sudo_wrong_password_failure(output) + cache_cleared = _invalidate_cached_sudo_on_auth_failure(command, output) + can_reprompt = cache_cleared and ( + tt._get_sudo_password_callback() is not None or env_var_enabled("HERMES_INTERACTIVE") + ) and not _in_delegated_child_context() + if can_reprompt: + output += ("\n\n⚠️ Sudo authentication failed — cached password " + "cleared. You will be prompted again on the next sudo command.") + return output, auth_failed, cache_cleared + + +def _apply_output_transform_hook(command, output, returncode, task_id, env_type) -> str: + """Plugin output-transform seam (fail-open; first string result wins). + Replacements are still subject to the output limit applied afterwards.""" + with _quiet("transform_terminal_output hook"): + from hermes_cli.lifecycle import invoke_hook + from tools.approval_context import _approval_tool_call_id + # Concurrent terminal calls in one turn must gate per call, not collapse into one; + # an empty id is treated as "no identity" by the hook gate. + results = invoke_hook("transform_terminal_output", command=command, output=output, + returncode=returncode, task_id=task_id or "", env_type=env_type, + tool_call_id=_approval_tool_call_id.get()) + output = next((r for r in results if isinstance(r, str)), output) + return output + + +def _truncate_head_tail(output: str) -> str: + from tools.tool_output_limits import get_max_bytes + from tools.tool_output_truncate import truncate_head_tail + return truncate_head_tail(output, get_max_bytes()) + + +def _failure_hint(command: str, returncode: int, output: str, exit_note) -> Optional[str]: + """Recovery hints for well-known failure shapes (tools/terminal_hints.py); + on rc=0, warn when a pipeline tail / `|| echo` may mask an upstream + failure and the output carries strong failure indicators (advisory only).""" + with _quiet("failure hint"): + from tools import terminal_hints + if returncode == 0: + return terminal_hints.annotate_masked_success(command, output) + if not exit_note: + return terminal_hints.annotate_failure(command, returncode, output) + return None + + +def _redact_spill_file(path, total_chars, command) -> list[tuple[str, Any]]: + """Spill handle so the model can read the omitted middle instead of + re-running. The collector wrote it raw; redact it with the same pass so no + secret persists unmasked on disk. On failure drop the handle (and file).""" + if not path: + return [] + try: + from agent.redact import redact_terminal_output + from tools.ansi_strip import strip_ansi + from tools.spill_safety import write_text_exclusive + raw_spill = Path(path).read_text(encoding="utf-8", errors="replace") + # lstat-checked unlink + exclusive create: the redacted copy can't + # be diverted through a symlink planted since the collector's write. + write_text_exclusive(Path(path), redact_terminal_output(strip_ansi(raw_spill), command), + private=True, overwrite=True, errors="replace") + except Exception: + logger.debug("spill redaction failed; dropping spill handle", exc_info=True) + with _quiet("spill unlink"): + Path(path).unlink() + return [] + note = ("Output exceeded the capture window (head+tail shown). " + f"Full output ({total_chars:,} chars) saved to {path} — search it with " + "search_files or page it with read_file instead of re-running the command.") + return [("output_total_chars", total_chars), ("full_output_path", path), ("truncation_note", note)] + + +def _verification_evidence(command, cwd, session_id, returncode, output) -> Optional[dict]: + with _quiet("verification evidence recording"): + from agent.verification_evidence import record_terminal_result + evidence = record_terminal_result(command=command, cwd=cwd, session_id=session_id, + exit_code=returncode, output=output) + if evidence: + return {k: evidence.get(k) for k in ("status", "kind", "scope", "canonical_command")} + return None + + +def finalize_foreground_result( + *, command: str, result: dict, env: Any, env_type: str, effective_task_id: str, + task_id: Optional[str], session_id: Optional[str], session_key: str, + workdir: Optional[str], command_cwd: Optional[str], approval_note: Optional[str], +) -> str: + """Turn a raw ``env.execute`` result into the tool's JSON result string.""" + from tools.terminal_tool import record_session_cwd + + # Record the cwd this command finished in as THIS session's durable cwd — + # only when the command actually reported it (an interrupted/killed command + # emits no marker, and env.cwd then holds another session's directory), and + # never for a transient per-command ``workdir`` (would hijack the session cwd + # for every later command). Prefer the result's own cwd; env.cwd is shared + # mutable compat state kept as fallback for third-party providers. + observed_cwd = None + if (result or {}).get("cwd_observed"): + observed_cwd = (result or {}).get("cwd") or getattr(env, "cwd", None) + if not workdir and observed_cwd: + record_session_cwd(session_key, observed_cwd) + + output = result.get("output", "") + returncode = result.get("returncode", 0) + output, sudo_auth_failed, sudo_cache_cleared = _sudo_annotations(command, output, env_type) + output = _apply_output_transform_hook(command, output, returncode, effective_task_id, env_type) + output = _truncate_head_tail(output) + # Strip ANSI so the model never copies escapes into file writes, then + # redact secrets; redact_terminal_output is command-aware (env-dump + # commands get the KEY=value pass, source/config dumps skip it). + from agent.redact import redact_terminal_output + from tools.ansi_strip import strip_ansi + output = strip_ansi(output) + # For source/config dumps (MAX_TOKENS=100, "apiKey": "x" fixtures, postgresql:// f-string templates) the + # ENV/JSON/template passes are skipped to avoid false positives (code_file=True). But for env-dump + # commands (env/printenv/set/export/declare) the output IS a KEY=value credential dump, so + # redact_terminal_output runs the ENV pass (code_file=False) to mask opaque tokens with no vendor + # prefix. Real prefixes, auth headers, JWTs, private keys are masked in both modes. See issue #43025. + output = redact_terminal_output(output.strip(), command) if output else "" + + exit_note = _interpret_exit_code(command, returncode) + failure_hint = _failure_hint(command, returncode, output, exit_note) + # cwd echo when the command changed directory (gated on the observation + # flag so an interrupted command can't echo another session's cwd). + changed_cwd = None + with _quiet("cwd comparison"): + if observed_cwd and command_cwd and os.path.realpath(str(observed_cwd)) != os.path.realpath(str(command_cwd)): + changed_cwd = str(observed_cwd) + # rc=130 is an interrupt only with the executor's marker — a command can + # legitimately `exit 130` itself. An interrupted approved run keeps the + # audit note but must never imply success. + if approval_note and returncode == 130 and "[Command interrupted]" in output: + approval_note = approval_note.rstrip(".") + ", then interrupted." + + result_dict = {"output": output, "exit_code": returncode, "error": None} + # Optional fields in observable JSON key order; None means "omit". Spill + # metadata is present only when output overflowed the capture window. + optional_fields: list[tuple[str, Any]] = [ + ("cwd", changed_cwd), + ("environment_recreated", _ENV_RECREATED_NOTE if result.get("environment_recreated") else None), + *_redact_spill_file(result.get("full_output_path"), result.get("output_total_chars"), command), + ("verification_evidence", _verification_evidence( + command, command_cwd, session_id or task_id or effective_task_id or "default", + returncode, output)), + ("approval", approval_note or None), + ("exit_code_meaning", exit_note or None), + ("hint", failure_hint or None), + ("sudo_auth_failed", True if sudo_auth_failed else None), + ("sudo_cache_cleared", True if sudo_cache_cleared else None), + ] + for key, value in optional_fields: + if value is not None: + result_dict[key] = value + return json.dumps(result_dict, ensure_ascii=False) diff --git a/tools/terminal_tool_sudo.py b/tools/terminal_tool_sudo.py new file mode 100644 index 0000000000000000000000000000000000000000..4f1b78949b7766c966fd8d6ce6e4be534b9dd87e --- /dev/null +++ b/tools/terminal_tool_sudo.py @@ -0,0 +1,484 @@ +"""Sudo password plumbing and shell-command rewrites for the terminal tool: per-scope +password cache, /dev/tty prompt, the quote-aware shell scanner behind the real-sudo rewrite +(``sudo -S -p ''``) and the compound-background brace-group rewrite, and the NOPASSWD probe. +Split out of ``tools/terminal_tool.py``; every public/patched name is re-imported there so +``tools.terminal_tool.<name>`` keeps resolving (and monkeypatching) as before.""" + +import logging +import os +import platform +import re +import shlex +import subprocess +import sys +import threading +import time +from collections.abc import Callable, Iterator +from contextvars import ContextVar + +from utils import env_var_enabled + +# Log-record parity with the origin module. +logger = logging.getLogger("tools.terminal_tool") + +# Interactive sudo password cache, scoped to the session key when present, else callback +# identity (ACP / CLI), else the current thread — so one session can never reuse another's +# cached password in a long-lived process. +_sudo_password_cache: dict[str, str] = {} +_sudo_password_cache_lock = threading.Lock() + +# Only populated while invoking a UI callback; preserve the zero-argument callback API. +_sudo_prompt_command: ContextVar[str] = ContextVar("sudo_prompt_command", default="") + + +def get_sudo_prompt_command() -> str: + """Original command for the current sudo password prompt, or '' outside its callback.""" + return _sudo_prompt_command.get() + + +def _get_sudo_password_cache_scope() -> str: + """Return the cache scope for interactive sudo passwords.""" + from tools.terminal_tool import _current_session_key, _get_sudo_password_callback + session_key = _current_session_key() + if session_key: + return f"session:{session_key}" + callback = _get_sudo_password_callback() + if callback is None: + return f"thread:{threading.get_ident()}" + owner = getattr(callback, "__self__", None) + func = getattr(callback, "__func__", None) + if owner is not None and func is not None: + return f"callback-owner:{id(owner)}:{id(func)}" + return f"callback:{id(callback)}" + + +def _get_cached_sudo_password() -> str: + """Return the cached sudo password for the current scope.""" + scope = _get_sudo_password_cache_scope() + with _sudo_password_cache_lock: + return _sudo_password_cache.get(scope, "") + + +def _set_cached_sudo_password(password: str) -> None: + """Persist a sudo password for the current scope ("" drops the entry).""" + scope = _get_sudo_password_cache_scope() + with _sudo_password_cache_lock: + if password: + _sudo_password_cache[scope] = password + else: + _sudo_password_cache.pop(scope, None) + + +def _reset_cached_sudo_passwords() -> None: + """Clear all cached sudo passwords (tests / process teardown).""" + with _sudo_password_cache_lock: + _sudo_password_cache.clear() + + +def _in_delegated_child_context() -> bool: + """True while running inside a delegate_task child. Subagents run on parent-process worker + threads and inherit process-wide ``HERMES_INTERACTIVE=1``, which does NOT mean they can reach + the user: a raw ``/dev/tty`` sudo prompt from a child races the TUI for the tty and blocks the + child for the full timeout, so children are always headless for sudo prompting. The ContextVar + is set by ``delegated_child_context()`` and propagates via ``copy_context``.""" + try: + from agent.delegation_context import is_delegated_child_context + return is_delegated_child_context() + except Exception: + return False + + +_SUDO_HEADLESS_FAILURES = ("sudo: a password is required", "sudo: no tty present", "sudo: a terminal is required") + + +def _handle_sudo_failure(output: str, env_type: str) -> str: + """Append a SUDO_PASSWORD tip when sudo failed in a headless context + (gateway session or delegate_task child); otherwise return *output* as is.""" + is_gateway = env_var_enabled("HERMES_GATEWAY_SESSION") + is_delegated_child = _in_delegated_child_context() + if not (is_gateway or is_delegated_child) or not any(f in output for f in _SUDO_HEADLESS_FAILURES): + return output + from hermes_constants import display_hermes_home as _dhh + if is_delegated_child: + return output + ( + "\n\n💡 Tip: Subagents cannot prompt for a sudo password. " + f"Add SUDO_PASSWORD to {_dhh()}/.env on the agent machine, " + "or run the command without sudo." + ) + return output + f"\n\n💡 Tip: To enable sudo over messaging, add SUDO_PASSWORD to {_dhh()}/.env on the agent machine." + + +# sudo -S rejects a bad cached/interactive password with these messages. +_SUDO_WRONG_PASSWORD_MARKERS = ( + "sudo: authentication failed", + "sudo: incorrect password attempt", + "sudo: maximum 3 incorrect authentication attempts", + "sudo: 3 incorrect password attempts", +) + + +def _sudo_wrong_password_failure(output: str) -> bool: + """Return True when sudo rejected a piped password.""" + lowered = (output or "").lower() + return any(marker in lowered for marker in _SUDO_WRONG_PASSWORD_MARKERS) + + +def _invalidate_cached_sudo_on_auth_failure(command: str | None, output: str) -> bool: + """Drop a session-cached sudo password after sudo rejects it. Env-configured + ``SUDO_PASSWORD`` is left alone — an explicit operator choice, not a cache entry.""" + if ( + "SUDO_PASSWORD" in os.environ + or not _sudo_wrong_password_failure(output) + or _count_real_sudo_invocations(command or "") == 0 + or not _get_cached_sudo_password() + ): + return False + _set_cached_sudo_password("") + return True + + +def _release_tty(tty_fd, old_attrs) -> None: + """Restore echo and close the /dev/tty fd opened by the password reader (best effort).""" + if tty_fd is None: + return + if old_attrs is not None: + try: + import termios as _termios + _termios.tcsetattr(tty_fd, _termios.TCSAFLUSH, old_attrs) + except Exception as e: + logger.debug("Failed to restore terminal attributes: %s", e) + try: + os.close(tty_fd) + except Exception as e: + logger.debug("Failed to close tty fd: %s", e) + + +def _read_hidden_password(result: dict) -> None: + """Read one line with echo disabled into ``result``. Uses msvcrt on Windows, /dev/tty on Unix.""" + tty_fd = old_attrs = None + try: + chars = [] + if platform.system() == "Windows": + import msvcrt + while (c := msvcrt.getwch()) not in {"\r", "\n"}: + if c == "\x03": + raise KeyboardInterrupt + chars.append(c) + result["password"] = "".join(chars) + else: + import termios + tty_fd = os.open("/dev/tty", os.O_RDONLY) + old_attrs = termios.tcgetattr(tty_fd) + new_attrs = termios.tcgetattr(tty_fd) + new_attrs[3] = new_attrs[3] & ~termios.ECHO + termios.tcsetattr(tty_fd, termios.TCSAFLUSH, new_attrs) + while (b := os.read(tty_fd, 1)) and b not in {b"\n", b"\r"}: + chars.append(b) + result["password"] = b"".join(chars).decode("utf-8", errors="replace") + except (KeyboardInterrupt, Exception): + result["password"] = "" + finally: + _release_tty(tty_fd, old_attrs) + result["done"] = True + + +def _prompt_for_sudo_password(timeout_seconds: int = 45, *, command: str = "") -> str: + """Prompt for a sudo password; "" on skip (empty Enter), timeout, or error. Prefers the + CLI-registered callback (prompt_toolkit-integrated); otherwise reads /dev/tty (msvcrt on + Windows) with echo disabled. Human wait time is excluded from tool deadlines (``human_wait_window``).""" + from tools.terminal_tool import _get_sudo_password_callback + _sudo_cb = _get_sudo_password_callback() + if _sudo_cb is not None: + token = _sudo_prompt_command.set(command) + try: + from tools.approval_human_wait import human_wait_window + with human_wait_window(): + return _sudo_cb() or "" + except Exception: + return "" + finally: + _sudo_prompt_command.reset(token) + + result = {"password": None, "done": False} + try: + os.environ["HERMES_SPINNER_PAUSE"] = "1" + time.sleep(0.2) + print("\n".join(( + "", + "┌" + "─" * 58 + "┐", + "│ 🔐 SUDO PASSWORD REQUIRED" + " " * 30 + "│", + "├" + "─" * 58 + "┤", + "│ Enter password below (input is hidden), or: │", + "│ • Press Enter to skip (command fails gracefully) │", + f"│ • Wait {timeout_seconds}s to auto-skip" + " " * 27 + "│", + "└" + "─" * 58 + "┘", + "", + ))) + print(" Password (hidden): ", end="", flush=True) + password_thread = threading.Thread(target=_read_hidden_password, args=(result,), daemon=True) + password_thread.start() + from tools.approval_human_wait import human_wait_window + with human_wait_window(): + password_thread.join(timeout=timeout_seconds) + if not result["done"]: + print("\n ⏱ Timeout - continuing without sudo\n (Press Enter to dismiss)\n") + sys.stdout.flush() + return "" + password = result["password"] or "" + # Newline after the hidden input, then the outcome line. + if password: + print("\n ✓ Password received (cached for this session)\n") + else: + print("\n ⏭ Skipped - continuing without sudo\n") + sys.stdout.flush() + return password + except (EOFError, KeyboardInterrupt): + print("\n ⏭ Cancelled - continuing without sudo\n") + sys.stdout.flush() + return "" + except Exception as e: + print(f"\n [sudo prompt error: {e}] - continuing without sudo\n") + sys.stdout.flush() + return "" + finally: + os.environ.pop("HERMES_SPINNER_PAUSE", None) + + +def _looks_like_env_assignment(token: str) -> bool: + """Return True when *token* is a leading shell environment assignment.""" + if "=" not in token or token.startswith("="): + return False + name, _value = token.split("=", 1) + return bool(re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", name)) + + +# One shell word: single-/double-quoted runs (unterminated ok; backslash escapes inside double +# quotes), a backslash escape (a trailing lone `\` is a plain char), or any non-`;|&()`/space char. +_SHELL_WORD_RE = re.compile(r"""(?:'[^']*'?|"(?:\\.|[^"])*"?|\\.|[^\s;|&()])*""", re.DOTALL) + + +def _read_shell_token(command: str, start: int) -> tuple[str, int]: + """Read one shell token, preserving quotes/escapes, starting at *start*.""" + end = _SHELL_WORD_RE.match(command, start).end() # type: ignore[union-attr] (`*` always matches) + return command[start:end], end + + +def _scan_shell(command: str, background: bool = False) -> Iterator[tuple[str, int, int, bool]]: + """Quote-aware shell scanner shared by the sudo and compound-background rewriters. + + Yields ``(kind, start, end, at_command_start)`` events that tile *command* exactly: + ``ws`` (one whitespace char), ``comment`` (``#`` up to, not including, the newline), + ``op`` (``&& || ;; ; | & ( )``), ``word`` (one ``_read_shell_token`` token). Comments open at word boundaries. + Background mode (compound-background semantics) additionally emits ``escape`` for a bare ``\\x``, ops ``&>``, ``{ `` and a closing + ``}``, and tracks ``(...)``/``{ ... }`` depth: inside a group nothing is an operator, so + every non-structural char (whitespace included) surfaces as a single ``skip`` event. + """ + i, n = 0, len(command) + at_start = True + parens = braces = 0 + two_char_ops = ("&&", "||", "&>") if background else ("&&", "||", ";;") + while i < n: + ch = command[i] + grouped = parens or braces + was_start = at_start + if ch.isspace(): + kind, end = ("skip" if grouped else "ws"), i + 1 + at_start = at_start or ch == "\n" + elif ch == "#": + end = command.find("\n", i) + kind, end = "comment", (n if end == -1 else end) + elif background and ch == "\\" and i + 1 < n: + kind, end = "escape", i + 2 + elif background and ch in "'\"": + kind, end = "word", _read_shell_token(command, i)[1] + elif background and ( + ch in "()" or (ch == "{" and i + 1 < n and command[i + 1].isspace()) or (ch == "}" and braces) + ): + parens = max(0, parens + (ch == "(") - (ch == ")")) + braces += (ch == "{") - (ch == "}") + kind, end = "op", i + 1 + elif background and grouped: + kind, end = "skip", i + 1 + elif command.startswith(two_char_ops, i): + kind, end, at_start = "op", i + 2, True + elif ch in ";|&()": + kind, end, at_start = "op", i + 1, ch != ")" + else: + token, end = _read_shell_token(command, i) + kind, at_start = "word", bool(at_start and _looks_like_env_assignment(token)) + yield kind, i, end, was_start + i = end + + +def _rewrite_real_sudo_invocations(command: str) -> tuple[str, int]: + """Rewrite literal sudo executable words, preserving their spelling and arguments. + + Follow ordinary env options/assignments, not shell payloads or env split strings: + interpreting those requires a second parser and rewriting inside another quoting layer. + """ + out: list[str] = [] + sudo_count = 0 + in_env = env_operand = env_options = False + value_options = {"-u", "--unset", "-C", "--chdir", "-a", "--argv0"} + flag_options = {"-i", "--ignore-environment", "-0", "--null", "-v", "--debug"} + for kind, start, end, at_start in _scan_shell(command): + text = command[start:end] + out.append(text) + if kind == "op" or (kind == "ws" and text == "\n"): + in_env = env_operand = env_options = False + if kind != "word" or not (at_start or in_env): + continue + try: + words = shlex.split(text) + except ValueError: + in_env = False + continue + # Redirections and expansions are not literal executable paths. + if len(words) != 1 or any(char in text for char in "$`*?[]~<>{}"): + in_env = False + continue + word = words[0] + if in_env: + if env_operand: + env_operand = False + continue + if env_options and word in {"-", "--"}: + env_options = False + continue + if env_options and word in value_options: + env_operand = True + continue + if env_options and (word in flag_options or + any(word.startswith(opt + "=") for opt in value_options if opt.startswith("--")) or + any(word.startswith(opt) and len(word) > 2 for opt in ("-u", "-C", "-a"))): + continue + if env_options and word.startswith("-"): + in_env = False + continue + if _looks_like_env_assignment(word): + env_options = False + continue + elif _looks_like_env_assignment(text): + continue + executable = word.rsplit("/", 1)[-1] + in_env = executable == "env" + env_options = in_env + if executable == "sudo": + out[-1] += " -S -p ''" + sudo_count += 1 + return "".join(out), sudo_count + + +def _count_real_sudo_invocations(command: str) -> int: + """Return how many real sudo command words appear in *command*.""" + return _rewrite_real_sudo_invocations(command)[1] + + +def _rewrite_compound_background(command: str) -> str: + """Wrap `A && B &` (or `A || B &`) to `A && { B & }` at depth 0. Bash binds `&&` tighter + than `&`, so `A && B &` backgrounds a subshell that runs B in the foreground and waits for + it; a long-running B leaves that subshell stuck in ``wait4`` forever, and its open stdout + pipe can keep the terminal tool from returning. The brace group keeps `&&`'s + skip-B-on-failure semantics without a fork: bash backgrounds B as a simple command and + exits immediately, orphaning B normally. Redirects (``&>``, ``2>&1``), quoted strings, + comments and ``(...)``/``{ ... }`` bodies never count as the backgrounding ``&`` (see + ``_scan_shell``); tracking brace depth also makes the rewrite idempotent. `(...)` subshells + have the same bug class but are not the common agent pattern; left for a follow-up. + Simple ``cmd &`` is left alone — it doesn't have the subshell-wait bug.""" + chain_end = -1 # just after the last depth-0 `&&`/`||` of this statement; -1 = none active + rewrites: list[tuple[int, int]] = [] # (chain_op_end, amp_pos) + for kind, start, end, _ in _scan_shell(command, background=True): + text = command[start:end] + if kind == "op" and text in ("&&", "||"): + chain_end = end + elif kind == "ws" and text == "\n" or kind == "op" and text in (";", "|", "}"): + # Newline / `;` end a statement, `|` starts a pipeline stage, `}` closes a group. + chain_end = -1 + elif kind == "op" and text == "&": + # `&&` and `&>` never reach here; a `>&` / `<&` fd target (look back past + # whitespace) is a redirect, anything else is the real background operator. + j = start - 1 + while j >= 0 and command[j].isspace(): + j -= 1 + if j >= 0 and command[j] in "<>": + continue + if chain_end >= 0: + rewrites.append((chain_end, start)) + chain_end = -1 + + # Apply rewrites back-to-front so earlier indices remain valid. + result = command + for chain_end, amp_pos in reversed(rewrites): + # Skip whitespace right after the `&&`/`||` so the brace group opens flush against + # the inner command. `{` needs a trailing space in bash; the closing `}` needs to be + # preceded by `;` or `&` — we're providing `&` from the backgrounding. + insert_pos = chain_end + while insert_pos < amp_pos and result[insert_pos].isspace(): + insert_pos += 1 + # The consumed `&` also separated the compound from any statement that followed + # on the same line (`A && B & C`); `{ B & } C` is a syntax error, so restore a `;` + # when the suffix resumes with command text. No separator when the suffix already + # starts with a terminator (`;` `&` `|` newline `)` `}`) — except `&>`, which is a + # redirect prefix for the NEXT command, not a terminator. Strip only spaces/tabs: + # a newline already terminates the group. + suffix = result[amp_pos + 1 :] + tail = suffix.lstrip(" \t") + needs_separator = bool(tail) and (tail[0] not in ";\n&|)}" or tail.startswith("&>")) + separator = " ;" if needs_separator else "" + result = result[:insert_pos] + "{ " + result[insert_pos:amp_pos] + "& }" + separator + suffix + return result + + +def _transform_sudo_command( + command: str | None, + sudo_nopasswd_check: Callable[[], bool] | None = None, +) -> tuple[str | None, str | None]: + """Rewrite command-position ``sudo`` executables to ``sudo -S -p ''`` when a password is available (shared by every + execution environment). Returns ``(command, sudo_stdin)``: ``sudo_stdin`` is one password + line per sudo invocation that the caller must PREPEND to the process stdin (sudo -S consumes + exactly one line and passes the rest through, so it's safe alongside the caller's own + stdin_data). Backends that can't pipe stdin (modal, daytona, vercel_sandbox) embed the + password in the command string themselves. With no password available the command is + returned unchanged and ``sudo_stdin`` is None, so it fails gracefully with "sudo: a password + is required". Password sources, in order: configured SUDO_PASSWORD, the session cache, then + an interactive prompt (45s timeout, cached on success) when a UI is reachable. + ``sudo_nopasswd_check`` (supplied by ``BaseEnvironment``) runs ``sudo -n true`` inside the + selected backend; a True result skips the prompt and the ``-S`` rewrite entirely.""" + from tools.terminal_tool import _get_sudo_password_callback + if command is None: + return None, None + transformed, sudo_count = _rewrite_real_sudo_invocations(command) + if sudo_count == 0: + return command, None + + # Scope-aware read: under multiplex the process env may hold another profile's SUDO_PASSWORD; + # unscoped callers (UnscopedSecretError) keep the os.environ read. + try: + from agent.secret_scope import get_secret + _configured_password = get_secret("SUDO_PASSWORD") + except Exception: + _configured_password = os.environ.get("SUDO_PASSWORD") + has_configured_password = _configured_password is not None + sudo_password = _configured_password if has_configured_password else _get_cached_sudo_password() + + # delegate_task children inherit HERMES_INTERACTIVE=1 (and possibly a stale thread-local + # callback on a recycled worker) but have no user on the other side — always headless; + # configured password and session cache still apply. + should_prompt_for_sudo = ( + env_var_enabled("HERMES_INTERACTIVE") or _get_sudo_password_callback() is not None + ) and not _in_delegated_child_context() + if not has_configured_password and not sudo_password and should_prompt_for_sudo: + # sudoers NOPASSWD must not be forced through the prompt or the -S pipe. The probe is + # a round trip on the selected backend (an ssh exec for SSH), so it only runs when a + # prompt would otherwise fire: headless callers end up at ``(command, None)`` either + # way. Re-probed every call so an expired sudo timestamp cannot silently block. + if sudo_nopasswd_check is not None and sudo_nopasswd_check(): + return command, None + sudo_password = _prompt_for_sudo_password(timeout_seconds=45, command=command) + if sudo_password: + _set_cached_sudo_password(sudo_password) + + if has_configured_password or sudo_password: + # sudo -S reads one line per invocation: compound `sudo a && sudo b` needs one line each. + return transformed, (sudo_password + "\n") * sudo_count + return command, None diff --git a/tools/tirith_security.py b/tools/tirith_security.py new file mode 100644 index 0000000000000000000000000000000000000000..8814e17f2d0661c8b91c2470c63fa9c82c9415f1 --- /dev/null +++ b/tools/tirith_security.py @@ -0,0 +1,560 @@ +"""Tirith pre-exec security scanning wrapper: runs the tirith binary as a subprocess to scan +commands for content-level threats (homograph URLs, pipe-to-interpreter, terminal injection). +The exit code is the verdict source of truth (0 allow, 1 block, 2 warn); JSON stdout only +enriches findings. Operational failures (spawn error, timeout, unknown exit) respect +``fail_open``; programming errors propagate. Auto-install: a missing tirith is downloaded from +GitHub releases to $HERMES_HOME/bin/tirith in a background thread -- SHA-256 always verified, +cosign provenance when cosign is on PATH.""" + +import hashlib +import json +import logging +import os +import platform +import shutil +import stat +import subprocess +import tarfile +import tempfile +import threading +import time +import urllib.request +from contextlib import suppress + +from hermes_constants import get_hermes_home, get_hermes_home_override, hermes_home_key + +logger = logging.getLogger(__name__) +_REPO = "sheeki03/tirith" +# Cosign provenance pinned to the release workflow, not the whole repo. +_COSIGN_IDENTITY_REGEXP = f"^https://github.com/{_REPO}/\\.github/workflows/release\\.yml@refs/tags/v" +_COSIGN_ISSUER = "https://token.actions.githubusercontent.com" + +# --- Config helpers --- +def _env_bool(key: str, default: bool) -> bool: + val = os.getenv(key) + return default if val is None else val.lower() in {"1", "true", "yes"} + + +def _env_int(key: str, default: int) -> int: + try: + return int(os.environ[key]) + except (KeyError, ValueError): + return default + + +def _load_security_config() -> dict: + """Security settings from config.yaml, with env var overrides.""" + try: + from hermes_cli.config import load_config_readonly + cfg = load_config_readonly().get("security", {}) or {} + except Exception: + cfg = {} + return { + "tirith_enabled": _env_bool("TIRITH_ENABLED", cfg.get("tirith_enabled", True)), + "tirith_path": os.getenv("TIRITH_BIN", cfg.get("tirith_path", "tirith")), + "tirith_timeout": _env_int("TIRITH_TIMEOUT", cfg.get("tirith_timeout", 5)), + "tirith_fail_open": _env_bool("TIRITH_FAIL_OPEN", cfg.get("tirith_fail_open", True))} + + +# --- Module state --- +# Cached path after first resolution. _INSTALL_FAILED means "tried and failed" (distinct +# from None = "not yet tried") so a failed install is not retried per command. +_resolved_path: str | None | bool = None +_INSTALL_FAILED = False +_install_failure_reason: str = "" # reason tag when _resolved_path is _INSTALL_FAILED +# Routed profiles (multiplexed gateway) resolve their own binary: ``security.tirith_path`` and +# ``<home>/bin/tirith`` are per profile, so the launch profile's slot above must not answer for them. +_resolved_path_by_home: dict[str, str] = {} + +# Circuit breaker: after _CRASH_LIMIT consecutive spawn/execution failures tirith is disabled +# for the rest of the process so a broken binary can't turn every tool call into a fail-open +# retry loop. Reset on success. Lock-free on purpose: a racing double-increment only opens the +# breaker one call early; no corruption or security bypass is possible. +_CRASH_LIMIT = 3 +# Reset on successful execution (see _record_tirith_crash / check_command_security). Thread safety: +# _crash_count and _circuit_open are module-level globals mutated without a lock. check_command_security can +# be called from concurrent agent threads (gateway multi-session). The race is benign — at worst two threads +# both increment past _CRASH_LIMIT and both set _circuit_open = True, opening the breaker one call early. +# This intentionally matches the lock-free style of error counters in mcp_tool.py rather than the locked +# _warn_once pattern, because the worst case is harmless. See #41400. +_crash_count: int = 0 +_circuit_open: bool = False + +_install_lock = threading.Lock() +_install_thread: threading.Thread | None = None + +# Warn-once: spawn/path warnings sit in the hot path and would otherwise repeat once per +# terminal command while tirith is unavailable (e.g. install thread still running). +_warned_messages: set[str] = set() +_warned_lock = threading.Lock() + +_MARKER_TTL = 86400 # disk failure marker validity (24h) -- avoids retry across restarts + + +def _record_tirith_crash() -> None: + global _crash_count, _circuit_open + _crash_count += 1 + if _crash_count >= _CRASH_LIMIT: + _circuit_open = True + logger.warning("tirith circuit breaker opened after %d consecutive failures; " + "disabling for the rest of the process", _crash_count) + + +def _warn_once(key: str, message: str, *args) -> None: + """``logger.warning`` at most once per ``key`` for the process lifetime.""" + with _warned_lock: + if key in _warned_messages: + return + _warned_messages.add(key) + logger.warning(message, *args) + + +def _cached_path() -> str | None: + """The path resolved on a previous call, or None if unresolved (None) / failed (_INSTALL_FAILED).""" + if get_hermes_home_override() is not None: + return _resolved_path_by_home.get(hermes_home_key()) + return _resolved_path or None + + +def _store_resolved(path: str) -> None: + global _resolved_path + if get_hermes_home_override() is not None: + _resolved_path_by_home[hermes_home_key()] = path + else: + _resolved_path = path + + +def _set_resolved(path: str) -> None: + global _install_failure_reason + _store_resolved(path) + _install_failure_reason = "" + + +def _set_failed(reason: str) -> None: + global _resolved_path, _install_failure_reason + _resolved_path, _install_failure_reason = _INSTALL_FAILED, reason + + +# --- Disk failure marker --- +def _failure_marker_path() -> str: + return os.path.join(str(get_hermes_home()), ".tirith-install-failed") + + +def _read_failure_reason() -> str | None: + """The marker's reason, or None if absent or older than _MARKER_TTL.""" + try: + p = _failure_marker_path() + if (time.time() - os.path.getmtime(p)) >= _MARKER_TTL: + return None + with open(p, "r", encoding="utf-8") as f: + return f.read().strip() + except OSError: + return None + + +def _is_install_failed_on_disk() -> bool: + """True if a recent install failure was persisted and is still non-retryable. + A 'cosign_missing' marker is auto-cleared once cosign appears on PATH.""" + reason = _read_failure_reason() + if reason == "cosign_missing" and shutil.which("cosign"): + _clear_install_failed() + return False + return reason is not None + + +def _mark_install_failed(reason: str = ""): + """Persist install failure to disk; ``reason`` is a short retryability tag.""" + with suppress(OSError): + p = _failure_marker_path() + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "w", encoding="utf-8") as f: + f.write(reason) + + +def _clear_install_failed(): + """Remove the failure marker and reset warn-once state (so a failure after a reinstall surfaces again).""" + with _warned_lock: + _warned_messages.clear() + with suppress(OSError): + os.unlink(_failure_marker_path()) + + +def _disk_marker_blocks_install() -> bool: + """Apply a still-valid disk marker to module state; True if install must be skipped. + Keeps the marker's real reason so in-process retry can detect cosign_missing.""" + if (disk_reason := _read_failure_reason()) is None or not _is_install_failed_on_disk(): + return False + _set_failed(disk_reason) + return True + + +# --- Auto-install --- +def _hermes_bin_dir() -> str: + """$HERMES_HOME/bin, created if needed.""" + os.makedirs(d := os.path.join(str(get_hermes_home()), "bin"), exist_ok=True) + return d + + +# Rust target triple components. Android (Termux) is ABI-compatible with Linux. Windows is +# absent on purpose (no tirith build): None = "never available here", pattern guards still run. +_TARGET_PLATFORMS = {"Darwin": "apple-darwin", "Linux": "unknown-linux-gnu", "Android": "unknown-linux-gnu"} +_TARGET_ARCHES = {"x86_64": "x86_64", "amd64": "x86_64", "aarch64": "aarch64", "arm64": "aarch64"} + + +def _detect_target() -> str | None: + """Rust target triple for this platform, or None if tirith has no build for it.""" + plat = _TARGET_PLATFORMS.get(platform.system()) + arch = _TARGET_ARCHES.get(platform.machine().lower()) + return f"{arch}-{plat}" if plat and arch else None + + +def is_platform_supported() -> bool: + """True when tirith ships a prebuilt binary for this OS+arch (CLI banner uses this).""" + return _detect_target() is not None + + +def _download_file(url: str, dest: str, timeout: int = 10): + from agent.secret_scope import get_secret + req = urllib.request.Request(url) + if token := get_secret("GITHUB_TOKEN"): + req.add_header("Authorization", f"token {token}") + with urllib.request.urlopen(req, timeout=timeout) as resp, open(dest, "wb") as f: + shutil.copyfileobj(resp, f) + + +def _verify_cosign(checksums_path: str, sig_path: str, cert_path: str) -> bool | None: + """Cosign provenance of checksums.txt: True verified, False rejected, None if cosign absent/failed.""" + if not (cosign := shutil.which("cosign")): + logger.info("cosign not found on PATH") + return None + try: + result = subprocess.run( + [cosign, "verify-blob", "--certificate", cert_path, "--signature", sig_path, + "--certificate-identity-regexp", _COSIGN_IDENTITY_REGEXP, + "--certificate-oidc-issuer", _COSIGN_ISSUER, checksums_path], + capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=15, stdin=subprocess.DEVNULL) + except (OSError, subprocess.TimeoutExpired) as exc: + logger.warning("cosign execution failed: %s", exc) + return None + if result.returncode: + logger.warning("cosign verification failed (exit %d): %s", result.returncode, result.stderr.strip()) + return False + logger.info("cosign provenance verification passed") + return True + + +def _verify_release_provenance(base_url: str, tmpdir: str, checksums_path: str, log) -> tuple[bool, str]: + """Cosign step of the install -> ``(cosign_verified, failure_reason)``. Only an explicit + cosign rejection aborts; missing/broken cosign or artifacts fall back to SHA-256 only.""" + if not shutil.which("cosign"): + logger.info("cosign not on PATH — installing tirith with SHA-256 verification only " + "(install cosign for full supply chain verification)") + return False, "" + sig_path, cert_path = os.path.join(tmpdir, "checksums.txt.sig"), os.path.join(tmpdir, "checksums.txt.pem") + try: + _download_file(f"{base_url}/checksums.txt.sig", sig_path) + _download_file(f"{base_url}/checksums.txt.pem", cert_path) + except Exception as exc: + logger.info("cosign artifacts unavailable (%s), proceeding with SHA-256 only", exc) + return False, "" + verified = _verify_cosign(checksums_path, sig_path, cert_path) + if verified is False: + log("tirith install aborted: cosign provenance verification failed") + return False, "cosign_verification_failed" + if verified is None: + logger.info("cosign execution failed, proceeding with SHA-256 only") + return verified is True, "" + + +def _verify_checksum(archive_path: str, checksums_path: str, archive_name: str) -> bool: + """Verify SHA-256 of the archive against checksums.txt ("<hash> <filename>" lines).""" + with open(checksums_path, encoding="utf-8") as f: + parsed = (line.strip().split(" ", 1) for line in f) + expected = next((h for h, *n in parsed if n == [archive_name]), None) + if not expected: + logger.warning("No checksum entry for %s", archive_name) + return False + sha = hashlib.sha256() + with open(archive_path, "rb") as f: + for chunk in iter(lambda: f.read(8192), b""): + sha.update(chunk) + actual = sha.hexdigest() + if actual != expected: + logger.warning("Checksum mismatch: expected %s, got %s", expected, actual) + return actual == expected + + +def _extract_tirith_binary(tar: tarfile.TarFile, dest_dir: str, log) -> tuple[str | None, str]: + """Extract the tirith binary from a release archive into dest_dir -> ``(path, reason)``.""" + for member in tar.getmembers(): + if member.name.rsplit("/", 1)[-1] != "tirith" or ".." in member.name: + continue + if not member.isfile(): + log("tirith archive member is not a regular file: %s", member.name) + return None, "binary_not_regular_file" + if (src_file := tar.extractfile(member)) is None: + log("tirith binary could not be read from archive") + return None, "binary_extract_failed" + dest_path = os.path.join(dest_dir, "tirith") + with src_file, open(dest_path, "wb") as out: + shutil.copyfileobj(src_file, out) + return dest_path, "" + log("tirith binary not found in archive") + return None, "binary_not_in_archive" + + +def _install_tirith(*, log_failures: bool = True) -> tuple[str | None, str]: + """Download and install tirith to $HERMES_HOME/bin/tirith -> ``(installed_path, + failure_reason)``; the reason ("" on success) is the disk marker's retryability tag.""" + log = logger.warning if log_failures else logger.debug + if not (target := _detect_target()): + logger.info("tirith auto-install: unsupported platform %s/%s", platform.system(), platform.machine()) + return None, "unsupported_platform" + archive_name = f"tirith-{target}.tar.gz" + base_url = f"https://github.com/{_REPO}/releases/latest/download" + try: + tmpdir = tempfile.mkdtemp(prefix="tirith-install-") + except OSError as exc: + log("tirith install failed: cannot create temp dir: %s", exc) + return None, "no_space" + try: + archive_path, checksums_path = os.path.join(tmpdir, archive_name), os.path.join(tmpdir, "checksums.txt") + logger.info("tirith not found — downloading latest release for %s...", target) + try: + _download_file(f"{base_url}/{archive_name}", archive_path) + _download_file(f"{base_url}/checksums.txt", checksums_path) + except Exception as exc: + log("tirith download failed: %s", exc) + return None, "download_failed" + cosign_verified, reason = _verify_release_provenance(base_url, tmpdir, checksums_path, log) + if reason: + return None, reason + if not _verify_checksum(archive_path, checksums_path, archive_name): + return None, "checksum_failed" + with tarfile.open(archive_path, "r:gz") as tar: + src, reason = _extract_tirith_binary(tar, tmpdir, log) + if src is None: + return None, reason + dest = os.path.join(_hermes_bin_dir(), "tirith") + try: + shutil.move(src, dest) + except OSError: + # Cross-device move (Docker, NFS): copy2's metadata step can raise PermissionError, + # so fall back to plain copy + chmod; a partial dest is removed to avoid a + # non-executable retry loop. + try: + shutil.copy(src, dest) + except OSError: + with suppress(OSError): + os.unlink(dest) + return None, "cross_device_copy_failed" + os.chmod(dest, os.stat(dest).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) + logger.info("tirith installed to %s (%s)", dest, "cosign + SHA-256" if cosign_verified else "SHA-256 only") + return dest, "" + finally: + shutil.rmtree(tmpdir, ignore_errors=True) + + +# --- Path resolution --- +def _is_executable(path: str) -> bool: + return os.path.isfile(path) and os.access(path, os.X_OK) + + +def _find_local_tirith() -> str | None: + """Cheap local lookup for the default "tirith": PATH, then $HERMES_HOME/bin.""" + hermes_bin = os.path.join(_hermes_bin_dir(), "tirith") + return shutil.which("tirith") or (hermes_bin if _is_executable(hermes_bin) else None) + + +def _resolve_locally(configured_path: str, *, warn_missing: bool) -> tuple[str | None, bool]: + """Network-free resolution -> ``(path, may_install)``: ``path`` set = resolved (module state + updated); else ``may_install`` False = terminal miss (explicit path missing, cached non-retryable + failure), True = the disk marker / install step may proceed.""" + global _resolved_path, _install_failure_reason + expanded = os.path.expanduser(configured_path) + # An explicit (non-"tirith") path is authoritative: never auto-download a replacement. + if configured_path != "tirith": + if found := (expanded if _is_executable(expanded) else shutil.which(expanded)): + _store_resolved(found) + return found, False + if warn_missing: + logger.warning("Configured tirith path %r not found; scanning disabled", configured_path) + _set_failed("explicit_path_missing") + return None, False + # Always re-run the cheap local checks so a manual install is picked up even after a + # previous network failure (a long-lived gateway recovers without restart). + if found := _find_local_tirith(): + _set_resolved(found) + _clear_install_failed() + return found, False + # Previous install failed: skip the network retry unless the retryable cosign_missing + # cause has been resolved in-process. + if _resolved_path is _INSTALL_FAILED: + if _install_failure_reason != "cosign_missing" or not shutil.which("cosign"): + return None, False + _resolved_path, _install_failure_reason = None, "" + _clear_install_failed() + return None, True + + +def _record_install_result(installed: str | None, reason: str) -> str | None: + """Cache an install outcome in module state + disk marker; returns *installed*.""" + if installed: + _set_resolved(installed) + _clear_install_failed() + else: + _set_failed(reason) + _mark_install_failed(reason) + return installed + + +def _resolve_tirith_path(configured_path: str) -> str: + """Resolve the tirith path, auto-installing synchronously if needed (default "tirith": PATH → + $HERMES_HOME/bin/tirith → install; failures cached in-process and on disk for 24h). On a miss + the expanded configured path is returned so the spawn fails open via the dedupe'd OSError.""" + if cached := _cached_path(): + return cached + expanded = os.path.expanduser(configured_path) + # No tirith build for this platform: cache the verdict; the spawn fails open once, then + # the fast path above short-circuits. + if configured_path == "tirith" and not is_platform_supported(): + _set_failed("unsupported_platform") + return expanded + found, may_install = _resolve_locally(configured_path, warn_missing=True) + if found or not may_install: + return found or expanded + # A background install is running: don't start a parallel one; fail-open until it finishes. + if _install_running() or _disk_marker_blocks_install(): + return expanded + installed = _record_install_result(*_install_tirith()) + return installed or expanded + + +def _install_running() -> bool: + return _install_thread is not None and _install_thread.is_alive() + + +def _background_install(*, log_failures: bool = True): + """Background thread target: download and install tirith.""" + with _install_lock: + if _resolved_path is not None: # another thread resolved meanwhile + return + if found := _find_local_tirith(): # may have been installed by another process + _set_resolved(found) + return + _record_install_result(*_install_tirith(log_failures=log_failures)) + + +def ensure_installed(*, log_failures: bool = True): + """Resolved path if available now, else None after kicking off a daemon-thread download (local + checks are synchronous; the download never blocks startup). Safe to call repeatedly.""" + global _install_thread + cfg = _load_security_config() + if not cfg["tirith_enabled"]: + return None + if cached := _cached_path(): + return cached if _is_executable(cached) else None + # No tirith build here (e.g. Windows): stay silent -- no PATH probe, no download thread, + # no disk marker. Pattern-matching guards still run. + if not is_platform_supported(): + _set_failed("unsupported_platform") + return None + found, may_install = _resolve_locally(cfg["tirith_path"], warn_missing=False) + if found or not may_install or _disk_marker_blocks_install(): + return found + if not _install_running(): + _install_thread = threading.Thread(target=_background_install, daemon=True, + kwargs={"log_failures": log_failures}) + _install_thread.start() + return None # not available yet; commands fail-open until ready + + +# --- Main API --- +_MAX_FINDINGS = 50 +_MAX_SUMMARY_LEN = 500 +_EXIT_ACTIONS = {0: "allow", 1: "block", 2: "warn"} +# Summary when tirith's JSON is unparseable and only the exit code is known. +_NO_DETAILS_SUMMARY = { + "block": "security issue detected (details unavailable)", + "warn": "security warning detected (details unavailable)"} + + +def _verdict(action: str, summary: str = "", findings: list | None = None) -> dict: + return {"action": action, "findings": [] if findings is None else findings, "summary": summary} + + +def _fail(fail_open: bool, open_summary: str, closed_summary: str) -> dict: + return _verdict("allow", open_summary) if fail_open else _verdict("block", closed_summary) + + +def _crash(fail_open: bool, open_summary: str, closed_summary: str) -> dict: + """An operational failure: count it toward the circuit breaker, then fail open/closed.""" + _record_tirith_crash() + return _fail(fail_open, open_summary, closed_summary) + + +def check_command_security(command: str) -> dict: + """Run the tirith scan on a command -> ``{"action": allow|warn|block, "findings", "summary"}``. + Exit code determines the action; JSON enriches. Spawn failures/timeouts respect fail_open.""" + global _crash_count + cfg = _load_security_config() + if not cfg["tirith_enabled"]: + return _verdict("allow") + # Circuit breaker: if tirith has crashed _CRASH_LIMIT times in a row, stop trying for the rest of the + # process. Without this, a corrupted or missing binary causes every tool call to hit the same spawn + # failure → fail-open → agent retry loop, hanging the user for 20+ minutes (issue #41400). + if _circuit_open: + return _verdict("allow", "tirith disabled (circuit breaker)") + # No binary for this platform, ever: skip the resolver so we never spawn. + if not is_platform_supported(): + return _verdict("allow") + tirith_path = _resolve_tirith_path(cfg["tirith_path"]) + timeout, fail_open = cfg["tirith_timeout"], cfg["tirith_fail_open"] + if tirith_path is None: + _warn_once("tirith_path_none", "tirith path resolved to None; scanning disabled") + return _fail(fail_open, "tirith path unavailable", "tirith path unavailable (fail-closed)") + try: + result = subprocess.run( + [tirith_path, "check", "--json", "--non-interactive", "--shell", "posix", "--", command], + capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=timeout, + stdin=subprocess.DEVNULL) + except OSError as exc: + # FileNotFoundError / PermissionError / exec format error: dedupe by (class, errno) + # so each failure mode surfaces once, not per command. + _warn_once(f"tirith_spawn_failed:{type(exc).__name__}:{getattr(exc, 'errno', '')}", + "tirith spawn failed: %s", exc) + return _crash(fail_open, f"tirith unavailable: {exc}", f"tirith spawn failed (fail-closed): {exc}") + except subprocess.TimeoutExpired: + _warn_once(f"tirith_timeout:{timeout}", "tirith timed out after %ds", timeout) + return _crash(fail_open, f"tirith timed out ({timeout}s)", "tirith timed out (fail-closed)") + exit_code = result.returncode + if (action := _EXIT_ACTIONS.get(exit_code)) is None: + # Unknown exit code (includes signal-killed, e.g. -11): respect fail_open. + logger.warning("tirith returned unexpected exit code %d", exit_code) + return _crash(fail_open, f"tirith exit code {exit_code} (fail-open)", + f"tirith exit code {exit_code} (fail-closed)") + if action == "allow": + _crash_count = 0 # successful execution resets the circuit breaker + # JSON enriches findings/summary; a parse failure never changes the verdict. + findings, summary = [], "" + try: + data = json.loads(result.stdout) if result.stdout.strip() else {} + findings = data.get("findings", [])[:_MAX_FINDINGS] + summary = (data.get("summary", "") or "")[:_MAX_SUMMARY_LEN] + except (json.JSONDecodeError, AttributeError): + logger.debug("tirith JSON parse failed, using exit code only") + summary = _NO_DETAILS_SUMMARY.get(action, "") + # .app is a legitimate gTLD: a warn consisting solely of lookalike_tld findings for .app is a + # known false positive and is downgraded to allow. Any other finding keeps the warn. + if action == "warn" and findings and all(_is_app_tld_finding(f) for f in findings): + return _verdict("allow") + return _verdict(action, summary, findings) + + +def _is_app_tld_finding(finding: dict) -> bool: + """True if this finding is a lookalike_tld warning for the .app TLD only.""" + if not isinstance(finding, dict) or finding.get("rule_id") != "lookalike_tld": + return False + return any( + val is not None and ".app" in str(val).lower() + for val in (finding.get(k) for k in ("value", "tld", "detail", "description", "message"))) diff --git a/tools/todo_tool.py b/tools/todo_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..1f5db2f85a9bbd56ddcf35eb2e908f0f6acb0e9a --- /dev/null +++ b/tools/todo_tool.py @@ -0,0 +1,284 @@ +"""Todo tool: in-memory, revisioned task list for multi-step work. State lives on the +AIAgent (one per session), is re-injected after context compression, and every write bumps +a monotonic revision so UI clients can reject stale updates. One ``todo_list`` tool: pass +``todos`` to write, omit to read; every call returns the full list. No system-prompt mutation.""" + +import json +from typing import Any, Dict, List, Optional + +VALID_STATUSES = {"pending", "in_progress", "completed", "cancelled"} +# The list is re-read after every compression (format_for_injection), so unbounded +# content/count would defeat the compression it rides through. Caps apply equally to +# model-authored items and caller-replayed API history. +MAX_TODO_CONTENT_CHARS = 4000 +MAX_TODO_ITEMS = 256 +# Max single todo tool-result payload accepted during history hydration, so a forged +# oversized result is dropped before parsing (AIAgent._hydrate_todo_store). +MAX_TODO_RESULT_CHARS = 512_000 +_TRUNCATION_MARKER = "… [truncated]" +# Persisted as ordinary message content; ContextCompressor keys on this stable header to +# tell the synthetic post-compaction row from a real user message. +TODO_INJECTION_HEADER = "[Your active task list was preserved across context compression]" +_STATUS_MARKERS = {"completed": "[x]", "in_progress": "[>]", "pending": "[ ]", "cancelled": "[~]"} +_ACTIVE_STATUSES = {"pending", "in_progress"} + + +class TodoStore: + """In-memory todo list, one per AIAgent. List position is priority; items are + ``{id, content, status, parent?}`` — ``parent`` nests a subtask.""" + + def __init__(self): + self._items: List[Dict[str, str]] = [] + self._revision = 0 + + def _fresh_items(self, todos: List[Dict[str, Any]]) -> List[Dict[str, str]]: + """Validate, dedupe and order a whole new list (replace / restore).""" + return self._normalize_order([self._validate(t) for t in self._dedupe_by_id(todos)]) + + def write(self, todos: List[Dict[str, Any]], merge: bool = False) -> List[Dict[str, str]]: + """Replace the list (default) or merge by id; returns the full list after writing.""" + before = self.read() + if merge: + self._merge(todos) + else: + self._items = self._fresh_items(todos) + del self._items[MAX_TODO_ITEMS:] # keep the priority head; replays can't grow unbounded + self._sanitize_parents(self._items) + if self._items != before: + self._revision += 1 + return self.read() + + def _merge(self, todos: List[Dict[str, Any]]) -> None: + """Update existing items only in the fields provided; append new ones (validated).""" + existing = {item["id"]: item for item in self._items} + for t in self._dedupe_by_id(todos): + item_id = str(t.get("id", "")).strip() + if not item_id: + continue # can't merge without an id + cur = existing.get(item_id) + if cur is None: + validated = self._validate(t) + existing[validated["id"]] = validated + self._items.append(validated) + continue + if t.get("content"): + cur["content"] = self._cap_content(str(t["content"]).strip()) + if t.get("status") and str(t["status"]).strip().lower() in VALID_STATUSES: + cur["status"] = str(t["status"]).strip().lower() + if "parent" in t: + parent = str(t["parent"] or "").strip() + if parent: + cur["parent"] = parent + else: + cur.pop("parent", None) + # Rebuild preserving original order for existing items (first occurrence wins). + rebuilt = {item["id"]: existing.get(item["id"], item) for item in self._items} + self._items = self._normalize_order(list(rebuilt.values())) + + def read(self) -> List[Dict[str, str]]: + return [item.copy() for item in self._items] + + def has_items(self) -> bool: + return bool(self._items) + + def snapshot(self) -> Dict[str, Any]: + """Full state clients can reconcile atomically.""" + return {"todos": self.read(), "revision": self._revision} + + def restore(self, todos: List[Dict[str, Any]], *, revision: Any = 0) -> List[Dict[str, str]]: + """Restore a trusted snapshot without manufacturing a new revision.""" + self._items = self._fresh_items(todos)[:MAX_TODO_ITEMS] + try: + self._revision = max(0, int(revision or 0)) + except (TypeError, ValueError): + self._revision = 0 + return self.read() + + def format_for_injection(self) -> Optional[str]: + """Render the list for post-compression injection, or None if nothing active. Only + pending/in_progress items are injected — finished ones make the model re-do work after + compression. A parent is kept (with its real status marker) when any descendant is + active so subtasks keep context.""" + if not self._items: + return None + children: Dict[str, List[Dict[str, str]]] = {} + for item in self._items: + if item.get("parent"): + children.setdefault(item["parent"], []).append(item) + + def render(item: Dict[str, str], depth: int, out: List[str]) -> bool: + kid_lines: List[str] = [] + has_active_kid = False + for kid in children.get(item["id"], []): + has_active_kid |= render(kid, depth + 1, kid_lines) + keep = item["status"] in _ACTIVE_STATUSES or has_active_kid + if keep: + marker = _STATUS_MARKERS.get(item["status"], "[?]") + out.append(f"{' ' * depth}- {marker} {item['id']}. " + f"{item['content']} ({item['status']})") + out.extend(kid_lines) + return keep + + lines = [TODO_INJECTION_HEADER] + for item in self._items: + if not item.get("parent"): + render(item, 0, lines) + return "\n".join(lines) if len(lines) > 1 else None + + @staticmethod + def _cap_content(content: str) -> str: + """Truncate to MAX_TODO_CONTENT_CHARS keeping the head (the actionable part) + marker.""" + if len(content) > MAX_TODO_CONTENT_CHARS: + return content[:MAX_TODO_CONTENT_CHARS - len(_TRUNCATION_MARKER)] + _TRUNCATION_MARKER + return content + + @staticmethod + def _validate(item: Dict[str, Any]) -> Dict[str, str]: + """Normalize one item to ``{id, content, status, parent?}`` (placeholders when missing).""" + if not isinstance(item, dict): + return {"id": "?", "content": "(invalid item)", "status": "pending"} + item_id = str(item.get("id", "")).strip() or "?" + content = str(item.get("content", "")).strip() + status = str(item.get("status", "pending")).strip().lower() + result = {"id": item_id, + "content": TodoStore._cap_content(content) if content else "(no description)", + "status": status if status in VALID_STATUSES else "pending"} + parent = str(item.get("parent") or "").strip() + if parent and parent != item_id: + result["parent"] = parent + return result + + @staticmethod + def _sanitize_parents(items: List[Dict[str, str]]) -> None: + """Drop dangling parent refs and break cycles in place (such items become roots).""" + by_id = {item["id"]: item for item in items} + for item in items: + if item.get("parent") and item["parent"] not in by_id: + item.pop("parent", None) + for item in items: + seen, node = {item["id"]}, item + while node.get("parent"): + if node["parent"] in seen: + item.pop("parent", None) + break + seen.add(node["parent"]) + node = by_id[node["parent"]] + + @staticmethod + def _dedupe_by_id(todos: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + """Collapse duplicate ids, keeping the last occurrence in its position.""" + last_index: Dict[str, int] = {} + for i, item in enumerate(todos): # non-dicts get a synthetic key; _validate handles them + key = str(item.get("id", "")).strip() if isinstance(item, dict) else f"__invalid_{i}" + last_index[key or "?"] = i + return [todos[i] for i in sorted(last_index.values())] + + @staticmethod + def _normalize_order(items: List[Dict[str, str]]) -> List[Dict[str, str]]: + """Lift the in_progress step ahead of any earlier pending placeholder. Nested lists + keep authored order — reordering would tear a subtask from its siblings.""" + statuses = [item["status"] for item in items] + if any(item.get("parent") for item in items) or "in_progress" not in statuses: + return items + active_index = statuses.index("in_progress") + if "pending" not in statuses[:active_index]: + return items + normalized = items.copy() + normalized.insert(statuses.index("pending"), normalized.pop(active_index)) + return normalized + + +def todo_tool(todos: Optional[List[Dict[str, Any]]] = None, merge: bool = False, + store: Optional[TodoStore] = None) -> str: + """Write ``todos`` (replace, or ``merge`` by id) or read when None -> list + summary JSON.""" + if store is None: + return tool_error("TodoStore not initialized") + if todos is None: + items = store.read() + else: + if isinstance(todos, str): # LLMs sometimes send a JSON string instead of a list + try: + todos = json.loads(todos) + except (json.JSONDecodeError, TypeError): + return tool_error("todos must be a list of objects, got unparseable string") + if not isinstance(todos, list): + return tool_error(f"todos must be a list, got {type(todos).__name__}") + items = store.write(todos, merge) + summary = {"total": len(items)} + for status in ("pending", "in_progress", "completed", "cancelled"): + summary[status] = sum(1 for i in items if i["status"] == status) + return json.dumps({"todos": items, "revision": store.snapshot()["revision"], + "summary": summary}, ensure_ascii=False) + + +def check_todo_requirements() -> bool: + """Todo tool has no external requirements -- always available.""" + return True + + +# Behavioral guidance is baked into the (static, cached) description; item shape and merge +# semantics live ONLY in the parameter schema. +TODO_SCHEMA = { + "name": "todo_list", + "description": ( + # See #95681. + "Track a task list for multi-step work (3+ steps). Use for complex tasks " + "with 3+ steps or when the user provides multiple tasks. " + "For 'all N items' tasks, enumerate every instance as its own checklist " + "item so none are silently dropped. " + "Call with no parameters to read the current list.\n" + "List order is priority. Only ONE item in_progress at a time. " + "Break large phases into subtasks via parent. " + "Mark an item completed only after the work is verified done, never " + "based on intent. If something fails, cancel it and add a revised " + "item. Always returns the full current list." + ), + "parameters": { + "type": "object", + "properties": { + "todos": { + "type": "array", + "description": "Task items to write.", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "content": { + "type": "string", + "description": "Task description" + }, + "status": { + "type": "string", + "enum": ["pending", "in_progress", "completed", "cancelled"] + }, + "parent": { + "type": "string", + "description": "Optional id of another item, making this a nested subtask. Omit for top-level." + } + }, + "required": ["id", "content", "status"] + } + }, + "merge": { + "type": "boolean", + "description": ( + "true: update existing items by id, add new ones. " + "false (default): replace the entire list with a fresh plan." + ), + "default": False + } + }, + "required": [] + } +} + + +from tools.registry import registry, tool_error + +registry.register( + name="todo_list", toolset="todo", schema=TODO_SCHEMA, check_fn=check_todo_requirements, + handler=lambda args, **kw: todo_tool( + todos=args.get("todos"), merge=args.get("merge", False), store=kw.get("store")), + emoji="📋") diff --git a/tools/tool_output_limits.py b/tools/tool_output_limits.py new file mode 100644 index 0000000000000000000000000000000000000000..c9099064448a9c7193b4b38bea719a9ea0aedd68 --- /dev/null +++ b/tools/tool_output_limits.py @@ -0,0 +1,64 @@ +"""Configurable tool-output truncation limits (``tool_output`` in config.yaml): +``max_bytes`` (terminal output cap), ``max_lines`` (read_file pagination cap), +``max_line_length`` (per-line cap before '... [truncated]'). Defaults equal the +constants once hardcoded in terminal_tool / file_operations and the reader never +raises, so behaviour is unchanged when the section is absent or malformed.""" + +from __future__ import annotations + +from typing import Any, Dict + +from hermes_constants import hermes_home_key + +DEFAULT_MAX_BYTES = 50_000 # terminal_tool.MAX_OUTPUT_CHARS +DEFAULT_MAX_LINES = 2000 # file_operations.MAX_LINES +DEFAULT_MAX_LINE_LENGTH = 2000 # file_operations.MAX_LINE_LENGTH +# Keyed by profile home: the multiplexed gateway serves every profile from one process, so a +# single slot would hand the launch profile's limits to every other profile. +_cached_limits: Dict[str, Dict[str, int]] = {} + + +def _coerce_int(value: Any, default: int, minimum: int) -> int: + """Return ``value`` as an int >= ``minimum``, or ``default`` on any issue.""" + try: + iv = int(value) + except (TypeError, ValueError): + return default + return default if iv < minimum else iv + + +def _coerce_positive_int(value: Any, default: int) -> int: + return _coerce_int(value, default, 1) # positive int, or ``default`` on any issue + + +def get_tool_output_limits() -> Dict[str, int]: + """Resolved ``{max_bytes, max_lines, max_line_length}``; never raises. Cached per profile + home for the process — ``_reset_tool_output_limits_cache()`` forces a fresh read.""" + key = hermes_home_key() + cached = _cached_limits.get(key) + if cached is not None: + return cached + try: + from hermes_cli.config import load_config + cfg = load_config() or {} + section = cfg.get("tool_output") if isinstance(cfg, dict) else None + except Exception: + section = None + if not isinstance(section, dict): + section = {} + _cached_limits[key] = limits = { + "max_bytes": _coerce_positive_int(section.get("max_bytes"), DEFAULT_MAX_BYTES), + "max_lines": _coerce_positive_int(section.get("max_lines"), DEFAULT_MAX_LINES), + "max_line_length": _coerce_positive_int( + section.get("max_line_length"), DEFAULT_MAX_LINE_LENGTH)} + return limits + + +def _reset_tool_output_limits_cache() -> None: + """Reset the cached limits — for tests or after config hot-reload.""" + _cached_limits.clear() + + +def get_max_bytes() -> int: return get_tool_output_limits()["max_bytes"] +def get_max_lines() -> int: return get_tool_output_limits()["max_lines"] +def get_max_line_length() -> int: return get_tool_output_limits()["max_line_length"] diff --git a/tools/tool_output_truncate.py b/tools/tool_output_truncate.py new file mode 100644 index 0000000000000000000000000000000000000000..99441aaaae4d9d52a5a454c53ccebe6af409d072 --- /dev/null +++ b/tools/tool_output_truncate.py @@ -0,0 +1,32 @@ +"""Head/tail truncation for oversized tool output (terminal, execute_code, MCP results). + +One algorithm and one notice wording: 40% head (errors surface early) / 60% tail (the most +recent lines matter most) around a single ``... [<LABEL> TRUNCATED - N <unit> omitted out of +T total] ...`` marker, so downstream code that recognises the marker sees one shape. Limits +live in ``tools/tool_output_limits.py``; line-snapped, path-bearing footers (web/browser, +read_file pagination) are different products and stay separate. +""" + +from __future__ import annotations + +HEAD_RATIO = 0.4 + + +def truncation_notice(omitted: int, total: int, *, label: str = "OUTPUT", unit: str = "chars") -> str: + return f"\n\n... [{label} TRUNCATED - {omitted:,} {unit} omitted out of {total:,} total] ...\n\n" + + +def head_tail_split(budget: int) -> tuple[int, int]: + """``(head, tail)`` character budgets for ``budget`` total.""" + head = int(budget * HEAD_RATIO) + return head, budget - head + + +def truncate_head_tail(text: str, max_chars: int, *, label: str = "OUTPUT") -> str: + """``text`` unchanged when it fits ``max_chars``; otherwise head + notice + tail (the kept + text is exactly ``max_chars`` long, the notice rides on top).""" + if len(text) <= max_chars: + return text + head, tail = head_tail_split(max_chars) + omitted = len(text) - head - tail + return text[:head] + truncation_notice(omitted, len(text), label=label) + text[-tail:] diff --git a/tools/tool_result_storage.py b/tools/tool_result_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..550106c71740e4811bdc355389168cdf210cda54 --- /dev/null +++ b/tools/tool_result_storage.py @@ -0,0 +1,269 @@ +"""Tool result persistence -- preserves large outputs instead of truncating. Layers against +context overflow: (1) per-tool caps inside each tool; (2) ``maybe_persist_tool_result`` — +output over the tool's threshold is persisted and replaced by a preview + path; canonical home +is ALWAYS host-side ``$HERMES_HOME/cache/spillover/{id}.txt`` (works for sessions that never +ran a terminal), remote backends get the translated in-sandbox path (probed for readability) +else a copy in the sandbox temp dir; (3) ``enforce_turn_budget``.""" + +import hashlib +import logging +import os +import re +import shlex +import threading +import time + +from tools.budget_config import DEFAULT_PREVIEW_SIZE_CHARS, BudgetConfig, DEFAULT_BUDGET + +logger = logging.getLogger(__name__) +PERSISTED_OUTPUT_TAG = "<persisted-output>" +PERSISTED_OUTPUT_CLOSING_TAG = "</persisted-output>" +STORAGE_DIR = "/tmp/hermes-results" +SPILLOVER_SUBDIR = "cache/spillover" +SPILLOVER_MAX_AGE_HOURS = 24 +_BUDGET_TOOL_NAME = "__budget_enforcement__" +_UNSAFE_RESULT_FILENAME_CHARS = re.compile(r"[^A-Za-z0-9_.-]+") +_MAX_RESULT_FILENAME_STEM = 120 + +_spillover_prune_lock = threading.Lock() +_spillover_pruned_homes: set = set() # profile home keys already swept this process + + +def get_spillover_dir(): + """Return $HERMES_HOME/cache/spillover as a Path (not created).""" + from hermes_constants import get_hermes_home + return get_hermes_home() / SPILLOVER_SUBDIR + + +def cleanup_spillover_cache(max_age_hours: int = SPILLOVER_MAX_AGE_HOURS) -> int: + """Delete spillover files older than *max_age_hours*; returns count removed (same + contract as the ``cleanup_*_cache`` helpers the gateway housekeeping loop runs hourly).""" + cutoff = time.time() - (max_age_hours * 3600) + removed = 0 + try: + entries = list(get_spillover_dir().iterdir()) + except OSError: + return 0 + for f in entries: + try: + if f.is_file() and f.stat().st_mtime < cutoff: + f.unlink() + removed += 1 + except OSError: + pass + return removed + + +def _prune_spillover_once() -> None: + """Best-effort prune, at most once per process PER PROFILE HOME (CLI-only installs never run + housekeeping; a multiplexed gateway must sweep every profile's ``cache/spillover``, not just the + first one that spilled).""" + from hermes_constants import hermes_home_key + home_key = hermes_home_key() + with _spillover_prune_lock: + if home_key in _spillover_pruned_homes: + return + _spillover_pruned_homes.add(home_key) + try: + if removed := cleanup_spillover_cache(): + logger.debug("Pruned %d expired spillover file(s)", removed) + except Exception as exc: + logger.debug("Spillover prune failed: %s", exc) + + +def _is_host_side_env(env) -> bool: + """True when this process should write the spill file directly: ``env=None`` (no sandbox + yet) or the local backend. Remote backends resolve ``read_file`` inside the sandbox.""" + if env is None: + return True + try: + from tools.environments.local import LocalEnvironment + return isinstance(env, LocalEnvironment) + except Exception: + return False + + +def _write_to_spillover(content: str, filename: str): + """Write host-side to $HERMES_HOME/cache/spillover; returns path str or None.""" + try: + spill_dir = get_spillover_dir() + spill_dir.mkdir(parents=True, exist_ok=True) + path = spill_dir / filename + path.write_text(content, encoding="utf-8", errors="replace") + except OSError as exc: + logger.warning("Spillover write failed for %s: %s", filename, exc) + return None + _prune_spillover_once() + return str(path) + + +def _sandbox_visible_spillover_path(host_path: str, env) -> str | None: + """Path where a remote backend can read *host_path*, or None. Translates via the image + tools' helper, forces a sync for synced backends, then PROBES readability — a persistent + container created before spillover joined the mount list lacks the bind mount and must + fall back to the in-sandbox write.""" + try: + from tools.credential_files import to_agent_visible_cache_path + visible = to_agent_visible_cache_path(host_path) + except Exception as exc: + logger.debug("Spillover path translation failed: %s", exc) + return None + try: + if (sync_manager := getattr(env, "_sync_manager", None)) is not None: + sync_manager.sync(force=True) + except Exception as exc: + logger.debug("Spillover sync failed: %s", exc) + try: + if env.execute(f"test -r {shlex.quote(visible)}", timeout=15).get("returncode", 1) == 0: + return visible + except Exception as exc: + logger.debug("Spillover readability probe failed: %s", exc) + return None + + +def _resolve_storage_dir(env) -> str: + """Return the best temp-backed storage dir for this environment.""" + get_temp_dir = getattr(env, "get_temp_dir", None) + temp_dir = None + if callable(get_temp_dir): + try: + temp_dir = get_temp_dir() + except Exception as exc: + logger.debug("Could not resolve env temp dir: %s", exc) + return f"{temp_dir.rstrip('/') or '/'}/hermes-results" if temp_dir else STORAGE_DIR + + +def _safe_result_filename(tool_use_id: str) -> str: + """Return a single safe filename for a tool result id.""" + raw_id = str(tool_use_id or "tool_result") + safe_stem = _UNSAFE_RESULT_FILENAME_CHARS.sub("_", raw_id).strip("._-") + changed = safe_stem != raw_id + safe_stem = safe_stem or "tool_result" + if changed or len(safe_stem) > _MAX_RESULT_FILENAME_STEM: + digest = hashlib.sha256(raw_id.encode("utf-8")).hexdigest()[:12] + safe_stem = safe_stem[:_MAX_RESULT_FILENAME_STEM].rstrip("._-") or "tool_result" + safe_stem = f"{safe_stem}_{digest}" + return f"{safe_stem}.txt" + + +def generate_preview(content: str, max_chars: int = DEFAULT_PREVIEW_SIZE_CHARS) -> tuple[str, bool]: + """Truncate at last newline within max_chars. Returns (preview, has_more).""" + if len(content) <= max_chars: + return content, False + last_nl = content.rfind("\n", 0, max_chars) + return content[:last_nl + 1 if last_nl > max_chars // 2 else max_chars], True + + +def _write_to_sandbox(content: str, remote_path: str, env) -> bool: + """Write content into the sandbox via env.execute(); True on success. Content goes through + stdin, not the command string: Linux ``MAX_ARG_STRLEN`` caps one argv element at 128 KB, + so a heredoc-in-command silently failed for exactly the oversized results this handles.""" + storage_dir = os.path.dirname(remote_path) + cmd = f"mkdir -p {shlex.quote(storage_dir)} && cat > {shlex.quote(remote_path)}" + return env.execute(cmd, timeout=30, stdin_data=content).get("returncode", 1) == 0 + + +def _build_persisted_message(preview: str, has_more: bool, original_size: int, + file_path: str) -> str: + """Build the <persisted-output> replacement block.""" + size_kb = original_size / 1024 + size_str = f"{size_kb / 1024:.1f} MB" if size_kb >= 1024 else f"{size_kb:.1f} KB" + return ( + f"{PERSISTED_OUTPUT_TAG}\n" + f"This tool result was too large ({original_size:,} characters, {size_str}).\n" + f"Full output saved to: {file_path}\n" + "Use the read_file tool with offset and limit to access specific sections of this output.\n" + "Recovery: page through the saved file with read_file (offset/limit) or " + "process it with execute_code — do NOT re-request the same data from the " + "remote API; the full result is already on disk.\n\n" + f"Preview (first {len(preview)} chars):\n" + + preview + ("\n..." if has_more else "") + + f"\n{PERSISTED_OUTPUT_CLOSING_TAG}") + + +_PERSISTED_PATH_RE = re.compile(r"^Full output saved to: (.+)$", re.MULTILINE) + + +def extract_persisted_path(content: str) -> str | None: + """File path from a <persisted-output> block, or None (lets the result-reference stubbing + guard in agent/tool_guardrails.py carry the spillover path instead of leaving it dangling).""" + match = (_PERSISTED_PATH_RE.search(content) + if isinstance(content, str) and PERSISTED_OUTPUT_TAG in content else None) + return match.group(1).strip() if match else None + + +def maybe_persist_tool_result(content: str, tool_name: str, tool_use_id: str, env=None, + config: BudgetConfig = DEFAULT_BUDGET, + threshold: int | float | None = None) -> str: + """Layer 2: persist an oversized result, return preview + path. ``threshold`` overrides + ``config.resolve_threshold(tool_name)``; falls back to inline truncation when no write + location succeeds.""" + if threshold is None: + threshold = config.resolve_threshold(tool_name) + if threshold == float("inf") or len(content) <= threshold: + return content + filename = _safe_result_filename(tool_use_id) + preview, has_more = generate_preview(content, max_chars=config.preview_size) + + def _persisted(path: str, host_suffix: str = "") -> str: + logger.info("Persisted large tool result: %s (%s, %d chars -> %s%s)", + tool_name, tool_use_id, len(content), path, host_suffix) + return _build_persisted_message(preview, has_more, len(content), path) + + # Always persist host-side first: cache/spillover is the single canonical home. + host_path = _write_to_spillover(content, filename) + host_side = _is_host_side_env(env) + if host_side and host_path is not None: + return _persisted(host_path) + if not host_side: + # Remote backend: reference the mounted/synced path when the sandbox can actually read + # it, else write into the sandbox temp dir (containers without the spillover mount). + visible = _sandbox_visible_spillover_path(host_path, env) if host_path else None + if visible is not None: + return _persisted(visible, f" [host: {host_path}]") + remote_path = f"{_resolve_storage_dir(env)}/{filename}" + try: + if _write_to_sandbox(content, remote_path, env): + return _persisted(remote_path) + except Exception as exc: + logger.warning("Sandbox write failed for %s: %s", tool_use_id, exc) + logger.info("Inline-truncating large tool result: %s (%d chars, no sandbox write)", + tool_name, len(content)) + return (f"{preview}\n\n[Truncated: tool response was {len(content):,} chars. " + "Full output could not be saved to sandbox.]") + + +def enforce_turn_budget(tool_messages: list[dict], env=None, + config: BudgetConfig = DEFAULT_BUDGET) -> list[dict]: + """Layer 3: persist the largest non-persisted results first until the turn's aggregate is + under budget. Mutates the list in-place and returns it.""" + sizes = [len(msg.get("content", "")) for msg in tool_messages] + total_size = sum(sizes) + candidates = [(i, size) for i, size in enumerate(sizes) + if PERSISTED_OUTPUT_TAG not in tool_messages[i].get("content", "")] + if total_size <= config.turn_budget: + return tool_messages + for idx, size in sorted(candidates, key=lambda x: x[1], reverse=True): + if total_size <= config.turn_budget: + break + content = tool_messages[idx]["content"] + tool_use_id = tool_messages[idx].get("tool_call_id", f"budget_{idx}") + replacement = maybe_persist_tool_result( + content=content, tool_name=_BUDGET_TOOL_NAME, tool_use_id=tool_use_id, + env=env, config=config, threshold=0) + if replacement != content: + total_size += len(replacement) - size + tool_messages[idx]["content"] = replacement + logger.info("Budget enforcement: persisted tool result %s (%d chars)", + tool_use_id, size) + return tool_messages + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. +import uuid # noqa: F401,E402 + +HEREDOC_MARKER = "HERMES_PERSIST_EOF" +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/tool_search.py b/tools/tool_search.py new file mode 100644 index 0000000000000000000000000000000000000000..dedc93929d725521a827c111220a17ec50449452 --- /dev/null +++ b/tools/tool_search.py @@ -0,0 +1,623 @@ +"""Progressive tool disclosure ("tool search"): MCP/plugin tools and a curated set of +event-triggered core tools are replaced in the model-visible array by three bridge tools — +tool_search / tool_describe / tool_call. Invariants: core tools (``toolsets._HERMES_CORE_TOOLS``) +and session-gated GUI toolsets never defer unless named in ``defer``; ANY deferrable tool +activates the bridge (the listing scales with budget, not activation); the catalog is +stateless — rebuilt from the live tool-defs every assembly (a session-keyed one drifts and +silently drops tools); bridge calls route through ``model_tools.handle_function_call``.""" + +from __future__ import annotations + +import functools +import json +import logging +import math +from collections import Counter +from dataclasses import dataclass +from typing import Any, Dict, Iterable, List, Optional, Tuple + +from tools.registry import tool_error +from tools.tool_search_catalog import ( + BRIDGE_TOOL_NAMES, CHARS_PER_TOKEN, TOOL_CALL_NAME, TOOL_DESCRIBE_NAME, TOOL_SEARCH_NAME, + CatalogEntry, _fn, _listing_group_label, _registry_entry, _registry_toolset, + build_catalog, build_catalog_listing_with_form, search_catalog) +from tools.tool_search_validation import normalize_tool_call_entries, validate_deferred_call_args +from tools.connectors import CONNECTOR_BATCH_SENTINEL, is_connector_name +from tools.connectors.search import connections_in_scope, connector_entries_by_group, remote_schemas_for + +logger = logging.getLogger("tools.tool_search") +# Bound the work one bridge call requests. Search is capped at the gateway's +# own limit: the connector search route answers 7 use_cases per request and +# returns HTTP 502 for 8 or more (measured 2026-09-09), and one local call +# maps to one gateway request. Describe has no such remote limit. +_MAX_QUERIES_PER_CALL = 7 +_MAX_DESCRIBE_NAMES_PER_CALL = 10 + + +@dataclass(frozen=True) +class ToolSearchConfig: + """Resolved, validated tool-search configuration for a single assembly.""" + enabled: str # "auto" | "on" | "off" — "auto" is an alias of "on" today + # Listing budget as % of context; does NOT gate activation, only bounds how much + # the embedded manifest may consume before it degrades (full -> names -> bare). + threshold_pct: float # 0..100 + search_default_limit: int + max_search_limit: int + listing: str = "auto" # "auto"/"on" = embed the manifest when it fits; "off" = bare bridge + listing_max_tokens: int = 4000 # budget = min(this, threshold_pct% of context) + # None = curated default; an explicit list replaces it wholesale ([] = defer no core tools). + defer_tools: Optional[frozenset] = None + + @property + def effective_defer_tools(self) -> frozenset: + return _DEFAULT_DEFERRED_TOOLS if self.defer_tools is None else self.defer_tools + + @classmethod + def from_raw(cls, raw: Any) -> "ToolSearchConfig": + """Build from a raw dict / legacy bool / None; every field is clamped and unknown + values fall back to safe defaults — a config typo must not break the agent.""" + if not isinstance(raw, dict): # legacy bool / None + raw = {"enabled": "off" if raw is False else "auto"} + max_search_limit = _clamped_int(raw.get("max_search_limit"), 25, 1, 50) + defer_raw = raw.get("defer") + return cls( + enabled=_tri_state(raw.get("enabled", "auto")), + threshold_pct=max(0.0, min(100.0, _safe_float(raw.get("threshold_pct"), 5.0))), + search_default_limit=_clamped_int( + raw.get("search_default_limit"), 5, 1, max_search_limit), + max_search_limit=max_search_limit, + listing=_tri_state(raw.get("listing", "auto")), + listing_max_tokens=_clamped_int(raw.get("listing_max_tokens"), 4000, 200, 60000), + defer_tools=(frozenset(str(n).strip() for n in defer_raw if str(n).strip()) + if isinstance(defer_raw, (list, tuple, set)) else None)) + + +_TRI_STATE_ALIASES = {"true": "on", "1": "on", "yes": "on", "false": "off", "0": "off", "no": "off"} + + +def _tri_state(value: Any) -> str: + """Normalize an ``auto``/``on``/``off`` setting (bool-ish aliases accepted).""" + text = str(value).strip().lower() + return _TRI_STATE_ALIASES.get(text, text if text in ("auto", "on", "off") else "auto") + + +def _clamped_int(value: Any, fallback: int, lo: int, hi: int) -> int: + """``int(value)`` (or ``fallback`` when unparseable) clamped to ``[lo, hi]``.""" + try: + value = int(value) + except (TypeError, ValueError): + value = fallback + return max(lo, min(hi, value)) + + +def _safe_float(value: Any, fallback: float) -> float: + try: + return float(value) + except (TypeError, ValueError): + return fallback + + +def _config_from_loader(loader_name: str) -> ToolSearchConfig: + """Tool-search config via ``hermes_cli.config.<loader_name>`` (defaults on any failure).""" + try: + import hermes_cli.config as _cfg_mod + tools_cfg = (getattr(_cfg_mod, loader_name)() or {}).get("tools") + tools_cfg = tools_cfg if isinstance(tools_cfg, dict) else {} + return ToolSearchConfig.from_raw(tools_cfg.get("tool_search")) + except Exception as e: + logger.debug("Failed to load tool-search config: %s", e) + return ToolSearchConfig.from_raw(None) + + +load_config = functools.partial(_config_from_loader, "load_config") +load_config_readonly = functools.partial(_config_from_loader, "load_config_readonly") # no copy + + +def _core_tool_names() -> frozenset[str]: + """Names that never defer by default (lazy: ``toolsets`` imports ``tools.registry``).""" + try: + from toolsets import _HERMES_CORE_TOOLS + return frozenset(_HERMES_CORE_TOOLS) + except Exception: + return frozenset() + + +# Session-gated GUI toolsets: off ``_HERMES_CORE_TOOLS`` so non-GUI clients never pay +# their schema; once enabled they stay direct unless the deferral list names them. +_DIRECT_SURFACE_TOOLSETS = frozenset({"desktop_ui", "project"}) + +# Event-triggered core tools deferred BY DEFAULT (a catalog stub suffices); the ``defer`` +# config replaces this wholesale ([] = everything eager). POST-rename names. ``clarify`` +# is deliberately absent: A/B showed deferring it collapsed structured-clarify usage +# (18/18 -> 7/18) — the ask-the-user affordance must be ambient, a stub is not enough. +_DEFAULT_DEFERRED_TOOLS = frozenset({ + "computer_use", "session_search", "image_generate", + "todo_list", "process_manage", "cronjob_manage", + # Desktop GUI surface (desktop_ui + project toolsets) + "drive_preview", "gui_tour", "desktop_preview", "annotate_preview", + "show_tip", "desktop_project", "close_terminal", + "apply_layout", "read_terminal", "read_window_below", "focus_pane"}) + + +def is_deferrable_tool_name(name: str, defer_tools: Optional[frozenset] = None) -> bool: + """True if a tool is *eligible* for deferral: named in ``defer_tools`` (curated set or + user override), OR an MCP tool, OR neither core nor a session-gated GUI surface (i.e. a + plugin tool). Bridge names never defer.""" + if name in BRIDGE_TOOL_NAMES: + return False + if defer_tools is not None and name in defer_tools: + return True + if name in _core_tool_names(): + return False + toolset = _registry_toolset(name) # None (unregistered/malformed) never defers + return toolset is not None and ( + toolset.startswith("mcp-") or toolset not in _DIRECT_SURFACE_TOOLSETS) + + +def _tool_def_names(tool_defs: Iterable[Dict[str, Any]]) -> Iterable[str]: + """Function names of a tool-defs list (``""`` for a nameless def).""" + return (_fn(td).get("name", "") for td in tool_defs) + + +def classify_tools(tool_defs: List[Dict[str, Any]], defer_tools: Optional[frozenset] = None, + ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: + """Split a tool-defs list into (visible, deferrable); bridge tools are dropped (re-added + after classification).""" + visible: List[Dict[str, Any]] = [] + deferrable: List[Dict[str, Any]] = [] + for td, name in zip(tool_defs, _tool_def_names(tool_defs)): + if name not in BRIDGE_TOOL_NAMES: + (deferrable if is_deferrable_tool_name(name, defer_tools) else visible).append(td) + return visible, deferrable + + +def _deferrable_in(tool_defs: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + """Deferrable subset of pre-assembly ``tool_defs`` under the read-only user config.""" + return classify_tools(tool_defs, load_config_readonly().effective_defer_tools)[1] + + +def estimate_tokens_from_schemas(tool_defs: Iterable[Dict[str, Any]]) -> int: + """Token cost via the chars/4 rule (order-of-magnitude precision suffices).""" + def _chars(td: Dict[str, Any]) -> int: + try: + return len(json.dumps(td, ensure_ascii=False, separators=(",", ":"))) + except (TypeError, ValueError): + return len(str(td)) + return int(math.ceil(sum(map(_chars, tool_defs)) / CHARS_PER_TOKEN)) + + +def should_activate(config: ToolSearchConfig, deferrable_tokens: int, + context_length: Optional[int], *, connections_granted: bool = False) -> bool: + """``"off"`` never activates; ``"on"``/``"auto"`` activate whenever any deferrable tool + exists ("auto" is reserved for a future budget-gated mode — do not distinguish them + without that design). ``context_length`` is kept for caller compatibility.""" + if config.enabled == "off": + return False + if deferrable_tokens > 0: + return True + return connections_granted + + +def listing_token_budget(config: ToolSearchConfig, context_length: Optional[int]) -> int: + """``min(listing_max_tokens, threshold_pct% of context)``; unknown context uses a 10K + percentage leg (5% of a typical 200K window).""" + pct_leg = (int(context_length * (config.threshold_pct / 100.0)) + if context_length and context_length > 0 else 10_000) + return max(0, min(config.listing_max_tokens, pct_leg)) + + +def _bridge_schema(name: str, description: str, properties: Dict[str, Any], + required: List[str]) -> Dict[str, Any]: + """One OpenAI-style function schema (key order is part of the frozen bytes).""" + return {"type": "function", "function": { + "name": name, "description": description, + "parameters": {"type": "object", "properties": properties, "required": required}}} + + +_CONNECTIONS_HINT = ( + " Names starting with `connectors__` are tools of remote connector accounts " + "(Gmail, Linear, Notion, ...); `manage_connections` checks whether an account " + "is connected and gets the authorization link when it is not.") + + +def _search_description(deferred_count: int, listing: Optional[str], listing_form: str, + connections_granted: bool = False) -> str: + """tool_search bridge description with the listing embedded (framing per ``listing_form``). + ``connections_granted`` adds the one sentence that ties ``connectors__`` names to + ``manage_connections``; without that tool in the session the sentence would name a tool + the model cannot call.""" + desc = ( + (f"Search {deferred_count} additional tools that are loaded on demand. " + if deferred_count else "Search remote connector tools (email, calendars, issue trackers, and more). ") + + "Takes a list of queries searched in parallel against the same " + "catalog; send one query per distinct capability you need. Returns " + "matching tool names grouped per query plus a shared map with each " + "tool's description. Follow with " + f"`{TOOL_DESCRIBE_NAME}` to load full parameter schemas, " + f"then `{TOOL_CALL_NAME}` to invoke. Tools listed at the top of this " + "system prompt are already available and do not need to be searched." + + (_CONNECTIONS_HINT if connections_granted else "")) + if not listing: + return desc + if listing_form == "groups": + return desc + ( + "\n\nThe servers below are connected and their tools ARE available " + "through this bridge. For any request in these domains, search " + "here FIRST — do not claim the capability is unavailable and do " + "not substitute a generic tool (terminal/browser) without " + "searching.\n\n" + listing) + desc += ( + "\n\nEvery deferred capability is listed below. If a tool name " + "appears here, do NOT claim it is unavailable — load it with " + f"`{TOOL_DESCRIBE_NAME}` (skip `{TOOL_SEARCH_NAME}` when you " + "already see the exact name).") + if listing_form == "mixed": + desc += ( + " For servers marked 'names not listed', the tools exist " + f"too — find them with `{TOOL_SEARCH_NAME}` before " + "concluding anything is missing.") + return desc + "\n\n" + listing + + +def bridge_tool_schemas(deferred_count: int, listing: Optional[str] = None, + listing_form: str = "", connections_granted: bool = False) -> List[Dict[str, Any]]: + """Bridge tool schemas injected in place of deferred tools; kept short — every byte is paid + every turn. ``listing`` is embedded in the tool_search description; per-tool forms say + "skip search when you see the exact name", "groups" says search is mandatory.""" + return [ + _bridge_schema( + TOOL_SEARCH_NAME, + _search_description(deferred_count, listing, listing_form, connections_granted), + { + "queries": { + "type": "array", + "items": {"type": "string"}, + "description": "Search queries, each a few keywords describing one capability (e.g. ['create github issue', 'send slack message']). Searched in parallel; results come back grouped per query. A single string is accepted and treated as one query.", + }, + "limit": { + "type": "integer", + "description": "Maximum number of matches per query. Defaults to 5 and is clamped to the configured maximum (25 by default).", + }, + }, + ["queries"], + ), + _bridge_schema( + TOOL_DESCRIBE_NAME, + f"Load the full JSON schemas for tools returned by `{TOOL_SEARCH_NAME}`. " + f"Required before `{TOOL_CALL_NAME}` if a tool's parameters are unknown. " + "Batch every schema you need into one call.", + { + "names": { + "type": "array", + "items": {"type": "string"}, + "description": "Exact tool names (as returned by tool_search). A single string is accepted and treated as one name.", + }, + }, + ["names"], + ), + _bridge_schema( + TOOL_CALL_NAME, + "Invoke deferred tools. Takes `calls`, an array of {name, arguments} " + "— one entry per invocation; a single call is an array of one. " + "Local tools require one entry per tool_call. Only connectors__ names " + "may be batched together; mixed and multi-local batches are rejected. " + "Connector entries execute individually with results in input order. " + f"Argument shapes match each tool's schema (see `{TOOL_DESCRIBE_NAME}`). " + "Policy, hooks, and approvals run as for directly-listed tools.", + { + "calls": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": {"type": "string", "description": "Exact tool name to invoke."}, + "arguments": {"type": "object", "description": "Arguments matching the tool schema."}, + }, + "required": ["name", "arguments"], + }, + "description": "One local invocation, or one or more connector invocations. Never mix local and connector tools.", + }, + }, + ["calls"], + ), + ] + + +@dataclass +class AssemblyResult: + """Outcome of one assembly (tests and observability).""" + tool_defs: List[Dict[str, Any]] + activated: bool + deferred_count: int = 0 + deferred_tokens: int = 0 + threshold_tokens: int = 0 + # 0 = passthrough; 1 = bridge + per-tool listing; 2 = bare bridge / server summary only. + tier: int = 0 + listing_form: str = "none" # "full" | "names" | "mixed" | "groups" | "none" + + +def assemble_tool_defs(tool_defs: List[Dict[str, Any]], *, context_length: Optional[int] = None, + config: Optional[ToolSearchConfig] = None) -> AssemblyResult: + """Tool-defs the model should see: passthrough when inactive, else deferrable tools + replaced by the three bridge tools. Idempotent — existing bridge tools are stripped first.""" + config = config or load_config() + incoming = [td for td, name in zip(tool_defs, _tool_def_names(tool_defs)) + if name not in BRIDGE_TOOL_NAMES] + visible, deferrable = classify_tools(incoming, config.effective_defer_tools) + connections_granted = connections_in_scope(incoming) + if not deferrable: + if should_activate(config, 0, context_length, connections_granted=connections_granted): + return AssemblyResult(tool_defs=incoming + bridge_tool_schemas(0, connections_granted=connections_granted), + activated=True, tier=2) + return AssemblyResult(tool_defs=incoming, activated=False) + deferrable_tokens = estimate_tokens_from_schemas(deferrable) + if not should_activate(config, deferrable_tokens, context_length): + return AssemblyResult( + tool_defs=incoming, activated=False, deferred_count=len(deferrable), + deferred_tokens=deferrable_tokens, + threshold_tokens=int((context_length or 0) * (config.threshold_pct / 100.0)), tier=0) + listing, listing_form = None, "none" + listing_budget = listing_token_budget(config, context_length) + if config.listing != "off": + listing, listing_form = build_catalog_listing_with_form( + deferrable, max_tokens=listing_budget) + bridge = bridge_tool_schemas(len(deferrable), listing=listing, listing_form=listing_form, + connections_granted=connections_granted) + tier = 1 if listing_form in ("full", "names", "mixed") else 2 + logger.info( + "tool_search activated (tier %d): %d core/visible tools kept, %d deferred " + "(~%d tokens), listing %s (budget ~%d tokens)", + tier, len(visible), len(deferrable), deferrable_tokens, listing_form, listing_budget) + return AssemblyResult( + tool_defs=visible + bridge, activated=True, deferred_count=len(deferrable), + deferred_tokens=deferrable_tokens, threshold_tokens=listing_budget, + tier=tier, listing_form=listing_form) + + +def is_bridge_tool(name: str) -> bool: + return name in BRIDGE_TOOL_NAMES + + +def _clip_description(text: str, cap: int = 500) -> str: + """Cap a record description, marking the cut so it reads as deliberate. + + A bare slice ends mid-word ("apply exponential bac") and looks like + corruption; the ellipsis says "there is more — tool_describe has it". + 500 keeps 9 in 10 vendor connector descriptions whole and every first + sentence (measured p90 575, first-sentence max 329 over 353 tools). + """ + return text if len(text) <= cap else text[:cap] + "…" + + +def _shared_tool_record(entry: CatalogEntry) -> Dict[str, Any]: + """One record for the shared ``tools`` map (per-query groups carry names only); + ``required`` lets the model attempt a trivial call without a ``tool_describe`` round-trip.""" + try: + required = entry.schema["function"]["parameters"]["required"] + except (TypeError, KeyError, AttributeError): + required = [] + return {"source": entry.source, "source_name": entry.source_name, + "description": _clip_description(entry.description or ""), + "required": [r[:64] for r in (required if isinstance(required, list) else []) + if isinstance(r, str)][:32]} + + +def _available_source_summary(catalog: List[CatalogEntry]) -> List[Dict[str, Any]]: + """Deterministic ``[{name, tool_count}]`` of connected sources (attached to empty query + groups so a lexical miss is not read as a missing capability).""" + counts = Counter(_listing_group_label(entry.source_name) for entry in catalog) + return [{"name": name, "tool_count": counts[name]} for name in sorted(counts)] + + +def _string_list_arg(args: Dict[str, Any], key: str, *, dedupe: bool, max_items: int, + retry_hint: str) -> Tuple[Optional[List[str]], Optional[str]]: + """Read a list-of-strings bridge argument -> ``(items, error_json)``. A bare string (a + common model slip) is a one-item list; rejects non-lists, all-blank lists, > ``max_items``.""" + raw = args.get(key) + raw = [raw] if isinstance(raw, str) else raw + if not isinstance(raw, list): + return None, tool_error(f"{key} is required and must be an array of strings") + out: List[str] = [] + for item in raw: + text = str(item or "").strip() + if text and (not dedupe or text not in out): + out.append(text) + if not out: + return None, tool_error(f"{key} is required and must contain at least one non-empty string") + if len(out) > max_items: + return None, tool_error(f"too many {key}: {len(out)} > max {max_items}. {retry_hint}") + return out, None + + +def dispatch_tool_search(args: Dict[str, Any], *, current_tool_defs: List[Dict[str, Any]], + config: Optional[ToolSearchConfig] = None, + connector_search: Optional[Any] = None) -> str: + """Execute the ``tool_search`` bridge tool -> JSON ``{queries, total_available, + results: [{query, matches: [names]}], tools: {name: {source, source_name, description, + required}}}``. ``limit`` is the total PER QUERY across local and connector tools: the + gateway's hits for a query join the local catalog as documents and one BM25 pass ranks + them together, so a connector tool that answers the query is never starved by local + tools that share one word with it. Empty groups get ``available_sources`` + ``hint`` so + a lexical miss is not mistaken for a missing capability.""" + config = config or load_config() + queries, err = _string_list_arg(args, "queries", dedupe=False, max_items=_MAX_QUERIES_PER_CALL, + retry_hint="Retry with fewer, more targeted queries.") + if err: + return err + raw_limit = args.get("limit") + limit = (config.search_default_limit if raw_limit is None + else _clamped_int(raw_limit, config.search_default_limit, 1, config.max_search_limit)) + catalog = build_catalog(_deferrable_in(current_tool_defs)) + remote_entries: List[List[CatalogEntry]] = [[] for _ in queries] + if connections_in_scope(current_tool_defs): + remote_entries = connector_entries_by_group(queries, connector_search=connector_search) + results: List[Dict[str, Any]] = [] + tools_map: Dict[str, Dict[str, Any]] = {} + available_sources = _available_source_summary(catalog) if catalog else [] + for position, query in enumerate(queries): + corpus = catalog + remote_entries[position] + hits = search_catalog(corpus, query, limit=limit) + for h in hits: + tools_map.setdefault(h.name, _shared_tool_record(h)) + matches = [h.name for h in hits] + group: Dict[str, Any] = {"query": query, "matches": matches} + if not matches and catalog: + group["available_sources"] = available_sources + group["hint"] = ( + "This query returned no lexical matches, but the sources above " + "are connected and their tools remain available. Retry " + "tool_search with the service name plus a concrete action or " + "object before concluding the capability is unavailable.") + results.append(group) + remote_count = sum(1 for name in tools_map if is_connector_name(name)) + return json.dumps({"queries": queries, "total_available": len(catalog) + remote_count, "results": results, + "tools": tools_map}, ensure_ascii=False) + + +def dispatch_tool_describe(args: Dict[str, Any], *, current_tool_defs: List[Dict[str, Any]], + config: Optional[ToolSearchConfig] = None, + connector_describe: Optional[Any] = None) -> str: + """Execute the ``tool_describe`` bridge tool -> JSON ``{tools: {name: {description, + parameters}}, not_found: [...] (unknown / not in this assembly; never fails the call), + errors: {name: msg} (registered but non-deferrable)}``. Duplicates dedupe silently.""" + config = config or load_config_readonly() + names, err = _string_list_arg( + args, "names", dedupe=True, max_items=_MAX_DESCRIBE_NAMES_PER_CALL, + retry_hint="Retry with fewer names per call.") + if err: + return err + deferrable = _deferrable_in(current_tool_defs) + by_name = {name: _fn(td) for td, name in zip(deferrable, _tool_def_names(deferrable)) if name} + remote_schemas = remote_schemas_for(names, current_tool_defs, connector_describe) + + tools: Dict[str, Dict[str, Any]] = {} + not_found: List[str] = [] + errors: Dict[str, str] = {} + for name in names: + fn = by_name.get(name) + remote_fn = remote_schemas.get(name) + if fn is not None: + tools[name] = {"description": fn.get("description", ""), + "parameters": fn.get("parameters", {})} + elif isinstance(remote_fn, dict): + tools[name] = {"description": str(remote_fn.get("description", "")), + "parameters": remote_fn.get("parameters", {})} + elif is_connector_name(name): + not_found.append(name) + elif _registry_entry(name) is not None and not is_deferrable_tool_name( + name, load_config_readonly().effective_defer_tools): + # Registered but bridge/core/GUI-surface: a real name, wrong door. + errors[name] = ( + f"'{name}' is not a deferrable tool. If you see it in the tools list " + "already, call it directly; otherwise check the spelling against tool_search.") + else: + not_found.append(name) + result: Dict[str, Any] = {"tools": tools} + if not_found: + result["not_found"] = not_found + result["hint"] = "Names in not_found are not currently available. Re-run tool_search to refresh." + if errors: + result["errors"] = errors + return json.dumps(result, ensure_ascii=False) + + +def scoped_deferrable_names(tool_defs: List[Dict[str, Any]]) -> frozenset[str]: + """Deferrable names in the *pre-assembly* ``tool_defs`` of the session scope — the + universe ``tool_call`` may reach. Gates bridge dispatch AND the executor unwrap so a + restricted session cannot invoke an out-of-scope tool via the bridge.""" + defer_tools = load_config_readonly().effective_defer_tools + return frozenset(n for n in _tool_def_names(tool_defs) + if n and is_deferrable_tool_name(n, defer_tools)) + + +def resolve_underlying_call(args: Dict[str, Any]) -> Tuple[Optional[str], Dict[str, Any], Optional[str]]: + """Parse a ``tool_call`` invocation into (underlying_name, args, error_msg). + + Used by: + * the dispatcher in ``model_tools.handle_function_call``, + * the display layer (so the activity feed shows the underlying tool), + * the trajectory recorder. + + A connector-only batch resolves + to ``(CONNECTOR_BATCH_SENTINEL, {"calls": [...]}, None)``: the batch is + one dispatch unit owned by the ``model_tools`` bridge branch, and the + sentinel is what planners/display layers see. A single local entry keeps + the historical single-tool contract unchanged. + + On parse error, returns ``(None, {}, error_message)``. + """ + entries, err = normalize_tool_call_entries(args) + if err: + return None, {}, err + + if len(entries) > 1 and any(not is_connector_name(e["name"]) for e in entries): + return None, {}, ( + "Local tools require one entry per tool_call; mixed and multi-local batches are not supported." + ) + if is_connector_name(entries[0]["name"]): + return CONNECTOR_BATCH_SENTINEL, {"calls": entries}, None + + name = entries[0]["name"] + raw_args = entries[0]["arguments"] + if not is_deferrable_tool_name(name, load_config_readonly().effective_defer_tools): + return None, {}, ( + f"'{name}' is not a deferrable tool. If it appears in the model-facing tools " + "list already, call it directly instead of via tool_call." + ) + return name, raw_args, None + + +__all__ = [ + "TOOL_SEARCH_NAME", "TOOL_DESCRIBE_NAME", "TOOL_CALL_NAME", "BRIDGE_TOOL_NAMES", + "ToolSearchConfig", "CatalogEntry", "AssemblyResult", "load_config", "is_deferrable_tool_name", + "classify_tools", "estimate_tokens_from_schemas", "should_activate", "build_catalog", + "build_catalog_listing_with_form", "listing_token_budget", "search_catalog", + "bridge_tool_schemas", "assemble_tool_defs", "is_bridge_tool", "dispatch_tool_search", + "dispatch_tool_describe", "resolve_underlying_call", "scoped_deferrable_names", + "validate_deferred_call_args", "normalize_tool_call_entries", + "CONNECTOR_BATCH_SENTINEL", "is_connector_name"] + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. +from typing import Literal # noqa: F401,E402 +import copy # noqa: F401,E402 +from dataclasses import field # noqa: F401,E402 +import re # noqa: F401,E402 +import snowballstemmer # noqa: F401,E402 +import threading # noqa: F401,E402 + +def build_catalog_listing( + deferrable: List[Dict[str, Any]], + *, + max_tokens: int = 4000, +) -> Optional[str]: + """Render a skills-style manifest of the deferred catalog. + + One line per tool — ``name: short description`` — grouped under a + heading per source (MCP server / plugin toolset), exactly like the + bundled-skills listing in the system prompt: + + github tools: (44) + - create_issue: Open a new issue in a GitHub repository. + - merge_pull_request: Merge an open pull request. + ... + + Ordering is deterministic (groups and tools sorted by name) so the + rendered block is byte-stable across assemblies of the same catalog — + this keeps the request prefix cacheable across turns. + + Token-budget fallbacks (cheap chars/4 estimate, same rule as the + activation gate): + 1. full listing (names + short descriptions) + 2. names-only listing, still grouped + 3. server-level summary — one line per MCP server / plugin toolset + (name + tool count), so the model always knows WHICH domains are + reachable through the bridge even when per-tool names don't fit + 4. ``None`` — only when the summary itself exceeds the budget + """ + text, _form = build_catalog_listing_with_form(deferrable, max_tokens=max_tokens) + return text +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/tool_search_catalog.py b/tools/tool_search_catalog.py new file mode 100644 index 0000000000000000000000000000000000000000..18cc3701464189c65a0d6881d31a727054e2d7c2 --- /dev/null +++ b/tools/tool_search_catalog.py @@ -0,0 +1,286 @@ +"""Deferred-tool catalog for tool search: BM25 retrieval over deferrable tool +defs plus the budgeted, byte-stable catalog listing embedded in the bridge.""" + +from __future__ import annotations + +import functools +import math +import re +import threading +from collections import Counter +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional, Tuple + +import snowballstemmer + +# Reserved bridge names: a user/plugin/MCP tool may not take them (registry override +# protection rejects such registrations). +TOOL_SEARCH_NAME = "tool_search" +TOOL_DESCRIBE_NAME = "tool_describe" +TOOL_CALL_NAME = "tool_call" +BRIDGE_TOOL_NAMES = frozenset({TOOL_SEARCH_NAME, TOOL_DESCRIBE_NAME, TOOL_CALL_NAME}) +# Chars-per-token rule of thumb; 4.0 slightly underestimates (fewer false activations). +CHARS_PER_TOKEN = 4.0 + + +@dataclass +class CatalogEntry: + """One deferrable tool, in a form the bridge tools can search and serve.""" + + name: str + description: str + schema: Dict[str, Any] # the full {"type":"function", "function": {...}} entry + source: str # "mcp" | "plugin" | "other" + source_name: str # toolset name, e.g. "mcp-github" or "kanban" + _tokens: List[str] = field(default_factory=list) # pre-tokenized for BM25 + + +_TOKEN_RE = re.compile(r"[A-Za-z0-9]+") +_thread_local = threading.local() + + +@functools.lru_cache(maxsize=16384) +def _stem(token: str) -> str: + """Stem one token, memoized across stateless catalog rebuilds. Snowball stemmers carry + mutable parsing state and bridge dispatch runs on parallel tool-call threads, so the + stemmer is one-per-thread, created lazily.""" + if getattr(_thread_local, "stemmer", None) is None: + _thread_local.stemmer = snowballstemmer.stemmer("english") + return _thread_local.stemmer.stemWord(token) + + +def _tokenize(text: str) -> List[str]: + """Lowercase alphanumeric tokens, Snowball-stemmed (English); shared by the index and + query paths so "issues" matches ``create_issue``.""" + return [_stem(token.lower()) for token in _TOKEN_RE.findall(text)] if text else [] + + +def _fn(td: Dict[str, Any]) -> Dict[str, Any]: + """The ``function`` block of a tool-def (``{}`` when absent/None).""" + return td.get("function") or {} + + +def _registry_entry(name: str) -> Any: + """Registry entry for ``name``; None when unregistered OR the registry raises (lookup + failures must never fail a bridge call). Lazy import: tests patch the registry.""" + try: + from tools.registry import registry + return registry.get_entry(name) + except Exception: + return None + + +def _registry_toolset(name: str) -> Optional[str]: + """Toolset of a registered tool; None when unregistered or malformed (no str toolset).""" + toolset = getattr(_registry_entry(name), "toolset", None) + return toolset if isinstance(toolset, str) else None + + +def _entry_search_text(td: Dict[str, Any], source_label: str = "") -> str: + """Search-text blob: split name words + source label + description + top-level parameter + names (schema bodies are noise with no recall gain). The ``mcp__`` prefix is dropped — it + is in every MCP document, so its IDF is ~0. The source label lets a service-name query + ("linear") reach a tool whose own name omits the vendor.""" + fn = _fn(td) + name = fn.get("name", "") + if name.startswith("mcp__"): + name = name[len("mcp__"):] + name_words = re.sub(r"[_.:-]", " ", name) + extra = source_label if source_label and source_label not in name_words.split() else "" + param_names = " ".join(((fn.get("parameters") or {}).get("properties") or {}).keys()) + return f"{name_words} {extra} {fn.get('description', '') or ''} {param_names}" + + +def _classify_source(name: str) -> Tuple[str, str]: + """Return (source_kind, source_name) for a registered tool name.""" + toolset = _registry_toolset(name) + if toolset is None: + return ("other", "") + return ("mcp" if toolset.startswith("mcp-") else "plugin", toolset) + + +def build_catalog(tool_defs: List[Dict[str, Any]]) -> List[CatalogEntry]: + """Build the deferred-tool catalog from the deferrable subset of tool-defs.""" + catalog: List[CatalogEntry] = [] + for td in tool_defs: + fn = _fn(td) + name = fn.get("name", "") + if not name: + continue + source, source_name = _classify_source(name) + # Index the human-facing label ("linear", not "mcp-linear"). + source_label = _listing_group_label(source_name) if source_name else "" + catalog.append(CatalogEntry( + name=name, description=fn.get("description", "") or "", schema=td, source=source, + source_name=source_name, _tokens=_tokenize(_entry_search_text(td, source_label)))) + return catalog + + +def _bm25_score(query_tokens: List[str], doc_tokens: List[str], doc_lengths: List[int], + avg_dl: float, doc_freq: Dict[str, int], n_docs: int, k1: float = 1.5, + b: float = 0.75) -> float: + """Standard BM25 for one query against one document (inlined; the catalog is bounded — + typically < 500 tools — so a dependency is not worth it).""" + score = 0.0 + dl = len(doc_tokens) + doc_tf = Counter(doc_tokens) + for q in query_tokens: + df, tf = doc_freq.get(q, 0), doc_tf.get(q, 0) + if df and tf: + idf = math.log(1 + (n_docs - df + 0.5) / (df + 0.5)) + score += idf * tf * (k1 + 1) / (tf + k1 * (1 - b + b * dl / max(avg_dl, 1.0))) + return score + + +_CorpusStats = Tuple[List[int], float, Dict[str, int], int] # doc_lengths, avg_dl, df, n_docs + + +def _corpus_stats(catalog: List[CatalogEntry]) -> _CorpusStats: + """Compute the BM25 statistics shared by every query over a catalog.""" + doc_lengths = [len(entry._tokens) for entry in catalog] + avg_dl = sum(doc_lengths) / max(len(doc_lengths), 1) + doc_freq = Counter(tok for entry in catalog for tok in set(entry._tokens)) + return doc_lengths, avg_dl, dict(doc_freq), len(catalog) + + +def _gate_token(query_tokens: List[str], doc_freq: Dict[str, int], n_docs: int) -> str: + """The query token with the highest IDF: the word that names the intent. ``send``, + ``read``, ``create`` sit in dozens of tool documents and separate nothing; ``gmail``, + ``github``, ``incident`` sit in a few and separate everything. A document without this + token answered a different question, however many common tokens it shares.""" + def _idf(token: str) -> float: + df = doc_freq.get(token, 0) + return math.log(1 + (n_docs - df + 0.5) / (df + 0.5)) + return max(query_tokens, key=_idf) + + +# Relevance floor. The rarest-token gate stops queries whose intent word no tool carries; it +# does not stop a long hunt whose every word exists SOMEWHERE in the catalog while no single +# tool carries more than one of them (observed: "run shell command execute code python" -> a +# workflow-rerun tool sharing only "run"; the model read "results exist" as "it is in here" +# and re-searched 216 times). A document must also match MIN_QUERY_TERM_COVERAGE of the +# query's ANSWERABLE terms (present in at least one document) before it is offered. Coverage +# only engages from MIN_ANSWERABLE_TERMS_FOR_COVERAGE terms up: short queries ("list issues") +# legitimately differ from a tool by a word, and are where a coverage rule costs real recall. +MIN_QUERY_TERM_COVERAGE = 0.5 +MIN_ANSWERABLE_TERMS_FOR_COVERAGE = 4 + + +def _required_term_coverage(answerable_term_count: int) -> int: + """How many of a query's ANSWERABLE unique terms a document must match to be offered: + one below the engagement floor, else at least half, rounded up.""" + if answerable_term_count < MIN_ANSWERABLE_TERMS_FOR_COVERAGE: + return 1 + return math.ceil(answerable_term_count * MIN_QUERY_TERM_COVERAGE) + + +def search_catalog(catalog: List[CatalogEntry], query: str, limit: int = 5, *, + corpus_stats: Optional[_CorpusStats] = None) -> List[CatalogEntry]: + """Top-``limit`` catalog entries for ``query`` by BM25 (exact name match ranks first). + + Admission is by the query's rarest token (:func:`_gate_token`), not by ``score > 0``: + BM25 is additive over the tokens a document shares with the query, so on a large catalog + ``score > 0`` admits one-token matches and fills every slot with them (measured: "send + gmail email" returned 5 incident tools that only shared ``email``). A token no document + carries admits nothing; the caller's empty-group hint tells the model to retry without it. + Long queries additionally need :func:`_required_term_coverage` of their answerable terms.""" + query_tokens = _tokenize(query) if catalog and limit > 0 else [] + if not query_tokens: + return [] + corpus_stats = corpus_stats or _corpus_stats(catalog) + doc_freq = corpus_stats[2] + gate = _gate_token(query_tokens, doc_freq, corpus_stats[3]) + answerable = {t for t in query_tokens if doc_freq.get(t, 0) > 0} + required_terms = _required_term_coverage(len(answerable)) + exact_name = query.strip().lower() + + def _admitted(entry: CatalogEntry) -> bool: + """Carries the intent word AND enough of the answerable terms (exact name is exempt).""" + if entry.name.lower() == exact_name: + return True + tokens = set(entry._tokens) + return gate in tokens and sum(1 for t in answerable if t in tokens) >= required_terms + + scored = [ + (float("inf") if entry.name.lower() == exact_name + else _bm25_score(query_tokens, entry._tokens, *corpus_stats), entry) + for entry in catalog if _admitted(entry)] + scored.sort(key=lambda x: x[0], reverse=True) + return [e for _, e in scored[:limit]] + + +# Sentence end: ., !, ? followed by whitespace/EOS, not inside e.g./i.e./etc. +_SENTENCE_END_RE = re.compile(r"(?<!\be\.g)(?<!\bi\.e)(?<!\betc)[.!?](?=\s|$)") + + +def _short_desc(description: str, max_chars: int = 60) -> str: + """First sentence of a tool description, clipped to ``max_chars`` on a word boundary. + ``e.g.``/``i.e.``/``etc.`` do not end a sentence; whitespace normalization and the regex + search stay linear-time on hostile input.""" + text = " ".join((description or "").split()) + m = _SENTENCE_END_RE.search(text) + text = text[:m.end()] if m else text + if len(text) <= max_chars: + return text + clipped = text[:max_chars] + clipped = clipped.rsplit(" ", 1)[0] if " " in clipped else clipped + return clipped.rstrip(",;: ") + "…" + + +def _listing_group_label(source_name: str) -> str: + """Human-facing group heading for a toolset, e.g. ``mcp-github`` -> ``github``.""" + label = source_name or "other" + return label[4:] if label.startswith("mcp-") else label + + +def build_catalog_listing_with_form( + deferrable: List[Dict[str, Any]], *, max_tokens: int = 4000) -> Tuple[Optional[str], str]: + """Render the deferred-catalog manifest: ``- name: short desc`` lines grouped per source. + Returns ``(text, form)``; form is ``"full"``, ``"names"``, ``"mixed"`` (oversized servers + collapsed to a name + count line), ``"groups"`` (every server summarized) or ``"none"`` + (over budget even summarized -> text is None). Ordering is deterministic (sorted groups + and tools) so the block is byte-stable — the request prefix stays cacheable. Degradation + is PER SERVER, largest first: one huge server must not cost a small one its listing.""" + groups: Dict[str, List[Tuple[str, str]]] = {} + for td in deferrable: + fn = _fn(td) + name = fn.get("name", "") + if name: + # _classify_source gives ("other", "") when unregistered; the label of "" is "other". + label = _listing_group_label(_classify_source(name)[1]) + groups.setdefault(label, []).append((name, _short_desc(fn.get("description", "")))) + if not groups: + return None, "none" + + def render_group(label: str, mode: str) -> str: + """Render one server's block. mode: 'full' | 'names' | 'summary'.""" + tools = sorted(groups[label]) + if mode == "summary": + return (f"{label} ({len(tools)} tools — names not listed; " + f"discover via `{TOOL_SEARCH_NAME}`)") + lines = [f"{label} tools ({len(tools)}):"] + if mode == "full": + lines.extend(f"- {name}: {desc}" if desc else f"- {name}" for name, desc in tools) + else: + lines.append(", ".join(name for name, _ in tools)) + return "\n".join(lines) + + header = ("Deferred tool catalog (call schemas via " + f"`{TOOL_DESCRIBE_NAME}`, invoke via `{TOOL_CALL_NAME}`):") + + def assemble_if_fits(modes: Dict[str, str]) -> Optional[str]: + text = "\n".join([header] + [render_group(lbl, modes[lbl]) for lbl in sorted(groups)]) + return text if math.ceil(len(text) / CHARS_PER_TOKEN) <= max_tokens else None + + for mode in ("full", "names"): # 1. everything full; 2. everything names-only + modes = {lbl: mode for lbl in groups} + text = assemble_if_fits(modes) + if text is not None: + return text, mode + # 3. Collapse the LARGEST rendered groups first (deterministic: size then label). + for lbl in sorted(groups, key=lambda lbl: (-len(render_group(lbl, "names")), lbl)): + modes[lbl] = "summary" + text = assemble_if_fits(modes) + if text is not None: + return text, "groups" if all(m == "summary" for m in modes.values()) else "mixed" + return None, "none" diff --git a/tools/tool_search_validation.py b/tools/tool_search_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..a2ee82b1e0426b84b1f92466a792c891e5392ac0 --- /dev/null +++ b/tools/tool_search_validation.py @@ -0,0 +1,179 @@ +"""Local argument validation for ``tool_call`` against a deferred tool's schema.""" + +from __future__ import annotations + +import copy +import json +import logging +import re +from typing import Any, Dict, List, Optional, Tuple + +from tools.registry import tool_error +from tools.tool_search_catalog import BRIDGE_TOOL_NAMES + +logger = logging.getLogger("tools.tool_search") + +_SCHEMA_LITERAL_KEYS = frozenset({"const", "default", "enum", "example", "examples"}) + + +def _schema_for_local_validation(node: Any) -> Any: + """JSON-Schema-compatible copy honoring OpenAPI ``nullable: true`` (the normal coercion + path accepts that shape, so local validation must too).""" + if isinstance(node, list): + return [_schema_for_local_validation(item) for item in node] + if not isinstance(node, dict): + return node + # Literal keywords hold instance data, not schemas: copy byte-for-byte. + normalized = {key: (copy.deepcopy(value) if key in _SCHEMA_LITERAL_KEYS + else _schema_for_local_validation(value)) + for key, value in node.items() if key != "nullable"} + if node.get("nullable") is not True: + return normalized + schema_type = normalized.get("type") + if isinstance(schema_type, str): + schema_type = [schema_type] + if isinstance(schema_type, list): + if "null" not in schema_type: + normalized["type"] = [*schema_type, "null"] + return normalized + # No ``type`` to extend ($ref/combinator): wrap so local refs still resolve from the + # root while null stays an explicit alternative. + return {"anyOf": [normalized, {"type": "null"}]} + + +def _schema_has_external_ref(node: Any) -> bool: + """True when *node* contains a non-local ``$ref`` — local validation must never turn a + tool call into an implicit network/file fetch (fail open).""" + if isinstance(node, list): + return any(_schema_has_external_ref(item) for item in node) + if not isinstance(node, dict): + return False + ref = node.get("$ref") + return (isinstance(ref, str) and not ref.startswith("#")) or any( + _schema_has_external_ref(value) for key, value in node.items() + if key not in _SCHEMA_LITERAL_KEYS) + + +def _validation_path(error: Any) -> str: + """Format a jsonschema error path as a compact argument path.""" + path = "arguments" + for part in getattr(error, "absolute_path", ()): + if isinstance(part, str) and re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", part): + path += f".{part}" + else: + path += f"[{part if isinstance(part, int) else json.dumps(part, ensure_ascii=False)}]" + return path + + +def _validation_error(message: str, *, path: str, constraint: str, parameters: Any) -> str: + return tool_error( + message, path=path, constraint=constraint, parameters=parameters, + hint="Retry tool_call with 'arguments' matching the parameters schema above.") + + +def validate_deferred_call_args(name: str, args: Dict[str, Any]) -> Optional[str]: + """Validate ``tool_call`` arguments against the deferred tool's schema. Models invoke + deferred tools "blind" (schema unseen) and omit required args; without this, the opaque + downstream failure makes cheap models loop. Required-field probe first, then the same + schema-guided coercion normal dispatch applies, then jsonschema on the repaired copy. + Missing/malformed schemas, no validator, and external refs all fail OPEN. Returns a JSON + error string when invalid, ``None`` when the call should dispatch. + + This restores the concrete-schema checks that the provider cannot perform through the generic + ``arguments: object`` bridge. See #5149. + """ + try: + from tools.registry import registry as _registry + schema = _registry.get_schema(name) + if not isinstance(schema, dict): + return None + fn = schema.get("function") if schema.get("type") == "function" else schema + params = fn.get("parameters") if isinstance(fn, dict) else None + if not isinstance(params, dict): + return None + required = params.get("required") + missing = ([r for r in required if isinstance(r, str) and r not in args] + if isinstance(required, list) else []) + if missing: + return _validation_error( + f"tool_call to '{name}' is missing required argument(s): " + f"{', '.join(missing)}. The tool was NOT invoked.", + path="arguments", constraint="required", parameters=params) + validation_schema = _schema_for_local_validation(params) + if _schema_has_external_ref(validation_schema): + logger.debug("Skipping local deferred-argument validation for %s: external $ref", name) + return None + # Validate the repaired shape dispatch will see; copy because coerce_tool_args may + # normalize in place (dispatch re-coerces canonically). + try: + from model_tools import coerce_tool_args + candidate_args = coerce_tool_args(name, dict(args)) + except Exception: + logger.debug("Deferred-argument coercion failed for %s", name, exc_info=True) + candidate_args = dict(args) + try: + from jsonschema.exceptions import best_match + from jsonschema.validators import validator_for + except ImportError: + logger.debug("jsonschema unavailable; keeping required-only validation for %s", name) + return None + validator_cls = validator_for(validation_schema) + validator_cls.check_schema(validation_schema) + validation_error = best_match(validator_cls(validation_schema).iter_errors(candidate_args)) + if validation_error is None: + return None + path = _validation_path(validation_error) + constraint = str(getattr(validation_error, "validator", None) or "schema") + detail = re.sub(r"\s+", " ", str(validation_error.message)).strip() + if len(detail) > 600: + detail = detail[:597] + "..." + return _validation_error( + f"tool_call to '{name}' failed argument validation at {path} " + f"({constraint}): {detail}. The tool was NOT invoked.", + path=path, constraint=constraint, parameters=params) + except Exception: # pragma: no cover — never block dispatch on validator bugs + logger.debug("validate_deferred_call_args failed for %s", name, exc_info=True) + return None + + +def normalize_tool_call_entries(args: Dict[str, Any]) -> Tuple[List[Dict[str, Any]], Optional[str]]: + """Normalize ``tool_call`` arguments into a ``calls[]`` list of entries. + + Accepts the advertised batch shape ``{"calls": [{"name", "arguments"}, ...]}`` + and, tolerantly, the legacy single shape ``{"name": ..., "arguments": ...}`` + (a single call is a batch of one). Each entry's ``arguments`` is coerced to + a dict (JSON strings parsed, ``None`` → ``{}``). Returns ``(entries, None)`` + or ``([], error_message)``. + """ + raw_calls = args.get("calls") + if raw_calls is None: + # Legacy single shape. + if not str(args.get("name") or "").strip(): + return [], "tool_call requires 'calls' (an array of {name, arguments})" + raw_calls = [{"name": args.get("name"), "arguments": args.get("arguments")}] + if isinstance(raw_calls, dict): + raw_calls = [raw_calls] + if not isinstance(raw_calls, list) or not raw_calls: + return [], "tool_call 'calls' must be a non-empty array of {name, arguments}" + + entries: List[Dict[str, Any]] = [] + for position, raw in enumerate(raw_calls): + if not isinstance(raw, dict): + return [], f"tool_call calls[{position}] must be an object with 'name' and 'arguments'" + name = str(raw.get("name") or "").strip() + if not name: + return [], f"tool_call calls[{position}] requires a 'name'" + if name in BRIDGE_TOOL_NAMES: + return [], f"tool_call cannot invoke '{name}' (it is itself a bridge tool)" + raw_args = raw.get("arguments") + if raw_args is None: + raw_args = {} + if isinstance(raw_args, str): + try: + raw_args = json.loads(raw_args) + except json.JSONDecodeError as e: + return [], f"tool_call calls[{position}].arguments is not valid JSON: {e}" + if not isinstance(raw_args, dict): + return [], f"tool_call calls[{position}].arguments must be an object" + entries.append({"name": name, "arguments": raw_args}) + return entries, None diff --git a/tools/transcription_audio.py b/tools/transcription_audio.py new file mode 100644 index 0000000000000000000000000000000000000000..45658e01b4e05896630f7b30556b5094e12dd70b --- /dev/null +++ b/tools/transcription_audio.py @@ -0,0 +1,279 @@ +"""Audio preprocessing for STT. + +Binary discovery, the shared ffmpeg m4a encode (transcode + silence trim), +source/format validation, WeChat .silk decoding, CAF conversion and the +best-effort cloud pre-upload silence trim. Facade-owned state (``_HAS_PILK``, +``_safe_find_spec``) is read lazily from ``tools.transcription_tools``. +""" + +from __future__ import annotations + +import logging +import os +import shutil +import subprocess +import tempfile +from functools import partial +from pathlib import Path +from typing import Any, Dict, Optional + +from hermes_cli._subprocess_compat import windows_hide_flags +from utils import is_truthy_value +from tools.transcription_common import ( + COMMON_LOCAL_BIN_DIRS, LOCAL_NATIVE_AUDIO_FORMATS, MAX_FILE_SIZE, SUPPORTED_FORMATS, + _config_number, _error_result, _lazy_ensure_quietly, _process_error_detail) + +# Log-record parity with the origin module. +logger = logging.getLogger("tools.transcription_tools") + + +def _find_binary(binary_name: str) -> Optional[str]: + """Find a local binary, checking common Homebrew/local prefixes as well as PATH.""" + for directory in COMMON_LOCAL_BIN_DIRS: + candidate = Path(directory) / binary_name + if candidate.exists() and os.access(candidate, os.X_OK): + return str(candidate) + return shutil.which(binary_name) + + +_find_ffmpeg_binary = partial(_find_binary, "ffmpeg") +_find_ffprobe_binary = partial(_find_binary, "ffprobe") +_find_whisper_binary = partial(_find_binary, "whisper") + + +def _run_quiet(command: list, *, timeout: float, env: Optional[dict] = None) -> subprocess.CompletedProcess: + """``subprocess.run`` for STT helper binaries: checked, captured, utf-8 text, no stdin, hidden window.""" + return subprocess.run( + command, check=True, capture_output=True, text=True, + encoding="utf-8", errors="replace", timeout=timeout, + stdin=subprocess.DEVNULL, env=env, creationflags=windows_hide_flags()) + + +# Shared encode profile for every STT-bound m4a (transcode and silence-trim): +# 16 kHz mono 32 kbps AAC, faststart. One owner so codec/bitrate never drift. +_STT_M4A_ENCODE_ARGS = ("-vn", "-ac", "1", "-ar", "16000", "-c:a", "aac", "-b:a", "32k", "-movflags", "+faststart") + + +def _run_ffmpeg_stt_encode(ffmpeg: str, input_path: str, output_path: str, *, audio_filter: Optional[str] = None) -> None: + """Run the shared STT m4a encode, optionally with an ``-af`` filter. Raises on failure; callers own the semantics.""" + filter_args = ["-af", audio_filter] if audio_filter else [] + _run_quiet([ffmpeg, "-y", "-i", input_path, *filter_args, *_STT_M4A_ENCODE_ARGS, output_path], + timeout=120) + + +def _transcode_audio_for_stt(file_path: str, work_dir: str) -> tuple[Optional[str], Optional[str]]: + """Transcode to a compact 16 kHz mono AAC/m4a for STT upload; ``(converted_path, None)`` or ``(None, error)``. + Newer OpenAI models reject containers ``whisper-1`` accepted (notably Ogg/Opus voice notes) and + gateway downloads may carry a misleading extension.""" + ffmpeg = _find_ffmpeg_binary() + if not ffmpeg: + return None, "audio needs transcoding for the STT API, but ffmpeg was not found" + converted_path = os.path.join(work_dir, f"{Path(file_path).stem or 'audio'}-stt.m4a") + try: + _run_ffmpeg_stt_encode(ffmpeg, file_path, converted_path) + return converted_path, None + except subprocess.CalledProcessError as exc: + details = _process_error_detail(exc) + logger.error("ffmpeg STT transcode failed for %s: %s", file_path, details) + return None, f"failed to transcode audio for the STT API: {details}" + except Exception as exc: # noqa: BLE001 - transcode is best-effort + logger.error("unexpected STT transcode failure for %s: %s", file_path, exc, exc_info=True) + return None, f"failed to transcode audio for the STT API: {exc}" + + +def _validate_audio_file_size(audio_path: Path, *, enforce_size_limit: bool = True) -> Optional[Dict[str, Any]]: + """Return an error when *audio_path* is inaccessible or (if enforced) exceeds the remote upload cap.""" + try: + file_size = audio_path.stat().st_size + except OSError as e: + return _error_result(f"Failed to access file: {e}") + if enforce_size_limit and file_size > MAX_FILE_SIZE: + return _error_result(f"File too large: {file_size / (1024*1024):.1f}MB (max {MAX_FILE_SIZE / (1024*1024):.0f}MB)") + return None + + +def _validate_audio_source_file(file_path: str, *, enforce_size_limit: bool = True) -> Optional[Dict[str, Any]]: + """Validate source path safety (and optionally size) before any decoder runs.""" + audio_path = Path(file_path) + if os.path.islink(audio_path): + return _error_result(f"Path is a symbolic link: {file_path}") + if not audio_path.exists(): + return _error_result(f"Audio file not found: {file_path}") + if not audio_path.is_file(): + return _error_result(f"Path is not a file: {file_path}") + return _validate_audio_file_size(audio_path, enforce_size_limit=enforce_size_limit) + + +def _validate_audio_file(file_path: str, *, enforce_size_limit: bool = True) -> Optional[Dict[str, Any]]: + """Validate a supported, decoder-safe audio file.""" + source_error = _validate_audio_source_file(file_path, enforce_size_limit=enforce_size_limit) + suffix = Path(file_path).suffix + if source_error or suffix.lower() in SUPPORTED_FORMATS: + return source_error + return _error_result(f"Unsupported format: {suffix}. Supported: {', '.join(sorted(SUPPORTED_FORMATS))}") + + +def _prepare_audio_for_transcription(file_path: str) -> tuple[Optional[str], Optional[str], Optional[Dict[str, Any]]]: + """Convert a decoder-safe .silk source to a temporary supported WAV file.""" + from tools.transcription_tools import _HAS_PILK, _safe_find_spec + audio_path = Path(file_path) + if audio_path.suffix.lower() != ".silk": + return file_path, None, None + if not _HAS_PILK: + # pilk is a tiny silk-v3 codec binding — lazy-installed on first .silk voice note. + _lazy_ensure_quietly("stt.silk") + if not _safe_find_spec("pilk"): + return None, None, _error_result( + "Unsupported format: .silk. Install the optional 'pilk' dependency to enable WeChat voice transcription." + ) + temp_dir = tempfile.mkdtemp(prefix="hermes-silk-") + converted_path = os.path.join(temp_dir, f"{audio_path.stem}.wav") + try: + import pilk + pilk.silk_to_wav(file_path, converted_path) + if not Path(converted_path).is_file() or Path(converted_path).stat().st_size == 0: + raise RuntimeError("pilk did not produce a readable WAV file") + return converted_path, temp_dir, None + except Exception as exc: + shutil.rmtree(temp_dir, ignore_errors=True) + logger.error("Failed to convert .silk audio %s: %s", file_path, exc, exc_info=True) + return None, None, _error_result(f"Failed to convert .silk audio for transcription: {exc}") + + +def _prepare_local_audio(file_path: str, work_dir: str) -> tuple[Optional[str], Optional[str]]: + """Normalize audio for local CLI STT when needed.""" + audio_path = Path(file_path) + if audio_path.suffix.lower() in LOCAL_NATIVE_AUDIO_FORMATS: + return file_path, None + ffmpeg = _find_ffmpeg_binary() + if not ffmpeg: + return None, "Local STT fallback requires ffmpeg for non-WAV inputs, but ffmpeg was not found" + converted_path = os.path.join(work_dir, f"{audio_path.stem}.wav") + try: + _run_quiet([ffmpeg, "-y", "-i", file_path, converted_path], timeout=300) + return converted_path, None + except subprocess.TimeoutExpired: + logger.error("ffmpeg conversion timed out for %s", file_path) + return None, "Audio conversion for local STT timed out" + except subprocess.CalledProcessError as e: + details = _process_error_detail(e) + logger.error("ffmpeg conversion failed for %s: %s", file_path, details) + return None, f"Failed to convert audio for local STT: {details}" + + +def _convert_caf_to_wav(file_path: str) -> Optional[str]: + """Convert CAF to WAV using ffmpeg or afconvert (macOS).""" + audio_path = Path(file_path) + wav_path = os.path.join(audio_path.parent, f"{audio_path.stem}.wav") + ffmpeg = _find_ffmpeg_binary() + afconvert = shutil.which("afconvert") + candidates = ( + ("ffmpeg", [ffmpeg, "-y", "-i", file_path, wav_path] if ffmpeg else None), + ("afconvert", [afconvert, file_path, wav_path, "-d", "LEI16", "-f", "WAVE"] if afconvert else None), + ) + for label, command in ((label, cmd) for label, cmd in candidates if cmd): + try: + _run_quiet(command, timeout=300) + return wav_path + except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e: + logger.warning("%s CAF to WAV failed for %s: %s", label, file_path, e) + return None + + +# ---- Cloud pre-upload silence trim -------------------------------------- +# +# Local faster-whisper gets Silero VAD; cloud providers get the raw file, so silence +# is paid for twice (upload + per-minute billing) and cloud Whisper hallucinates on +# it. Before uploading to a built-in cloud provider we collapse long pauses with +# ffmpeg's silenceremove, keeping ``stt.cloud_trim_keep_ms`` of each pause so word +# boundaries survive. Purely best-effort — ANY of these uploads the original: +# ``stt.cloud_trim_silence: false``, ffmpeg/ffprobe missing, trim failure/timeout, a +# ~empty result (the provider, not a dB heuristic, decides "no speech"), or <10% +# saving. Command-type and plugin providers are NOT trimmed: they may wrap local +# CLIs that want the original bytes. + +_CLOUD_TRIM_THRESHOLD_DB_DEFAULT = -40 # audio below this level counts as silence +_CLOUD_TRIM_KEEP_MS_DEFAULT = 300 # how much of each pause survives the trim +_CLOUD_TRIM_MIN_SAVING = 0.10 # use the trimmed file only when >=10% shorter +_CLOUD_TRIM_MIN_RESULT_SECONDS = 0.3 # all-silence guard floor: never upload ~empty audio +# Below this the trim can't pay for itself (several providers bill a 10s minimum) +# and the encode would sit on the synchronous voice-note path. +_CLOUD_TRIM_MIN_INPUT_SECONDS = 12.0 + + +def _probe_audio_duration(file_path: str) -> Optional[float]: + """Return the audio duration in seconds via ffprobe, or None. Canonical sync probe; + ``gateway/run.py._probe_audio_duration`` and the Telegram adapter carry local variants — keep + the command shape in sync.""" + ffprobe = _find_ffprobe_binary() + if not ffprobe: + return None + try: + probe = _run_quiet([ffprobe, "-v", "error", "-show_entries", "format=duration", "-of", + "default=noprint_wrappers=1:nokey=1", file_path], timeout=30) + return float(probe.stdout.strip()) + except Exception: # noqa: BLE001 - probe is best-effort + return None + + +def _cloud_trim_settings(stt_config: Dict[str, Any]) -> tuple[bool, int, int]: + """Resolve (enabled, threshold_db, keep_ms) for the cloud silence trim.""" + cfg = stt_config if isinstance(stt_config, dict) else {} + # is_truthy_value: a YAML string "false" must disable, exactly like is_stt_enabled. + enabled = is_truthy_value(cfg.get("cloud_trim_silence", True), default=True) + threshold_db = _config_number(cfg, "cloud_trim_threshold_db", _CLOUD_TRIM_THRESHOLD_DB_DEFAULT, int) + keep_ms = _config_number(cfg, "cloud_trim_keep_ms", _CLOUD_TRIM_KEEP_MS_DEFAULT, int) + return enabled, threshold_db, max(keep_ms, 0) + + +def _trim_silence_for_cloud_stt(file_path: str, stt_config: Dict[str, Any]) -> Optional[str]: + """Return a silence-trimmed copy of *file_path* for cloud upload, or None (= upload the original). + On success the caller owns deleting the returned file's parent directory.""" + enabled, threshold_db, keep_ms = _cloud_trim_settings(stt_config) + if not enabled: + return None + ffmpeg = _find_ffmpeg_binary() + if not ffmpeg: + logger.debug("Cloud STT silence trim skipped: ffmpeg not found") + return None + original_duration = _probe_audio_duration(file_path) + if not original_duration or original_duration <= 0: + logger.debug("Cloud STT silence trim skipped: could not probe %s", file_path) + return None + name = Path(file_path).name + if original_duration < _CLOUD_TRIM_MIN_INPUT_SECONDS: + logger.debug("Cloud STT silence trim skipped for %s: %.1fs is below the %.0fs gate", + name, original_duration, _CLOUD_TRIM_MIN_INPUT_SECONDS) + return None + keep_seconds = keep_ms / 1000.0 + # start_periods=1 strips leading silence; stop_periods=-1 collapses every interior/trailing silence. + filter_expr = ( + f"silenceremove=" + f"start_periods=1:start_threshold={threshold_db}dB:start_silence={keep_seconds}:" + f"stop_periods=-1:stop_threshold={threshold_db}dB:stop_silence={keep_seconds}") + work_dir = tempfile.mkdtemp(prefix="hermes-stt-trim-") + trimmed_path = os.path.join(work_dir, f"{Path(file_path).stem or 'audio'}-trimmed.m4a") + # Scale the all-silence guard with keep_ms: output that is solely kept pause must never upload as "speech". + min_result_seconds = max(_CLOUD_TRIM_MIN_RESULT_SECONDS, 2 * keep_seconds) + keep_result = False + try: + _run_ffmpeg_stt_encode(ffmpeg, file_path, trimmed_path, audio_filter=filter_expr) + trimmed_duration = _probe_audio_duration(trimmed_path) + if not trimmed_duration or trimmed_duration < min_result_seconds: + logger.debug("Cloud STT silence trim discarded for %s: trimmed result ~empty (%.2fs)", + name, trimmed_duration or 0.0) + return None + if trimmed_duration > original_duration * (1 - _CLOUD_TRIM_MIN_SAVING): + logger.debug("Cloud STT silence trim discarded for %s: saves <%.0f%% (%.1fs -> %.1fs)", + name, _CLOUD_TRIM_MIN_SAVING * 100, original_duration, trimmed_duration) + return None + logger.info("Trimmed silence from %s before cloud STT upload (%.1fs -> %.1fs, -%d%%)", name, + original_duration, trimmed_duration, round((1 - trimmed_duration / original_duration) * 100)) + keep_result = True + return trimmed_path + except Exception as exc: # noqa: BLE001 - trim is best-effort + logger.debug("Cloud STT silence trim failed for %s: %s", file_path, exc) + return None + finally: + if not keep_result: + shutil.rmtree(work_dir, ignore_errors=True) diff --git a/tools/transcription_cloud.py b/tools/transcription_cloud.py new file mode 100644 index 0000000000000000000000000000000000000000..890dd38a8ca89dd8f66cba6911c7b579e028330b --- /dev/null +++ b/tools/transcription_cloud.py @@ -0,0 +1,428 @@ +"""Cloud STT providers. + +OpenAI-SDK-shaped backends (groq, openai, deepinfra), Mistral Voxtral, REST multipart +backends (xAI, ElevenLabs), and OpenAI audio credential resolution (config > keyless +local server > env > managed Nous gateway). Facade-owned state and helpers +(``_HAS_OPENAI``, ``_resolve_provider_key``, ``_resolve_stt_language``, ``_load_stt_config``) +are read lazily from ``tools.transcription_tools``. +""" + +from __future__ import annotations + +import logging +import re +import tempfile +from pathlib import Path +from typing import Any, Callable, Dict, Optional +from urllib.parse import urljoin + +from utils import is_truthy_value +from tools.transcription_audio import _transcode_audio_for_stt +from tools.transcription_common import ( + DEFAULT_GROQ_STT_MODEL, DEFAULT_STT_MODEL, ELEVENLABS_STT_BASE_URL, GROQ_BASE_URL, GROQ_MODELS, + OPENAI_BASE_URL, OPENAI_MODELS, XAI_STT_BASE_URL, _error_result, _get_stt_section, + _lazy_ensure_quietly, _log_prompt_unsupported, _ok_result) + +# Log-record parity with the origin module. +logger = logging.getLogger("tools.transcription_tools") +# Voxtral-style ``language xx <asr_text> ...`` prefix some SDK responses carry. +_ASR_TEXT_RE = re.compile( + r"\s*language\s+[\w.-]+(?:\s*<audio_language>[^<]*</audio_language>)?\s*<asr_text>\s*(?P<text>.*)", + flags=re.IGNORECASE | re.DOTALL) + + +def _has_xai_stt_credentials() -> bool: + from tools.xai_http import resolve_xai_http_credentials + return bool(resolve_xai_http_credentials().get("api_key")) + + +def _with_openai_client(api_key: str, base_url: Optional[str], file_path: str, log_label: str, body): + """Run ``body(client)`` on a fresh OpenAI SDK client (30s timeout, no retries); always closed. + Errors map to the shared envelope. APIConnectionError is checked before APITimeoutError (its + subclass) so timeouts report as connection errors, as they always have.""" + try: + from openai import OpenAI + client = OpenAI(api_key=api_key, base_url=base_url, timeout=30, max_retries=0) + try: + return body(client) + finally: + close = getattr(client, "close", None) + if callable(close): + close() + except Exception as exc: + try: + from openai import APIError, APIConnectionError, APITimeoutError + except ImportError: # pragma: no cover — callers gate on _HAS_OPENAI + APIError = APIConnectionError = APITimeoutError = () + if isinstance(exc, PermissionError): + return _error_result(f"Permission denied: {file_path}") + for cls, label in ((APIConnectionError, "Connection error"), (APITimeoutError, "Request timeout"), + (APIError, "API error")): + if isinstance(exc, cls): + return _error_result(f"{label}: {exc}") + logger.error("%s transcription failed: %s", log_label, exc, exc_info=True) + return _error_result(f"Transcription failed: {exc}") + + +def _cloud_failure(exc: BaseException, file_path: str, label: str, detail: Optional[str] = None) -> Dict[str, Any]: + """Map a REST/SDK provider exception to the shared envelope (``label`` e.g. ``"xAI STT transcription"``).""" + if isinstance(exc, PermissionError): + return _error_result(f"Permission denied: {file_path}") + logger.error("%s failed: %s", label, exc, exc_info=True) + return _error_result(f"{label} failed: {exc if detail is None else detail}") + + +def _sdk_prompt_kwargs(language: Optional[str], prompt: Optional[str]) -> Dict[str, Any]: + """``language``/``prompt`` create-kwargs, each only when set so the bare request stays byte-identical.""" + return {key: value for key, value in (("language", language), ("prompt", prompt)) if value} + + +def _transcribe_groq( + file_path: str, model_name: str, *, language: Optional[str] = None, prompt: Optional[str] = None +) -> Dict[str, Any]: + """Transcribe via the Groq Whisper API; language: hook > ``stt.groq.language`` > ``stt.language`` > env > auto.""" + from tools.transcription_tools import _HAS_OPENAI, _resolve_provider_key, _resolve_stt_language + api_key = _resolve_provider_key("GROQ_API_KEY", "groq") + if not api_key: + return _error_result("GROQ_API_KEY not set") + if not _HAS_OPENAI: + return _error_result("openai package not installed") + if model_name in OPENAI_MODELS: # auto-correct an OpenAI-only model + logger.info("Model %s not available on Groq, using %s", model_name, DEFAULT_GROQ_STT_MODEL) + model_name = DEFAULT_GROQ_STT_MODEL + language = language or _resolve_stt_language("groq") + + def _run(client): + with open(file_path, "rb") as audio_file: + transcription = client.audio.transcriptions.create(file=audio_file, model=model_name, + response_format="text", + **_sdk_prompt_kwargs(language, prompt)) + transcript_text = str(transcription).strip() + logger.info("Transcribed %s via Groq API (%s, lang=%s, %d chars)", + Path(file_path).name, model_name, language or "auto", len(transcript_text)) + return _ok_result(transcript_text, "groq") + return _with_openai_client(api_key, GROQ_BASE_URL, file_path, "Groq", _run) + + +def _transcribe_openai( + file_path: str, model_name: str, *, api_key: Optional[str] = None, + base_url: Optional[str] = None, provider_label: str = "openai", language: Optional[str] = None, + prompt: Optional[str] = None) -> Dict[str, Any]: + """Transcribe via the OpenAI ``audio.transcriptions.create`` SDK shape, shared by every + OpenAI-compatible endpoint (DeepInfra etc.): explicit ``api_key``/``base_url`` skip the + OpenAI-only auth chain; ``provider_label`` names the response's provider.""" + from tools.transcription_tools import _HAS_OPENAI, _resolve_stt_language + if api_key is None: + try: + api_key, fallback_base = _resolve_openai_audio_client_config() + except ValueError as exc: + return _error_result(str(exc)) + base_url = base_url or fallback_base + # Language: hook override > stt.<provider>.language > stt.language > env > auto. + language = language or _resolve_stt_language(provider_label) + if not _HAS_OPENAI: + return _error_result("openai package not installed") + # Auto-correct a Groq-only model on the native OpenAI path only (third-party endpoints may serve it). + if provider_label == "openai" and model_name in GROQ_MODELS: + logger.info("Model %s not available on OpenAI, using %s", model_name, DEFAULT_STT_MODEL) + model_name = DEFAULT_STT_MODEL + + def _run(client): + from openai import BadRequestError + + def _create_transcription(path: str): + create_kwargs: Dict[str, Any] = { + "model": model_name, "response_format": "text" if model_name == "whisper-1" else "json", + } + if language: + # gpt-transcribe takes a ``languages`` list and rejects the legacy field. + if model_name == "gpt-transcribe": + create_kwargs["extra_body"] = {"languages": [language]} + else: + create_kwargs["language"] = language + logger.debug("Using language hint '%s' for OpenAI STT", language) + if prompt: # only when set so the bare request stays byte-identical + create_kwargs["prompt"] = prompt + with open(path, "rb") as audio_file: + return client.audio.transcriptions.create(file=audio_file, **create_kwargs) + with tempfile.TemporaryDirectory(prefix="hermes-stt-") as work_dir: + try: + transcription = _create_transcription(file_path) + except BadRequestError as exc: + if not any(k in str(exc).lower() for k in ("unsupported", "corrupted", "invalid file")): + raise + # Newer models reject containers whisper-1 accepted (Ogg/Opus voice notes): transcode, retry once. + converted_path, transcode_error = _transcode_audio_for_stt(file_path, work_dir) + if transcode_error: + return _error_result(transcode_error) + logger.info("Retrying %s STT after transcoding %s to m4a (API rejected the original container)", + provider_label, Path(file_path).name) + transcription = _create_transcription(converted_path) + transcript_text = _extract_transcript_text(transcription) + logger.info("Transcribed %s via %s (%s, %d chars)", + Path(file_path).name, provider_label, model_name, len(transcript_text)) + return _ok_result(transcript_text, provider_label) + return _with_openai_client(api_key, base_url, file_path, provider_label, _run) + + +def _transcribe_mistral( + file_path: str, model_name: str, *, language: Optional[str] = None, prompt: Optional[str] = None +) -> Dict[str, Any]: + """Transcribe with the ``mistralai`` SDK (``/v1/audio/transcriptions``); requires ``MISTRAL_API_KEY``.""" + from tools.transcription_tools import _resolve_provider_key, _resolve_stt_language + api_key = _resolve_provider_key("MISTRAL_API_KEY", "mistral") + if not api_key: + return _error_result("MISTRAL_API_KEY not set") + try: + _lazy_ensure_quietly("stt.mistral") + from mistralai.client import Mistral + with Mistral(api_key=api_key) as client, open(file_path, "rb") as audio_file: + # Language: hook override > stt.mistral.language > stt.language > env > auto. + language = language or _resolve_stt_language("mistral") + result = client.audio.transcriptions.complete( + model=model_name, file={"content": audio_file, "file_name": Path(file_path).name}, + **_sdk_prompt_kwargs(language, prompt)) + transcript_text = _extract_transcript_text(result) + logger.info("Transcribed %s via Mistral API (%s, %d chars)", + Path(file_path).name, model_name, len(transcript_text)) + return _ok_result(transcript_text, "mistral") + except Exception as e: + return _cloud_failure(e, file_path, "Mistral transcription", type(e).__name__) + + +# ---- REST multipart backends (xAI, ElevenLabs) ---------------------------- +def _post_audio_multipart(url: str, headers: Dict[str, str], file_path: str, data: Dict[str, str]): + import requests + with open(file_path, "rb") as audio_file: + return requests.post(url, headers=headers, files={"file": (Path(file_path).name, audio_file)}, + data=data, timeout=120) + + +def _rest_provider( + file_path: str, provider: str, label: str, post: Callable[[], Any], extract_detail, + extract_text, log: Callable[[str, Dict[str, Any]], None]) -> Dict[str, Any]: + """Shared multipart REST flow: ``post()`` -> ``log(text, body)`` -> ok envelope. Non-200 -> + ``"<label> API error (HTTP n): detail"`` (JSON detail via *extract_detail*, else the first 300 + body chars); empty text -> the ``no_speech`` envelope (silence is non-fatal); exceptions -> + ``_cloud_failure``.""" + try: + response = post() + if response.status_code != 200: + try: + detail = extract_detail(response.json()) or response.text[:300] + except Exception: + detail = response.text[:300] + return _error_result(f"{label} API error (HTTP {response.status_code}): {detail}") + body = response.json() + transcript_text = extract_text(body) + if not transcript_text: + return _error_result(f"{label} returned empty transcript", no_speech=True) + log(transcript_text, body) + return _ok_result(transcript_text, provider) + except Exception as e: + return _cloud_failure(e, file_path, f"{label} transcription") + + +def _transcribe_xai( + file_path: str, model_name: str, *, language: Optional[str] = None, prompt: Optional[str] = None +) -> Dict[str, Any]: + """Transcribe via xAI ``POST /v1/stt`` (multipart). Supports ITN, diarization, word timestamps.""" + from hermes_cli.config import get_env_value + from tools.transcription_tools import _load_stt_config, _resolve_stt_language + from tools.xai_http import resolve_xai_http_credentials + if prompt: + _log_prompt_unsupported("STT provider 'xai'") + # STT is API-billed: prefer the explicit XAI_API_KEY over the xAI OAuth/Grok-subscription + # credential, which may be valid for Grok yet hit spending-limit errors on /v1/stt. + direct_api_key = str(get_env_value("XAI_API_KEY") or "").strip() + creds = {"provider": "xai", "api_key": direct_api_key, + "base_url": str(get_env_value("XAI_BASE_URL") or "https://api.x.ai/v1").strip().rstrip("/") + } if direct_api_key else resolve_xai_http_credentials() + api_key = str(creds.get("api_key") or "").strip() + if not api_key: + return _error_result("No xAI credentials found. Configure xAI OAuth in `hermes model` or set XAI_API_KEY") + stt_config = _load_stt_config() + xai_config = stt_config.get("xai") or {} + + def _resolve_base_url(resolved_creds: Dict[str, str]) -> str: + # OAuth bearers are pinned to the resolver-validated origin; overrides apply to API keys only. + url = resolved_creds.get("base_url") + if resolved_creds.get("provider") != "xai-oauth": + url = xai_config.get("base_url") or get_env_value("XAI_STT_BASE_URL") or url + return str(url or XAI_STT_BASE_URL).strip().rstrip("/") + + # Language: hook override > stt.xai.language > stt.language > env. + language = language or _resolve_stt_language("xai", stt_config) or "" + + def _post() -> Any: + from tools.xai_http import hermes_xai_user_agent + data: Dict[str, str] = {"language": language} if language else {} + data.update({flag: "true" for flag, default in (("format", True), ("diarize", False)) + if is_truthy_value(xai_config.get(flag, default))}) + + def _post_transcription(bearer: str, endpoint_base_url: str): + headers = {"Authorization": f"Bearer {bearer}", "User-Agent": hermes_xai_user_agent()} + return _post_audio_multipart(f"{endpoint_base_url}/stt", headers, file_path, data) + + response = _post_transcription(api_key, _resolve_base_url(creds)) + if response.status_code in {401, 403} and creds.get("provider") == "xai-oauth": + logger.info("xAI STT got HTTP %d; refreshing OAuth credentials and retrying once", response.status_code) + try: + refreshed_creds = resolve_xai_http_credentials(force_refresh=True, api_key_hint=api_key) + refreshed_key = str(refreshed_creds.get("api_key") or "").strip() + if refreshed_key and refreshed_key != api_key: + response = _post_transcription(refreshed_key, _resolve_base_url(refreshed_creds)) + except Exception as retry_exc: + logger.warning("xAI STT OAuth refresh-and-retry after HTTP %d failed: %s", + response.status_code, retry_exc) + return response + + def _log(transcript_text: str, result: Dict[str, Any]) -> None: + logger.info("Transcribed %s via xAI Grok STT (lang=%s, %.1fs audio, %d chars)", Path(file_path).name, + result.get("language", language), result.get("duration", 0), len(transcript_text)) + + return _rest_provider(file_path, "xai", "xAI STT", _post, lambda body: body.get("error", {}).get("message", ""), + lambda body: body.get("text", "").strip(), _log) + + +def _elevenlabs_error_detail(err_body: Dict[str, Any]) -> str: + error_value = err_body.get("detail") or err_body.get("error") + if isinstance(error_value, dict): + return str(error_value.get("message") or error_value) + return str(error_value) if error_value else "" + + +def _transcribe_elevenlabs( + file_path: str, model_name: str, *, language: Optional[str] = None, prompt: Optional[str] = None +) -> Dict[str, Any]: + """Transcribe using ElevenLabs Scribe STT API.""" + from hermes_cli.config import get_env_value + from tools.transcription_tools import _load_stt_config, _resolve_provider_key, _resolve_stt_language + if prompt: + _log_prompt_unsupported("STT provider 'elevenlabs'") + api_key = _resolve_provider_key("ELEVENLABS_API_KEY", "elevenlabs") + if not api_key: + return _error_result("ELEVENLABS_API_KEY not set") + stt_config = _load_stt_config() + elevenlabs_config = stt_config.get("elevenlabs") or {} + base_url = str( + elevenlabs_config.get("base_url") or get_env_value("ELEVENLABS_STT_BASE_URL") or ELEVENLABS_STT_BASE_URL + ).strip().rstrip("/") + # Language: hook override > stt.elevenlabs.language(_code) > stt.language. + language_code = language or _resolve_stt_language("elevenlabs", stt_config, extra_keys=("language_code",)) or "" + + def _post() -> Any: + data: Dict[str, str] = { + "model_id": model_name, + "tag_audio_events": str(is_truthy_value(elevenlabs_config.get("tag_audio_events", False))).lower(), + "diarize": str(is_truthy_value(elevenlabs_config.get("diarize", False))).lower(), + **({"language_code": language_code} if language_code else {})} + return _post_audio_multipart(f"{base_url}/speech-to-text", {"xi-api-key": api_key}, file_path, data) + + def _log(transcript_text: str, _body: Dict[str, Any]) -> None: + logger.info("Transcribed %s via ElevenLabs Scribe (%s, %d chars)", + Path(file_path).name, model_name, len(transcript_text)) + + return _rest_provider(file_path, "elevenlabs", "ElevenLabs STT", _post, _elevenlabs_error_detail, + _extract_transcript_text, _log) + + +def _transcribe_deepinfra( + file_path: str, model_name: str, *, language: Optional[str] = None, prompt: Optional[str] = None +) -> Dict[str, Any]: + """Resolve DeepInfra credentials/model (shared ``hermes_cli.models`` helpers), then delegate to :func:`_transcribe_openai`.""" + from tools.transcription_tools import _load_stt_config, _resolve_provider_key + api_key = _resolve_provider_key("DEEPINFRA_API_KEY", "deepinfra") + if not api_key: + return _error_result("DEEPINFRA_API_KEY not set") + from hermes_cli.models import deepinfra_base_url, deepinfra_model_ids + # ``stt.deepinfra: null`` in YAML yields None, not {} — coalesce. + base_url = deepinfra_base_url(_get_stt_section(_load_stt_config(), "deepinfra")) + model_name = model_name or next(iter(deepinfra_model_ids("stt")), None) + if not model_name: + return _error_result( + "No DeepInfra STT model available. Pin one in config.yaml under stt.deepinfra.model, " + "or check connectivity to api.deepinfra.com so the live catalog can be fetched.") + return _transcribe_openai(file_path, model_name, api_key=api_key, base_url=base_url, + provider_label="deepinfra", language=language, prompt=prompt) + + +# ---- OpenAI audio credential resolution ----------------------------------- +def _is_local_or_private_url(url: str) -> bool: + """True for loopback/RFC-1918/LAN-internal hosts, where an empty ``stt.openai.api_key`` is acceptable + (local OpenAI-compatible servers ignore the auth header — no sham ``api_key: not-needed`` needed).""" + try: + from urllib.parse import urlparse + import ipaddress + host = (urlparse(url).hostname or "").lower() + if host == "localhost" or host.endswith((".local", ".lan", ".internal")): + return True + addr = ipaddress.ip_address(host) # raises for "" and non-IP hostnames + return addr.is_private or addr.is_loopback + except Exception: # unparsable URL or non-IP hostname + return False + + +def _direct_openai_credentials(cfg_api_key: str, cfg_base_url: str) -> Optional[tuple[str, str]]: + """Direct-credential ladder: config key > keyless local base_url (placeholder key so the SDK + constructs a client) > env key; None if none apply.""" + from tools.tool_backend_helpers import resolve_openai_audio_api_key + if cfg_api_key: + return cfg_api_key, (cfg_base_url or OPENAI_BASE_URL) + # A local OpenAI-compatible server needs no key — send a placeholder so the SDK doesn't refuse to + # construct a client (#25193, credit @nnnet). + if cfg_base_url and _is_local_or_private_url(cfg_base_url): + return "not-needed", cfg_base_url + direct_api_key = resolve_openai_audio_api_key() + return (direct_api_key, OPENAI_BASE_URL) if direct_api_key else None + + +def _resolve_openai_audio_client_config() -> tuple[str, str]: + """``(api_key, base_url)`` for the OpenAI STT client, strict on the stored ``stt`` selection: + ``"nous"`` -> managed gateway ONLY (a direct OPENAI_API_KEY must NOT override it); any other + stored provider -> direct credentials ONLY (no silent managed fallback); never-configured -> + legacy ladder: direct credentials, then the managed gateway. Failures raise ValueError.""" + from tools.transcription_tools import _load_stt_config + from tools.managed_tool_gateway import resolve_managed_tool_gateway + from tools.tool_backend_helpers import ( + NOUS_MANAGED_PROVIDER, managed_nous_tools_enabled, nous_tool_gateway_unavailable_message, + read_selection, selection_error) + openai_cfg = _load_stt_config().get("openai") or {} + selected = read_selection("stt") + + def _managed() -> Optional[tuple[str, str]]: + gateway = resolve_managed_tool_gateway("openai-audio") + if gateway is None: + return None + return gateway.nous_user_token, urljoin(f"{gateway.gateway_origin.rstrip('/')}/", "v1") + + if selected == NOUS_MANAGED_PROVIDER: + managed = _managed() + if managed is None: + raise ValueError(selection_error("stt", NOUS_MANAGED_PROVIDER, + "the Nous Tool Gateway is not available (not entitled or unreachable)")) + return managed + direct = _direct_openai_credentials(openai_cfg.get("api_key", ""), openai_cfg.get("base_url", "")) + if direct is not None: + return direct + if selected is not None: + raise ValueError(selection_error( + "stt", selected, + "neither stt.openai.api_key in config nor VOICE_TOOLS_OPENAI_KEY/OPENAI_API_KEY is set")) + managed = _managed() + if managed is None: + message = "Neither stt.openai.api_key in config nor VOICE_TOOLS_OPENAI_KEY/OPENAI_API_KEY is set" + if managed_nous_tools_enabled(): + message += ". " + nous_tool_gateway_unavailable_message("managed OpenAI audio for transcription") + raise ValueError(message) + return managed + + +def _extract_transcript_text(transcription: Any) -> str: + """Normalize text / object / dict transcription responses to a plain string.""" + value = transcription if isinstance(transcription, str) else getattr(transcription, "text", None) + if not isinstance(value, str) and isinstance(transcription, dict): + value = transcription.get("text") + text = (value if isinstance(value, str) else str(transcription)).strip() + match = _ASR_TEXT_RE.match(text) + return match.group("text").strip() if match else text diff --git a/tools/transcription_command.py b/tools/transcription_command.py new file mode 100644 index 0000000000000000000000000000000000000000..422b8c3a13a66021f8c0a6e68e8408188056c101 --- /dev/null +++ b/tools/transcription_command.py @@ -0,0 +1,253 @@ +"""User-declared and plugin STT providers. + +``stt.providers.<name>: type: command`` registry, plugin-registered +``TranscriptionProvider`` dispatch, and the ``pre_transcription`` hook that +threads prompt/language/model overrides into every backend. ``_resolve_stt_language`` +is read lazily from ``tools.transcription_tools``. +""" + +from __future__ import annotations + +import logging +import subprocess +import tempfile +from functools import partial +from pathlib import Path +from typing import Any, Dict, Optional + +from agent.model_metadata import CHARS_PER_TOKEN +from tools.tts_command_provider import ( + _command_output_format, _command_timeout, _is_command_provider_config as _is_command_stt_provider_config, + _named_provider_config, _resolve_command_config, command_env_passthrough as _command_stt_env_passthrough, + command_failure_detail, render_command_template as _render_command_stt_template, + run_command_provider as _run_command_stt) +from tools.transcription_common import ( + BUILTIN_STT_PROVIDERS, _error_result, _log_prompt_unsupported, _ok_result) + +# Log-record parity with the origin module. +logger = logging.getLogger("tools.transcription_tools") + + +# ---- Command-provider registry (``stt.providers.<name>: type: command``) --- +# +# Mirrors the TTS command-provider registry (same placeholder grammar, quote-aware +# rendering, process-tree termination on timeout). Resolution order: built-in name +# (always wins) > stt.providers.<name> command > plugin TranscriptionProvider > +# "No STT provider available". The single-env-var HERMES_LOCAL_STT_COMMAND escape +# hatch stays untouched via the built-in ``local_command`` path. +# Lets any whisper CLI / ASR CLI / curl pipeline become an STT backend with zero Python. 1. Built-in +# (``local``, ``local_command``, ``groq``, ``openai``, ``mistral``, ``xai``) → native handler. +# **Always wins.** 2. 3. 4. Use the command-provider registry when you want MULTIPLE shell-driven STT +# engines, or you want a named provider you can pick via ``stt.provider`` in config.yaml. See #17843. +DEFAULT_COMMAND_STT_TIMEOUT_SECONDS = 300 +DEFAULT_COMMAND_STT_LANGUAGE = "en" +DEFAULT_COMMAND_STT_OUTPUT_FORMAT = "txt" +COMMAND_STT_OUTPUT_FORMATS = frozenset({"txt", "json", "srt", "vtt"}) +_NON_COMMAND_STT_NAMES = frozenset(BUILTIN_STT_PROVIDERS | {"none"}) + + +# ``stt.providers.<name>`` (canonical), else ``stt.<name>`` for non-built-in names only. +_get_named_stt_provider_config = partial(_named_provider_config, builtins=BUILTIN_STT_PROVIDERS) +# The provider config if it is a command type; None for built-ins, ``none``, unknown. +_resolve_command_stt_provider_config = partial(_resolve_command_config, + reserved=_NON_COMMAND_STT_NAMES) +_get_command_stt_timeout = partial(_command_timeout, default=DEFAULT_COMMAND_STT_TIMEOUT_SECONDS) +_get_command_stt_output_format = partial(_command_output_format, formats=COMMAND_STT_OUTPUT_FORMATS, + default=DEFAULT_COMMAND_STT_OUTPUT_FORMAT) + + +def _read_command_stt_output(output_path: Path, stdout: str, fmt: str) -> str: + """Transcript: non-empty output file > non-empty stdout (curl one-liners) > RuntimeError. JSON is returned raw.""" + content = (output_path.read_bytes().decode("utf-8", errors="replace").strip() + if output_path.exists() else "") + if content or (stdout or "").strip(): + return content or stdout.strip() + raise RuntimeError(f"Command STT provider wrote no output file at {output_path} and produced no stdout") + + +def _transcribe_command_stt( + file_path: str, provider_name: str, config: Dict[str, Any], stt_config: Dict[str, Any], + model_override: Optional[str] = None, language_override: Optional[str] = None, + prompt: Optional[str] = None) -> Dict[str, Any]: + """Transcribe via a user-declared ``stt.providers.<name>: type: command``. Placeholders + (shell-quote-aware; ``{{``/``}}`` stay literal): ``{input_path}``, ``{output_path}`` (transcript + file), ``{output_dir}``, ``{format}`` txt/json/srt/vtt, ``{language}`` (default ``en``), + ``{model}`` (empty when unset).""" + from tools.transcription_tools import _resolve_stt_language + if prompt: + _log_prompt_unsupported(f"Command STT provider '{provider_name}'") + + def fail(error: str) -> Dict[str, Any]: + return _error_result(error, provider=provider_name) + command_template = str(config.get("command") or "").strip() + if not command_template: + return fail(f"stt.providers.{provider_name}.command is not configured") + audio = Path(file_path).expanduser() + if not audio.exists(): + return fail(f"Audio file not found: {file_path}") + timeout = _get_command_stt_timeout(config) + output_format = _get_command_stt_output_format(config) + language = (language_override or config.get("language") + or _resolve_stt_language(provider_name, stt_config) or DEFAULT_COMMAND_STT_LANGUAGE) + try: + with tempfile.TemporaryDirectory(prefix=f"hermes-cmd-stt-{provider_name}-") as tmpdir: + output_path = Path(tmpdir) / f"transcript.{output_format}" + command = _render_command_stt_template(command_template, { + "input_path": str(audio.resolve()), "output_path": str(output_path), + "output_dir": str(output_path.parent), "format": output_format, + "language": str(language), "model": str(model_override or config.get("model") or ""), + }) + logger.info("Transcribing %s via command STT provider '%s'...", audio.name, provider_name) + result = _run_command_stt(command, timeout, env_passthrough=_command_stt_env_passthrough(config)) + transcript_text = _read_command_stt_output(output_path, result.stdout or "", output_format) + except subprocess.TimeoutExpired: + return fail(f"STT command provider '{provider_name}' timed out after {timeout:g}s") + except subprocess.CalledProcessError as exc: + return fail( + f"STT command provider '{provider_name}' exited with code {exc.returncode}: {command_failure_detail(exc)}" + ) + except RuntimeError as exc: + return fail(str(exc)) + except OSError as exc: + return fail(f"STT command provider '{provider_name}' failed: {exc}") + logger.info("Transcribed %s via command STT provider '%s' (%d chars)", audio.name, provider_name, len(transcript_text)) + return _ok_result(transcript_text, provider_name) + + +def _unregistered_stt_provider_error(provider: str) -> Dict[str, Any]: + key = str(provider or "").strip() + return _error_result( + f"stt.provider='{key}' is set but no built-in, command, or plugin " + "provider registered that name. Run `hermes plugins list` to see " + "installed STT plugins, or configure a command provider under " + f"`stt.providers.{key}.command`.", + provider=key, + error_type="provider_not_registered") + + +# --------------------------------------------------------------------------- Plugin provider dispatch +# (issue follow-up to #30398 — STT pluggability) +# --------------------------------------------------------------------------- +def _dispatch_to_plugin_provider( + file_path: str, provider: str, stt_config: Optional[Dict[str, Any]] = None, *, + model: Optional[str] = None, language: Optional[str] = None, prompt: Optional[str] = None, +) -> Optional[Dict[str, Any]]: + """Route to a plugin-registered transcription provider; None when no plugin claims the name. + Invariants re-verified here so a caller refactor can't break them: built-in names never reach + the registry; a same-name command provider wins over a plugin. A matched plugin with + ``is_available() == False`` returns an error envelope — not None — because the user + explicitly opted in via ``stt.provider``. Provider exceptions become the error envelope.""" + key = (provider or "").lower().strip() + if not key or key in _NON_COMMAND_STT_NAMES: + return None + if stt_config is not None and _is_command_stt_provider_config(_get_named_stt_provider_config(stt_config, key)): + return None + try: + from agent.transcription_registry import get_provider + from hermes_cli.plugins import _ensure_plugins_discovered + _ensure_plugins_discovered() + plugin_provider = get_provider(key) + if plugin_provider is None: + # Long-lived sessions may have discovered plugins before a backend + # was patched in or config changed — retry once with a forced refresh. + _ensure_plugins_discovered(force=True) + plugin_provider = get_provider(key) + except Exception as exc: # noqa: BLE001 — discovery failure is non-fatal + logger.debug("STT plugin dispatch skipped (discovery failed): %s", exc) + return None + if plugin_provider is None: + return None + # ``is_available()`` MUST NOT raise per the ABC contract; defend anyway so + # a buggy plugin can't break dispatch for everyone. + try: + available = plugin_provider.is_available() + except Exception as exc: # noqa: BLE001 + logger.warning( + "STT plugin provider '%s' is_available() raised: %s — treating as unavailable", key, exc, exc_info=True, + ) + available = False + if not available: + logger.info("STT plugin provider '%s' reports not available; returning unavailability envelope.", key) + return _error_result( + f"STT plugin '{key}' is not available — check that its required credentials / dependencies are configured.", + provider=key) + logger.info("Transcribing with plugin STT provider '%s'...", key) + # The prompt travels via the ABC's ``**extra`` kwargs and is only sent when + # set, so pre-prompt providers see byte-identical calls on the no-prompt path. + extra_kwargs: Dict[str, Any] = {} if prompt is None else {"prompt": prompt} + try: + result = plugin_provider.transcribe(file_path, model=model, language=language, **extra_kwargs) + except Exception as exc: # noqa: BLE001 + logger.warning("STT plugin provider '%s' raised: %s", key, exc, exc_info=True) + return _error_result(f"STT plugin '{key}' raised: {exc}", provider=key) + if not isinstance(result, dict): + return _error_result(f"STT plugin '{key}' returned a non-dict result", provider=key) + result.setdefault("provider", key) + return result + + +# Fields a pre_transcription hook may mutate; ``file_path`` is read-only (logged and dropped). +# --------------------------------------------------------------------------- pre_transcription plugin hook +# (issue #64168 — STT prompt/vocab threading) +# --------------------------------------------------------------------------- +_PRE_TRANSCRIPTION_MUTABLE_FIELDS = ("prompt", "language", "model") + +# Whisper-family models only use the final ~224 tokens of the prompt; longer values +# waste upload bytes and can trip stricter OpenAI-compatible servers. Enforced +# client-side (truncate with a warning, never error), ~4 chars/token. +_WHISPER_PROMPT_TOKEN_CAP = 224 +_PROMPT_CHARS_PER_TOKEN = CHARS_PER_TOKEN +_WHISPER_PROMPT_CAPPED_PROVIDERS = frozenset({"local", "openai", "groq", "deepinfra"}) + + +def _enforce_prompt_length_limit(prompt: Optional[str], provider: str) -> Optional[str]: + """Truncate *prompt* to the whisper-family token cap, keeping the TAIL (whisper conditions + on the final context window, so the newest hints survive). Other providers self-validate.""" + max_chars = _WHISPER_PROMPT_TOKEN_CAP * _PROMPT_CHARS_PER_TOKEN + if not prompt or provider not in _WHISPER_PROMPT_CAPPED_PROVIDERS or len(prompt) <= max_chars: + return prompt + logger.warning( + "Transcription prompt is ~%d tokens; whisper-family provider '%s' " + "only uses the final ~%d — truncating to the last %d characters.", + len(prompt) // _PROMPT_CHARS_PER_TOKEN, provider, _WHISPER_PROMPT_TOKEN_CAP, max_chars) + return prompt[-max_chars:] + + +def _apply_pre_transcription_hook( + *, file_path: str, provider: str, model: Optional[str], language: Optional[str], + prompt: Optional[str], source: Optional[str], +) -> tuple[Optional[str], Optional[str], Optional[str]]: + """Fire the ``pre_transcription`` plugin hook; returns ``(model, language_override, prompt)``. + Gated on ``has_hook`` (the no-hook path never builds kwargs) and fail-open: any plumbing error + leaves the dispatch untouched. Results apply field-by-field in registration order (last hook + wins). ``language_override`` is None unless a hook explicitly set ``language``, so backends keep + their own config/env resolution.""" + try: + from hermes_cli.plugins import has_hook, invoke_hook + if not has_hook("pre_transcription"): + return model, None, prompt + hook_results = invoke_hook( + "pre_transcription", file_path=file_path, provider=provider, + model=model, language=language, prompt=prompt, source=source) + overrides: Dict[str, Any] = {} + for hook_result in hook_results: + for key, value in (hook_result.items() if isinstance(hook_result, dict) else ()): + if key == "file_path": + logger.warning( + "pre_transcription hook attempted to change " + "file_path (read-only) — ignoring the attempt.") + elif key not in _PRE_TRANSCRIPTION_MUTABLE_FIELDS: + logger.debug("pre_transcription hook returned unsupported field %r — ignoring.", key) + elif not isinstance(value, str): + logger.debug( + "pre_transcription hook returned non-string value %r for field %r — ignoring.", value, key, + ) + else: + overrides[key] = value + # Hooks win over the static ``stt.prompt`` config; "" clears it. + if "prompt" in overrides: + prompt = overrides["prompt"] or None + return overrides.get("model", model), overrides.get("language") or None, prompt + except Exception as _hook_err: # noqa: BLE001 — hook plumbing is fail-open + logger.debug("pre_transcription hook error: %s", _hook_err) + return model, None, prompt diff --git a/tools/transcription_tools.py b/tools/transcription_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..ff6df1b39a8efbf4b63ac071cd08ab3d838b1983 --- /dev/null +++ b/tools/transcription_tools.py @@ -0,0 +1,589 @@ +#!/usr/bin/env python3 +"""Speech-to-text transcription used by the gateway for voice messages. + +Built-in providers: local (faster-whisper, default/free), local_command, groq, openai +(also serves the managed ``nous`` selection), mistral, xai, elevenlabs, deepinfra; plus +user-declared command providers and plugin providers. ``transcribe_audio(path)`` returns +``{"success", "transcript", "error"?, "provider"?}``. This module owns provider resolution, +the dispatcher and the cached local model + idle-unload state; backends live in +``transcription_{common,audio,local,cloud,command}``. +""" + +import logging +import os +import shutil +import threading +import time +import importlib.util as _ilu +from pathlib import Path +from typing import Optional, Dict, Any + +from utils import is_truthy_value +from tools.transcription_common import ( + BUILTIN_STT_PROVIDERS, CLOUD_STT_PROVIDERS, DEFAULT_ELEVENLABS_STT_MODEL, + DEFAULT_GROQ_STT_MODEL, DEFAULT_LOCAL_MODEL, DEFAULT_MISTRAL_STT_MODEL, DEFAULT_PROVIDER, + DEFAULT_STT_MODEL, LOCAL_STT_COMMAND_ENV, LOCAL_STT_LANGUAGE_ENV, _error_result, + _get_stt_section, _ok_result) +from tools.transcription_audio import ( + _convert_caf_to_wav, _prepare_audio_for_transcription, _trim_silence_for_cloud_stt, + _validate_audio_file, _validate_audio_file_size, _validate_audio_source_file) +from tools.transcription_local import ( + _get_idle_unload_seconds, _has_local_command, _join_confident_segments, + _load_local_whisper_model, _looks_like_cuda_lib_error, _normalize_local_model, + _transcribe_local_command, _try_lazy_install_stt, build_local_transcribe_kwargs) +# The ``_transcribe_<provider>`` handlers are looked up in this module's globals by _dispatch_stt_provider. +from tools.transcription_cloud import ( # noqa: F401 (handlers dispatched via globals()) + _has_xai_stt_credentials, _resolve_openai_audio_client_config, _transcribe_deepinfra, + _transcribe_elevenlabs, _transcribe_groq, _transcribe_mistral, _transcribe_openai, + _transcribe_xai) +from tools.transcription_command import ( + _apply_pre_transcription_hook, _dispatch_to_plugin_provider, _enforce_prompt_length_limit, + _resolve_command_stt_provider_config, _transcribe_command_stt, _unregistered_stt_provider_error) + +logger = logging.getLogger(__name__) + + +def _resolve_provider_key(env_var: str, provider_id: str) -> str: + """STT API key via the shared voice-key resolver (config > env/.env > credential pool); resolved per call.""" + from tools.tool_backend_helpers import resolve_provider_secret + return resolve_provider_secret(env_var, provider_id) + + +def _safe_find_spec(module_name: str) -> bool: + try: + return _ilu.find_spec(module_name) is not None + except (ImportError, ValueError): + return module_name in globals() or module_name in os.sys.modules + + +_HAS_FASTER_WHISPER, _HAS_OPENAI, _HAS_MISTRAL, _HAS_PILK = map( + _safe_find_spec, ("faster_whisper", "openai", "mistralai", "pilk")) + +# Local model singleton; the lock guards check-then-load against concurrent voice messages. +_local_model: Optional[object] = None +_local_model_name: Optional[str] = None +# See #24767. +_local_model_lock = threading.Lock() + +# Idle unload: one daemon thread releases the model (hundreds of MB of RAM/VRAM) after a +# configurable idle period, then exits; the next voice message reloads and restarts it. +# _idle_unload_mgmt_lock serializes the start check so no duplicate watchers spawn. +_last_transcription_time: float = 0.0 +_idle_unload_thread: Optional[threading.Thread] = None +_idle_unload_stop = threading.Event() +_idle_unload_mgmt_lock = threading.Lock() +_IDLE_UNLOAD_CHECK_INTERVAL = 30 # seconds between idle checks + + +# ---- Config helpers ----------------------------------------------------- +def _load_stt_config() -> dict: + """Load the ``stt`` section from user config, falling back to defaults.""" + try: + from hermes_cli.config import load_config + return load_config().get("stt") or {} + except Exception: + return {} + + +def is_stt_enabled(stt_config: Optional[dict] = None) -> bool: + cfg = _load_stt_config() if stt_config is None else stt_config + return is_truthy_value(cfg.get("enabled", True), default=True) + + +def _resolve_stt_language( + provider_key: str, stt_config: Optional[Dict[str, Any]] = None, *, extra_keys: tuple = () +) -> Optional[str]: + """Language hint for an STT provider, first non-empty wins (never ""): ``stt.<provider>.language`` + (plus *extra_keys* aliases, e.g. ``language_code``) > ``stt.language`` > ``HERMES_LOCAL_STT_LANGUAGE`` + env > None (provider auto-detects).""" + if stt_config is None: + stt_config = _load_stt_config() + provider_cfg = _get_stt_section(stt_config, provider_key) + candidates = [provider_cfg.get(key) for key in ("language", *extra_keys)] + if isinstance(stt_config, dict): + candidates.append(stt_config.get("language")) + candidates.append(os.getenv(LOCAL_STT_LANGUAGE_ENV)) + return next((c.strip() for c in candidates if isinstance(c, str) and c.strip()), None) + + +def _openai_audio_unavailable_reason() -> Optional[str]: + """None when OpenAI audio has usable credentials (config, env, or managed gateway); else the reason.""" + try: + # Resolve directly instead of via the boolean probe: the probe flattens + # _resolve_openai_audio_client_config's selection-specific ValueError into False, so a managed + # openai-audio gateway outage would be logged as a generic "no API key" hint (#93045). + _resolve_openai_audio_client_config() + return None + except ValueError as exc: + return str(exc) + + +def _has_openai_audio_backend() -> bool: + return _openai_audio_unavailable_reason() is None + + +def _is_local_stt_provider(provider: str, stt_config: Dict[str, Any]) -> bool: + """Whether *provider* is exempt from Hermes's remote upload cap.""" + return (provider or "").lower().strip() in {"local", "local_command"} + + +# ---- Provider resolution ------------------------------------------------ +def _has_key(env_var: str, provider: str, *, needs_openai: bool = False, needs_mistral: bool = False): + """Availability probe factory: optional SDK flag AND a resolvable API key.""" + def probe() -> bool: + sdk_ok = (not needs_openai or _HAS_OPENAI) and (not needs_mistral or _HAS_MISTRAL) + return sdk_ok and bool(_resolve_provider_key(env_var, provider)) + return probe + + +def _has_xai_stt_credentials_quietly() -> bool: + try: + return _has_xai_stt_credentials() + except Exception: + return False + + +def _resolve_explicit_openai() -> str: + if not _HAS_OPENAI: + logger.warning("STT provider 'openai' configured but no API key available") + return "none" + # Resolved directly so a managed openai-audio gateway outage is logged with its real reason. + reason = _openai_audio_unavailable_reason() + if reason is None: + return "openai" + logger.warning("STT provider 'openai' configured but unavailable: %s", reason) + return "none" + + +def _detect_local_backend() -> Optional[str]: + """faster-whisper > local whisper CLI > lazy-installed faster-whisper; None when nothing local works.""" + if _HAS_FASTER_WHISPER: + return "local" + return "local_command" if _has_local_command() else ("local" if _try_lazy_install_stt() else None) + + +def _resolve_explicit_local() -> str: + backend = _detect_local_backend() + if not backend: + logger.warning("STT provider 'local' configured but unavailable " + "(install faster-whisper or set HERMES_LOCAL_STT_COMMAND)") + return backend or "none" + + +def _resolve_explicit_local_command() -> str: + if _has_local_command(): + return "local_command" + if _HAS_FASTER_WHISPER: + logger.info("Local STT command unavailable, using local faster-whisper") + return "local" + logger.warning("STT provider 'local_command' configured but unavailable") + return "none" + + +_has_groq_key = _has_key("GROQ_API_KEY", "groq", needs_openai=True) +_has_mistral_key = _has_key("MISTRAL_API_KEY", "mistral", needs_mistral=True) +_has_elevenlabs_key = _has_key("ELEVENLABS_API_KEY", "elevenlabs") +_has_deepinfra_key = _has_key("DEEPINFRA_API_KEY", "deepinfra", needs_openai=True) + +# Cloud providers in AUTO-DETECT priority order: +# name -> (explicit-selection probe, auto-detect probe, explicit warning, auto-detect log) +# The probes differ only for openai (explicit has its own resolver in _EXPLICIT_RESOLVERS; +# auto-detect also requires the SDK) and xai (auto-detect must never raise). DeepInfra is +# LAST so a DEEPINFRA_API_KEY set for chat never displaces an xAI/ElevenLabs auto-selection. +# Mistral only auto-selects when the SDK is present — no lazy-install during passive +# auto-detection (explicit ``provider: mistral`` installs on first use). +_CLOUD_PROVIDER_SPECS = { + "groq": (_has_groq_key, _has_groq_key, + "STT provider 'groq' configured but GROQ_API_KEY not set", + "No local STT available, using Groq Whisper API"), + "openai": (None, lambda: _HAS_OPENAI and _has_openai_audio_backend(), + None, + "No local STT available, using OpenAI Whisper API"), + "mistral": (_has_mistral_key, _has_mistral_key, + "STT provider 'mistral' configured but mistralai package not installed or MISTRAL_API_KEY not set", + "No local STT available, using Mistral Voxtral Transcribe API"), + "xai": (_has_xai_stt_credentials, _has_xai_stt_credentials_quietly, + "STT provider 'xai' configured but no xAI credentials are available", + "No local STT available, using xAI Grok STT API"), + "elevenlabs": (_has_elevenlabs_key, _has_elevenlabs_key, + "STT provider 'elevenlabs' configured but ELEVENLABS_API_KEY not set", + "No local STT available, using ElevenLabs Scribe STT API"), + "deepinfra": (_has_deepinfra_key, _has_deepinfra_key, + "STT provider 'deepinfra' configured but DEEPINFRA_API_KEY not set (or openai package missing)", + "No local STT available, using DeepInfra Whisper API")} + +# Explicit selections whose resolution is more than a probe + warning. +_EXPLICIT_RESOLVERS = { + "local": _resolve_explicit_local, + "local_command": _resolve_explicit_local_command, + "openai": _resolve_explicit_openai} + + +def _resolve_explicit_provider(provider: str) -> str: + """Explicit ``stt.provider`` -> usable name or ``"none"``; unknown names pass through untouched + so the dispatcher fails with the provider-not-registered message.""" + resolver = _EXPLICIT_RESOLVERS.get(provider) + if resolver is not None: + return resolver() + spec = _CLOUD_PROVIDER_SPECS.get(provider) + if spec is None or spec[0](): + return provider + logger.warning(spec[2]) + return "none" + + +def _get_provider(stt_config: dict) -> str: + """Which STT provider to use: an explicit ``stt.provider`` is honoured (no silent cloud + fallback); otherwise auto-detect local > groq > openai > mistral > xai > elevenlabs > deepinfra.""" + if not is_stt_enabled(stt_config): + return "none" + explicit = "provider" in stt_config + provider = stt_config.get("provider", DEFAULT_PROVIDER) + # The managed "Nous Subscription" selection is the OpenAI backend routed via the managed gateway. + if isinstance(provider, str) and provider.strip().lower() == "nous": + provider = "openai" + if explicit and provider == "local": + # Legacy DEFAULT_CONFIG seeded ``stt.provider: local`` on every install, so only a + # raw config.yaml selection counts as explicit; otherwise autodetect (local-first anyway). + try: + from tools.tool_backend_helpers import read_selection + if read_selection("stt") is None: + explicit = False + except Exception: # pragma: no cover — helpers are in-repo + pass + if explicit: + return _resolve_explicit_provider(provider) + backend = _detect_local_backend() + if backend: + return backend + for name, (_probe, available, _warning, message) in _CLOUD_PROVIDER_SPECS.items(): + if available(): + logger.info(message) + return name + return "none" + + +# ---- Provider: local (faster-whisper) ----------------------------------- +def _unload_local_model() -> None: + """Release the cached local whisper model. Thread-safe via the model lock.""" + global _local_model, _local_model_name + with _local_model_lock: + if _local_model is not None: + logger.info("Unloading local whisper model '%s' after idle timeout", _local_model_name or "unknown") + _local_model = None + _local_model_name = None + + +def _start_idle_unload_watcher(timeout_seconds: int) -> None: + """Ensure the single idle-unload watcher thread is running. The loop re-reads + ``stt.local.unload_after_idle_seconds`` every cycle so config edits apply within one interval; + ``timeout_seconds`` seeds the first cycle so a just-written config is honored even if a + concurrent read races. Exits after unloading, when the timeout becomes 0, or when the model is gone.""" + global _idle_unload_thread + with _idle_unload_mgmt_lock: + if _idle_unload_thread is not None and _idle_unload_thread.is_alive(): + return + + def _watch(initial_timeout=timeout_seconds): + while not _idle_unload_stop.wait(_IDLE_UNLOAD_CHECK_INTERVAL) and _local_model is not None: + try: + timeout = _get_idle_unload_seconds(_load_stt_config().get("local") or {}) + except Exception: # noqa: BLE001 - keep the seed value + timeout = initial_timeout + if timeout <= 0: + break # unload disabled mid-flight — stand down + if time.monotonic() - _last_transcription_time >= timeout: + _unload_local_model() + break + _idle_unload_stop.clear() + _idle_unload_thread = threading.Thread(target=_watch, name="hermes-stt-idle-unload", daemon=True) + _idle_unload_thread.start() + + +def _touch_transcription_time() -> None: + """Record transcription activity (resets the idle timer).""" + global _last_transcription_time + _last_transcription_time = time.monotonic() + + +def _get_or_load_local_model(model_name: str, local_cfg: Dict[str, Any]): + """Cached faster-whisper model, (re)loaded under a double-checked lock when needed. The returned + strong reference stays valid even if the idle watcher nulls the global mid-transcription.""" + global _local_model, _local_model_name + model = _local_model + # Lazy-load the model (downloads on first use, ~150 MB for 'base'). Double-checked lock: concurrent + # voice messages must not both download/load the model (#24767). ``model`` is a strong local reference + # bound under the lock: the idle watcher may null the module global at any time, but this transcription + # keeps using the instance it grabbed. + if model is None or _local_model_name != model_name: + with _local_model_lock: + if _local_model is None or _local_model_name != model_name: + logger.info("Loading faster-whisper model '%s' (first load downloads the model)...", model_name) + # stt.local.device / compute_type pin a configuration where ``auto`` mis-detects. + _local_model = _load_local_whisper_model(model_name, device=local_cfg.get("device", "auto"), + compute_type=local_cfg.get("compute_type", "auto")) + _local_model_name = model_name + model = _local_model + return model + + +def _replace_cached_model_on_cpu(model_name: str): + """Load *model_name* on CPU/int8 and make it the cached singleton.""" + global _local_model, _local_model_name + from faster_whisper import WhisperModel + model = WhisperModel(model_name, device="cpu", compute_type="int8") + with _local_model_lock: + _local_model, _local_model_name = model, model_name + return model + + +def _transcribe_local( + file_path: str, model_name: str, *, language: Optional[str] = None, prompt: Optional[str] = None +) -> Dict[str, Any]: + """Transcribe using faster-whisper (local, free).""" + if not _HAS_FASTER_WHISPER and not _try_lazy_install_stt(): + return _error_result("faster-whisper not installed") + try: + stt_config = _load_stt_config() + local_cfg = stt_config.get("local") or {} + # Reset the idle timer BEFORE loading so a long in-flight transcription isn't counted as idle. + _touch_transcription_time() + model = _get_or_load_local_model(model_name, local_cfg) + if model is None: # defensive: load failed without raising + return _error_result("Local whisper model failed to load") + # pre_transcription hook overrides win over config-resolved values. + transcribe_kwargs = build_local_transcribe_kwargs(stt_config) + transcribe_kwargs.update({k: v for k, v in (("language", language), ("initial_prompt", prompt)) + if v}) + try: + segments, info = model.transcribe(file_path, **transcribe_kwargs) + except Exception as exc: + # CUDA libs can fail at dlopen-on-first-use, AFTER loading: evict the poisoned + # cached model, reload on CPU and retry once, else every later message fails. + if not _looks_like_cuda_lib_error(exc): + raise + logger.warning("faster-whisper CUDA runtime failed mid-transcribe (%s) — " + "evicting cached model and retrying on CPU (int8).", exc) + model = _replace_cached_model_on_cpu(model_name) + segments, info = model.transcribe(file_path, **transcribe_kwargs) + transcript = _join_confident_segments(segments, local_cfg) + logger.info("Transcribed %s via local whisper (%s, lang=%s, %.1fs audio)", + Path(file_path).name, model_name, info.language, info.duration) + _touch_transcription_time() + idle_timeout = _get_idle_unload_seconds(local_cfg) + if idle_timeout > 0: + _start_idle_unload_watcher(idle_timeout) + return _ok_result(transcript, "local") + except Exception as e: + logger.error("Local transcription failed: %s", e, exc_info=True) + return _error_result(f"Local transcription failed: {e}") + + +# ---- Public API --------------------------------------------------------- +def _read_block_error(file_path: str) -> Optional[Dict[str, Any]]: + """Refuse to ship a credential store (auth.json, .env, OAuth tokens) to an STT provider. + Mirrors the image-gen / video-gen read guards.""" + from agent.file_safety import get_read_block_error + blocked = get_read_block_error(file_path) + return _error_result(blocked) if blocked else None + + +def _transcribe_prepared_audio( + file_path: str, model: Optional[str] = None, source: Optional[str] = None) -> Dict[str, Any]: + """Transcribe a validated audio file with the configured STT provider. ``model`` overrides the + config default; ``source`` is a caller-surface label (``"gateway"``, ``"voice_mode"``) forwarded + to the ``pre_transcription`` hook only.""" + # Validate before provider resolution so invalid files can't trigger provider setup + # or lazy installation; the remote-upload size cap applies to non-local only. + error = _read_block_error(file_path) or _validate_audio_file(file_path, enforce_size_limit=False) + if error: + return error + stt_config = _load_stt_config() + if not is_stt_enabled(stt_config): + return _error_result("STT is disabled in config.yaml (stt.enabled: false).") + provider = _get_provider(stt_config) + if not _is_local_stt_provider(provider, stt_config): + error = _validate_audio_file_size(Path(file_path)) + if error: + return error + # Convert CAF (iMessage voice notes) to WAV for cloud STT providers. + if Path(file_path).suffix.lower() == ".caf": + file_path = _convert_caf_to_wav(file_path) + if not file_path: + return _error_result("CAF audio could not be converted to WAV.") + # Best-effort pre-upload silence trim for built-in cloud providers. + trim_cleanup_dir: Optional[str] = None + if provider in CLOUD_STT_PROVIDERS: + trimmed = _trim_silence_for_cloud_stt(file_path, stt_config) + if trimmed: + file_path = trimmed + trim_cleanup_dir = os.path.dirname(trimmed) + try: + return _dispatch_stt_provider(file_path, provider, stt_config, model, source) + finally: + if trim_cleanup_dir: + shutil.rmtree(trim_cleanup_dir, ignore_errors=True) + + +# Built-in provider -> (stt section, config key, default, treat-empty-as-missing). "local_command" +# shares ``stt.local``; xAI takes no model (logging-only); deepinfra uses the live catalog when empty. +_BUILTIN_MODEL_KEYS = { + "local": ("local", "model", DEFAULT_LOCAL_MODEL, False), + "local_command": ("local", "model", DEFAULT_LOCAL_MODEL, False), + "groq": ("groq", "model", DEFAULT_GROQ_STT_MODEL, True), + "openai": ("openai", "model", DEFAULT_STT_MODEL, False), + "mistral": ("mistral", "model", DEFAULT_MISTRAL_STT_MODEL, False), + "elevenlabs": ("elevenlabs", "model_id", DEFAULT_ELEVENLABS_STT_MODEL, False), + "deepinfra": ("deepinfra", "model", "", True)} + + +def _builtin_model_name(provider: str, stt_config: Dict[str, Any], model: Optional[str]) -> str: + """Resolve the model for a built-in provider: caller override > ``stt.<provider>`` config > default.""" + if model: + return model + if provider == "xai": + return "grok-stt" + section, key, default, empty_is_missing = _BUILTIN_MODEL_KEYS[provider] + cfg = _get_stt_section(stt_config, section) + return (cfg.get(key) or default) if empty_is_missing else cfg.get(key, default) + + +def _dispatch_stt_provider( + file_path: str, provider: str, stt_config: Dict[str, Any], model: Optional[str] = None, + source: Optional[str] = None) -> Dict[str, Any]: + """Route *file_path* to the handler for *provider* (built-in > command > plugin).""" + # Static ``stt.prompt`` is the base; hook results mutate on top (last hook to set a field wins). + prompt = stt_config.get("prompt") + prompt = prompt if isinstance(prompt, str) and prompt.strip() else None + # Fires after provider resolution and BEFORE any backend; ``language`` stays None unless a hook sets it. + model, language, prompt = _apply_pre_transcription_hook( + file_path=file_path, provider=provider, model=model, + language=_get_stt_section(stt_config, provider).get("language"), prompt=prompt, source=source, + ) + prompt = _enforce_prompt_length_limit(prompt, provider) + if provider in BUILTIN_STT_PROVIDERS: + # Looked up in this module at call time so tests may patch ``_transcribe_*``. + handler = globals()[f"_transcribe_{provider}"] + model_name = _builtin_model_name(provider, stt_config, model) + if provider in ("local", "local_command"): + model_name = _normalize_local_model(model_name) + return handler(file_path, model_name, language=language, prompt=prompt) + # Command providers: after built-ins (``stt.providers.openai.command`` can't override the + # real handler) and BEFORE plugins, since config is more local than a plugin install. + # User-declared command-type provider (``stt.providers.<name>: type: command``). See #17843. + command_provider_config = _resolve_command_stt_provider_config(provider, stt_config) + if command_provider_config is not None: + return _transcribe_command_stt(file_path, provider, command_provider_config, stt_config, + model_override=model, language_override=language, prompt=prompt) + # Plugin backend: reads ``stt.<provider>`` like built-ins; the ``model`` argument overrides it. + plugin_result = _dispatch_to_plugin_provider( + file_path, provider, stt_config, model=model or _get_stt_section(stt_config, provider).get("model"), + language=language or _resolve_stt_language(provider, stt_config), prompt=prompt) + return plugin_result if plugin_result is not None else _no_provider_error(provider, stt_config) + + +def _no_provider_error(provider: str, stt_config: Dict[str, Any]) -> Dict[str, Any]: + """Error envelope when nothing claimed *provider*: unregistered name > openai selection reason > generic hint.""" + provider_key = str(provider or "").strip().lower() + if "provider" in stt_config and provider_key and provider_key not in BUILTIN_STT_PROVIDERS and provider_key != "none": + return _unregistered_stt_provider_error(provider_key) + # An explicit openai selection flattened to "none" has a specific reason (e.g. managed gateway down). + # Surface it — with its `hermes tools` remediation — instead of the all-provider setup hint (#93045). + if provider_key == "none" and str(stt_config.get("provider") or "") == "openai" and _HAS_OPENAI: + reason = _openai_audio_unavailable_reason() + if reason is not None: + return _error_result(reason) + return _error_result( + "No STT provider available. Install faster-whisper for free local " + f"transcription, configure {LOCAL_STT_COMMAND_ENV} or install a local whisper CLI, " + "set GROQ_API_KEY for free Groq Whisper, set MISTRAL_API_KEY for Mistral " + "Voxtral Transcribe, configure xAI OAuth or set XAI_API_KEY for xAI Grok STT, " + "set ELEVENLABS_API_KEY for ElevenLabs Scribe, or set VOICE_TOOLS_OPENAI_KEY " + "or OPENAI_API_KEY for the OpenAI Whisper API.") + + +def transcribe_audio( + file_path: str, model: Optional[str] = None, source: Optional[str] = None) -> Dict[str, Any]: + """Validate, preprocess supported inputs, and dispatch transcription. ``source`` is a caller-surface + label (``"gateway"``, ``"voice_mode"``) forwarded to the ``pre_transcription`` hook only.""" + # Secret-store refusal runs before ANY validation so the error names the real reason. + blocked = _read_block_error(file_path) + if blocked: + return blocked + # Cap .silk sources before the decoder runs; for other inputs the upload cap is + # provider-scoped in _transcribe_prepared_audio so local whisper can take big files. + is_silk = Path(file_path).suffix.lower() == ".silk" + source_error = _validate_audio_source_file(file_path, enforce_size_limit=is_silk) + if source_error: + return source_error + prepared_path, cleanup_dir, prep_error = _prepare_audio_for_transcription(file_path) + if prep_error or prepared_path is None: + return prep_error or _error_result("Audio preprocessing did not produce a file for transcription.") + try: + return (_validate_audio_file(prepared_path, enforce_size_limit=False) + or _transcribe_prepared_audio(prepared_path, model, source)) + finally: + if cleanup_dir: + shutil.rmtree(cleanup_dir, ignore_errors=True) + + +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 lazy-installs or falls through to cloud.""" + error = _validate_audio_file(file_path) + if error: + return error + local_model = model or (_load_stt_config().get("local") or {}).get("model", DEFAULT_LOCAL_MODEL) + if _HAS_FASTER_WHISPER: + return _transcribe_local(file_path, _normalize_local_model(local_model)) + if _has_local_command(): + return _transcribe_local_command(file_path, _normalize_local_model(local_model)) + return _error_result("No installed local STT backend is available.", provider="local") + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. +import platform # noqa: F401,E402 +import queue # noqa: F401,E402 +import re # noqa: F401,E402 +import shlex # noqa: F401,E402 +import subprocess # noqa: F401,E402 +import tempfile # noqa: F401,E402 +from urllib.parse import urljoin # noqa: F401,E402 + + +_PLUGIN_COMPAT_LAZY = { + 'COMMAND_STT_OUTPUT_FORMATS': ('tools.transcription_command', 'COMMAND_STT_OUTPUT_FORMATS'), + 'COMMON_LOCAL_BIN_DIRS': ('tools.transcription_common', 'COMMON_LOCAL_BIN_DIRS'), + 'DEFAULT_COMMAND_STT_LANGUAGE': ('tools.transcription_command', 'DEFAULT_COMMAND_STT_LANGUAGE'), + 'DEFAULT_COMMAND_STT_OUTPUT_FORMAT': ('tools.transcription_command', 'DEFAULT_COMMAND_STT_OUTPUT_FORMAT'), + 'DEFAULT_COMMAND_STT_TIMEOUT_SECONDS': ('tools.transcription_command', 'DEFAULT_COMMAND_STT_TIMEOUT_SECONDS'), + 'DEFAULT_LOCAL_STT_LANGUAGE': ('tools.transcription_common', 'DEFAULT_LOCAL_STT_LANGUAGE'), + 'ELEVENLABS_STT_BASE_URL': ('tools.transcription_common', 'ELEVENLABS_STT_BASE_URL'), + 'GROQ_BASE_URL': ('tools.transcription_common', 'GROQ_BASE_URL'), + 'GROQ_MODELS': ('tools.transcription_common', 'GROQ_MODELS'), + 'LOCAL_NATIVE_AUDIO_FORMATS': ('tools.transcription_common', 'LOCAL_NATIVE_AUDIO_FORMATS'), + 'MAX_FILE_SIZE': ('tools.transcription_common', 'MAX_FILE_SIZE'), + 'OPENAI_BASE_URL': ('tools.transcription_common', 'OPENAI_BASE_URL'), + 'OPENAI_MODELS': ('tools.transcription_common', 'OPENAI_MODELS'), + 'SUPPORTED_FORMATS': ('tools.transcription_common', 'SUPPORTED_FORMATS'), + 'XAI_STT_BASE_URL': ('tools.transcription_common', 'XAI_STT_BASE_URL'), + 'managed_nous_tools_enabled': ('tools.tool_backend_helpers', 'managed_nous_tools_enabled'), + 'nous_tool_gateway_unavailable_message': ('tools.tool_backend_helpers', 'nous_tool_gateway_unavailable_message'), + 'resolve_managed_tool_gateway': ('tools.managed_tool_gateway', 'resolve_managed_tool_gateway'), + 'resolve_openai_audio_api_key': ('tools.tool_backend_helpers', 'resolve_openai_audio_api_key'), + 'windows_hide_flags': ('hermes_cli._subprocess_compat', 'windows_hide_flags'), +} + + +def __getattr__(name): # PEP 562 — lazy so no import cycles + target = _PLUGIN_COMPAT_LAZY.get(name) + if target is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + import importlib + from hermes_cli.plugin_compat import warn_once + warn_once(__name__, name, *target) + return getattr(importlib.import_module(target[0]), target[1]) +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/tts_streaming.py b/tools/tts_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..e325d621232f867d47d8cb7ebac7d66963a0d340 --- /dev/null +++ b/tools/tts_streaming.py @@ -0,0 +1,343 @@ +"""Provider-agnostic streaming TTS: sentence text → int16 mono PCM chunk iterator. + +``stream_tts_to_speaker`` (``tools.tts_tool``) owns the sentence buffer, sounddevice +output and stop/queue protocol; this module owns the *provider* half so playback +starts on sentence one. True streamers (``StreamingTTSProvider.stream``) wrap chunked +APIs; providers with no chunked API (edge, the default) get per-sentence playback via +the sync ``text_to_speech_tool`` path. Adding a streamer is ``@register("name")`` on +a subclass; the dispatcher, config gate (``tts.<name>.streaming``) and resolver come free. +""" + +from __future__ import annotations + +import logging +import re +import time +from abc import ABC, abstractmethod +from typing import Callable, Dict, Iterator, List, Optional + +from tools.tool_backend_helpers import resolve_openai_audio_api_key +from tools.tts_tool import _get_provider, _load_tts_config + +logger = logging.getLogger(__name__) + +# Per-sentence PCM byte cap, mirroring the sync providers' 16 MiB bounded-body invariant. +_STREAM_SENTENCE_BYTE_CAP = 16 * 1024 * 1024 + + +def _resolve_key(env_var: str, provider_id: str) -> str: + """Provider secret lookup (config > env/.env > credential pool); seam over ``tts_tool._resolve_provider_key``. + ALL streaming-provider key lookups go through here — never bare ``get_env_value``.""" + try: + from tools.tts_tool import _resolve_provider_key + return _resolve_provider_key(env_var, provider_id) or "" + except Exception: + from hermes_cli.config import get_env_value + return get_env_value(env_var) or "" + + +def _gemini_key() -> str: + return _resolve_key("GEMINI_API_KEY", "gemini") or _resolve_key("GOOGLE_API_KEY", "gemini") + + +# Interruption latch: a barge-in on a spoken reply marks it; the next turn's submit path takes it +# and prepends SPEECH_INTERRUPTED_NOTE to the model-bound message (API-call local, never +# persisted). The TTL keeps a stale barge from annotating an unrelated message minutes later. +SPEECH_INTERRUPTED_NOTE = "[Note: the user interrupted your previous spoken reply before it finished.]" +_INTERRUPT_TTL_S = 120.0 +_interrupted_at: Optional[float] = None + + +def mark_speech_interrupted() -> None: + global _interrupted_at + _interrupted_at = time.monotonic() + + +def take_speech_interrupted() -> bool: + """Pop the latch; True when a barge happened within the TTL.""" + global _interrupted_at + at, _interrupted_at = _interrupted_at, None + return at is not None and time.monotonic() - at < _INTERRUPT_TTL_S + +# Sentence boundary: after .!? followed by whitespace, or a blank line. +SENTENCE_BOUNDARY_RE = re.compile(r"(?<=[.!?])(?:\s|\n)|(?:\n\n)") +_THINK_BLOCK_RE = re.compile(r"<think[\s>].*?</think>", flags=re.DOTALL) + + +class SentenceChunker: + """Incremental sentence cutter for LLM token deltas, shared by the speaker pipeline and the + speak-stream WebSocket so every surface cuts speech identically. Strips ``<think>`` blocks (even + split across deltas) and merges fragments shorter than *min_len* into the following sentence.""" + + def __init__(self, min_len: int = 20): + self.min_len = min_len + self.buf = "" + + def feed(self, delta: str) -> List[str]: + """Absorb *delta*; return every complete sentence now ready to speak.""" + self.buf = _THINK_BLOCK_RE.sub("", self.buf + delta) + if "<think" in self.buf and "</think>" not in self.buf: + return [] # open think tag — the closing tag may arrive next delta + out: List[str] = [] + start = 0 # skip boundaries that would leave the head too short + while m := SENTENCE_BOUNDARY_RE.search(self.buf, start): + head = self.buf[: m.end()] + if len(head.strip()) < self.min_len: + start = m.end() + continue + out.append(head) + self.buf = self.buf[m.end():] + start = 0 + return out + + def flush(self) -> List[str]: + """Drain the tail (end-of-text or long-idle flush).""" + tail, self.buf = _THINK_BLOCK_RE.sub("", self.buf).strip(), "" + return [tail] if tail else [] + + +class StreamingTTSProvider(ABC): + """Yields raw int16, little-endian, mono PCM chunks at ``sample_rate`` (built-ins: 24 kHz).""" + + sample_rate: int = 24000 + channels: int = 1 + sample_width: int = 2 # bytes/sample (int16) + + def __init__(self, tts_config: Dict, section: Dict): + self.tts_config = tts_config + self.section = section + + @staticmethod + @abstractmethod + def available() -> bool: + """True when this provider's credentials/SDK are usable right now.""" + + @abstractmethod + def stream(self, text: str) -> Iterator[bytes]: + """Yield PCM chunks for ``text``. Raise on failure (caller logs).""" + + +_REGISTRY: Dict[str, type[StreamingTTSProvider]] = {} + + +def register(name: str) -> Callable[[type[StreamingTTSProvider]], type[StreamingTTSProvider]]: + def _wrap(cls: type[StreamingTTSProvider]) -> type[StreamingTTSProvider]: + _REGISTRY[name] = cls + return cls + return _wrap + + +def _try_instantiate(name: str, tts_config: Dict) -> Optional[StreamingTTSProvider]: + """Construct the registered streamer *name* if it's usable, else None.""" + cls = _REGISTRY.get(name) + if cls is None or not cls.available(): + return None + try: + return cls(tts_config, tts_config.get(name) or {}) + except Exception as exc: # pragma: no cover - defensive + logger.debug("streaming provider %s init failed: %s", name, exc) + return None + + +# Fallback priority for ``tts.streaming.provider: auto`` — best chunked latency/quality +# first. Deliberately hard-coded (a UX decision); edge is absent (no chunked-PCM API). +_PROVIDER_PRIORITY: List[str] = ["elevenlabs", "gemini", "openai", "xai"] + + +def resolve_streaming_provider( + tts_config: Dict, preferred: Optional[str] = None) -> Optional[StreamingTTSProvider]: + """Return a ready streamer for the *configured* provider, else ``None``. + ``tts.streaming.provider`` when set: a name pins that exact streamer (``None`` if unusable); + ``auto`` returns the first usable in ``_PROVIDER_PRIORITY``. Otherwise the configured TTS + provider (or ``preferred``): ``None`` means "no chunked API" — the dispatcher speaks + per-sentence via the sync path, preserving the user's chosen voice. We never silently swap + providers just to get streaming.""" + pinned = str((tts_config.get("streaming") or {}).get("provider") or "").lower().strip() + if pinned == "auto": + return next((inst for name in _PROVIDER_PRIORITY + if (inst := _try_instantiate(name, tts_config))), None) + return _try_instantiate(pinned or (preferred or _get_provider(tts_config)).lower().strip(), tts_config) + + +def _capped(chunks: Iterator[bytes], label: str) -> Iterator[bytes]: + """Pass chunks through, aborting past the per-sentence byte cap (runaway/hostile upstream).""" + total = 0 + for chunk in chunks: + total += len(chunk) + if total > _STREAM_SENTENCE_BYTE_CAP: + logger.warning("%s exceeded %d bytes for one sentence; truncating", label, _STREAM_SENTENCE_BYTE_CAP) + return + yield chunk + + +@register("elevenlabs") +class ElevenLabsStreamer(StreamingTTSProvider): + """ElevenLabs chunked HTTP → pcm_24000 (the original reference path).""" + + @staticmethod + def available() -> bool: + return bool(_resolve_key("ELEVENLABS_API_KEY", "elevenlabs")) + + def stream(self, text: str) -> Iterator[bytes]: + from tools.tts_tool import _import_elevenlabs + from tools.tts_tool_providers import ( + DEFAULT_ELEVENLABS_STREAMING_MODEL_ID, DEFAULT_ELEVENLABS_VOICE_ID, _elevenlabs_environment_kwargs, + ) + client = _import_elevenlabs()( + api_key=_resolve_key("ELEVENLABS_API_KEY", "elevenlabs"), **_elevenlabs_environment_kwargs(self.section), + ) + yield from client.text_to_speech.convert( + text=text, voice_id=self.section.get("voice_id", DEFAULT_ELEVENLABS_VOICE_ID), + model_id=self.section.get("streaming_model_id", + self.section.get("model_id", DEFAULT_ELEVENLABS_STREAMING_MODEL_ID)), + output_format="pcm_24000") + + +def _openai_config_api_key() -> str: + """Return ``tts.openai.api_key`` from config.yaml, or empty string.""" + try: + return (_load_tts_config().get("openai") or {}).get("api_key") or "" + except Exception: + return "" + + +@register("openai") +class OpenAIStreamer(StreamingTTSProvider): + """OpenAI speech with ``response_format=pcm`` (24 kHz mono int16).""" + + @staticmethod + def available() -> bool: + return bool(_openai_config_api_key() or resolve_openai_audio_api_key()) + + def stream(self, text: str) -> Iterator[bytes]: + from openai import OpenAI + from hermes_cli.config import get_env_value + client = OpenAI( + api_key=(self.section.get("api_key") or resolve_openai_audio_api_key()), + base_url=(self.section.get("base_url") or get_env_value("OPENAI_BASE_URL") or None)) + with client.audio.speech.with_streaming_response.create( + model=self.section.get("model", "gpt-4o-mini-tts"), voice=self.section.get("voice", "alloy"), + input=text, response_format="pcm", + ) as response: + yield from _capped(response.iter_bytes(), "OpenAI streaming TTS") + + +@register("gemini") +class GeminiStreamer(StreamingTTSProvider): + """Gemini ``streamGenerateContent?alt=sse`` → SSE feed of base64 PCM chunks (24 kHz), bounded streamed body. + + Salvaged from PR #47588 (@Cdddo) and rebased onto the post-campaign infrastructure: credentials via the + provider-secret resolver, requests (not httpx) with a bounded streamed body, and main's provider ABC. + """ + + @staticmethod + def available() -> bool: + return bool(_gemini_key()) + + def stream(self, text: str) -> Iterator[bytes]: + import base64 + import json as _json + import requests + from tools.tts_tool_providers import ( + DEFAULT_GEMINI_TTS_BASE_URL, DEFAULT_GEMINI_TTS_MODEL, DEFAULT_GEMINI_TTS_VOICE) + from hermes_cli.config import get_env_value + api_key = _gemini_key() + model = str(self.section.get("model", DEFAULT_GEMINI_TTS_MODEL)).strip() or DEFAULT_GEMINI_TTS_MODEL + voice = str(self.section.get("voice", DEFAULT_GEMINI_TTS_VOICE)).strip() or DEFAULT_GEMINI_TTS_VOICE + base_url = str( + self.section.get("base_url") or get_env_value("GEMINI_BASE_URL") or DEFAULT_GEMINI_TTS_BASE_URL + ).strip().rstrip("/") + payload = { + "contents": [{"parts": [{"text": text}]}], + "generationConfig": { + "responseModalities": ["AUDIO"], + "speechConfig": {"voiceConfig": {"prebuiltVoiceConfig": {"voiceName": voice}}}}} + url = f"{base_url}/models/{model}:streamGenerateContent" + + def _sse_chunks() -> Iterator[bytes]: + with requests.post( + url, params={"alt": "sse", "key": api_key}, json=payload, timeout=60, stream=True, + ) as response: + response.raise_for_status() + for line in response.iter_lines(decode_unicode=True): + if not line or not line.startswith("data: "): + continue + try: + parts = _json.loads(line[len("data: "):])["candidates"][0]["content"]["parts"] + except (ValueError, KeyError, IndexError, TypeError): + continue + for part in parts: + b64 = (part.get("inlineData") or part.get("inline_data") or {}).get("data", "") + if not b64: + continue + try: + yield base64.b64decode(b64) + except (ValueError, TypeError) as exc: + logger.warning("Gemini SSE: bad base64 audio: %s", exc) + + yield from _capped(_sse_chunks(), "Gemini streaming TTS") + + +@register("xai") +class XAIStreamer(StreamingTTSProvider): + """xAI WebSocket TTS (``wss://api.x.ai/v1/tts``) → binary PCM frames (24 kHz mono int16). + Credentials route through ``resolve_xai_http_credentials`` (OAuth or XAI_API_KEY), same as the + sync path. ``_collect_async`` bridges the async WS loop to the sync iterator contract (test + seam). + + Salvaged from PR #47588 (@Cdddo): xAI's chunked TTS API is WebSocket-only (``wss://api.x.ai/v1/tts``). + """ + + @staticmethod + def available() -> bool: + try: + from tools.xai_http import resolve_xai_http_credentials + return bool(str(resolve_xai_http_credentials().get("api_key") or "").strip()) + except Exception: + return False + + def stream(self, text: str) -> Iterator[bytes]: + yield from _capped(iter(self._collect_async(text)), "xAI streaming TTS") + + def _collect_async(self, text: str) -> List[bytes]: + import asyncio + + async def _drain() -> List[bytes]: + return [frame async for frame in self._async_frames(text)] + return asyncio.run(_drain()) + + async def _async_frames(self, text: str): + import json as _json + import websockets + from tools.tts_tool_providers import DEFAULT_XAI_VOICE_ID + from tools.xai_http import resolve_xai_http_credentials + api_key = str(resolve_xai_http_credentials().get("api_key") or "").strip() + if not api_key: + raise RuntimeError("No xAI credentials for streaming TTS") + voice = str(self.section.get("voice_id", DEFAULT_XAI_VOICE_ID)).strip() or DEFAULT_XAI_VOICE_ID + ws_url = str(self.section.get("streaming_url") or "wss://api.x.ai/v1/tts").strip() + async with websockets.connect(ws_url, extra_headers={"Authorization": f"Bearer {api_key}"}) as ws: + await ws.send(_json.dumps({"text": text, "voice_id": voice, "response_format": "pcm"})) + try: + while True: + message = await ws.recv() + if isinstance(message, (bytes, bytearray, memoryview)): + yield bytes(message) + continue + try: + envelope = _json.loads(message) + except (ValueError, TypeError): + if message == "done": + return + continue + etype = envelope.get("type") + if etype == "error": + logger.warning( + "xAI WS error envelope: %s", envelope.get("error") or envelope.get("message") or envelope, + ) + if etype in ("done", "error"): + return + except Exception as exc: + if exc.__class__.__name__ != "ConnectionClosed": + logger.warning("xAI WS receive failed: %s", exc) + return diff --git a/tools/tts_text_normalize.py b/tools/tts_text_normalize.py new file mode 100644 index 0000000000000000000000000000000000000000..6aa5ca53741e841b1600bff3e9c4b7f50de3f3fa --- /dev/null +++ b/tools/tts_text_normalize.py @@ -0,0 +1,219 @@ +"""Deterministic cleanup turning assistant Markdown into a spoken script. + +Shared by explicit TTS calls, gateway auto-TTS, voice-mode streaming and the web +dashboard. Non-ASCII characters are written as escapes on purpose so the file +stays free of invisible/look-alike glyphs. +""" + +from __future__ import annotations + +import html +import re + +# Sentinel appended to former heading lines so smooth_whitespace_for_tts folds the +# heading into the sentence after it ("Weather, it will be sunny") instead of a bare +# "Weather." label. +_HEAD = "\x00" + +_MD_CODE_BLOCK_RE = re.compile(r"```[\s\S]*?```") +_MD_LINK_RE = re.compile(r"\[([^\]]+)\]\((?:[^()]|\([^)]*\))*\)") +_MD_IMAGE_RE = re.compile(r"!\[([^\]]*)\]\((?:[^()]|\([^)]*\))*\)") +_MD_INLINE_CODE_RE = re.compile(r"`([^`]+)`") +_MD_BOLD_RE = re.compile(r"\*\*(.+?)\*\*", flags=re.DOTALL) +_MD_UNDERSCORE_BOLD_RE = re.compile(r"__(.+?)__", flags=re.DOTALL) +_MD_ITALIC_RE = re.compile(r"(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)", flags=re.DOTALL) +_MD_UNDERSCORE_ITALIC_RE = re.compile(r"(?<!_)_(?!_)(.+?)(?<!_)_(?!_)", flags=re.DOTALL) +_MD_STRIKE_RE = re.compile(r"~~(.+?)~~", flags=re.DOTALL) +_MD_HEADING_LINE_RE = re.compile(r"^[ \t]{0,3}#{1,6}[ \t]+(.+?)[ \t]*#*[ \t]*$", flags=re.MULTILINE) +_MD_BLOCKQUOTE_RE = re.compile(r"^\s*>\s?", flags=re.MULTILINE) +_MD_LIST_ITEM_RE = re.compile(r"^\s*(?:[-*+]|\d+[.)])\s+", flags=re.MULTILINE) +_MD_HR_RE = re.compile(r"^\s*[-*_]{3,}\s*$", flags=re.MULTILINE) +_MD_TABLE_PIPE_RE = re.compile(r"\s*\|\s*") +_URL_RE = re.compile(r"https?://\S+") + +_DEGREE_UNITS = (("C", "Celsius"), ("F", "Fahrenheit")) +# Unit suffix (regex, after a digit) -> spoken word; km/h variants before the bare "m". +_UNIT_WORDS = ( + (r"km\s*/\s*h", "kilometres per hour"), (r"km/h", "kilometres per hour"), + (r"mm", "millimetres"), (r"cm", "centimetres"), (r"m", "metres")) +# Currency prefix (regex) -> spoken word; order matters (NZ$/A$/US$ before bare $). +_CURRENCY_WORDS = ( + (r"NZ\$", "New Zealand dollars", re.IGNORECASE), (r"A\$", "Australian dollars", re.IGNORECASE), + (r"US\$", "US dollars", re.IGNORECASE), ("€", "euros", 0), ("£", "pounds", 0), (r"\$", "dollars", 0), +) + +# Broad emoji / pictograph cleanup: most voice providers read emojis as awkward labels. +_EMOJI_RE = re.compile( + "[\U0001F1E6-\U0001F1FF\U0001F300-\U0001F5FF\U0001F600-\U0001F64F\U0001F680-\U0001F6FF" + "\U0001F700-\U0001F77F\U0001F780-\U0001F7FF\U0001F800-\U0001F8FF\U0001F900-\U0001F9FF" + "\U0001FA00-\U0001FAFF☀-➿]+", + flags=re.UNICODE) +_VARIATION_SELECTOR_RE = re.compile("[︎️]") + + +def strip_markdown_for_tts(text: str) -> str: + """Strip Markdown/Telegram formatting while preserving readable words.""" + if not text: + return "" + text = html.unescape(str(text)) + text = _MD_CODE_BLOCK_RE.sub(" ", text) + text = _MD_IMAGE_RE.sub(lambda m: f" {m.group(1)} " if m.group(1) else " ", text) + text = _MD_LINK_RE.sub(r"\1", text) + text = _URL_RE.sub("", text) + text = _MD_INLINE_CODE_RE.sub(r"\1", text) + text = _MD_BOLD_RE.sub(r"\1", text) + text = _MD_UNDERSCORE_BOLD_RE.sub(r"\1", text) + text = _MD_ITALIC_RE.sub(r"\1", text) + text = _MD_UNDERSCORE_ITALIC_RE.sub(r"\1", text) + text = _MD_STRIKE_RE.sub(r"\1", text) + # Mark headings (do not just delete the marker): see _HEAD. + text = _MD_HEADING_LINE_RE.sub(lambda m: m.group(1).rstrip() + _HEAD, text) + text = _MD_BLOCKQUOTE_RE.sub("", text) + text = _MD_LIST_ITEM_RE.sub("", text) + text = _MD_HR_RE.sub("", text) + # Leftover table pipes become pauses instead of a spoken "vertical bar". + return _MD_TABLE_PIPE_RE.sub("; ", text) + + +def _normalize_temperature_ranges(text: str) -> str: + """``11-17°C`` -> ``11 to 17 degrees Celsius`` (en/em dash or hyphen; unicode minus normalized).""" + number = r"([-+\u2212]?\d+(?:\.\d+)?)" + for unit, word in _DEGREE_UNITS: + text = re.sub( + r"(?<!\w)" + number + r"\s*[\u2013\u2014-]\s*" + number + r"\s*°\s*" + unit + r"\b", + lambda m, w=word: ( + f"{m.group(1).replace(chr(0x2212), '-')} to {m.group(2).replace(chr(0x2212), '-')} degrees {w}" + ), + text, flags=re.IGNORECASE) + return text + + +def normalize_symbols_for_tts(text: str) -> str: + """Expand common symbols/shorthand into words a TTS engine reads well.""" + if not text: + return "" + text = re.sub("[   ]", " ", str(text)) # non-breaking / thin spaces + text = text.replace("\u2212", "-").replace("…", "...") # minus sign, ellipsis + text = _normalize_temperature_ranges(text) + # Temperatures with a number first, then bare units ("measured in degrees C"), + # then any remaining degree symbol (angles, stray cases). + for unit, word in _DEGREE_UNITS: + text = re.sub( + r"(?<!\w)([-+]?\d+(?:\.\d+)?)\s*°\s*" + unit + r"\b", r"\1 degrees " + word, text, flags=re.IGNORECASE, + ) + for unit, word in _DEGREE_UNITS: + text = re.sub(r"°\s*" + unit + r"\b", "degrees " + word, text, flags=re.IGNORECASE) + text = re.sub(r"(?<!\w)([-+]?\d+(?:\.\d+)?)\s*°", r"\1 degrees", text).replace("°", " degrees") + # Common weather/travel units. + for pattern, word in _UNIT_WORDS: + text = re.sub(r"(?<=\d)\s*" + pattern + r"\b", " " + word, text, flags=re.IGNORECASE) + # Numeric rates only ("5/month" -> "5 per month"). Requiring digit-then-letter + # keeps "and/or", "N/A", "TCP/IP" and dates like "2026/06" intact. + text = re.sub(r"(?<=\d)\s*/\s*(?=[A-Za-z])", " per ", text) + # Money and percentages. The integer part must END in a digit so a trailing + # comma ("A$50, ...") is not swallowed into the spoken amount. Prefixed + # currencies run first so "$" doesn't eat "NZ$". + for symbol, word, flags in _CURRENCY_WORDS: + text = re.sub(symbol + r"\s*([\d,]*\d(?:\.\d+)?)", r"\1 " + word, text, flags=flags) + text = re.sub(r"(?<=\d)\s*%", " percent", text) + # Operators and separators that commonly leak from formatted answers. + text = re.sub("[•◦▪▫]", " ", text.replace("&", " and ")) # bullet glyphs + for symbol, word in (("→", " to "), ("⇒", " to "), ("≈", " about "), ("~", " about ")): + text = text.replace(symbol, word) + return _EMOJI_RE.sub("", _VARIATION_SELECTOR_RE.sub("", text)) + + +def smooth_whitespace_for_tts(text: str) -> str: + """Collapse visual formatting into calm spoken paragraphs. A _HEAD-marked heading folds into + the next content line as a lead-in ("Weather, It will be sunny."); a heading with no content + after it becomes its own sentence.""" + if not text: + return "" + raw_lines = text.splitlines() + add_sentence_pauses = sum(1 for raw_line in raw_lines if raw_line.replace(_HEAD, "").strip()) > 1 + lines: list[str] = [] + pending_heading: str | None = None + + def flush_pending() -> None: + nonlocal pending_heading + if pending_heading is not None: + lines.append(pending_heading.rstrip(".:;,") + ".") + pending_heading = None + for raw_line in raw_lines: + is_heading = raw_line.rstrip().endswith(_HEAD) + line = raw_line.replace(_HEAD, "").strip() + if not line: + # Hold a pending heading across blank lines so it still folds into the next content line. + if pending_heading is None and lines and lines[-1] != "": + lines.append("") + continue + if is_heading: + flush_pending() + pending_heading = line.rstrip(".:;,") + continue + if pending_heading is not None: + line = f"{pending_heading.rstrip('.:;,')}, {line}" + pending_heading = None + if add_sentence_pauses and line[-1] not in ".!?;:": + line += "." + lines.append(line) + flush_pending() + text = "\n".join(lines) + for pattern, repl in ((r"\n{3,}", "\n\n"), (r"[ \t]{2,}", " "), (r"\s+([,.;:!?])", r"\1"), + (r"([,.;:!?])([A-Za-z])", r"\1 \2"), (r"\.{4,}", "...")): + text = re.sub(pattern, repl, text) + return text.strip() + + +# ``/reasoning show`` emits ``<think>...</think>`` in the final message: users want to +# SEE reasoning, not hear it. An unterminated block (streaming cut-off) is also silenced. +# Reasoning blocks: models with ``/reasoning show`` enabled emit ``<think>...</think>`` blocks in the final +# assistant message. See #34213. +_THINK_BLOCK_RE = re.compile(r"<think[\s>].*?</think>", flags=re.DOTALL | re.IGNORECASE) +_THINK_BLOCK_OPEN_RE = re.compile(r"<think[\s>].*\Z", flags=re.DOTALL | re.IGNORECASE) + +# run_agent.py's turn-end file-mutation verifier footer (a ``⚠️ File-mutation verifier:`` +# header line plus indented ``•`` bullets) is a UI affordance, not speech. +_VERIFIER_FOOTER_RE = re.compile(r"^\s*⚠️?\s*File-mutation verifier:.*(?:\n[ \t]+•.*)*", flags=re.MULTILINE) + + +def strip_nonspoken_blocks(text: str) -> str: + """Remove ``<think>`` reasoning blocks and the file-mutation verifier footer.""" + if not text: + return "" + for pattern in (_THINK_BLOCK_RE, _THINK_BLOCK_OPEN_RE, _VERIFIER_FOOTER_RE): + text = pattern.sub(" ", text) + return text + + +def flatten_newlines_for_payload(text: str) -> str: + """Collapse newlines into sentence breaks for single-line TTS payloads: some OpenAI-compatible + backends (e.g. Kokoro) truncate at the first newline; smoothing already ends each line with + punctuation, so this is safe. + + See #9004. + """ + if not text: + return "" + for pattern, repl in ((r"\n{2,}", ". "), (r"(?<=[.!?;:,])\n", " "), (r"\n", ". "), (r"\.\s*\.", "."), + (r"[ \t]{2,}", " ")): + text = re.sub(pattern, repl, text) + return text.strip() + + +def prepare_spoken_text(text: str, max_chars: int | None = 4000) -> str: + """Return a TTS-friendly script from assistant text (deterministic cleanup, not a rewrite). + Pipeline: non-spoken blocks > Markdown > symbols/units > line formatting into sentence + pauses > single line (for newline-sensitive providers), then ``max_chars``.""" + spoken = text + for step in (strip_nonspoken_blocks, strip_markdown_for_tts, normalize_symbols_for_tts, + smooth_whitespace_for_tts, flatten_newlines_for_payload): + spoken = step(spoken) + if max_chars is not None and max_chars > 0 and len(spoken) > max_chars: + spoken = spoken[:max_chars].rstrip() + return spoken + + +def _strip_markdown_for_tts(text: str) -> str: + """``prepare_spoken_text`` without a length cap (``tts_tool`` compatibility name).""" + return prepare_spoken_text(text, max_chars=None) diff --git a/tools/tts_tool.py b/tools/tts_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..4d27cced659b4298744b3f917f3f84b47d96a646 --- /dev/null +++ b/tools/tts_tool.py @@ -0,0 +1,685 @@ +#!/usr/bin/env python3 +"""Text-to-speech tool: config resolution, built-in provider dispatch, output policy, registration. + +Built-ins: Edge (free default), ElevenLabs, OpenAI, DeepInfra, MiniMax, Mistral, Gemini, xAI, +local NeuTTS / KittenTTS / Piper; plus ``type: command`` providers under ``tts.providers.<name>`` +and plugin-registered ones. Output is Opus (.ogg) on voice-bubble platforms, MP3 elsewhere. +Sibling ``tts_tool_*`` modules hold backends/delivery/lifecycle; they read the seams defined +here (config, provider resolution, lazy SDK importers) through ``_origin()`` at call time. +""" + +import asyncio +import contextlib +import datetime +import importlib.util +import json +import logging +import os +import tempfile +from pathlib import Path +from typing import Callable, Dict, Any, List, Optional + +import copy + +from hermes_constants import display_hermes_home + +logger = logging.getLogger(__name__) + + +def _resolve_provider_key(env_var: str, provider_id: str) -> str: + """Resolve a TTS provider API key via the shared voice-key resolver (config > env/.env > pool).""" + from tools.tool_backend_helpers import resolve_provider_secret + return resolve_provider_secret(env_var, provider_id) + + +from tools.tts_command_provider import ( + BUILTIN_TTS_PROVIDERS, _configured_command_tts_output_path, _generate_command_tts, + _get_command_tts_output_format, _is_command_tts_voice_compatible, _resolve_command_provider_config) +from tools.tool_backend_helpers import NOUS_MANAGED_PROVIDER +from tools.tts_tool_delivery import ( + _resolve_max_text_length, _build_audio_delivery_files, _convert_to_opus, _remove_quietly, + _repair_ogg_container, _resolve_audio_delivery_profile, _split_text_for_tts) +from tools.tts_tool_providers import ( + _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 _generate_kittentts, _generate_neutts, _generate_piper_tts +from tools.tts_tool_plugins import ( + _dispatch_to_plugin_provider, _plugin_provider_is_available, + _plugin_provider_is_voice_compatible) +from tools.tts_tool_openai import _generate_deepinfra_tts, _generate_openai_tts, _has_openai_audio_backend + + +# --- 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 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: + with contextlib.suppress(Exception): + from tools.lazy_deps import ensure + ensure(feature, prompt=False) + mod = importlib.import_module(module) + return getattr(mod, attr) if attr else mod + _import.__name__ = f"_import_{module.split('.')[0]}" + return _import + + +_import_edge_tts = _sdk_importer("edge_tts", feature="tts.edge") +_import_elevenlabs = _sdk_importer("elevenlabs.client", "ElevenLabs", feature="tts.elevenlabs") +_import_openai_client = _sdk_importer("openai", "OpenAI") +_import_mistral_client = _sdk_importer("mistralai.client", "Mistral", feature="tts.mistral") +_import_sounddevice = _sdk_importer("sounddevice") +_import_kittentts = _sdk_importer("kittentts", "KittenTTS") +_import_piper = _sdk_importer("piper", "PiperVoice") # piper-tts wheels embed espeak-ng + + +def _importable(importer: Callable[[], Any]) -> bool: + try: + importer() + return True + except ImportError: + return False + + +def _package_installed(name: str) -> bool: + try: + return importlib.util.find_spec(name) is not None + except Exception: + return False + + +def _check_neutts_available() -> bool: return _package_installed("neutts") +def _check_kittentts_available() -> bool: return _package_installed("kittentts") +def _check_piper_available() -> bool: return _package_installed("piper") + + +# --- Defaults / config --- +DEFAULT_PROVIDER = "edge" + + +def _get_default_output_dir() -> str: + from hermes_constants import get_hermes_dir + return str(get_hermes_dir("cache/audio", "audio_cache")) + + +DEFAULT_OUTPUT_DIR = _DEFAULT_OUTPUT_DIR_AT_IMPORT = _get_default_output_dir() + + +def _default_output_dir() -> str: + """The active profile's audio output dir at call time (long-lived runtimes switch profiles + after import); a monkeypatched ``DEFAULT_OUTPUT_DIR`` wins. + + Same bug class as skills_tool (f8723c478) and skills_sync (#65828): long-lived multi-profile runtimes + (dashboard console, TUI/Desktop backend, cron, kanban workers) import this module once under the launch + HERMES_HOME and later scope requests to a different profile via + ``hermes_constants.set_hermes_home_override()`` — a frozen module constant keeps writing synthesized + audio into the launch profile's cache instead of the active profile's (#98749). Keep the legacy + ``DEFAULT_OUTPUT_DIR`` module attribute for tests and external patchers; when it has not been patched, + re-resolve from the live profile-scoped HERMES_HOME on every call. + """ + if DEFAULT_OUTPUT_DIR != _DEFAULT_OUTPUT_DIR_AT_IMPORT: + return DEFAULT_OUTPUT_DIR + return _get_default_output_dir() + + +def _load_tts_config() -> Dict[str, Any]: + """Return the ``tts`` config section ({} when unavailable).""" + try: + from hermes_cli.config import load_config + return load_config().get("tts") or {} + except ImportError: + logger.debug("hermes_cli.config not available, using default TTS config") + except Exception as e: + logger.warning("Failed to load TTS config: %s", e, exc_info=True) + return {} + + +def _get_provider(tts_config: Dict[str, Any]) -> str: + """Configured provider or the free default (inference credentials never imply consent to paid + speech); ``nous`` is serviced by the OpenAI path through the managed openai-audio gateway.""" + provider = (tts_config.get("provider") or DEFAULT_PROVIDER).lower().strip() + return "openai" if provider == NOUS_MANAGED_PROVIDER else provider + + +# Platforms whose native voice-bubble delivery requires Ogg/Opus (MP3 renders broken there). +OPUS_VOICE_PLATFORMS = frozenset({"telegram", "matrix", "feishu", "whatsapp", "signal"}) +# Built-ins that emit Opus natively when asked for .ogg; the rest need ffmpeg for voice bubbles. +_NATIVE_OPUS_PROVIDERS = frozenset({"openai", "elevenlabs", "mistral", "gemini"}) +_FFMPEG_OPUS_PROVIDERS = frozenset({"edge", "neutts", "minimax", "xai", "kittentts", "piper"}) + + +# --- Built-in provider dispatch --- +# provider -> (availability predicate or None, log label, generator name, "package missing" error). +# Predicates/generator names resolve module globals at call time so test monkeypatches apply. +_BUILTIN_DISPATCH: Dict[str, tuple] = { + "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")} + + +def _error_json(message: str) -> str: + return json.dumps({"success": False, "error": message}, ensure_ascii=False) + + +def _run_edge_tts(text: str, file_str: str, tts_config: Dict[str, Any]) -> None: + """Run the async Edge generator from sync code (worker thread; direct run if that fails).""" + run = lambda: asyncio.run(_generate_edge_tts(text, file_str, tts_config)) # noqa: E731 + try: + from concurrent.futures import ThreadPoolExecutor + with ThreadPoolExecutor(max_workers=1) as pool: + pool.submit(run).result(timeout=60) + except RuntimeError: + run() + + +def _select_builtin_engine(provider: str) -> tuple: + """SDK check -> ``(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, _label, _generator, missing_error = entry + return provider, (_error_json(missing_error) if available is not None and not available() else None) + if _importable(_import_edge_tts): + return provider, None # Edge default; the reported provider stays as configured + if _check_neutts_available(): + logger.info("Edge TTS not available, falling back to NeuTTS (local)...") + return "neutts", None + return provider, _error_json( + "No TTS provider available. Install edge-tts (pip install edge-tts) " + "or set up NeuTTS for local synthesis.") + + +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: + _run_edge_tts(text, file_str, tts_config) + elif engine == "openai": + _generate_openai_tts(text, file_str, tts_config, instructions=instructions) + else: + 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: + """Voice-bubble eligibility (Opus-converting when needed) -> ``(path, voice_compatible)``. + + 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: + opted_in = _plugin_provider_is_voice_compatible(provider) + elif want_opus and provider in _FFMPEG_OPUS_PROVIDERS and not file_str.endswith(".ogg"): + opus_path = _convert_to_opus(file_str) + return (opus_path, True) if opus_path else (file_str, False) + else: + native = provider in _NATIVE_OPUS_PROVIDERS + return file_str, native and want_opus and file_str.endswith(".ogg") + if not opted_in: + return file_str, False + # Plugin-registered provider (issue #30398). Voice-bubble delivery opts in via + # ``TTSProvider.voice_compatible`` (mirrors the command-provider opt-in). Plugins that already write + # Opus skip the ffmpeg conversion. + if not file_str.endswith(".ogg"): + file_str = _convert_to_opus(file_str) or file_str + return file_str, file_str.endswith(".ogg") + + +# --- 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 so the cached config isn't mutated) and + resolve the provider name.""" + if speed is not None: + tts_config = {**tts_config, "speed": max(0.25, min(4.0, float(speed)))} + return tts_config, provider.lower().strip() if provider else _get_provider(tts_config) + + +def _session_platform() -> tuple: + """``(platform, wants_opus)`` — platforms delivering voice bubbles only as Ogg/Opus want Opus.""" + from gateway.session_context import get_session_env + platform = get_session_env("HERMES_SESSION_PLATFORM", "").lower() + return platform, platform in OPUS_VOICE_PLATFORMS + + +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 -> ``(Path, None)`` or ``(None, error_json)``. + + 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): + return None, _error_json( + f"output_path contains '..' traversal component: {output_path}. " + "Use an absolute path or one relative to the current directory without '..'.") + file_path = Path(output_path).expanduser() + if command_provider_config is not None: + file_path = _configured_command_tts_output_path(file_path, command_provider_config) + from agent.file_safety import is_write_approval_required, is_write_denied + if is_write_denied(str(file_path)) or is_write_approval_required(str(file_path)): + return None, _error_json( + f"output_path targets a protected credential or system path: " + f"{file_path}. Choose a normal audio output location.") + else: + if command_provider_config is not None: + ext = _get_command_tts_output_format(command_provider_config) + else: + ext = "ogg" if want_opus and provider in _NATIVE_OPUS_PROVIDERS else "mp3" + timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%f") + file_path = Path(_default_output_dir()) / f"tts_{timestamp}.{ext}" + file_path.parent.mkdir(parents=True, exist_ok=True) + return file_path, None + + +def _media_tag(paths: List[str], voice_compatible: bool) -> str: + """``MEDIA:<path>`` lines; the ``[[audio_as_voice]]`` marker asks the platform for a voice bubble.""" + media_tag = "\n".join(f"MEDIA:{path}" for path in paths) + return f"[[audio_as_voice]]\n{media_tag}" if voice_compatible else media_tag + + +def _tool_failure(prefix: str, provider: str, exc: BaseException) -> str: + """Log and wrap a synthesis failure as the standard error envelope (traceback except for config errors).""" + error_msg = f"{prefix} ({provider}): {exc}" + logger.error("%s", error_msg, exc_info=not isinstance(exc, ValueError)) + return tool_error(error_msg, success=False) + + +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], +) -> str: + """Synthesize one provider-safe chunk into *file_str*; returns the result envelope. + + 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) + file_str = _generate_command_tts( + text, file_str, provider, command_provider_config, tts_config) + # Plugin-registered TTS backend (issue #30398). Fires when the configured provider is neither a + # built-in nor a command-type entry, AND a plugin is registered under that name. The walrus binds + # `_plugin_path` only when the dispatcher returns a path (i.e. a plugin was actually found); a None + # return falls through to the built-in elif chain so unknown names hit the Edge TTS default at the + # bottom. The dispatcher itself enforces built-ins-always-win + command-wins-over-plugin + # defensively. + elif provider not in BUILTIN_TTS_PROVIDERS and ( + _plugin_path := _dispatch_to_plugin_provider(text, file_str, provider, tts_config) + ) is not None: + file_str = _plugin_path + else: + provider, error = _select_builtin_engine(provider) + if error: + return error + _synthesize_builtin(provider, text, file_str, tts_config, instructions) + if not os.path.exists(file_str) or os.path.getsize(file_str) == 0: + return _error_json(f"TTS generation produced no output (provider: {provider})") + + # Sniff once for every provider: MP3/WAV bytes in a .ogg path render as 0-second bubbles. + file_str = _repair_ogg_container(file_str) + file_str, voice_compatible = _finalize_voice_delivery( + file_str, provider, command_provider_config, want_opus) + logger.info("TTS audio saved: %s (%s bytes, provider: %s)", file_str, f"{os.path.getsize(file_str):,}", provider) + return json.dumps({ + "success": True, "file_path": file_str, "media_tag": _media_tag([file_str], voice_compatible), + "provider": provider, "voice_compatible": voice_compatible, + }, ensure_ascii=False) + except ValueError as e: + return _tool_failure("TTS configuration error", provider, e) + except FileNotFoundError as e: + return _tool_failure("TTS dependency missing", provider, e) + except Exception as e: + return _tool_failure("TTS generation failed", provider, e) + + +class _ChunkFailed(Exception): + """One chunk's synthesis returned an error envelope; message is the final tool error text.""" + + +def _synthesize_chunks(chunks: List[str], base_path: Path, generated_artifacts: set, **single_kwargs) -> tuple: + """Synthesize chunks into ``<base>.chunkNNN<ext>`` (or ``base`` alone) -> ``(encoded_paths, results)``. + + 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]] = [] + for index, chunk in enumerate(chunks, start=1): + chunk_path = base_path + if len(chunks) > 1: + chunk_path = base_path.with_name(f"{base_path.stem}.chunk{index:03d}{base_path.suffix}") + generated_artifacts.add(str(chunk_path)) + raw_result = _text_to_speech_single(chunk, str(chunk_path), **single_kwargs) + try: + chunk_result = json.loads(raw_result) + except (json.JSONDecodeError, TypeError): + raise RuntimeError(f"TTS chunk {index} returned invalid JSON: {str(raw_result)[:200]}") + if not chunk_result.get("success"): + error_msg = chunk_result.get("error", "unknown error") + raise _ChunkFailed(f"TTS chunk {index} failed ({provider}): {error_msg}") + actual_path = str(chunk_result.get("file_path") or chunk_path) + if not os.path.isfile(actual_path) or os.path.getsize(actual_path) <= 0: + raise RuntimeError(f"TTS chunk {index} produced no final audio: {actual_path}") + generated_artifacts.add(actual_path) + encoded_paths.append(actual_path) + chunk_results.append(chunk_result) + return encoded_paths, chunk_results + + +def text_to_speech_tool( + text: str, output_path: Optional[str] = None, speed: Optional[float] = None, + instructions: Optional[str] = None, provider: Optional[str] = None) -> str: + """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, 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) + try: # shared cleaner: markdown, emoji, think blocks, verifier footer, units, newlines + from tools.tts_text_normalize import prepare_spoken_text + text = prepare_spoken_text(text, max_chars=None) + except Exception: + text = text.strip() + if not text: + return tool_error("Text is empty after TTS cleanup", success=False) + tts_config, provider = _apply_call_overrides(_load_tts_config(), speed, provider) + command_provider_config = _resolve_command_provider_config(provider, tts_config) + max_len = _resolve_max_text_length(provider, tts_config) + chunks = _split_text_for_tts(text, max_len) + if not chunks: + return tool_error("Text is required", success=False) + if len(chunks) > 1: + logger.info("TTS text for provider %s split into %d chunks (input=%d chars, cap=%d)", + provider, len(chunks), len(text), max_len) + platform, want_opus = _session_platform() + delivery_profile = _resolve_audio_delivery_profile(platform, tts_config) + base_path, error = _resolve_output_base( + output_path, provider, command_provider_config, want_opus) + if error: + return error + generated_artifacts: set[str] = set() + 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, + instructions=instructions) + voice_compatible = bool(chunk_results) and all(bool(r.get("voice_compatible")) for r in chunk_results) + delivery_base = base_path.with_suffix(Path(encoded_paths[0]).suffix) + final_paths, combined_chunks = _build_audio_delivery_files( + encoded_paths, str(delivery_base), delivery_profile, voice_compatible=voice_compatible) + for path in final_paths: + logger.info("TTS audio saved: %s (%s bytes, provider: %s)", path, f"{os.path.getsize(path):,}", provider) + return json.dumps({ + "success": True, "file_path": final_paths[0], "file_paths": final_paths, + "media_tag": _media_tag(final_paths, voice_compatible), + "provider": chunk_results[0].get("provider", provider), "voice_compatible": voice_compatible, + "chunk_count": len(chunks), "delivery_file_count": len(final_paths), + "combined_chunks": bool(combined_chunks), + "delivery_profile": { + "platform": delivery_profile.platform, "max_file_bytes": delivery_profile.max_file_bytes, + "target_file_bytes": delivery_profile.target_file_bytes}, + }, ensure_ascii=False) + except _ChunkFailed as exc: + return tool_error(str(exc), success=False) + except ValueError as exc: + return _tool_failure("TTS delivery error", provider, exc) + except Exception as exc: + return _tool_failure("TTS long-form generation failed", provider, exc) + finally: + final_absolute = {os.path.abspath(path) for path in final_paths} + for artifact in generated_artifacts: + if os.path.abspath(artifact) not in final_absolute: + _remove_quietly(artifact) + + +# --- check_fn --- +def _minimax_requirements() -> bool: + try: + _resolve_minimax_tts_runtime(_load_tts_config()) + return True + except ValueError: + return False + + +def _xai_requirements() -> bool: + try: + from tools.xai_http import resolve_xai_http_credentials + return bool(resolve_xai_http_credentials().get("api_key")) + except Exception: + return False + + +# Must mirror text_to_speech_tool dispatch: unrelated cloud credentials never make the Edge +# default usable, and an explicit provider is checked on its own. +_BUILTIN_REQUIREMENTS: Dict[str, Callable[[], bool]] = { + "edge": lambda: _importable(_import_edge_tts) or _check_neutts_available(), + "elevenlabs": lambda: _importable(_import_elevenlabs) and bool(_resolve_provider_key("ELEVENLABS_API_KEY", "elevenlabs")), + "openai": lambda: _package_installed("openai") and _has_openai_audio_backend(), + "deepinfra": lambda: _package_installed("openai") and bool(_resolve_provider_key("DEEPINFRA_API_KEY", "deepinfra")), + "minimax": _minimax_requirements, + "xai": _xai_requirements, + "gemini": lambda: bool(_resolve_provider_key("GEMINI_API_KEY", "gemini") or _resolve_provider_key("GOOGLE_API_KEY", "gemini")), + "mistral": lambda: _importable(_import_mistral_client) and bool(_resolve_provider_key("MISTRAL_API_KEY", "mistral")), + "neutts": lambda: _check_neutts_available(), + "kittentts": lambda: _check_kittentts_available(), + "piper": lambda: _check_piper_available()} + + +def check_tts_requirements() -> bool: + """Return whether the explicitly resolved TTS provider can run.""" + tts_config = _load_tts_config() + provider = _get_provider(tts_config) + if _resolve_command_provider_config(provider, tts_config) is not None: + return True + check = _BUILTIN_REQUIREMENTS.get(provider) + return check() if check is not None else _plugin_provider_is_available(provider) + + +# --- Registry --- +from tools.registry import registry, tool_error + +def _output_path_description(home: str) -> str: + return f"Optional custom file path to save the audio. Defaults to {home}/audio_cache/<timestamp>.mp3" + + +def _tts_schema_overrides() -> dict: + """Rebuild the ``output_path`` default hint from the ACTIVE profile at every get_definitions(): + the multiplexed gateway serves every profile from one process, so a path baked in at import + would name the launch profile's home for everyone else (#95685).""" + params = copy.deepcopy(TTS_SCHEMA["parameters"]) + params["properties"]["output_path"]["description"] = _output_path_description(display_hermes_home()) + return {"parameters": params} + + +TTS_SCHEMA = { + "name": "text_to_speech", + "description": "Convert text to speech audio. Returns a MEDIA: path that the platform delivers as native audio. Compatible providers render as a voice bubble on Telegram; otherwise audio is sent as a regular attachment. In CLI mode, saves to ~/voice-memos/. Voice and provider are user-configured (built-in providers like edge/openai or custom command providers under tts.providers.<name>), not model-selected.", + "parameters": { + "type": "object", + "properties": { + "text": { + "type": "string", + "description": "The text to convert to speech. Provider-specific per-request character caps apply automatically (OpenAI 4096, xAI 15000, MiniMax 10000, ElevenLabs 5k-40k depending on model); longer input is split into ordered chunks without silent truncation." + }, + "output_path": { + "type": "string", + "description": _output_path_description("the profile HERMES_HOME") + }, + "speed": { + "type": "number", + "description": "Playback speed multiplier. 1.0 = normal, 0.5 = very slow (language learning), 2.0 = fast. Range: 0.25-4.0. Overrides the speed configured in config.yaml." + }, + "instructions": { + "type": "string", + "description": ( + "Optional voice-design guidance: tone, emotion, pacing, accent, " + "whispering, impressions (e.g. 'Speak in a cheerful, excited whisper'). " + "Forwarded to the OpenAI backend (gpt-4o-mini-tts and OpenAI-compatible " + "voice-design servers). Silently ignored by backends that don't support it." + ) + }, + "provider": { + "type": "string", + "description": ( + "Optional TTS provider override. Accepts built-in names " + "(edge, openai, elevenlabs, minimax, xai, mistral, gemini, " + "neutts, kittentts, piper), user-declared command provider " + "names from tts.providers.<name>, or plugin-registered names. " + "When omitted, the configured tts.provider from config.yaml is used." + ) + } + }, + "required": ["text"] + } +} + +registry.register( + name="text_to_speech", + toolset="tts", + schema=TTS_SCHEMA, + handler=lambda args, **kw: text_to_speech_tool( + text=args.get("text", ""), + **{k: args.get(k) for k in ("output_path", "speed", "instructions", "provider")}), + check_fn=check_tts_requirements, + emoji="🔊", + dynamic_schema_overrides=_tts_schema_overrides) + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. +from concurrent.futures import Future # noqa: F401,E402 +from typing import Iterator # noqa: F401,E402 +from concurrent.futures import ThreadPoolExecutor # noqa: F401,E402 +from typing import Tuple # noqa: F401,E402 +import base64 # noqa: F401,E402 +from dataclasses import dataclass # noqa: F401,E402 +from dataclasses import field # noqa: F401,E402 +import platform # noqa: F401,E402 +import queue # noqa: F401,E402 +import re # noqa: F401,E402 +import shlex # noqa: F401,E402 +import shutil # noqa: F401,E402 +import subprocess # noqa: F401,E402 +import threading # noqa: F401,E402 +import time # noqa: F401,E402 +from urllib.parse import urljoin # noqa: F401,E402 +from urllib.parse import urlparse # noqa: F401,E402 +import uuid # noqa: F401,E402 + +GEMINI_TTS_CHANNELS = 1 + +GEMINI_TTS_SAMPLE_RATE = 24000 + +GEMINI_TTS_SAMPLE_WIDTH = 2 # 16-bit PCM (L16) + +FALLBACK_MAX_TEXT_LENGTH = 4000 + +MAX_TEXT_LENGTH = FALLBACK_MAX_TEXT_LENGTH + + +_PLUGIN_COMPAT_LAZY = { + 'AudioDeliveryProfile': ('tools.tts_tool_delivery', 'AudioDeliveryProfile'), + 'COMMAND_TTS_OUTPUT_FORMATS': ('tools.tts_command_provider', 'COMMAND_TTS_OUTPUT_FORMATS'), + 'DEFAULT_COMMAND_TTS_MAX_TEXT_LENGTH': ('tools.tts_command_provider', 'DEFAULT_COMMAND_TTS_MAX_TEXT_LENGTH'), + 'DEFAULT_COMMAND_TTS_OUTPUT_FORMAT': ('tools.tts_command_provider', 'DEFAULT_COMMAND_TTS_OUTPUT_FORMAT'), + 'DEFAULT_COMMAND_TTS_TIMEOUT_SECONDS': ('tools.tts_command_provider', 'DEFAULT_COMMAND_TTS_TIMEOUT_SECONDS'), + 'DEFAULT_DEEPINFRA_TTS_VOICE': ('tools.tts_tool_openai', 'DEFAULT_DEEPINFRA_TTS_VOICE'), + 'DEFAULT_EDGE_VOICE': ('tools.tts_tool_providers', 'DEFAULT_EDGE_VOICE'), + 'DEFAULT_ELEVENLABS_MODEL_ID': ('tools.tts_tool_providers', 'DEFAULT_ELEVENLABS_MODEL_ID'), + 'DEFAULT_ELEVENLABS_STREAMING_MODEL_ID': ('tools.tts_tool_providers', 'DEFAULT_ELEVENLABS_STREAMING_MODEL_ID'), + 'DEFAULT_ELEVENLABS_VOICE_ID': ('tools.tts_tool_providers', 'DEFAULT_ELEVENLABS_VOICE_ID'), + 'DEFAULT_GEMINI_AUDIO_TAGS': ('tools.tts_tool_providers', 'DEFAULT_GEMINI_AUDIO_TAGS'), + 'DEFAULT_GEMINI_TTS_BASE_URL': ('tools.tts_tool_providers', 'DEFAULT_GEMINI_TTS_BASE_URL'), + 'DEFAULT_GEMINI_TTS_MODEL': ('tools.tts_tool_providers', 'DEFAULT_GEMINI_TTS_MODEL'), + 'DEFAULT_GEMINI_TTS_VOICE': ('tools.tts_tool_providers', 'DEFAULT_GEMINI_TTS_VOICE'), + 'DEFAULT_KITTENTTS_MODEL': ('tools.tts_tool_local', 'DEFAULT_KITTENTTS_MODEL'), + 'DEFAULT_KITTENTTS_VOICE': ('tools.tts_tool_local', 'DEFAULT_KITTENTTS_VOICE'), + 'DEFAULT_MINIMAX_BASE_URL': ('tools.tts_tool_providers', 'DEFAULT_MINIMAX_BASE_URL'), + 'DEFAULT_MINIMAX_CN_BASE_URL': ('tools.tts_tool_providers', 'DEFAULT_MINIMAX_CN_BASE_URL'), + 'DEFAULT_MINIMAX_MODEL': ('tools.tts_tool_providers', 'DEFAULT_MINIMAX_MODEL'), + 'DEFAULT_MINIMAX_VOICE_ID': ('tools.tts_tool_providers', 'DEFAULT_MINIMAX_VOICE_ID'), + 'DEFAULT_MISTRAL_TTS_MODEL': ('tools.tts_tool_providers', 'DEFAULT_MISTRAL_TTS_MODEL'), + 'DEFAULT_MISTRAL_TTS_VOICE_ID': ('tools.tts_tool_providers', 'DEFAULT_MISTRAL_TTS_VOICE_ID'), + 'DEFAULT_OPENAI_BASE_URL': ('tools.tts_tool_openai', 'DEFAULT_OPENAI_BASE_URL'), + 'DEFAULT_OPENAI_MODEL': ('tools.tts_tool_openai', 'DEFAULT_OPENAI_MODEL'), + 'DEFAULT_OPENAI_VOICE': ('tools.tts_tool_openai', 'DEFAULT_OPENAI_VOICE'), + 'DEFAULT_PIPER_VOICE': ('tools.tts_tool_local', 'DEFAULT_PIPER_VOICE'), + 'DEFAULT_XAI_AUTO_SPEECH_TAGS': ('tools.tts_tool_providers', 'DEFAULT_XAI_AUTO_SPEECH_TAGS'), + 'DEFAULT_XAI_BASE_URL': ('tools.tts_tool_providers', 'DEFAULT_XAI_BASE_URL'), + 'DEFAULT_XAI_BIT_RATE': ('tools.tts_tool_providers', 'DEFAULT_XAI_BIT_RATE'), + 'DEFAULT_XAI_LANGUAGE': ('tools.tts_tool_providers', 'DEFAULT_XAI_LANGUAGE'), + 'DEFAULT_XAI_OPTIMIZE_STREAMING_LATENCY_DEFAULT': ('tools.tts_tool_providers', 'DEFAULT_XAI_OPTIMIZE_STREAMING_LATENCY_DEFAULT'), + 'DEFAULT_XAI_SAMPLE_RATE': ('tools.tts_tool_providers', 'DEFAULT_XAI_SAMPLE_RATE'), + 'DEFAULT_XAI_SPEED_DEFAULT': ('tools.tts_tool_providers', 'DEFAULT_XAI_SPEED_DEFAULT'), + 'DEFAULT_XAI_SPEED_MAX': ('tools.tts_tool_providers', 'DEFAULT_XAI_SPEED_MAX'), + 'DEFAULT_XAI_SPEED_MIN': ('tools.tts_tool_providers', 'DEFAULT_XAI_SPEED_MIN'), + 'DEFAULT_XAI_TEXT_NORMALIZATION_DEFAULT': ('tools.tts_tool_providers', 'DEFAULT_XAI_TEXT_NORMALIZATION_DEFAULT'), + 'DEFAULT_XAI_VOICE_ID': ('tools.tts_tool_providers', 'DEFAULT_XAI_VOICE_ID'), + 'ELEVENLABS_MODEL_MAX_TEXT_LENGTH': ('tools.tts_tool_delivery', 'ELEVENLABS_MODEL_MAX_TEXT_LENGTH'), + 'FALLBACK_MAX_TEXT_LENGTH': ('tools.tts_tool_delivery', 'FALLBACK_MAX_TEXT_LENGTH'), + 'GEMINI_AUDIO_TAG_REWRITE_TASK': ('tools.tts_tool_providers', 'GEMINI_AUDIO_TAG_REWRITE_TASK'), + 'MANAGED_OPENAI_TTS_MODELS': ('tools.tts_tool_openai', 'MANAGED_OPENAI_TTS_MODELS'), + 'PROVIDER_MAX_TEXT_LENGTH': ('tools.tts_tool_delivery', 'PROVIDER_MAX_TEXT_LENGTH'), + 'TTS_RESPONSE_BODY_CHUNK_BYTES': ('tools.tts_tool_providers', 'TTS_RESPONSE_BODY_CHUNK_BYTES'), + 'TTS_RESPONSE_BODY_LIMIT_BYTES': ('tools.tts_tool_providers', 'TTS_RESPONSE_BODY_LIMIT_BYTES'), + 'acquire_tts_lease': ('tools.tts_tool_lifecycle', 'acquire_tts_lease'), + 'hermes_xai_user_agent': ('tools.xai_http', 'hermes_xai_user_agent'), + 'managed_nous_tools_enabled': ('tools.tool_backend_helpers', 'managed_nous_tools_enabled'), + 'nous_tool_gateway_unavailable_message': ('tools.tool_backend_helpers', 'nous_tool_gateway_unavailable_message'), + 'read_selection': ('tools.tool_backend_helpers', 'read_selection'), + 'release_tts_lease': ('tools.tts_tool_lifecycle', 'release_tts_lease'), + 'release_tts_provider': ('tools.tts_tool_lifecycle', 'release_tts_provider'), + 'resolve_managed_tool_gateway': ('tools.managed_tool_gateway', 'resolve_managed_tool_gateway'), + 'resolve_openai_audio_api_key': ('tools.tool_backend_helpers', 'resolve_openai_audio_api_key'), + 'selection_error': ('tools.tool_backend_helpers', 'selection_error'), + 'stream_tts_to_speaker': ('tools.tts_tool_speaker', 'stream_tts_to_speaker'), + 'tts_lease_holders': ('tools.tts_tool_lifecycle', 'tts_lease_holders'), + 'warm_tts_provider': ('tools.tts_tool_lifecycle', 'warm_tts_provider'), + 'windows_hide_flags': ('hermes_cli._subprocess_compat', 'windows_hide_flags'), +} + + +def __getattr__(name): # PEP 562 — lazy so no import cycles + target = _PLUGIN_COMPAT_LAZY.get(name) + if target is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + import importlib + from hermes_cli.plugin_compat import warn_once + warn_once(__name__, name, *target) + return getattr(importlib.import_module(target[0]), target[1]) +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/tts_tool_delivery.py b/tools/tts_tool_delivery.py new file mode 100644 index 0000000000000000000000000000000000000000..3c8459cd48bc55ea9ac9decc0da6df9f169f70ee --- /dev/null +++ b/tools/tts_tool_delivery.py @@ -0,0 +1,425 @@ +"""Long-form chunking, ffmpeg encoding, container repair and delivery packing (``tools.tts_tool``). + +Provider-agnostic post-processing: split text under a per-request cap, wrap raw PCM as WAV, +convert WAV/MP3 to the target container, sniff/repair mislabelled ``.ogg`` files, and combine +final-encoded chunks under a destination platform's upload limit. Also home of the sibling +helpers ``_origin`` / ``_section`` / ``_remove_quietly``. +""" + +from __future__ import annotations + +import logging +import os +import re +import shlex +import shutil +import struct +import subprocess +import tempfile +import uuid +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple + +from hermes_cli._subprocess_compat import windows_hide_flags +from tools.tts_command_provider import ( + BUILTIN_TTS_PROVIDERS, DEFAULT_COMMAND_TTS_MAX_TEXT_LENGTH, _get_named_provider_config, + _is_command_provider_config) + +logger = logging.getLogger("tools.tts_tool") + + +def _origin(): + """``tools.tts_tool``, resolved per call so seams monkeypatched there still apply.""" + from tools import tts_tool + return tts_tool + + +def _section(tts_config: Any, key: str) -> Dict[str, Any]: + """``tts.<key>`` as a dict (``null``/non-dict sections read as empty).""" + section = tts_config.get(key) if isinstance(tts_config, dict) else None + return section if isinstance(section, dict) else {} + + +FALLBACK_MAX_TEXT_LENGTH = 4000 # provider not recognised at all + +# Per-provider input-character caps (official docs); override: ``tts.<provider>.max_text_length``. +PROVIDER_MAX_TEXT_LENGTH: Dict[str, int] = { + "edge": 5000, # edge-tts practical sync limit + "openai": 4096, # https://platform.openai.com/docs/guides/text-to-speech + "xai": 15000, # https://docs.x.ai/developers/model-capabilities/audio/text-to-speech + "minimax": 10000, # https://platform.minimax.io/docs/api-reference/speech-t2a-http (sync) + "mistral": 4000, # conservative; no published per-request cap + "gemini": 32000, # 32k-token context window; char cap is conservative + "elevenlabs": 10000, # fallback when model-aware lookup can't resolve (multilingual_v2) + "neutts": 2000, # local model, quality falls off on long text + "kittentts": 2000, # local 25MB model + "piper": 5000, # local VITS model, phoneme-based; practical cap +} + +# ElevenLabs caps vary by model_id. https://elevenlabs.io/docs/overview/models +ELEVENLABS_MODEL_MAX_TEXT_LENGTH: Dict[str, int] = { + "eleven_v3": 5000, "eleven_ttv_v3": 5000, + "eleven_multilingual_v2": 10000, "eleven_multilingual_v1": 10000, + "eleven_english_sts_v2": 10000, "eleven_english_sts_v1": 10000, + "eleven_flash_v2": 30000, "eleven_flash_v2_5": 40000} + + +def _positive_int(value: Any) -> Optional[int]: + """*value* when it is a positive non-bool int, else None.""" + return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else None + + +def _resolve_max_text_length(provider: Optional[str], tts_config: Optional[Dict[str, Any]] = None) -> int: + """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() + cfg = tts_config or {} + prov_cfg = _section(cfg, key) + override = _positive_int(prov_cfg.get("max_text_length")) + if override: + return override + if key == "elevenlabs": + from tools.tts_tool_providers import DEFAULT_ELEVENLABS_MODEL_ID # providers imports this module + model_id = prov_cfg.get("model_id") or DEFAULT_ELEVENLABS_MODEL_ID + mapped = ELEVENLABS_MODEL_MAX_TEXT_LENGTH.get(str(model_id).strip()) + if mapped: + return mapped + if key in PROVIDER_MAX_TEXT_LENGTH: + return PROVIDER_MAX_TEXT_LENGTH[key] + if key not in BUILTIN_TTS_PROVIDERS: + named = _get_named_provider_config(cfg, key) + if _is_command_provider_config(named): + return _positive_int(named.get("max_text_length")) or DEFAULT_COMMAND_TTS_MAX_TEXT_LENGTH + return FALLBACK_MAX_TEXT_LENGTH + + +# PCM output specs for Gemini TTS (fixed by the API): 24kHz mono 16-bit (L16). +GEMINI_TTS_SAMPLE_RATE, GEMINI_TTS_CHANNELS, GEMINI_TTS_SAMPLE_WIDTH = 24000, 1, 2 + +# ffmpeg args producing the Ogg/Opus voice-bubble encoding Telegram & co expect. +_OPUS_VOICE_ARGS = [ + "-acodec", "libopus", "-ac", "1", "-b:a", "48k", "-vbr", "on", + "-application", "voip", "-compression_level", "10"] + + +# --- Text chunking and delivery profiles --- +@dataclass(frozen=True) +class AudioDeliveryProfile: + """Destination-platform constraints for generated TTS audio.""" + + platform: str + max_file_bytes: int + safety_ratio: float = 0.85 + + @property + def target_file_bytes(self) -> int: + """Conservative packing target below the platform hard limit.""" + return max(1, int(self.max_file_bytes * self.safety_ratio)) + + +_PLATFORM_AUDIO_DEFAULTS: Dict[str, Dict[str, Any]] = { + "discord": {"max_file_bytes": 10 * 1024 * 1024, "safety_ratio": 0.85}, + "telegram": {"max_file_bytes": 50 * 1024 * 1024, "safety_ratio": 0.85}, + "default": {"max_file_bytes": 10 * 1024 * 1024, "safety_ratio": 0.85}} + + +def _resolve_audio_delivery_profile( + platform: Optional[str], tts_config: Optional[Dict[str, Any]] = None) -> AudioDeliveryProfile: + """Resolve upload constraints, including optional ``tts.delivery_profiles`` overrides.""" + key = (platform or "default").lower().strip() or "default" + defaults = dict(_PLATFORM_AUDIO_DEFAULTS.get(key) or _PLATFORM_AUDIO_DEFAULTS["default"]) + overrides = _section(_section(tts_config, "delivery_profiles"), key) + defaults.update({k: v for k, v in overrides.items() if v is not None}) + max_file_bytes = (_positive_int(defaults.get("max_file_bytes")) + or _PLATFORM_AUDIO_DEFAULTS["default"]["max_file_bytes"]) + safety_ratio = defaults.get("safety_ratio", 0.85) + if (isinstance(safety_ratio, bool) or not isinstance(safety_ratio, (int, float)) + or not 0 < safety_ratio <= 1): + safety_ratio = 0.85 + 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, *, 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) + current = piece + else: + current = candidate + if current: + chunks.append(current) + return chunks + + +def _split_oversized_sentence(sentence: str, max_chars: int) -> List[str]: + """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]: + """Split text under a provider cap without dropping normalized content.""" + if max_chars <= 0: + max_chars = FALLBACK_MAX_TEXT_LENGTH + normalized = " ".join((text or "").split()) + if not normalized: + return [] + if len(normalized) <= max_chars: + return [normalized] + expanded: List[str] = [] + for sentence in filter(None, (s.strip() for s in re.split(r"(?<=[.!?;:,])\s+", normalized))): + if len(sentence) <= max_chars: + expanded.append(sentence) + else: + expanded.extend(_split_oversized_sentence(sentence, max_chars)) + return _pack_under_cap(expanded, max_chars) + + +def _pack_audio_files_for_delivery(audio_paths: List[str], profile: AudioDeliveryProfile) -> List[List[str]]: + """Group final-encoded chunks under the size target; never mixes suffixes (can't concat-copy).""" + groups: List[List[str]] = [] + current: List[str] = [] + current_size, current_suffix = 0, "" + for path in audio_paths: + size, suffix = Path(path).stat().st_size, Path(path).suffix.lower() + if current and (current_size + size > profile.target_file_bytes or suffix != current_suffix): + groups.append(current) + current, current_size = [], 0 + current.append(path) + current_size, current_suffix = current_size + size, suffix + return groups + [current] if current else groups + + +# --- ffmpeg encoding helpers --- +def _ffmpeg_run( + ffmpeg: str, args: List[str], *, timeout: int = 30, check: bool = False, capture: bool = True, +) -> subprocess.CompletedProcess: + """Run ``ffmpeg <args>`` headless (no stdin, hidden window on Windows).""" + return subprocess.run([ffmpeg, *args], capture_output=capture, check=check, timeout=timeout, + stdin=subprocess.DEVNULL, creationflags=windows_hide_flags()) + + +def _remove_quietly(path: Optional[str]) -> None: + """Best-effort unlink (missing/locked files are ignored); None is a no-op.""" + if path: + try: + os.remove(path) + except OSError: + pass + + +def _wav_sidecar_path(output_path: str) -> str: + """Path a WAV-native engine writes to before conversion to *output_path*'s format.""" + return output_path if output_path.endswith(".wav") else output_path.rsplit(".", 1)[0] + ".wav" + + +def _finalize_wav_output(wav_path: str, output_path: str) -> str: + """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") + if not ffmpeg: + os.rename(wav_path, output_path) + return output_path + _ffmpeg_run(ffmpeg, ["-i", wav_path, "-y", "-loglevel", "error", output_path], + check=True, capture=False) + _remove_quietly(wav_path) + return output_path + + +def _wrap_pcm_as_wav( + pcm_bytes: bytes, sample_rate: int = GEMINI_TTS_SAMPLE_RATE, + channels: int = GEMINI_TTS_CHANNELS, sample_width: int = GEMINI_TTS_SAMPLE_WIDTH) -> bytes: + """Wrap raw signed-little-endian PCM (e.g. Gemini's L16) with a minimal WAV RIFF header.""" + block_align = channels * sample_width + fmt_chunk = struct.pack("<4sIHHIIHH", b"fmt ", 16, 1, channels, sample_rate, + sample_rate * block_align, block_align, sample_width * 8) + data_chunk_header = struct.pack("<4sI", b"data", len(pcm_bytes)) + riff_size = 4 + len(fmt_chunk) + len(data_chunk_header) + len(pcm_bytes) + riff_header = struct.pack("<4sI4s", b"RIFF", riff_size, b"WAVE") + return riff_header + fmt_chunk + data_chunk_header + pcm_bytes + + +def _write_wav_bytes_as(wav_bytes: bytes, output_path: str) -> str: + """Write in-memory WAV to *output_path*, ffmpeg-converting to its container. ``.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) + return output_path + with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp: + tmp.write(wav_bytes) + wav_path = tmp.name + try: + ffmpeg = shutil.which("ffmpeg") + if ffmpeg: + opus = _OPUS_VOICE_ARGS if output_path.lower().endswith(".ogg") else [] + result = _ffmpeg_run( + ffmpeg, ["-i", wav_path, *opus, "-y", "-loglevel", "error", output_path]) + if result.returncode != 0: + stderr = result.stderr.decode("utf-8", errors="ignore")[:300] + raise RuntimeError(f"ffmpeg conversion failed: {stderr}") + else: + logger.warning("ffmpeg not found; writing raw WAV to %s (extension may be misleading)", output_path) + shutil.copyfile(wav_path, output_path) + finally: + _remove_quietly(wav_path) + return output_path + + +def _convert_to_opus(mp3_path: str) -> Optional[str]: + """Convert any ffmpeg-readable audio file to OGG Opus next to it; None on failure.""" + from gateway.platforms.base import transcode_to_ogg_opus + return transcode_to_ogg_opus(mp3_path, bitrate="48k", timeout=30, output_path=mp3_path.rsplit(".", 1)[0] + ".ogg") + + +# --- Container sniffing / repair --- +# Several backends ignore the requested opus format (Edge/xAI emit MP3, Piper WAV, some +# OpenAI-compatible servers ignore response_format="opus"), which breaks native voice bubbles: +# sniff the magic bytes once after synthesis and repair when they don't match the extension. + +def _sniff_audio_container(path: str) -> str: + """Return a container id ('ogg', 'wav', 'mp3', 'flac', ...) or 'unknown'.""" + from tools.audio_container import sniff_container + try: + with open(path, "rb") as fh: + return sniff_container(fh.read(12)) or "unknown" + except OSError: + return "unknown" + + +def _repair_ogg_container(file_str: str) -> str: + """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.""" + container = _sniff_audio_container(file_str) if file_str.endswith(".ogg") else "ogg" + if container in ("ogg", "unknown"): + return file_str + logger.info("TTS wrote %s bytes into a .ogg path (%s) — transcoding to real Ogg/Opus", container, file_str) + from gateway.platforms.base import transcode_to_ogg_opus + repaired = transcode_to_ogg_opus(file_str, bitrate="48k", timeout=30, output_path=file_str) + if repaired: + return repaired + honest = f"{file_str[:-4]}.{container}" + try: + os.replace(file_str, honest) + except OSError: + return file_str + logger.warning("Could not transcode %s to Ogg/Opus — renamed to %s so the " + "file is delivered with its real format", file_str, honest) + return honest + + +# --- 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 (never byte-joined). 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: + if os.path.abspath(audio_paths[0]) != os.path.abspath(output_path): + shutil.copyfile(audio_paths[0], output_path) + return output_path + ffmpeg = shutil.which("ffmpeg") + if not ffmpeg: + return None + destination = Path(output_path) + destination.parent.mkdir(parents=True, exist_ok=True) + concat_path = destination.with_name(f".{destination.name}.{uuid.uuid4().hex}.concat.txt") + temp_output = destination.with_name(f".{destination.stem}.{uuid.uuid4().hex}.combining{destination.suffix}") + try: + entries = "".join(f"file {shlex.quote(os.path.abspath(p))}\n" for p in audio_paths) + concat_path.write_text(entries, encoding="utf-8") + args = ["-y", "-loglevel", "error", "-f", "concat", "-safe", "0", "-i", str(concat_path), "-vn"] + suffix = destination.suffix.lower() + if voice_compatible or suffix in {".ogg", ".opus"}: + args += ["-c:a", "libopus", "-ac", "1", "-b:a", "64k", "-vbr", "off"] + elif suffix == ".mp3" and all(Path(path).suffix.lower() == ".mp3" for path in audio_paths): + args += ["-c:a", "copy"] + result = _ffmpeg_run(ffmpeg, [*args, str(temp_output)], timeout=120) + if result.returncode == 0 and temp_output.exists() and temp_output.stat().st_size > 0: + os.replace(temp_output, destination) + return str(destination) + logger.warning("ffmpeg audio combine failed: %s", result.stderr.decode("utf-8", errors="ignore")[:500]) + except (OSError, subprocess.TimeoutExpired) as exc: + logger.warning("ffmpeg audio combine failed: %s", exc) + finally: + for path in (concat_path, temp_output): + _remove_quietly(path) + return None + + +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 under the hard upload limit -> ``(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: + size = Path(path).stat().st_size + if size > profile.max_file_bytes: + raise ValueError( + f"Final-encoded TTS chunk exceeds {profile.platform} delivery " + f"limit ({size} > {profile.max_file_bytes} bytes): {path}") + base = Path(output_path) + scratch_outputs: List[str] = [] + combined_any, combine_index = False, 0 + + def emit(group: List[str]) -> List[str]: + nonlocal combined_any, combine_index + if len(group) == 1: + return list(group) + combine_index += 1 + scratch = base.with_name(f".{base.stem}.delivery{combine_index:03d}.{uuid.uuid4().hex}{base.suffix}") + combined = _concat_audio_files(group, str(scratch), voice_compatible=voice_compatible) + if not combined: + return list(group) + scratch_outputs.append(combined) + if Path(combined).stat().st_size <= profile.max_file_bytes: + combined_any = True + return [combined] + _remove_quietly(combined) + midpoint = max(1, len(group) // 2) + return emit(group[:midpoint]) + emit(group[midpoint:]) + groups = _pack_audio_files_for_delivery(audio_paths, profile) + packed = [path for group in groups for path in emit(group)] + final_paths: List[str] = [] + for index, source in enumerate(packed, start=1): + destination = base + if len(packed) > 1: + destination = base.with_name(f"{base.stem}.part{index:02d}{Path(source).suffix or base.suffix}") + if os.path.abspath(source) != os.path.abspath(destination): + destination.parent.mkdir(parents=True, exist_ok=True) + os.replace(source, destination) + if destination.stat().st_size > profile.max_file_bytes: + raise ValueError(f"Final TTS deliverable exceeds {profile.platform} delivery limit: {destination}") + final_paths.append(str(destination)) + try: + return final_paths, combined_any + finally: + for scratch in scratch_outputs: + if scratch not in final_paths: + _remove_quietly(scratch) diff --git a/tools/tts_tool_local.py b/tools/tts_tool_local.py new file mode 100644 index 0000000000000000000000000000000000000000..96a08d2445afe07de01b52692e58d1a41c725ebb --- /dev/null +++ b/tools/tts_tool_local.py @@ -0,0 +1,194 @@ +"""Local on-device TTS engines for ``tools.tts_tool``: NeuTTS, Piper, KittenTTS. + +All three synthesize WAV natively; :func:`_finalize_wav_output` converts/renames to the requested +container. Piper and KittenTTS keep loaded models in small LRU caches registered in +``_LOCAL_TTS_MODEL_CACHES`` so warm/release can pre-load or drop them. ``_import_piper`` / +``_import_kittentts`` are resolved through the origin module at call time (test monkeypatches). +""" + +from __future__ import annotations + +import logging +import subprocess +import sys +from pathlib import Path +from typing import Any, Callable, Dict, Tuple + +from tools.tts_tool_delivery import _finalize_wav_output, _origin, _section, _wav_sidecar_path + +logger = logging.getLogger("tools.tts_tool") + +DEFAULT_KITTENTTS_MODEL = "KittenML/kitten-tts-nano-0.8-int8" # 25MB +DEFAULT_KITTENTTS_VOICE = "Jasper" +DEFAULT_PIPER_VOICE = "en_US-lessac-medium" # balanced size/quality +_NEUTTS_SAMPLES = Path(__file__).parent / "neutts_samples" + +# --- Bounded model caches --- +# Each entry is a whole loaded model (tens of MB); unbounded, one would be pinned per distinct +# voice for the process lifetime. Most sessions use one or two voices; a cold reload is cheap. +_TTS_MODEL_CACHE_MAX = 3 + +# Provider name -> the cache it populates (warm/release in tts_tool_lifecycle; a new local engine +# adds a row here plus a loader in _local_tts_warmers()). Piper keyed on absolute .onnx path +# (+cuda flag); KittenTTS on model name. +_piper_voice_cache: Dict[str, Any] = {} +_kittentts_model_cache: Dict[str, Any] = {} +_LOCAL_TTS_MODEL_CACHES: Dict[str, Dict[str, Any]] = { + "piper": _piper_voice_cache, "kittentts": _kittentts_model_cache} + + +def _tts_cache_get_or_load(cache: Dict[str, Any], key: str, load: Callable[[], Any]) -> Any: + """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] + value = load() + cache[key] = value + while len(cache) > _TTS_MODEL_CACHE_MAX: + cache.pop(next(iter(cache)), None) + return value + + +def _run_helper(cmd: list, timeout: int) -> subprocess.CompletedProcess: + return subprocess.run( + cmd, capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=timeout, stdin=subprocess.DEVNULL, + ) + + +# --- 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 {} + wav_path = _wav_sidecar_path(output_path) + cmd = [ + sys.executable, str(Path(__file__).parent / "neutts_synth.py"), + "--text", text, + "--out", wav_path, + "--ref-audio", neutts_config.get("ref_audio", "") or str(_NEUTTS_SAMPLES / "jo.wav"), + "--ref-text", neutts_config.get("ref_text", "") or str(_NEUTTS_SAMPLES / "jo.txt"), + "--model", neutts_config.get("model", "neuphonic/neutts-air-q4-gguf"), + "--device", neutts_config.get("device", "cpu")] + result = _run_helper(cmd, 120) + if result.returncode != 0: # the synth script reports success lines as "OK:" on stderr too + error_lines = [l for l in result.stderr.strip().splitlines() if not l.startswith("OK:")] + raise RuntimeError(f"NeuTTS synthesis failed: {chr(10).join(error_lines) or 'unknown error'}") + return _finalize_wav_output(wav_path, output_path) + + +# --- Piper (local neural VITS, 44 languages) --- +def _get_piper_voices_dir() -> Path: + """``<HERMES_HOME>/cache/piper-voices/`` so voice downloads follow profile boundaries.""" + from hermes_constants import get_hermes_dir + root = Path(get_hermes_dir("cache/piper-voices", "piper_voices_cache")) + root.mkdir(parents=True, exist_ok=True) + return root + + +def _resolve_piper_voice_path(voice: str, download_dir: Path) -> str: + """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(): + return str(candidate) + cached = download_dir / f"{voice}.onnx" + if cached.exists() and (download_dir / f"{voice}.onnx.json").exists(): + return str(cached) + logger.info("[Piper] Downloading voice '%s' to %s (first use)", voice, download_dir) + try: + result = _run_helper( + [sys.executable, "-m", "piper.download_voices", voice, "--download-dir", str(download_dir)], 300, + ) + except subprocess.TimeoutExpired as exc: + raise RuntimeError(f"Piper voice download timed out after 300s for '{voice}'") from exc + if result.returncode != 0: + stderr = (result.stderr or "").strip() or "no stderr output" + raise RuntimeError(f"Piper voice download failed for '{voice}': {stderr[:400]}") + if not cached.exists(): + raise RuntimeError( + f"Piper voice download completed but {cached} is missing — " + f"check voice name (see: https://github.com/OHF-Voice/piper1-gpl/" + f"blob/main/docs/VOICES.md)") + return str(cached) + + +def _load_piper_voice_for_config(tts_config: Dict[str, Any]) -> Tuple[Any, Dict[str, Any]]: + """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 + download_dir = Path(piper_config.get("voices_dir") or _get_piper_voices_dir()).expanduser() + download_dir.mkdir(parents=True, exist_ok=True) + use_cuda = bool(piper_config.get("use_cuda", False)) + model_path = _resolve_piper_voice_path(voice_name, download_dir) + + def _load_piper_voice(): + logger.info("[Piper] Loading voice: %s", model_path) + v = PiperVoice.load(model_path, use_cuda=use_cuda) + logger.info("[Piper] Voice loaded") + return v + + # speaker_id is applied per call via syn_config, so one instance serves every speaker. + cache_key = f"{model_path}::cuda={use_cuda}" + return _tts_cache_get_or_load(_piper_voice_cache, cache_key, _load_piper_voice), piper_config + + +_PIPER_ADVANCED_KNOBS = ("length_scale", "noise_scale", "noise_w_scale", "volume", "normalize_audio", "speaker_id") + + +def _generate_piper_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str: + import wave + voice, piper_config = _load_piper_voice_for_config(tts_config) + # Bad speaker_id drops to 0 (Piper's default); bools are rejected (they'd coerce to 1/0). + _raw_speaker = piper_config.get("speaker_id", 0) + speaker_id = _raw_speaker if type(_raw_speaker) is int else 0 + # Only build a SynthesisConfig when an advanced knob is configured, so we don't depend on a + # newer piper-tts than the user's unless we must. + syn_config = None + if any(k in piper_config for k in _PIPER_ADVANCED_KNOBS): + try: + from piper import SynthesisConfig # type: ignore + syn_config = SynthesisConfig( + length_scale=float(piper_config.get("length_scale", 1.0)), + noise_scale=float(piper_config.get("noise_scale", 0.667)), + noise_w_scale=float(piper_config.get("noise_w_scale", 0.8)), + volume=float(piper_config.get("volume", 1.0)), + normalize_audio=bool(piper_config.get("normalize_audio", True)), + speaker_id=speaker_id) + except ImportError: + logger.warning("[Piper] SynthesisConfig not available in this piper-tts version — advanced knobs ignored") + wav_path = _wav_sidecar_path(output_path) + with wave.open(wav_path, "wb") as wav_file: + if syn_config is not None: + voice.synthesize_wav(text, wav_file, syn_config=syn_config) + else: + voice.synthesize_wav(text, wav_file) + return _finalize_wav_output(wav_path, output_path) + + +# --- 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)``.""" + KittenTTS = _origin()._import_kittentts() + kt_config = _section(tts_config, "kittentts") + model_name = kt_config.get("model", DEFAULT_KITTENTTS_MODEL) + + def _load_kittentts_model(): + logger.info("[KittenTTS] Loading model: %s", model_name) + m = KittenTTS(model_name) + logger.info("[KittenTTS] Model loaded successfully") + return m + + return _tts_cache_get_or_load(_kittentts_model_cache, model_name, _load_kittentts_model), kt_config + + +def _generate_kittentts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str: + model, kt_config = _load_kittentts_model_for_config(tts_config) + audio = model.generate( # numpy array at 24kHz + text, voice=kt_config.get("voice", DEFAULT_KITTENTTS_VOICE), + speed=kt_config.get("speed", 1.0), clean_text=kt_config.get("clean_text", True)) + import soundfile as sf + wav_path = _wav_sidecar_path(output_path) + sf.write(wav_path, audio, 24000) + return _finalize_wav_output(wav_path, output_path) diff --git a/tools/tts_tool_plugins.py b/tools/tts_tool_plugins.py new file mode 100644 index 0000000000000000000000000000000000000000..12eeda9be1c9c60d90ac0e16d3dc223e97420b81 --- /dev/null +++ b/tools/tts_tool_plugins.py @@ -0,0 +1,91 @@ +"""Plugin-registered TTS providers for ``tools.tts_tool``: routes ``tts.provider: <name>`` values +that are neither built-in nor ``type: command`` to a plugin :class:`agent.tts_provider.TTSProvider`. +Discovery goes through ``hermes_cli.plugins._ensure_plugins_discovered`` (imported lazily so the +tool module stays importable without the plugin machinery). +""" + +from __future__ import annotations + +import logging +from typing import Any, Dict, Optional + +from tools.tts_command_provider import ( + BUILTIN_TTS_PROVIDERS, DEFAULT_COMMAND_TTS_OUTPUT_FORMAT, _get_named_provider_config, + _is_command_provider_config) + +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 (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: + from hermes_cli.plugins import _ensure_plugins_discovered + _ensure_plugins_discovered() + plugin_provider = get_provider(key) + if plugin_provider is None and retry: + _ensure_plugins_discovered(force=True) + plugin_provider = get_provider(key) + return plugin_provider + + +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 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. + + Resolution invariants enforced here (matches issue #30398): + 1. The caller is responsible for the elif chain that handles ``edge``/``openai``/etc.; this function + explicitly rejects those names defensively. 2. 3. Plugin dispatch fires only when ``provider`` matches a + registered :class:`TTSProvider` whose ``name`` equals the configured value. Unknown names return None + (caller falls through to Edge default). See #17843. + """ + key = (provider or "").lower().strip() + if not key or key in BUILTIN_TTS_PROVIDERS: + return None + if _is_command_provider_config(_get_named_provider_config(tts_config, key)): + return None + try: + plugin_provider = _lookup_plugin_provider(key, retry=True) + except Exception as exc: # noqa: BLE001 — discovery failure is non-fatal + logger.debug("tts plugin dispatch skipped (discovery failed): %s", exc) + return None + if plugin_provider is None: + return None + # voice/model/speed/format are optional per TTSProvider.synthesize; providers default on None. + cfg = tts_config if isinstance(tts_config, dict) else {} + voice, model, speed = cfg.get("voice"), cfg.get("model"), cfg.get("speed") + fmt = cfg.get("output_format", DEFAULT_COMMAND_TTS_OUTPUT_FORMAT) + logger.info("Generating speech with plugin TTS provider '%s'...", key) + written = plugin_provider.synthesize( + text, output_path, voice=voice if isinstance(voice, str) and voice else None, + model=model if isinstance(model, str) and model else None, + speed=float(speed) if isinstance(speed, (int, float)) else None, + format=str(fmt).lower() if fmt else "mp3") + return written if isinstance(written, str) and written else output_path + + +def _plugin_provider_is_voice_compatible(provider: str) -> bool: + """True when the registered plugin provider opts into voice-bubble delivery (any failure -> False).""" + key = (provider or "").lower().strip() + if not key or key in BUILTIN_TTS_PROVIDERS: + return False + try: + plugin_provider = _lookup_plugin_provider(key, discover=False) + return plugin_provider is not None and bool(plugin_provider.voice_compatible) + except Exception as exc: # noqa: BLE001 + logger.debug("tts plugin voice_compatible check failed for '%s': %s", key, exc) + return False + + +def _plugin_provider_is_available(provider: str) -> bool: + """``check_fn`` leg for plugin names: discovered provider reports ``is_available()``; any failure is False.""" + try: + plugin = _lookup_plugin_provider(provider) + return bool(plugin and plugin.is_available()) + except Exception: + return False diff --git a/tools/tts_tool_speaker.py b/tools/tts_tool_speaker.py new file mode 100644 index 0000000000000000000000000000000000000000..2d05938a7ec738b5d26ada70439c1b8d33a50529 --- /dev/null +++ b/tools/tts_tool_speaker.py @@ -0,0 +1,353 @@ +"""Speaker-side streaming pipeline: ``stream_tts_to_speaker``. + +Turns a queue of LLM text deltas into audio the moment each sentence is complete. Two paths +share the sentence cutter (``tools.tts_streaming``): :class:`_StreamerPlayback` for a registered +chunked streamer (prefetch thread per sentence, one FIFO playback worker through a sounddevice +OutputStream or temp WAV + system player) and :class:`_SyncSentencePipeline` for every other +provider (per-sentence ``text_to_speech_tool`` on a single-thread executor, overlapped with +playback). Origin seams are resolved through :func:`_origin` at call time. +""" + +from __future__ import annotations + +import contextlib +import logging +import os +import platform +import queue +import tempfile +import threading +from concurrent.futures import Future, ThreadPoolExecutor +from typing import Callable, Iterable, Iterator, List, Optional + +from tools.tts_text_normalize import _strip_markdown_for_tts +from tools.tts_tool_delivery import _origin, _remove_quietly as _unlink_quietly + +logger = logging.getLogger("tools.tts_tool") + +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(): + break + buf = leftover + chunk + aligned_len = len(buf) - (len(buf) % 2) + if aligned_len >= 2: + yield buf[:aligned_len] + leftover = buf[aligned_len:] + if leftover and pad_tail: + yield b"\x00" + + +def _play_via_tempfile(audio_iter: Iterable[bytes], stop_evt: threading.Event, sample_rate: int = 24000) -> None: + """Write PCM chunks to a temp WAV file and play it with the system player.""" + tmp = tmp_path = None + try: + import wave + tmp = tempfile.NamedTemporaryFile(suffix=".wav", delete=False) + tmp_path = tmp.name + with wave.open(tmp, "wb") as wf: + wf.setnchannels(1) + wf.setsampwidth(2) # 16-bit + wf.setframerate(sample_rate) + for aligned in _align_int16_chunks(audio_iter, stop_evt): + wf.writeframes(aligned) + # wave.open() on a file object does NOT close it; on Windows the open write + # handle blocks the player and the unlink below (WinError 32). + tmp.close() + from tools.voice_mode import play_audio_file + play_audio_file(tmp_path) + except Exception as exc: + logger.warning("Temp-file TTS fallback failed: %s", exc) + finally: + if tmp is not None: + with contextlib.suppress(Exception): + tmp.close() # idempotent; ensures close on early error + _unlink_quietly(tmp_path) + + +def _drain_chunks(chunk_queue: "queue.Queue[Optional[bytes]]") -> List[bytes]: + """Collect one sentence's PCM chunks up to the ``None`` sentinel.""" + return list(iter(chunk_queue.get, None)) + + +class _SyncSentencePipeline: + """Overlap per-sentence synthesis with playback for non-streaming providers. + + 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 + self._queue: "queue.Queue[Optional[tuple[str, Future]]]" = queue.Queue(maxsize=max(1, lookahead)) + self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="tts-sync-synth") + self._player = threading.Thread(target=self._drain, name="tts-sync-play", daemon=True) + self._player.start() + + def speak(self, cleaned: str) -> None: + """Queue one sentence. Blocks only when the lookahead bound is full.""" + if not self._stop.is_set(): + self._queue.put((cleaned, self._executor.submit(self._synthesize_to_tmp, cleaned))) + + def close(self) -> None: + """Flush queued sentences in order (skipped if stopped), then join.""" + self._queue.put(None) + self._player.join() + self._executor.shutdown(wait=True) + + def _synthesize_to_tmp(self, cleaned: str) -> Optional[str]: + if self._stop.is_set(): + return None + tmp_path = None + try: + fd, tmp_path = tempfile.mkstemp(suffix=".mp3") + os.close(fd) + _origin().text_to_speech_tool(text=cleaned, output_path=tmp_path) + return tmp_path + except Exception as exc: + logger.warning("Sync per-sentence TTS synthesis failed: %s", exc) + _unlink_quietly(tmp_path) + return None + + def _drain(self) -> None: + for _sentence, future in iter(self._queue.get, None): + tmp_path = None + try: + tmp_path = future.result() + if tmp_path and not self._stop.is_set() and os.path.isfile(tmp_path) and os.path.getsize(tmp_path) > 0: + from tools.voice_mode import play_audio_file + play_audio_file(tmp_path) + except Exception as exc: + logger.warning("Sync per-sentence TTS failed: %s", exc) + finally: + _unlink_quietly(tmp_path) + + +class _StreamerPlayback: + """Prefetch + FIFO playback for a chunked :class:`StreamingTTSProvider`. + + ``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.""" + + _MAX_REINIT = 3 + _CHUNK_QUEUE_MAX = 64 + + def __init__(self, streamer, stop_event: threading.Event): + self.streamer, self.stop_event = streamer, stop_event + self.output_stream = self._open_output_stream() + self._audio_queue: "queue.Queue[Optional[queue.Queue[Optional[bytes]]]]" = queue.Queue() + self._prefetch_threads: List[threading.Thread] = [] + self._prefetch_sem = threading.Semaphore(3) + self._worker = threading.Thread(target=self._playback_worker, daemon=True) + self._worker.start() + + def _create_output_stream(self): + sd = _origin()._import_sounddevice() + stream = sd.OutputStream( + samplerate=self.streamer.sample_rate, channels=self.streamer.channels, dtype="int16") + stream.start() + return stream + + def _open_output_stream(self): + # macOS skips sounddevice entirely: PortAudio/CoreAudio init triggers a + # kTCCServiceMediaLibrary prompt though output needs no media-library access. + # None routes every sentence through tempfile -> afplay. + # See PR #62601 / #13291. + if platform.system() == "Darwin": + return None + try: + return self._create_output_stream() + except (ImportError, OSError) as exc: + logger.debug("sounddevice not available, streamer→tempfile: %s", exc) + except Exception as exc: + logger.warning("sounddevice OutputStream failed: %s", exc) + return None + + def close_output_stream(self) -> None: + """Always release the device so a later stream can open it.""" + if self.output_stream is not None: + with contextlib.suppress(Exception): + self.output_stream.stop() + self.output_stream.close() + + def speak(self, text: str) -> None: + """Start ``streamer.stream(text)`` and prefetch its chunks immediately.""" + try: + audio_iter = self.streamer.stream(text) + except Exception as exc: + logger.warning("Streaming TTS synthesis failed: %s", exc) + return + self._prefetch_sem.acquire() + chunk_queue: "queue.Queue[Optional[bytes]]" = queue.Queue(maxsize=self._CHUNK_QUEUE_MAX) + self._audio_queue.put(chunk_queue) + self._prefetch_threads.append(threading.Thread( + target=self._consume_to_queue, args=(audio_iter, chunk_queue), daemon=True)) + self._prefetch_threads[-1].start() + + def _consume_to_queue(self, audio_iter: Iterator[bytes], chunk_queue: "queue.Queue[Optional[bytes]]") -> None: + try: + for chunk in audio_iter: + if self.stop_event.is_set(): + logger.info("TTS CUT: prefetch cancelled (stop_event set mid-sentence) — partial audio only") + break + chunk_queue.put(chunk, timeout=30.0) + except Exception as exc: + logger.warning("TTS CUT: streaming TTS prefetch failed mid-sentence (partial audio only): %s", exc) + finally: + chunk_queue.put(None) # sentinel: no more chunks + self._prefetch_sem.release() + + def _play_sentence_via_tempfile(self, chunk_queue) -> None: + _play_via_tempfile(_drain_chunks(chunk_queue), self.stop_event, self.streamer.sample_rate) + + def _for_each_sentence(self, play: Callable[[queue.Queue], None]) -> None: + """Feed queued sentences to *play* in order until the end sentinel; stopped sentences are skipped.""" + for chunk_queue in iter(self._audio_queue.get, None): + if not self.stop_event.is_set(): + play(chunk_queue) + + def _write_pcm(self, buf: bytes) -> None: + self._current_stream.write(self._np.frombuffer(buf, dtype="<i2").reshape(-1, 1)) + + def _recover_stream(self) -> bool: + """Close the broken PortAudio stream and open a fresh one after a failed write; False once + ``_MAX_REINIT`` is exhausted (remaining sentences go through temp files).""" + if self._reinit_count >= self._MAX_REINIT: + logger.warning( + "TTS: PortAudio reinit exhausted after %d attempts, falling back to tempfile for remaining sentences", + self._MAX_REINIT) + self._current_stream = None + return False + self._reinit_count += 1 + self.close_output_stream() + try: + self.output_stream = self._create_output_stream() + logger.info("TTS: PortAudio output stream reinitialized after error") + except Exception as exc: + logger.warning("TTS: PortAudio stream reinit failed: %s", exc) + self.output_stream = None + self._current_stream = self.output_stream + return self._current_stream is not None + + def _play_sentence_via_stream(self, chunk_queue) -> None: + """Write one sentence's PCM to PortAudio; after an unrecoverable write failure the rest is dropped.""" + if self._current_stream is None: + self._play_sentence_via_tempfile(chunk_queue) + return + 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 + with contextlib.suppress(Exception): + self._write_pcm(aligned) + + def _playback_worker(self) -> None: + """Single consumer: play audio segments from the queue in order.""" + if self.output_stream is None: + self._for_each_sentence(self._play_sentence_via_tempfile) + return + import numpy as _np + try: + from tools.voice_mode import mark_audio_output_active + except Exception: + mark_audio_output_active = lambda _active: None # noqa: E731 + self._np, self._reinit_count, self._current_stream = _np, 0, self.output_stream + mark_audio_output_active(True) + try: + self._for_each_sentence(self._play_sentence_via_stream) + finally: + mark_audio_output_active(False) + + def finish(self) -> None: + """Send the end sentinel, then wait for playback and prefetch threads.""" + self._audio_queue.put(None) + self._worker.join(timeout=300.0) + for t in self._prefetch_threads: + t.join(timeout=10.0) + self.close_output_stream() + + +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): + """Consume text deltas from *text_queue*, cut into sentences, speak each the moment it's ready. + + 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 + playback: Optional[_StreamerPlayback] = None + try: + tts_config = origin._load_tts_config() + # Prefer a chunked streamer for low time-to-first-audio; otherwise per-sentence sync + # synthesis (universal — edge + every non-streamer). + from tools.tts_streaming import SentenceChunker, resolve_streaming_provider + streamer = resolve_streaming_provider(tts_config, preferred=provider) + stream_max_len = 0 + if streamer is None: + sync_pipeline = _SyncSentencePipeline(stop_event) + else: + with contextlib.suppress(Exception): + stream_max_len = origin._resolve_max_text_length( + provider or origin._get_provider(tts_config), tts_config) + playback = _StreamerPlayback(streamer, stop_event) + chunker = SentenceChunker() + spoken_sentences: list[str] = [] # skip duplicate/near-duplicate sentences (LLM repetition) + + def _speak_sentence(sentence: str) -> None: + if stop_event.is_set(): + return + cleaned = _strip_markdown_for_tts(sentence).strip() + if not cleaned: + return + cleaned_lower = cleaned.lower().rstrip(".!,") + if any(prev.lower().rstrip(".!,") == cleaned_lower for prev in spoken_sentences): + return + spoken_sentences.append(cleaned) + if display_callback is not None: + display_callback(sentence) # raw sentence on screen before TTS processing + if sync_pipeline is not None: + sync_pipeline.speak(cleaned) + return + if stream_max_len and len(cleaned) > stream_max_len: + cleaned = cleaned[:stream_max_len] + playback.speak(cleaned) + while not stop_event.is_set(): + try: + delta = text_queue.get(timeout=0.5) + except queue.Empty: + delta = "" # idle producer: flush a long buffer instead of sitting on it + sentences = chunker.flush() if len(chunker.buf) > 100 else () + else: + sentences = chunker.flush() if delta is None else chunker.feed(delta) + for sentence in sentences: + _speak_sentence(sentence) + if delta is None: + break + with contextlib.suppress(queue.Empty): + while True: + text_queue.get_nowait() + except Exception as exc: + logger.warning("Streaming TTS pipeline error: %s", exc) + finally: + # Flush the sync pipeline first: queued sentences finish playing (or are skipped when + # stop_event is set) BEFORE tts_done_event fires, so continuous voice mode never reopens + # the mic over its own voice. The end sentinel lives in finally: so an exception in the + # text pump still lets the playback worker exit. + if sync_pipeline is not None: + with contextlib.suppress(Exception): + sync_pipeline.close() + if playback is not None: + playback.finish() + tts_done_event.set() diff --git a/tools/url_safety.py b/tools/url_safety.py new file mode 100644 index 0000000000000000000000000000000000000000..539362ffa5885cbe9de61fddfbdeb94300b1bb13 --- /dev/null +++ b/tools/url_safety.py @@ -0,0 +1,555 @@ +"""URL safety checks — blocks requests to private/internal network addresses (SSRF). + +``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 +import logging +import os +import socket +import asyncio +import re +from contextlib import contextmanager +from typing import Any, Optional +from urllib.parse import parse_qsl, quote, unquote, urljoin, urlparse, urlsplit, urlunsplit + +from hermes_constants import get_hermes_home_override +from utils import is_truthy_value + +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 + + +def _proxy_is_configured() -> bool: + return any(os.environ.get(v) for v in _PROXY_ENV_VARS) + + +def normalize_url_for_request(url: str) -> str: + """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 + + # 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, hostname = parsed.netloc, parsed.hostname + if hostname: + try: + ascii_host = hostname.encode("idna").decode("ascii") + except UnicodeError: + ascii_host = hostname + if ascii_host != hostname: + netloc = netloc.replace(hostname, ascii_host, 1) + 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 +# English words that double as page facets (``code``, ``key``, ``auth``, +# ``session``, ``sig``) are EXCLUDED so ordinary browsing is not blocked. +_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"}) + + +def sensitive_query_param_name(url: str) -> Optional[str]: + """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: + parsed = urlsplit(url.strip()) + except ValueError: + return None + if parsed.scheme.lower() not in _HTTP_SCHEMES or not parsed.query: + 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, 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) + "169.254.169.253", # Azure IMDS wire server + "100.100.100.200", # Alibaba Cloud metadata +) +_ALWAYS_BLOCKED_IPS = frozenset( + {ipaddress.ip_address(ip) for ip in _METADATA_V4} + | {ipaddress.ip_address("::ffff:" + ip) for ip in _METADATA_V4} + | {ipaddress.ip_address("fd00:ec2::254")} # AWS metadata (IPv6) +) +# 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 +# ipaddress — must be blocked explicitly (Tailscale/WireGuard, cloud internal nets). +_CGNAT_NETWORK = ipaddress.ip_network("100.64.0.0/10") + +# Global toggle cache (process lifetime; see _global_allow_private_urls). +_allow_private_resolved, _cached_allow_private = False, False + + +def _global_allow_private_urls() -> bool: + """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, _cached_allow_private = True, _resolve_allow_private_urls() + return _cached_allow_private + + +def _resolve_allow_private_urls() -> bool: + """Resolve the effective private-URL toggle from the active config scope.""" + env_val = os.getenv("HERMES_ALLOW_PRIVATE_URLS", "").strip().lower() + if env_val in {"true", "1", "yes"}: + 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() + for section in ("security", "browser"): # preferred, then legacy + block = cfg.get(section, {}) + if isinstance(block, dict) and is_truthy_value(block.get("allow_private_urls"), default=False): + 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 = _cached_allow_private = False + + +def _normalize_hostname(host: Optional[str]) -> str: + return (host or "").strip().lower().rstrip(".") + + +def _parse_ip(hostname: str) -> Optional[_IPAddress]: + """IP object for a literal-IP hostname, else None.""" + try: + return ipaddress.ip_address(hostname) + except ValueError: + return None + + +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 still unparseable — each caller decides skip/fail/raise.""" + for _family, _, _, _, sockaddr in addr_info: + raw = sockaddr[0] + ip_str = raw.split("%")[0] + yield raw, ip_str, _parse_ip(ip_str) + + +def _getaddrinfo(hostname: str, port: Optional[int] = None): + return socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM) + + +def _is_always_blocked_ip(ip: _IPAddress) -> bool: + return ip in _ALWAYS_BLOCKED_IPS or any(ip in net for net in _ALWAYS_BLOCKED_NETWORKS) + + +def _is_blocked_ip(ip: _IPAddress) -> bool: + """Return True if the IP should be blocked for SSRF protection.""" + # IPv4-mapped IPv6 (``::ffff:x.x.x.x``) is classified by its embedded IPv4. + if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None: + ip = ip.ipv4_mapped + return (ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved + or ip.is_multicast or ip.is_unspecified or ip in _CGNAT_NETWORK) + + +def is_always_blocked_url(url: str) -> bool: + """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) + continue + if _is_always_blocked_ip(resolved): + logger.warning( + "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) + return False + + +def _allows_private_ip_resolution(hostname: str, scheme: str) -> bool: + """Return True when a trusted HTTPS hostname may bypass IP-class blocking.""" + return scheme == "https" and hostname in _TRUSTED_PRIVATE_IP_HOSTS + + +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 + 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): + return "private/internal address" + return None + + +def is_safe_url(url: str) -> bool: + """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) + scheme = (parsed.scheme or "").strip().lower() + if scheme not in _HTTP_SCHEMES: + logger.warning("Blocked request — unsupported URL scheme: %s", scheme or "<empty>") + return False + if not hostname: + return False + + # Metadata hostnames are blocked BEFORE consulting the toggle. + 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: + # Sandbox/proxy environments may block direct DNS; when a proxy is + # configured, delegate resolution to it (metadata hostnames were already + # rejected above). Literal IPs need no DNS, so a failure on one is not a + # proxy symptom — keep them fail-closed. + 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) + 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) + return False + + +async def async_is_safe_url(url: str) -> bool: + """:func:`is_safe_url` with the blocking DNS work off the event loop.""" + return await asyncio.to_thread(is_safe_url, url) + + +class SSRFConnectionBlocked(ValueError): + """Raised when connect-time DNS resolution violates the URL safety policy.""" + + +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 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 + + +class _SSRFGuardedBackendBase: + """httpcore backend that re-resolves + validates at connect time and dials a vetted IP. + 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 + self._schemes_by_origin_var = schemes_by_origin_var + + def _connect_ips(self, host: str, port: int) -> list[str]: + 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: + return last_exc + return SSRFConnectionBlocked(f"Blocked request - DNS returned no usable IPs for: {host}") + + def connect_unix_socket(self, path: str, timeout: float | None = None, socket_options: Any = None) -> Any: + raise SSRFConnectionBlocked("Blocked Unix socket connection in SSRF-safe transport") + + +class _SSRFGuardedAsyncNetworkBackend(_SSRFGuardedBackendBase): + def __init__(self, schemes_by_origin_var: Any): + from httpcore._backends.auto import AutoBackend + super().__init__(AutoBackend(), schemes_by_origin_var) + + async def connect_tcp(self, host: str, port: int, timeout: float | None = None, + local_address: str | None = None, socket_options: Any = None) -> Any: + last_exc: Exception | None = None + 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 self._connect_errors() as exc: + last_exc = exc + raise self._no_usable_ips(host, last_exc) + + async def connect_unix_socket(self, path: str, timeout: float | None = None, socket_options: Any = None) -> Any: + raise SSRFConnectionBlocked("Blocked Unix socket connection in SSRF-safe transport") + + async def sleep(self, seconds: float) -> None: + await self._backend.sleep(seconds) + + +class _SSRFGuardedNetworkBackend(_SSRFGuardedBackendBase): + def __init__(self, schemes_by_origin_var: Any): + from httpcore._backends.sync import SyncBackend + super().__init__(SyncBackend(), schemes_by_origin_var) + + def connect_tcp(self, host: str, port: int, timeout: float | None = None, + local_address: str | None = None, socket_options: Any = None) -> Any: + 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 self._connect_errors() as exc: + last_exc = exc + raise self._no_usable_ips(host, last_exc) + + def sleep(self, seconds: float) -> None: + self._backend.sleep(seconds) + + +def _origin_scheme_context(request: Any) -> dict[tuple[str, int], str]: + host, port, scheme = request.url.host, request.url.port, request.url.scheme + return {(host, port): scheme} if host and port is not None and scheme in _HTTP_SCHEMES else {} + + +@contextmanager +def _origin_scope(schemes_by_origin_var: Any, request: Any): + """Expose the request's origin scheme to the connect-time backend for this request only.""" + token = schemes_by_origin_var.set(_origin_scheme_context(request)) + try: + yield + finally: + schemes_by_origin_var.reset(token) + + +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 + 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: + raise SSRFConnectionBlocked(f"Unsupported {label} cannot be made SSRF-safe") + + async def guarded_async(request: Any) -> Any: + with _origin_scope(schemes_by_origin_var, request): + return await handle(request) + + 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 + + +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) + + +def create_ssrf_safe_async_client(**kwargs: Any) -> Any: + """``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 + + +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]: + """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 + location = (getattr(response, "headers", {}) or {}).get("location") + if location: + return urljoin(str(getattr(response, "url", "")), str(location)) + next_request = getattr(response, "next_request", None) + return str(next_request.url) if next_request else None + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. + +def has_sensitive_query_params(url: str) -> bool: + """Return True when ``url`` carries likely credential-bearing query params.""" + return sensitive_query_param_name(url) is not None + +def ssrf_safe_async_http_transport(**kwargs: Any) -> Any: + """Return an httpx async transport that pins direct TCP connects to vetted IPs.""" + import contextvars + import httpx + + schemes_by_origin_var = contextvars.ContextVar("hermes_ssrf_async_origin_schemes") + + class _Transport(httpx.AsyncHTTPTransport): + def __init__(self, **transport_kwargs: Any): + super().__init__(**transport_kwargs) + self._pool._network_backend = _SSRFGuardedAsyncNetworkBackend( # type: ignore[attr-defined] + schemes_by_origin_var + ) + + async def handle_async_request(self, request: Any) -> Any: + token = schemes_by_origin_var.set(_origin_scheme_context(request)) + try: + return await super().handle_async_request(request) + finally: + schemes_by_origin_var.reset(token) + + return _Transport(**kwargs) + +def ssrf_safe_http_transport(**kwargs: Any) -> Any: + """Return an httpx sync transport that pins direct TCP connects to vetted IPs.""" + import contextvars + import httpx + + schemes_by_origin_var = contextvars.ContextVar("hermes_ssrf_origin_schemes") + + class _Transport(httpx.HTTPTransport): + def __init__(self, **transport_kwargs: Any): + super().__init__(**transport_kwargs) + self._pool._network_backend = _SSRFGuardedNetworkBackend( # type: ignore[attr-defined] + schemes_by_origin_var + ) + + def handle_request(self, request: Any) -> Any: + token = schemes_by_origin_var.set(_origin_scheme_context(request)) + try: + return super().handle_request(request) + finally: + schemes_by_origin_var.reset(token) + + return _Transport(**kwargs) +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/video_generation_tool.py b/tools/video_generation_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..731bd884514059a5fce078721aa9a063f8f4dc08 --- /dev/null +++ b/tools/video_generation_tool.py @@ -0,0 +1,388 @@ +#!/usr/bin/env python3 +"""``video_generate``: one tool dispatching to a plugin-registered :class:`VideoGenProvider` +(``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. 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 + +import json +import logging +from typing import Any, Dict, List, Optional + +from agent.video_gen_provider import ( + COMMON_ASPECT_RATIOS, + COMMON_RESOLUTIONS, + DEFAULT_ASPECT_RATIO, + DEFAULT_RESOLUTION, + error_response) +from tools.registry import registry, tool_error + +logger = logging.getLogger(__name__) + + +VIDEO_GENERATE_SCHEMA: Dict[str, Any] = { + "name": "video_generate", + # Placeholder: description AND params are rebuilt at get_tool_definitions() time by + # _build_dynamic_video_schema() from capabilities() + the model's catalog entry. Optional + # args are advertised ONLY when honored; the handler accepts them regardless (replay compat). + "description": "(rebuilt at get_definitions() time — see _build_dynamic_video_schema)", + "parameters": { + "type": "object", + "properties": { + "prompt": { + "type": "string", + "description": ( + "Text instruction describing the desired video, motion, " + "subject, style, camera movement, etc." + ), + }, + "duration": { + "type": "integer", + "description": ( + "Desired video duration in seconds. Providers clamp to " + "their supported range. Omit for the provider default." + ), + }, + "aspect_ratio": { + "type": "string", + "enum": list(COMMON_ASPECT_RATIOS), + "description": "Output aspect ratio.", + "default": DEFAULT_ASPECT_RATIO, + }, + "resolution": { + "type": "string", + "enum": list(COMMON_RESOLUTIONS), + "description": "Output resolution.", + "default": DEFAULT_RESOLUTION, + }, + "model": { + "type": "string", + "description": ( + "Optional model override; defaults to the configured " + "``video_gen.model``. Unknown models are rejected." + ), + }, + # Capability-gated args are added by _build_dynamic_video_schema; never statically. + }, + # NOTE (schema diet, #95681): image_url / reference_image_urls / negative_prompt / audio / seed / + # upscale are added per-capability by _build_dynamic_video_schema. + "required": ["prompt"], + }, +} + + +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 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 + return value.strip() if isinstance(value, str) and value.strip() else None + + +def _read_configured_video_provider() -> Optional[str]: + return _read_video_gen_key("provider") + + +def _read_configured_video_model() -> Optional[str]: + return _read_video_gen_key("model") + + +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 + + +def check_video_generation_requirements() -> bool: + """True when at least one registered provider reports available.""" + registry_mod, _ = _discovered_registry() + return any(_provider_call(p, "is_available", False) for p in registry_mod.list_providers()) + + +def _resolve_active_provider(): + """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() + if provider is None: + ensure_discovered(force=True) + provider = registry_mod.get_active_provider() + return provider + except Exception as exc: + logger.debug("video_gen provider resolution failed: %s", exc) + return None + + +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 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, OpenRouter, or DeepInfra)."), + error_type="no_provider_configured")) + + +_BOOL_WORDS = {"true": True, "1": True, "yes": True, "on": True, + "false": False, "0": False, "no": False, "off": False} + + +def _coerce_int(value: Any) -> Optional[int]: + try: + return None if value is None or value == "" else int(value) + except (TypeError, ValueError): + return None + + +def _coerce_bool(value: Any) -> Optional[bool]: + if isinstance(value, bool): + return value + return _BOOL_WORDS.get(value.strip().lower()) if isinstance(value, str) else None + + +def _normalize_reference_images(value: Any) -> Optional[List[str]]: + if isinstance(value, str): + value = [value] + if not isinstance(value, (list, tuple)): + return 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: + prompt = (args.get("prompt") or "").strip() + image_url = (args.get("image_url") or "").strip() or None + reference_image_urls = _normalize_reference_images(args.get("reference_image_urls")) + task_id = _kw.get("task_id") + + # 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 + # 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; 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") + configured = _read_configured_video_provider() + provider = _resolve_active_provider() + if provider is None: + return _missing_provider_error(configured) + + # 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, **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", "?") + + 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)) + 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) + return _err( + 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 — 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", + "description": "Content to avoid in the output.", + }), + ("supports_audio", "audio", { + "type": "boolean", + "description": "Enable native audio generation (affects pricing tier).", + }), + ("supports_seed", "seed", { + "type": "integer", + "description": "Seed for reproducible outputs.", + }), + ("supports_upscale", "upscale", { + "type": "boolean", + "description": ( + "High-resolution pass via the backend's video upscaler " + "(~2x, extra cost/latency). Omit for native resolution." + ), + }), +) + +_GENERIC_DESCRIPTION = ( + "Generate a video from a text prompt (text-to-video), animate a " + "still image (image-to-video), or guide generation with reference images. " + "Pass `image_url` to animate an image or `reference_image_urls` for " + "reference-to-video. Video edit/extend workflows are not part of this " + "unified surface; use a dedicated provider-specific tool when one is " + "available. The backend and model family are user-configured via " + "`hermes tools` → Video Generation; the agent does not pick them. " + "Long-running generations may take 30 seconds to several minutes — " + "the call blocks until the video is ready. Returns the result in the " + "`video` field — either an HTTP URL or an absolute file path. To show " + "it to the user, reference that path/URL in your response using the " + "file-delivery convention for the current platform (your platform " + "guidance describes how files are delivered here)." +) + + +def _schema(description: str, properties: Dict[str, Any]) -> Dict[str, Any]: + return { + "description": description, + "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]: + """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.") + return _schema("\n".join(parts), {"prompt": static_props["prompt"]}) + 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), {}) + + # Model caveats surface only what differs from the backend's overall capabilities. + # FAL's plugin uses the singular ``modality`` key for single-modality entries. + model_modalities = set(model_meta.get("modalities") or []) + modality = model_meta.get("modality") + if modality: + model_modalities.add(modality) + 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") + 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 + if can_i2v and not t2v: + 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") + 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.")} + max_refs = int(caps.get("max_reference_images") or 0) + if max_refs > 0: + properties["reference_image_urls"] = { + "type": "array", + "items": {"type": "string"}, + "maxItems": max_refs, + "description": ( + f"Up to {max_refs} public HTTPS reference image URLs " + "(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"]) + if min_duration and max_duration: + duration_param["minimum"] = int(min_duration) + duration_param["maximum"] = int(max_duration) + duration_param["description"] = ( + f"Video duration in seconds ({min_duration}-{max_duration}). " + "Omit for the provider default.") + properties["duration"] = duration_param + + # Tighten enums to the active backend's actual sets when declared. + for key, caps_key in (("aspect_ratio", "aspect_ratios"), ("resolution", "resolutions")): + param = dict(static_props[key]) + 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 + if caps.get("audio_always_on") and not caps.get("supports_audio"): + parts.append( + "- audio: native stereo audio is generated with every video " + "(always on; no toggle) — describe the desired sound in the " + "prompt") + properties["model"] = static_props["model"] + return _schema("\n".join(parts), properties) + + +registry.register( + name="video_generate", + toolset="video_gen", + schema=VIDEO_GENERATE_SCHEMA, + handler=_handle_video_generate, + check_fn=check_video_generation_requirements, + requires_env=[], + is_async=False, + emoji="🎬", + dynamic_schema_overrides=_build_dynamic_video_schema) diff --git a/tools/vision_tools.py b/tools/vision_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..a16c228d8a63f07468239970f900eac379526a79 --- /dev/null +++ b/tools/vision_tools.py @@ -0,0 +1,1068 @@ +#!/usr/bin/env python3 +"""Vision tools: ``vision_analyze`` (image) and ``video_analyze``. + +Images resolve through :mod:`tools.image_source`, are normalized to a provider-supported format +(:mod:`tools.vision_tools_image_prep`), then either attach natively to a vision-capable main +model (multimodal tool-result envelope) or are described by the auxiliary vision LLM router. +""" + +import base64 +import asyncio +import json +from concurrent.futures import ThreadPoolExecutor +from io import BytesIO +import logging +import os +import uuid +from pathlib import Path +from typing import Any, Awaitable, Callable, Dict, NamedTuple, Optional +from urllib.parse import urlparse +import httpx + +# ``agent.auxiliary_client`` costs ~50 ms cold; only the handlers need it. Both names stay +# module attributes so tests can patch ``tools.vision_tools.async_call_llm`` (truthy-skip: mocks win). +async_call_llm: Any = None +extract_content_or_reasoning: Any = None + + +def _load_auxiliary_client() -> None: + global async_call_llm, extract_content_or_reasoning + if async_call_llm is None or extract_content_or_reasoning is None: + from agent import auxiliary_client as _aux + async_call_llm = async_call_llm or _aux.async_call_llm + extract_content_or_reasoning = extract_content_or_reasoning or _aux.extract_content_or_reasoning + + +from hermes_constants import get_hermes_dir +from tools.debug_helpers import DebugSession +from tools.website_policy import check_website_access +from tools.vision_tools_image_prep import ( + _VISION_MAX_VALIDATED_AGGREGATE_PIXELS, + _VISION_MAX_VALIDATED_FRAME_COUNT, + _crop_image_region, + _determine_mime_type, + _image_exceeds_dimension, + _normalize_to_supported_image, + _validate_raster_image_decodable) + +logger = logging.getLogger(__name__) + +_debug = DebugSession("vision_tools", env_var="VISION_TOOLS_DEBUG") + + +def _cfg_auxiliary(*keys: str, default=None): + """``auxiliary.<keys...>`` from config.yaml; ``default`` when config is unavailable.""" + try: + from hermes_cli.config import cfg_get, load_config + return cfg_get(load_config(), "auxiliary", *keys, default=default) + except Exception: + return default + + +def _read_vision_setting(env_var: str, key: str, cast, minimum=None): + """Env var → ``auxiliary.vision.<key>`` → None. Values that fail ``cast`` or fall below + ``minimum`` are skipped in favor of the next source (a cap can never be disabled by a bad value).""" + def _accept(raw): + try: + val = cast(raw) + except (TypeError, ValueError): + return None + return val if minimum is None or val >= minimum else None + val = _accept(os.getenv(env_var, "").strip() or None) + return val if val is not None else _accept(_cfg_auxiliary("vision", key)) + + +# HTTP download timeout (separate from ``auxiliary.vision.timeout``, which governs the LLM call). +_VISION_DOWNLOAD_TIMEOUT = _read_vision_setting("HERMES_VISION_DOWNLOAD_TIMEOUT", "download_timeout", float) +if _VISION_DOWNLOAD_TIMEOUT is None: + _VISION_DOWNLOAD_TIMEOUT = 30.0 + +# Hard cap on downloaded media (50 MB): bounds memory/disk against attacker-hosted files. +_VISION_MAX_DOWNLOAD_BYTES = 50 * 1024 * 1024 + + +# CPU-burst cap: a turn can fan out dozens of vision_analyze calls (base64 encode + Pillow +# resize each) that would saturate every core and starve the shared event loop. Only the CPU +# burst is capped (LLM calls stay concurrent), on a dedicated executor sized to usable cores. +# Must be a threading primitive — each call runs via model_tools._run_async on a PER-THREAD +# loop, so an asyncio semaphore cannot coordinate; the default executor is shared with the +# gateway/web server and is deliberately NOT used. +def _detect_host_cpus() -> int: + """Usable CPU count (``sched_getaffinity`` honors cpuset pinning), at least 1.""" + try: + return max(1, len(os.sched_getaffinity(0))) # type: ignore[attr-defined] + except (AttributeError, OSError): + return max(1, os.cpu_count() or 1) + + +def _resolve_vision_cpu_workers() -> int: + """HERMES_VISION_MAX_CONCURRENCY → ``auxiliary.vision.max_concurrency`` → host cores (< 1 ignored).""" + val = _read_vision_setting("HERMES_VISION_MAX_CONCURRENCY", "max_concurrency", int, minimum=1) + return val or _detect_host_cpus() + + +_VISION_CPU_WORKERS = _resolve_vision_cpu_workers() + +_vision_cpu_executor = ThreadPoolExecutor( + max_workers=_VISION_CPU_WORKERS, thread_name_prefix="vision-encode", +) + + +async def _run_encode_on_cpu_executor(fn, *args, **kwargs): + """Run a sync encode/resize callable on the bounded vision CPU executor (never the LLM call).""" + import functools + loop = asyncio.get_running_loop() + return await loop.run_in_executor(_vision_cpu_executor, functools.partial(fn, *args, **kwargs)) + + +async def _validate_image_url_async(url: str) -> bool: + """HTTP(S) shape check (scheme, netloc; extension-less CDN URLs pass) + SSRF guard with DNS + off the event loop.""" + if not (isinstance(url, str) and url.startswith(("http://", "https://")) and urlparse(url).netloc): + return False + from tools.url_safety import async_is_safe_url + return await async_is_safe_url(url) + + +def _is_retryable_download_error(error: Exception) -> bool: + """Transient failures only: 429, 5xx, transport errors and anything unclassified. Fail-fast on + other 4xx, PermissionError (policy/SSRF block) and ValueError (too large / blocked redirect).""" + if isinstance(error, (PermissionError, ValueError)): + return False + if isinstance(error, httpx.HTTPStatusError): + status = error.response.status_code + return status == 429 or not 400 <= status < 500 + return True + + +_DOWNLOAD_USER_AGENT = ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" +) + + +async def _ssrf_redirect_guard(response): + """Re-validate each redirect target (a public URL 302ing to 169.254.169.254 would otherwise + bypass the pre-flight check). Async because httpx.AsyncClient awaits hooks.""" + from tools.url_safety import async_is_safe_url, redirect_target_from_response + redirect_url = redirect_target_from_response(response) + if redirect_url and not await async_is_safe_url(redirect_url): + raise ValueError(f"Blocked redirect to private/internal address: {redirect_url}") + + +async def _download_media( + url: str, destination: Path, max_retries: int, *, + media_label: str, accept: str, max_bytes: int, timeout: float, retry_all: bool) -> Path: + """SSRF-safe streaming download with exponential backoff (2s/4s/8s). ``retry_all=False`` (images) + retries only :func:`_is_retryable_download_error` errors — a 404/403 never succeeds on retry.""" + from utils import atomic_replace + from tools.url_safety import create_ssrf_safe_async_client + destination.parent.mkdir(parents=True, exist_ok=True) + last_error = None + for attempt in range(max_retries): + try: + blocked = check_website_access(url) + if blocked: + raise PermissionError(blocked["message"]) + + # follow_redirects for CDNs; the client validates DNS at connect + # time and the hook re-validates each redirect target. + async with create_ssrf_safe_async_client( + timeout=timeout, follow_redirects=True, event_hooks={"response": [_ssrf_redirect_guard]}, + ) as client, client.stream( + "GET", url, headers={"User-Agent": _DOWNLOAD_USER_AGENT, "Accept": accept}, + ) as response: + response.raise_for_status() + + # Content-Length gives an early reject but servers can omit or lie, + # so the streaming cap below is authoritative. + cl = response.headers.get("content-length") + try: + declared_size = int(cl) if cl else None + except ValueError: + declared_size = None + if declared_size is not None and declared_size > max_bytes: + raise ValueError(f"{media_label} too large ({declared_size} bytes, max {max_bytes})") + blocked = check_website_access(str(response.url)) + if blocked: + raise PermissionError(blocked["message"]) + + # Stream to a temp file, atomically moved onto destination on success. + tmp_destination = destination.with_name(f".{destination.name}.{uuid.uuid4().hex}.tmp") + bytes_written = 0 + try: + with tmp_destination.open("wb") as f: + async for chunk in response.aiter_bytes(): + if not chunk: + continue + bytes_written += len(chunk) + if bytes_written > max_bytes: + raise ValueError( + f"{media_label} too large ({bytes_written} bytes, max {max_bytes})" + ) + f.write(chunk) + atomic_replace(tmp_destination, destination) + except Exception: + try: + tmp_destination.unlink(missing_ok=True) + except OSError: + logger.debug("Could not delete partial download: %s", tmp_destination, exc_info=True) + raise + return destination + except Exception as e: + last_error = e + if attempt >= max_retries - 1 or (not retry_all and not _is_retryable_download_error(e)): + logger.error("%s download failed after %s attempt(s): %s", + media_label, attempt + 1, str(e)[:100], exc_info=True) + if not retry_all: + raise + break + wait_time = 2 ** (attempt + 1) + logger.warning("%s download failed (attempt %s/%s): %s", + media_label, attempt + 1, max_retries, str(e)[:50]) + if not retry_all: + logger.warning("Retrying in %ss...", wait_time) + await asyncio.sleep(wait_time) + # Reaching here means max_retries was non-positive (or video exhausted retries). + if last_error is not None: + raise last_error + raise RuntimeError( + f"_download_{media_label.lower()} exited retry loop without attempting (max_retries={max_retries})") + + +async def _download_image(image_url: str, destination: Path, max_retries: int = 3) -> Path: + """Download an image with SSRF protection and error-class-aware retry.""" + return await _download_media( + image_url, destination, max_retries, + media_label="Image", accept="image/*,*/*;q=0.8", + max_bytes=_VISION_MAX_DOWNLOAD_BYTES, timeout=_VISION_DOWNLOAD_TIMEOUT, retry_all=False) + + +def _image_to_base64_data_url(image_path: Path, mime_type: Optional[str] = None) -> str: + """``data:<mime>;base64,...`` for a file (MIME from extension when not given).""" + mime = mime_type or _determine_mime_type(image_path) + return f"data:{mime};base64,{base64.b64encode(image_path.read_bytes()).decode('ascii')}" + + +# Absolute hard ceiling for vision payloads (20 MB): no major provider accepts more. +_MAX_BASE64_BYTES = 20 * 1024 * 1024 + +# Proactive embed caps for history reuse: the native path bakes the data URL into the tool +# result, re-sent every later turn (a 4 MB embed cost ~100-260K billed tokens). Anthropic +# downsamples to a 1568px long edge anyway, so pixels past that cost wire bytes for no fidelity. +# The 20 MB hard ceiling / Anthropic 5 MB reject-cap still apply as safety nets; those are one-shot viewing +# limits, not history-reuse sizes. A 4 MB / 7900px embed was observed at ~400K chars and ~100–260K billed +# tokens per image (#92699), so we size for model reading instead: 256 KB keeps a 1568px screenshot cheap +# enough to ride the session (PNGs that exceed it are downscaled further by the byte-budget ladder), well +# under every provider's per-image limit. +_EMBED_TARGET_BYTES = 256 * 1024 +_EMBED_MAX_DIMENSION = 1568 + +# Target when auto-resizing after a provider size rejection (retry once). +_RESIZE_TARGET_BYTES = 5 * 1024 * 1024 + +_SIZE_ERROR_HINTS = ( + "too large", "payload", "413", "content_too_large", + "request_too_large", "exceeds", "size limit", +) + + +def _is_image_size_error(error: Exception) -> bool: + """Detect if an API error is related to image or payload size.""" + err_str = str(error).lower() + return any(hint in err_str for hint in _SIZE_ERROR_HINTS + ("image_url", "invalid_request")) + + +def _build_scale_note(scale_info: Optional[dict], crop_offset: Optional[dict]) -> Optional[str]: + """Coordinate-mapping disclosure for downscale and/or region crop; ``None`` when neither applied.""" + parts = [] + if scale_info: + ow, oh = scale_info["orig_width"], scale_info["orig_height"] + nw, nh = scale_info["new_width"], scale_info["new_height"] + fx, fy = (ow / nw if nw else 1.0), (oh / nh if nh else 1.0) + axes = (f"any coordinates you report by {fx:.2f}" if f"{fx:.2f}" == f"{fy:.2f}" + else f"any x coordinates you report by {fx:.2f} and any y coordinates by {fy:.2f}") + parts.append(f"Image downscaled from {ow}x{oh} to {nw}x{nh} for vision; " + f"multiply {axes} to map back to the original image.") + if crop_offset: + parts.append( + f"Analysis was performed on a cropped region of the original " + f"image starting at offset ({crop_offset['x']}, " + f"{crop_offset['y']}); coordinates are relative to that crop " + f"origin — add the offset to map back to the full image.") + return " ".join(parts) if parts else None + + +def _import_pillow_for_resize(): + """Return ``PIL.Image`` or None (Pillow is a lazy-installable soft dependency). ``prompt=False``: + a blocking input() deadlocks the CLI where prompt_toolkit owns stdin; the install is already + gated by security.allow_lazy_installs.""" + try: + from PIL import Image + except ImportError: + try: + from tools.lazy_deps import ensure as _ensure_dep + # prompt=False: never raise a blocking input() prompt mid-session. Under the interactive CLI + # prompt_toolkit owns stdin, so a bare input() deadlocks the terminal (#40490). The install is + # already gated by security.allow_lazy_installs, so reaching here is opt-in. + _ensure_dep("tool.vision", prompt=False) + from PIL import Image + except Exception: + return None + return Image + + +def _resize_image_for_vision(image_path: Path, mime_type: Optional[str] = None, + max_base64_bytes: int = _RESIZE_TARGET_BYTES, + max_dimension: Optional[int] = None, + scale_out: Optional[dict] = None, + force_jpeg: bool = False) -> str: + """Base64 data URL, progressively downscaled with Pillow while over budget. + + Halves dimensions (aspect-preserving, 64px floor) up to 4 times; JPEG also walks a + quality ladder (85/70/50) per step. Without Pillow, or if it still doesn't fit, returns + the best attempt (or raw bytes) and lets the caller apply the size check. + ``max_dimension``: force a downscale above this long edge even when bytes fit + (Anthropic's 8000px cap is independent of bytes). ``force_jpeg``: re-encode PNG as JPEG + when resizing — halving PNG dimensions destroys text legibility on dense screenshots. + + Args: max_dimension: If set, images whose longest side exceeds this pixel count are forcibly downscaled + even if they're under the byte budget. Anthropic enforces an 8000 px per-side cap independently of the 5 + MB byte cap. force_jpeg: Re-encode as JPEG even for PNG input when a resize is needed. History-reuse + embeds (#92699) opt in so a text-heavy screenshot keeps its readable resolution and shrinks via JPEG + quality instead. Images already under both caps are returned unchanged (still PNG). + """ + file_size = image_path.stat().st_size + estimated_b64 = (file_size * 4) // 3 + 100 # base64 ~4/3 + data URL header + data_url = None + if estimated_b64 <= max_base64_bytes and not ( + max_dimension is not None and _image_exceeds_dimension(image_path, max_dimension) + ): + data_url = _image_to_base64_data_url(image_path, mime_type=mime_type) + if len(data_url) <= max_base64_bytes: + return data_url + + def _raw() -> str: + return data_url or _image_to_base64_data_url(image_path, mime_type=mime_type) + Image = _import_pillow_for_resize() + if Image is None: + logger.info("Pillow not installed — cannot auto-resize oversized image") + return _raw() # caller will raise the size error + logger.info("Image file is %.1f MB (estimated base64 %.1f MB, limit %.1f MB, max_dimension=%s), auto-resizing...", + file_size / (1024 * 1024), estimated_b64 / (1024 * 1024), + max_base64_bytes / (1024 * 1024), max_dimension) + # JPEG for photos (smaller), PNG for transparency — unless force_jpeg. + is_png = (mime_type or _determine_mime_type(image_path)) == "image/png" and not force_jpeg + pil_format, out_mime = ("PNG", "image/png") if is_png else ("JPEG", "image/jpeg") + try: + img = Image.open(image_path) + except Exception as exc: + logger.info("Pillow cannot open image for resizing: %s", exc) + return _raw() + + # JPEG cannot encode alpha/palette modes (force_jpeg routes PNGs here). + if not is_png and img.mode not in {"RGB", "L"}: + img = img.convert("RGB") + quality_steps = (None,) if is_png else (85, 70, 50) + orig_dims = prev_dims = (img.width, img.height) + candidate = None + + def _record_scale(w: int, h: int) -> None: + if scale_out is not None and (w, h) != orig_dims: + scale_out.update(orig_width=orig_dims[0], orig_height=orig_dims[1], new_width=w, new_height=h) + for attempt in range(5): + if attempt > 0: + # Halve, then re-derive from whichever axis hit the 64px floor so both shrink equally. + new_w, new_h = max(int(img.width * 0.5), 64), max(int(img.height * 0.5), 64) + if new_w == 64 and img.width > 0: + new_h = max(int(img.height * (64 / img.width)), 64) + elif new_h == 64 and img.height > 0: + new_w = max(int(img.width * (64 / img.height)), 64) + if (new_w, new_h) == prev_dims: + break + img = img.resize((new_w, new_h), Image.LANCZOS) + prev_dims = (new_w, new_h) + logger.info("Resized to %dx%d (attempt %d)", new_w, new_h, attempt) + dims_ok = max_dimension is None or max(img.width, img.height) <= max_dimension + for q in quality_steps: + buf = BytesIO() + img.save(buf, format=pil_format, **({} if q is None else {"quality": q})) + candidate = f"data:{out_mime};base64,{base64.b64encode(buf.getvalue()).decode('ascii')}" + if len(candidate) <= max_base64_bytes and dims_ok: + logger.info("Auto-resized image fits: %.1f MB (quality=%s, %dx%d)", + len(candidate) / (1024 * 1024), q, img.width, img.height) + _record_scale(img.width, img.height) + return candidate + if candidate is None: + return _raw() + logger.warning("Auto-resize could not fit image under %.1f MB (best: %.1f MB)", + max_base64_bytes / (1024 * 1024), len(candidate) / (1024 * 1024)) + _record_scale(img.width, img.height) + return candidate + + +# Native fast path: a vision-capable main model gets the image bytes as a multimodal +# tool-result envelope (the agent loop unwraps it into an OpenAI-style content list on the +# `tool` role); no aux LLM, no information loss. Providers whose tool results accept image +# content: Anthropic Messages (and aggregators proxying Claude — assume support), OpenAI +# Chat/Responses. Gemini is gated on model: only 3.x supports multimodal functionResponse. +_TOOL_RESULT_MEDIA_PROVIDERS = frozenset({ + "openrouter", "nous", "vertex", "bedrock", "anthropic-vertex", "google-vertex", + "anthropic", "claude", "anthropic-direct", + "openai", "openai-chat", "openai-codex", "azure-openai", +}) +_GEMINI_PROVIDERS = frozenset({"google", "gemini", "google-gemini", "google-vertex-gemini"}) + + +def _profile_rejects_tool_media(provider: str) -> bool: + """Hard veto: the provider's ``ProviderProfile`` declares + ``supports_vision_tool_messages=False`` — images are accepted in user + messages but list-type tool-result content is rejected with 400 + (xiaomi/MiMo "text is not set"). ``supports_vision`` alone must not + override this, or the multimodal tool-result envelope 400s every turn + and the image never enters context (#89981). + """ + try: + from providers import get_provider_profile + profile = get_provider_profile(str(provider or "").strip().lower()) + return profile is not None and profile.supports_vision_tool_messages is False + except Exception: + return False + + +def _supports_media_in_tool_results(provider: str, model: str) -> bool: + """Whether provider+model accepts image content inside a tool-result message. Unknown + providers are False (caller falls back to aux-LLM text) unless their ``ProviderProfile`` + declares ``supports_vision``; ``supports_vision_tool_messages=False`` is a hard veto.""" + p = provider.strip().lower() if isinstance(provider, str) else "" + if not p or _profile_rejects_tool_media(p): + return False + if p in _TOOL_RESULT_MEDIA_PROVIDERS: + return True + if p in _GEMINI_PROVIDERS: + m = model.strip().lower() if isinstance(model, str) else "" + return any(tag in m for tag in ("gemini-3", "gemini-pro-3", "gemini-flash-3")) + try: + from providers import get_provider_profile + profile = get_provider_profile(p) + return profile is not None and bool(profile.supports_vision) + except Exception: + return False + + +def _should_use_native_vision_fast_path() -> bool: + """True when image routing resolves to ``native`` AND the provider accepts images in tool + results, or the user set the ``model.supports_vision`` override (escape hatch for + custom/local providers). Any failure → False.""" + try: + from agent.auxiliary_client import _read_main_provider, _read_main_model + from agent.image_routing import decide_image_input_mode, _lookup_supports_vision + from hermes_cli.config import load_config + provider = _read_main_provider() + model = _read_main_model() + cfg = load_config() + if decide_image_input_mode(provider, model, cfg) != "native": + return False + # The profile veto applies ahead of the capability lookup too: a + # model marked vision-capable by models.dev / custom_providers must + # not re-open the multimodal-envelope route the profile rejects. + if _profile_rejects_tool_media(provider): + return False + return ( + _supports_media_in_tool_results(provider, model) + or _lookup_supports_vision(provider, model, cfg) is True) + except Exception as exc: + logger.debug("Native vision fast-path check failed: %s", exc) + return False + + +def _build_native_vision_tool_result( + image_url: str, question: str, image_data_url: str, image_size_bytes: int, + scale_note: Optional[str] = None, +) -> Dict[str, Any]: + """Multimodal tool-result envelope. The text part is intentionally minimal (the model already + has the question); ``text_summary`` is the fallback for providers without multimodal tool results.""" + text_part = ( + "Image loaded into your context — you can see it natively now. " + "Use your built-in vision to answer the user.") + if isinstance(question, str) and question.strip(): + text_part += f"\n\nQuestion: {question.strip()}" + if scale_note: + text_part += f"\n\nNote: {scale_note}" + return { + "_multimodal": True, + "content": [ + {"type": "text", "text": text_part}, + {"type": "image_url", "image_url": {"url": image_data_url}}], + "text_summary": ( + f"Image attached natively for the main model ({image_size_bytes / 1024:.1f} KB). " + "Answer using built-in vision."), + "meta": {"image_url": image_url[:200], "size_bytes": image_size_bytes, "native_vision": True}} + + +def _unlink_quietly(path: Optional[Path]) -> None: + if path is not None: + try: + path.unlink(missing_ok=True) + except Exception: + pass + + +class _ImagePrepError(ValueError): + """Raised by :func:`_prepare_image`; the message is user-facing.""" + + +class _PreparedImage(NamedTuple): + """Temp image ready to encode; ``path`` is owned by the caller (delete it).""" + path: Path + mime: Optional[str] + size_bytes: int + crop_offset: dict + + +async def _prepare_image( + image_url: str, task_id: Optional[str], region: Optional[list], *, validate_decode: bool, +) -> _PreparedImage: + """Resolve → materialize → normalize → (validate) → (crop). Raises ``_ImagePrepError``. + Unsupported formats (SVG, BMP) become PNG BEFORE encoding — an unsupported media_type baked + into immutable history would 400 on every resume. The crop runs BEFORE any downscale so the + region keeps the full resolution budget. On error no temp file is left.""" + from tools.image_source import ImageResolutionError, ResolveContext, resolve_image_source + try: + resolved = await resolve_image_source(image_url, ResolveContext(task_id=task_id)) + except ImageResolutionError as exc: + raise _ImagePrepError(str(exc)) from exc + temp_dir = get_hermes_dir("cache/vision", "temp_vision_images") + temp_dir.mkdir(parents=True, exist_ok=True) + path = temp_dir / f"temp_image_{uuid.uuid4()}.img" + await asyncio.to_thread(path.write_bytes, resolved.data) + mime, size_bytes, crop_offset = resolved.mime, len(resolved.data), {} + try: + normalized_path, mime, norm_err = await asyncio.to_thread(_normalize_to_supported_image, path, mime) + if norm_err or normalized_path is None: + raise _ImagePrepError(norm_err or "Image normalization failed.") + if normalized_path != path: + _unlink_quietly(path) + path = normalized_path + size_bytes = path.stat().st_size + if validate_decode: + decode_error = await _run_encode_on_cpu_executor( + _validate_raster_image_decodable, path, + _VISION_MAX_VALIDATED_FRAME_COUNT, _VISION_MAX_VALIDATED_AGGREGATE_PIXELS) + if decode_error: + raise _ImagePrepError(decode_error) + if region is not None: + cropped_path, cropped_mime, crop_err = await asyncio.to_thread( + _crop_image_region, path, region, offset_out=crop_offset) + if crop_err or cropped_path is None: + raise _ImagePrepError(crop_err or "Region crop failed.") + _unlink_quietly(path) + path, mime, size_bytes = cropped_path, cropped_mime, cropped_path.stat().st_size + except BaseException: + _unlink_quietly(path) + raise + return _PreparedImage(path, mime, size_bytes, crop_offset) + + +def _too_large_message(image_data_url: str) -> str: + return ( + f"Image too large for vision API: base64 payload is {len(image_data_url) / (1024 * 1024):.1f} MB " + f"(limit {_MAX_BASE64_BYTES / (1024 * 1024):.0f} MB) even after resizing. Install Pillow " + f"(`pip install Pillow`) for better auto-resize, or compress the image manually.") + + +async def _resize_prepared(prepared: _PreparedImage, scale_info: dict, **kwargs) -> str: + """Run :func:`_resize_image_for_vision` on the CPU executor for a prepared image.""" + return await _run_encode_on_cpu_executor( + _resize_image_for_vision, prepared.path, mime_type=prepared.mime, scale_out=scale_info, **kwargs, + ) + + +async def _vision_analyze_native( + image_url: str, question: str, task_id: Optional[str] = None, region: Optional[list] = None, +) -> Any: + """Fast path for vision-capable main models: a ``_multimodal`` envelope dict on success, + or a JSON error string (the normal tool-result contract) on failure.""" + if not isinstance(image_url, str) or not image_url.strip(): + return tool_error("image_url is required", success=False) + prepared: Optional[_PreparedImage] = None + try: + from tools.interrupt import is_interrupted + if is_interrupted(): + return tool_error("Interrupted", success=False) + try: + prepared = await _prepare_image(image_url, task_id, region, validate_decode=True) + except _ImagePrepError as exc: + return tool_error(str(exc), success=False) + image_data_url = await _run_encode_on_cpu_executor( + _image_to_base64_data_url, prepared.path, mime_type=prepared.mime) + # Proactive embed cap: this image is re-sent on every later turn, so resize DOWN to the + # history-reuse target whenever the byte or long-edge cap is exceeded, not just at 20 MB. + _scale_info: dict = {} + # Anthropic still rejects >5 MB / >8000px with a non-retryable 400, but those are one-shot viewing + # limits — history embeds are sized smaller so repeated vision_analyze turns don't blow the context + # (#92699). + _over_dims = await _run_encode_on_cpu_executor( + _image_exceeds_dimension, prepared.path, _EMBED_MAX_DIMENSION) + if len(image_data_url) > _EMBED_TARGET_BYTES or _over_dims: + image_data_url = await _resize_prepared( + prepared, _scale_info, + max_base64_bytes=_EMBED_TARGET_BYTES, max_dimension=_EMBED_MAX_DIMENSION, force_jpeg=True) + # Reject rather than embed a session-wedging payload. + if len(image_data_url) > _MAX_BASE64_BYTES: + return tool_error(_too_large_message(image_data_url), success=False) + return _build_native_vision_tool_result( + image_url=image_url, question=question, image_data_url=image_data_url, + image_size_bytes=prepared.size_bytes, + scale_note=_build_scale_note(_scale_info or None, prepared.crop_offset or None)) + except Exception as exc: + logger.warning("Native vision fast path failed: %s", exc) + return tool_error(f"Native vision failed: {exc}", success=False) + finally: + # Only delete temp files we created — never user-provided paths. + if prepared is not None: + _unlink_quietly(prepared.path) + + +def _aux_call_kwargs(messages: list, model: Optional[str], default_timeout: float, *, + min_timeout: Optional[float] = None) -> dict: + """``async_call_llm`` kwargs with ``auxiliary.vision.timeout`` / ``.temperature`` from config. + Local vision models (llama.cpp, ollama) can take well over 30s, hence generous defaults + (temperature 0.1); ``min_timeout`` lets video enforce a floor.""" + timeout, temperature = default_timeout, 0.1 + try: + _vision_cfg = _cfg_auxiliary("vision", default={}) or {} + if _vision_cfg.get("timeout") is not None: + timeout = max(float(_vision_cfg["timeout"]), float("-inf") if min_timeout is None else min_timeout) + if _vision_cfg.get("temperature") is not None: + temperature = float(_vision_cfg["temperature"]) + except Exception: + pass + return {"task": "vision", "messages": messages, "temperature": temperature, "timeout": timeout, + **({"model": model} if model else {})} + + +def _media_messages(user_prompt: str, part_type: str, data_url: str) -> list: + """Single user message: text + one ``image_url``/``video_url`` data-URL part.""" + return [{"role": "user", "content": [ + {"type": "text", "text": user_prompt}, {"type": part_type, part_type: {"url": data_url}}]}] + + +# Aux-LLM error classification: first matching hint set wins (billing → capability → size/format). +_BILLING_HINTS = ("402", "insufficient", "payment required", "credits", "billing") +_IMAGE_ERROR_RULES = ( + (_BILLING_HINTS, + "Insufficient credits or payment required. Please top up your " + "API provider account and try again. Error: {e}"), + (("does not support", "not support image", "content_policy", "multimodal", + "unrecognized request argument", "image input"), + "{model} does not support vision or our request was not " + "accepted by the server. Error: {e}"), + (("invalid_request", "image_url"), + "The vision API rejected the image. This can happen when the " + "image is in an unsupported format, corrupted, or still too " + "large after auto-resize. Try a smaller JPEG/PNG and retry. " + "Error: {e}"), +) +_VIDEO_ERROR_RULES = ( + (_BILLING_HINTS, _IMAGE_ERROR_RULES[0][1]), + (("does not support", "not support video", "content_policy", "multimodal", + "unrecognized request argument", "video input", "video_url"), + "The model does not support video analysis or the request was " + "rejected. Ensure you're using a video-capable model " + "(e.g. google/gemini-2.5-flash). Error: {e}"), + (_SIZE_ERROR_HINTS, + "The video is too large for the API. Try compressing or trimming " + "the video (max ~50 MB). Error: {e}"), +) +# kind -> (debug tool name, error rules) +_ANALYSIS_KINDS = { + "image": ("vision_analyze_tool", _IMAGE_ERROR_RULES), + "video": ("video_analyze_tool", _VIDEO_ERROR_RULES)} + + +def _debug_call_data(kind: str, source: str, user_prompt: str, model) -> dict: + prompt = user_prompt[:200] + "..." if len(user_prompt) > 200 else user_prompt + return { + "parameters": {f"{kind}_url": source, "user_prompt": prompt, "model": model}, + "error": None, "success": False, "analysis_length": 0, "model_used": model, f"{kind}_size_bytes": 0} + + +async def _call_vision_llm(call_kwargs: dict, empty_log: str, response=None): + """Aux vision LLM analysis text, retrying once on empty content (reasoning-only response). + ``response``: an already-made first call (the image path handles size-error retries itself).""" + _load_auxiliary_client() + if response is None: + response = await async_call_llm(**call_kwargs) + analysis = extract_content_or_reasoning(response) + if not analysis: + logger.warning(empty_log) + analysis = extract_content_or_reasoning(await async_call_llm(**call_kwargs)) + return analysis + + +async def _run_analysis( + kind: str, source: str, user_prompt: str, model: Optional[str], + stage: Callable[[str, dict, list], Awaitable[tuple]]) -> str: + """Aux-LLM analysis skeleton for image/video: interrupt check → ``stage`` → JSON result. + + ``stage(user_prompt, debug_call_data, temp_paths)`` returns ``(analysis, scale_note)``; temp + files it appends to ``temp_paths`` are deleted in ``finally``. Returns JSON + ``{"success": bool, "analysis": str}`` (``analysis`` carries the error explanation on failure). + """ + tool_name, rules = _ANALYSIS_KINDS[kind] + if not isinstance(user_prompt, str): + user_prompt = str(user_prompt) if user_prompt is not None else "" + debug_call_data = _debug_call_data(kind, source, user_prompt, model) + temp_paths: list = [] + + def finish(result: dict) -> str: + _debug.log_call(tool_name, debug_call_data) + _debug.save() + return json.dumps(result, indent=2, ensure_ascii=False) + + try: + from tools.interrupt import is_interrupted + if is_interrupted(): + return tool_error("Interrupted", success=False) + logger.info("Analyzing %s: %s", kind, source[:60]) + logger.info("User prompt: %s", user_prompt[:100]) + analysis, scale_note = await stage(user_prompt, debug_call_data, temp_paths) + analysis_length = len(analysis) if analysis else 0 + logger.info("%s analysis completed (%s characters)", kind.capitalize(), analysis_length) + analysis = analysis or f"There was a problem with the request and the {kind} could not be analyzed." + result = {"success": True, "analysis": f"[{scale_note}] {analysis}" if scale_note else analysis} + if scale_note: + result["scale_note"] = scale_note + debug_call_data.update(success=True, analysis_length=analysis_length) + return finish(result) + except Exception as e: + error_msg = f"Error analyzing {kind}: {str(e)}" + logger.error("%s", error_msg, exc_info=True) + err_str = str(e).lower() + template = next( + (tpl for hints, tpl in rules if any(hint in err_str for hint in hints)), + f"There was a problem with the request and the {kind} could not be analyzed. Error: {{e}}") + analysis = template.format(e=e, model=model) + debug_call_data["error"] = error_msg + return finish({"success": False, "error": error_msg, "analysis": analysis}) + finally: + for path in temp_paths: + if path and path.exists(): + try: + path.unlink() + logger.debug("Cleaned up temporary %s file", kind) + except Exception as cleanup_error: + logger.warning("Could not delete temporary file: %s", cleanup_error, exc_info=True) + + +async def vision_analyze_tool( + image_url: str, user_prompt: str, model: str = None, + task_id: Optional[str] = None, region: Optional[list] = None) -> str: + """Describe an image (URL, local path, data: URL) with the auxiliary vision LLM. ``user_prompt`` + is pre-formatted by the caller. Temp images live under $HERMES_HOME/cache/vision/.""" + async def stage(prompt: str, debug_call_data: dict, temp_paths: list) -> tuple: + prepared = await _prepare_image(image_url, task_id, region, validate_decode=False) + temp_paths.append(prepared.path) + logger.info("Image ready (%.1f KB)", prepared.size_bytes / 1024) + # Send at full resolution first; on a size rejection, downscale and retry. + logger.info("Converting image to base64...") + image_data_url = await _run_encode_on_cpu_executor( + _image_to_base64_data_url, prepared.path, mime_type=prepared.mime) + logger.info("Image converted to base64 (%.1f KB)", len(image_data_url) / 1024) + _scale_info: dict = {} + if len(image_data_url) > _MAX_BASE64_BYTES: + image_data_url = await _resize_prepared(prepared, _scale_info) + if len(image_data_url) > _MAX_BASE64_BYTES: + raise ValueError(_too_large_message(image_data_url)) + debug_call_data["image_size_bytes"] = prepared.size_bytes + messages = _media_messages(prompt, "image_url", image_data_url) + logger.info("Processing image with vision model...") + call_kwargs = _aux_call_kwargs(messages, model, 120.0) + _load_auxiliary_client() + try: + response = await async_call_llm(**call_kwargs) + except Exception as _api_err: + if not (_is_image_size_error(_api_err) and len(image_data_url) > _RESIZE_TARGET_BYTES): + raise + logger.info( + "API rejected image (%.1f MB, likely too large); auto-resizing to ~%.0f MB and retrying...", + len(image_data_url) / (1024 * 1024), _RESIZE_TARGET_BYTES / (1024 * 1024)) + image_data_url = await _resize_prepared(prepared, _scale_info) + messages[0]["content"][1]["image_url"]["url"] = image_data_url + response = await async_call_llm(**call_kwargs) + analysis = await _call_vision_llm( + call_kwargs, "Vision LLM returned empty content, retrying once", response) + return analysis, _build_scale_note(_scale_info or None, prepared.crop_offset or None) + return await _run_analysis("image", image_url, user_prompt, model, stage) + + +def check_video_requirements() -> bool: + """True when ``call_llm(task="vision")`` could resolve a client. + + Mirrors its fallback chain: explicit ``auxiliary.vision.provider``, then auto (main + provider → openrouter → nous) — without the auto step the tool would vanish whenever + the explicit name was unresolvable. Probe mode skips real SDK client construction. + + See #31179. + """ + from agent.auxiliary_client import aux_probe_mode, resolve_vision_provider_client + # No blanket except: a resolver crash must reach the registry, which logs it with a + # traceback; a swallowed exception reads as "no vision backend configured" (#87950). + with aux_probe_mode(): + return any( + resolve_vision_provider_client(**kw)[1] is not None for kw in ({}, {"provider": "auto"}) + ) + + +def check_vision_requirements() -> bool: + """Image gate (``vision_analyze``, ``browser_vision``): an aux vision client OR the native fast + path. Both handlers attach pixels straight to a vision-capable main model, so a main model on a + provider the aux resolver does not know (OAuth, local vLLM) must not hide a working tool (#47149). + ``video_analyze`` keeps the aux-only gate — its handler has no native path. + """ + return _should_use_native_vision_fast_path() or check_video_requirements() + + +from tools.registry import registry, tool_error + +VISION_ANALYZE_SCHEMA = { + "name": "vision_analyze", + # Routing mechanics are deliberately absent (the route is automatic and the + # native result says so itself); region keeps its pre-effect guidance — a + # model that doesn't know crops keep full resolution never zooms. + "description": ( + # Dieted (#95681): routing mechanics (native attach vs aux-model text fallback) removed — the route + # is automatic and the native path's own tool result says "you can see it natively now"; the schema + # doesn't need to predict plumbing. + "Load an image into the conversation so you can see it. Call it " + "any time the user references an image — then answer from what " + "you see." + ), + "parameters": { + "type": "object", + "properties": { + "image_url": { + "type": "string", + "description": "Image URL (http/https), local file path, or data: URL to load." + }, + "question": { + "type": "string", + "description": "Your question or request about the image." + }, + "region": { + "type": "array", + "items": {"type": "integer"}, + "minItems": 4, + "maxItems": 4, + "description": ( + "Optional [x1, y1, x2, y2] crop in ORIGINAL-image pixel " + "coordinates, applied before any downscaling — the crop " + "keeps full resolution. Load the full image first, then " + "re-call with a region to zoom into small text or fine " + "detail." + ) + } + }, + "required": ["image_url", "question"] + } +} + + +def _configured_aux_model(sections: tuple, env_vars: tuple) -> Optional[str]: + """First non-empty ``auxiliary.<section>.model`` from config.yaml, else the first non-empty + env var (legacy override), else None.""" + for section in sections: + _vmodel = _cfg_auxiliary(section, "model") + if _vmodel: + if str(_vmodel).strip(): + return str(_vmodel).strip() + break + return next((v for v in (os.getenv(e, "").strip() for e in env_vars) if v), None) + + +async def _handle_vision_analyze(args: Dict[str, Any], **kw: Any) -> str: + image_url, question, region = args.get("image_url", ""), args.get("question", ""), args.get("region") + task_id = kw.get("task_id") + # No concurrency gate around the whole analysis — the CPU burst is bounded inside the + # encode/resize step, so multi-image fan-out keeps full request concurrency. + if _should_use_native_vision_fast_path(): + logger.info("vision_analyze: native fast path") + return await _vision_analyze_native(image_url, question, task_id=task_id, region=region) + + # Legacy path: aux LLM describes the image and we return its text. + full_prompt = ( + "Fully describe and explain everything about this image, then answer the " + f"following question:\n\n{question}") + model = _configured_aux_model(("vision",), ("AUXILIARY_VISION_MODEL",)) + return await vision_analyze_tool(image_url, full_prompt, model, task_id=task_id, region=region) + + +registry.register( + name="vision_analyze", + toolset="vision", + schema=VISION_ANALYZE_SCHEMA, + handler=_handle_vision_analyze, + check_fn=check_vision_requirements, + is_async=True, + emoji="👁️") + + +# --- video_analyze -------------------------------------------------------- +# Extension → MIME. avi/mkv fall back to mp4. +_VIDEO_MIME_TYPES = { + ".mp4": "video/mp4", + ".webm": "video/webm", + ".mov": "video/mov", + ".avi": "video/mp4", + ".mkv": "video/mp4", + ".mpeg": "video/mpeg", + ".mpg": "video/mpeg", +} + +_MAX_VIDEO_BASE64_BYTES = 50 * 1024 * 1024 # 50 MB hard cap +_VIDEO_SIZE_WARN_BYTES = 20 * 1024 * 1024 + + +def _detect_video_mime_type(video_path: Path) -> Optional[str]: + """Video MIME type from extension, or None if unsupported.""" + return _VIDEO_MIME_TYPES.get(video_path.suffix.lower()) + + +def _unsupported_video_format(suffix: str) -> str: + return f"Unsupported video format: '{suffix}'. Supported: {', '.join(sorted(_VIDEO_MIME_TYPES.keys()))}" + + +def _video_to_base64_data_url(video_path: Path, mime_type: Optional[str] = None) -> str: + mime = mime_type or _detect_video_mime_type(video_path) or "video/mp4" + return f"data:{mime};base64,{base64.b64encode(video_path.read_bytes()).decode('ascii')}" + + +async def _materialize_video(video_url: str, task_id: Optional[str], temp_paths: list) -> Path: + """Local video path for a terminal-backend path, local file, or HTTP(S) URL. Only files created + here are appended to ``temp_paths`` — never user-provided paths. Terminal-backend reads use the + shared media resolver with ``permitted=("video",)`` — the exact pipeline vision_analyze uses + (media-cache host reads, bounded in-sandbox exec-read, credential-read guard, 50MB cap).""" + from tools.image_source import ( + ImageResolutionError, ResolveContext, _is_local_terminal_backend, resolve_image_source, + ) + source = video_url.removeprefix("file://") + local_path = Path(os.path.expanduser(source)) + lowered = (video_url or "").strip().lower() + path_like = bool(lowered) and not lowered.startswith(("http://", "https://", "data:")) + if not _is_local_terminal_backend() and path_like: + logger.info("Reading video source via terminal backend: %s", video_url) + suffix = Path(source).suffix.lower() + if suffix not in _VIDEO_MIME_TYPES: + raise ValueError(_unsupported_video_format(suffix)) + try: + resolved = await resolve_image_source( + video_url, ResolveContext(task_id=task_id), permitted=("video",)) + except ImageResolutionError as exc: + raise ValueError(f"Could not read video from terminal backend: {exc}") from exc + temp_dir = get_hermes_dir("cache/video", "temp_video_files") + temp_dir.mkdir(parents=True, exist_ok=True) + path = temp_dir / f"terminal_video_{uuid.uuid4()}{suffix}" + path.write_bytes(resolved.data) + temp_paths.append(path) + return path + if local_path.is_file(): + from agent.file_safety import raise_if_read_blocked + raise_if_read_blocked(str(local_path)) + logger.info("Using local video file: %s", video_url) + return local_path + if await _validate_image_url_async(video_url): + blocked = check_website_access(video_url) + if blocked: + raise PermissionError(blocked["message"]) + path = get_hermes_dir("cache/video", "temp_video_files") / f"temp_video_{uuid.uuid4()}.mp4" + temp_paths.append(path) + # Video downloads retry every failure class (legacy behavior). + await _download_media( + video_url, path, 3, media_label="Video", accept="video/*,*/*;q=0.8", + max_bytes=_MAX_VIDEO_BASE64_BYTES, timeout=60.0, retry_all=True) + return path + raise ValueError("Invalid video source. Provide an HTTP/HTTPS URL or a valid local file path.") + + +async def video_analyze_tool( + video_url: str, user_prompt: str, model: str = None, task_id: Optional[str] = None) -> str: + """Analyze a video via multimodal LLM. Returns JSON {success, analysis}.""" + async def stage(prompt: str, debug_call_data: dict, temp_paths: list) -> tuple: + temp_video_path = await _materialize_video(video_url, task_id, temp_paths) + video_size_bytes = temp_video_path.stat().st_size + video_size_mb = video_size_bytes / (1024 * 1024) + logger.info("Video ready (%.1f MB)", video_size_mb) + detected_mime = _detect_video_mime_type(temp_video_path) + if not detected_mime: + raise ValueError(_unsupported_video_format(temp_video_path.suffix)) + if video_size_bytes > _VIDEO_SIZE_WARN_BYTES: + logger.warning("Video is %.1f MB — may be slow or rejected", video_size_mb) + video_data_url = _video_to_base64_data_url(temp_video_path, mime_type=detected_mime) + if len(video_data_url) > _MAX_VIDEO_BASE64_BYTES: + raise ValueError( + f"Video too large for API: base64 payload is {len(video_data_url) / (1024 * 1024):.1f} MB " + f"(limit {_MAX_VIDEO_BASE64_BYTES / (1024 * 1024):.0f} MB). " + f"Compress or trim the video and retry.") + debug_call_data["video_size_bytes"] = video_size_bytes + messages = _media_messages(prompt, "video_url", video_data_url) + call_kwargs = _aux_call_kwargs(messages, model, 180.0, min_timeout=180.0) + analysis = await _call_vision_llm(call_kwargs, "Empty video response, retrying once") + return analysis, None + return await _run_analysis("video", video_url, user_prompt, model, stage) + + +VIDEO_ANALYZE_SCHEMA = { + "name": "video_analyze", + "description": ( + "Analyze a video from a URL or local file path using a multimodal AI model. " + "Sends the video to a video-capable model (e.g. Gemini) for understanding. " + "Use this for video files — for images, use vision_analyze instead. " + "Supports mp4, webm, mov, avi, mkv, mpeg formats. " + "Note: large videos (>20 MB) may be slow; max ~50 MB." + ), + "parameters": { + "type": "object", + "properties": { + "video_url": { + "type": "string", + "description": "Video URL (http/https) or local file path to analyze.", + }, + "question": { + "type": "string", + "description": "Your specific question about the video. The AI will describe what happens in the video and answer your question.", + }, + }, + "required": ["video_url", "question"], + }, +} + + +def _handle_video_analyze(args: Dict[str, Any], **kw: Any) -> Awaitable[str]: + video_url, question = args.get("video_url", ""), args.get("question", "") + full_prompt = ( + "Fully describe and explain everything happening in this video, " + "including visual content, motion, audio cues, text overlays, and scene " + f"transitions. Then answer the following question:\n\n{question}") + model = _configured_aux_model(("video", "vision"), ("AUXILIARY_VIDEO_MODEL", "AUXILIARY_VISION_MODEL")) + return video_analyze_tool(video_url, full_prompt, model, task_id=kw.get("task_id")) + + +registry.register( + name="video_analyze", + toolset="video", + schema=VIDEO_ANALYZE_SCHEMA, + handler=_handle_video_analyze, + check_fn=check_video_requirements, + is_async=True, + emoji="🎬") + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. +import contextlib # noqa: F401,E402 +import sys # noqa: F401,E402 +import threading # noqa: F401,E402 +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/vision_tools_image_prep.py b/tools/vision_tools_image_prep.py new file mode 100644 index 0000000000000000000000000000000000000000..dac11878c6bcc43f4bb1847878c4bcdc4abff071 --- /dev/null +++ b/tools/vision_tools_image_prep.py @@ -0,0 +1,299 @@ +"""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 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 + +import logging +import uuid +from io import BytesIO +from pathlib import Path +from typing import Any, Optional + +from hermes_constants import get_hermes_dir + +logger = logging.getLogger("tools.vision_tools") + +_EXTENSION_MIME_TYPES = { + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".png": "image/png", + ".gif": "image/gif", + ".bmp": "image/bmp", + ".webp": "image/webp", + ".svg": "image/svg+xml", +} + +# 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"}) + + +_MAGIC_MIME_TYPES = ( + (b"\xff\xd8\xff", "image/jpeg"), ((b"GIF87a", b"GIF89a"), "image/gif"), (b"BM", "image/bmp"), +) + + +def _determine_mime_type(image_path: Path) -> str: + """MIME type from file extension (defaults to image/jpeg).""" + return _EXTENSION_MIME_TYPES.get(image_path.suffix.lower(), "image/jpeg") + + +def _detect_image_mime_type_from_bytes(data: bytes) -> Optional[str]: + """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"): + # 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: + return "image/png" + try: + with Image.open(BytesIO(data)) as image: + image.verify() + return "image/png" + except Exception: + return None + 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" + # HEIF/HEIC/AVIF — ISO-BMFF container: bytes 0-4 are the box size, 4-8 the box type 'ftyp', + # 8-12 the major brand, and every 4 bytes from 16 a compatible brand. iPhone photos are HEIC + # (often mislabeled .jpg by upload pipelines); vision providers don't ingest HEIF, but + # _normalize_to_supported_image re-encodes it to PNG via pillow-heif (same soft-dependency + # pattern as SVG). The major brand alone can't tell AVIF from HEIC: AVIF files routinely carry + # generic 'mif1' as major and identify the codec only in the compatible-brand list. + if len(header) >= 12 and header[4:8] == b"ftyp": + major = header[8:12] + # Bound the brand scan by the declared box size so brands are never read out of a FOLLOWING + # box. A malformed size fails CLOSED (no compatible brands scanned) — falling back to the + # whole sniff window would widen the scan exactly when an attacker controls the size field. + # A size >= 16 overrunning the sniffed window is merely a truncated read: clamp it. + box_size = int.from_bytes(header[:4], "big") + limit = 16 if box_size < 16 else min(box_size, len(header)) + brands = {major} | {header[i:i + 4] for i in range(16, limit - 3, 4)} + # AV1-coded brands win over the generic HEIF ones when both appear. + if brands & {b"avif", b"avis", b"av01"}: + return "image/avif" + if brands & { + b"heic", b"heix", b"heim", b"heis", # HEVC-coded HEIF still/sequence + b"hevc", b"hevx", + b"mif1", b"msf1", # generic HEIF image / sequence + }: + return "image/heic" + 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.""" + try: + 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: # 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).""" + try: + import cairosvg # type: ignore + cairosvg.svg2png(url=str(svg_path), write_to=str(out_path)) + return _nonempty_file(out_path) + except Exception: + pass + try: + from svglib.svglib import svg2rlg # type: ignore + from reportlab.graphics import renderPM # type: ignore + drawing = svg2rlg(str(svg_path)) + if drawing is not None: + renderPM.drawToFile(drawing, str(out_path), fmt="PNG") + 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}"]): + if shutil.which(cmd[0]): + try: + subprocess.run(cmd, check=True, capture_output=True, timeout=30, stdin=subprocess.DEVNULL) + if _nonempty_file(out_path): + return True + except Exception: + continue + return False + + +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 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, ( + "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.") + # HEIF/AVIF need a codec Pillow's core doesn't always carry, served by DIFFERENT optional + # backends that must not be gated on one another: HEIC/HEIF (HEVC) needs the pillow-heif + # plugin registered; AVIF (AV1) is native in Pillow >= 11.3 while pillow-heif wheels are + # frequently built with NO AV1 codec at all. Register whatever backend is available, let the + # decode attempt be the arbiter, and only emit a codec-specific error if it really fails — + # same soft-dependency posture as the SVG branch. + if detected_mime in ("image/heic", "image/avif"): + try: + import pillow_heif # type: ignore + pillow_heif.register_heif_opener() + except Exception: + logger.debug("pillow-heif unavailable; relying on Pillow for %s", detected_mime) + 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 _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) + # Codec-specific guidance: name the backend that actually serves this format. + if detected_mime == "image/heic": + return None, None, ( + "This is a HEIC/HEIF image (common for iPhone photos), which " + "vision models cannot read directly, and no HEIF decoder is " + "available. Install one (`pip install pillow-heif`) and re-run " + "vision_analyze, or convert the image to PNG/JPEG first.") + if detected_mime == "image/avif": + return None, None, ( + "This is an AVIF image, which vision models cannot read " + "directly, and no AV1 decoder is available. Upgrade Pillow " + "(>= 11.3 bundles AVIF support) or install a pillow-heif build " + "with an AV1 codec, then re-run vision_analyze — or convert the " + "image to PNG/JPEG first.") + 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.") + + +# 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 + + +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.""" + try: + from PIL import Image as _PILImage, ImageSequence as _PILImageSequence + except ImportError: + return None + try: + with _PILImage.open(image_path) as image: + image.verify() + with _PILImage.open(image_path) as image: + validated_pixels = 0 + 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.") + 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}.") + frame.load() + validated_pixels = next_validated_pixels + except Exception as exc: + return f"Image could not be fully decoded: {exc}" + return None + + +def _image_exceeds_dimension(image_path: Path, max_dimension: int) -> bool: + """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: + return max(_img.size) > max_dimension + except Exception: + return False + + +def _crop_image_region( + 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), 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)) 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).") + try: + with Image.open(image_path) as img: + width, height = img.size + x1, y1, x2, y2 = (int(v) for v in region) + 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}].") + 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") + if cropped.mode not in ("RGB", "RGBA", "L", "LA", "P"): + cropped = cropped.convert("RGB") + cropped.save(out_path, format="PNG") + return out_path, "image/png", None + except Exception as exc: + return None, None, f"Failed to crop region: {exc}" diff --git a/tools/voice_client_config.py b/tools/voice_client_config.py new file mode 100644 index 0000000000000000000000000000000000000000..87b201dac85505ac3f69402d8a211923126eaf1c --- /dev/null +++ b/tools/voice_client_config.py @@ -0,0 +1,220 @@ +"""Resolve the active profile's STT/TTS config for CLIENT-DIRECT voice. + +Single resolver behind ``GET /api/audio/voice-config``: the desktop skips the +audio relay hop by calling providers directly with the profile's own +credentials, resolved through the exact chains of ``tools.transcription_tools`` +and ``tools.tts_tool`` so the client gets byte-for-byte what the gateway uses. +Rules: same trust boundary as every REST route (keys never logged, never hit +client disk); relay is the floor, not an error (server-host-only providers and +resolution failures return ``{"mode": "relay"}``); no new key stores. +Config gate: ``voice.client_direct`` (default ``true``). +""" + +from __future__ import annotations + +import logging +from typing import Any, Dict, Optional + +logger = logging.getLogger(__name__) + +# Wire shapes the desktop knows how to speak. Anything else → relay. +# openai-multipart : POST {base_url}/audio/transcriptions (multipart, Bearer) +# xai-stt : POST {base_url}/stt (multipart, Bearer, format=true) +# elevenlabs-stt : POST {base_url}/speech-to-text (multipart, xi-api-key) +# openai-speech : POST {base_url}/audio/speech (JSON, Bearer) → audio bytes +# elevenlabs-tts : POST {base_url}/text-to-speech/{voice_id} (JSON, xi-api-key) +STT_WIRE_OPENAI = "openai-multipart" +STT_WIRE_XAI = "xai-stt" +STT_WIRE_ELEVENLABS = "elevenlabs-stt" +TTS_WIRE_OPENAI = "openai-speech" +TTS_WIRE_ELEVENLABS = "elevenlabs-tts" + + +def _client_direct_enabled() -> bool: + try: + from hermes_cli.config import load_config + voice_cfg = load_config().get("voice") or {} + if not isinstance(voice_cfg, dict): + return True + value = voice_cfg.get("client_direct", True) + except Exception: + return True + if isinstance(value, bool): + return value + if isinstance(value, str): + return value.strip().lower() not in {"0", "false", "no", "off"} + return True + + +def _relay(reason: str) -> Dict[str, Any]: + """A relay verdict that tells the client WHY, without secrets.""" + return {"mode": "relay", "reason": reason} + + +def _section(config: Any, provider: str) -> Dict[str, Any]: + """The provider's own sub-dict of an STT/TTS config, shape-guarded.""" + section = config.get(provider) if isinstance(config, dict) else None + return section if isinstance(section, dict) else {} + + +def _direct(wire: str, provider: str, base_url: Any, api_key: str, model: Any, **extra: Any) -> Dict[str, Any]: + return {"mode": "direct", "wire": wire, "provider": provider, "base_url": base_url, + "api_key": api_key, "model": model, **extra} + + +def _deepinfra_model(section: Dict[str, Any], kind: str) -> Optional[str]: + """Configured model, else the first catalog model of ``kind`` (stt/tts).""" + from hermes_cli.models import deepinfra_model_ids + return section.get("model") or next(iter(deepinfra_model_ids(kind)), None) + + +# ── STT ── +# provider -> (env var, default-model attr on transcription_common, base_url). +# ``base_url`` is a transcription_common attr name or a literal URL. +_STT_KEYED: Dict[str, tuple[str, str, str]] = { + "groq": ("GROQ_API_KEY", "DEFAULT_GROQ_STT_MODEL", "GROQ_BASE_URL"), + "mistral": ("MISTRAL_API_KEY", "DEFAULT_MISTRAL_STT_MODEL", "https://api.mistral.ai/v1"), +} + + +def _resolve_stt_client_config() -> Dict[str, Any]: + from tools import transcription_common as tc + from tools import transcription_tools as tt + + stt_config = tt._load_stt_config() + if not tt.is_stt_enabled(stt_config): + return _relay("stt disabled") + provider = tt._get_provider(stt_config) + # Server-host-only: local whisper, the env-var command escape hatch, + # declared command providers, and anything plugin-registered. + if tt._is_local_stt_provider(provider, stt_config): + return _relay("local provider") + if provider not in tc.BUILTIN_STT_PROVIDERS: + return _relay("command/plugin provider") + + language = tt._resolve_stt_language( + provider, stt_config, extra_keys=("language_code",) if provider == "elevenlabs" else ()) + section = _section(stt_config, provider) + + def direct(wire: str, base_url: Any, api_key: str, model: Any) -> Dict[str, Any]: + return _direct(wire, provider, base_url, api_key, model, language=language) + + def env_base_url(env_var: str, default: str) -> str: + from hermes_cli.config import get_env_value + return str(section.get("base_url") or get_env_value(env_var) or default).strip().rstrip("/") + + if provider in _STT_KEYED: + env_var, default_model, base = _STT_KEYED[provider] + api_key = tt._resolve_provider_key(env_var, provider) + if not api_key: + return _relay("no credentials") + return direct(STT_WIRE_OPENAI, getattr(tc, base, base), api_key, + section.get("model") or getattr(tc, default_model)) + if provider == "openai": + # Covers the Nous-managed selection too: the resolver returns the user's + # own gateway token + managed base URL — exactly what the client should use. + try: + api_key, base_url = tt._resolve_openai_audio_client_config() + except ValueError as exc: + return _relay(f"openai resolution failed: {exc}") + return direct(STT_WIRE_OPENAI, base_url, api_key, section.get("model") or tc.DEFAULT_STT_MODEL) + if provider == "xai": + # API key only: an xAI OAuth bearer refreshes server-side mid-session and + # would strand the client on the first 401. + from hermes_cli.config import get_env_value + api_key = str(get_env_value("XAI_API_KEY") or "").strip() + if not api_key: + return _relay("xai oauth (server-managed) or no credentials") + return direct(STT_WIRE_XAI, env_base_url("XAI_STT_BASE_URL", tc.XAI_STT_BASE_URL), api_key, None) + if provider == "elevenlabs": + api_key = tt._resolve_provider_key("ELEVENLABS_API_KEY", "elevenlabs") + if not api_key: + return _relay("no credentials") + return direct(STT_WIRE_ELEVENLABS, env_base_url("ELEVENLABS_STT_BASE_URL", tc.ELEVENLABS_STT_BASE_URL), + api_key, section.get("model") or tc.DEFAULT_ELEVENLABS_STT_MODEL) + if provider == "deepinfra": + api_key = tt._resolve_provider_key("DEEPINFRA_API_KEY", "deepinfra") + if not api_key: + return _relay("no credentials") + from hermes_cli.models import deepinfra_base_url + model = _deepinfra_model(section, "stt") + if not model: + return _relay("no deepinfra stt model") + return direct(STT_WIRE_OPENAI, deepinfra_base_url(section), api_key, model) + return _relay(f"provider {provider!r} has no client wire") + + +# ── TTS ── +def _resolve_tts_client_config() -> Dict[str, Any]: + from tools import tts_tool as tts + from tools import tts_tool_openai, tts_tool_providers + + tts_config = tts._load_tts_config() + provider = tts._get_provider(tts_config) + if provider not in tts.BUILTIN_TTS_PROVIDERS: + return _relay("command/plugin provider") + + if provider == "openai": + # Covers the direct-key, custom-base_url, and Nous-managed selections. + try: + api_key, base_url, is_managed = tts_tool_openai._resolve_openai_audio_client_config() + except ValueError as exc: + return _relay(f"openai resolution failed: {exc}") + oai = _section(tts_config, "openai") + model = oai.get("model") or tts_tool_openai.DEFAULT_OPENAI_MODEL + config_base = oai.get("base_url") + base_url = config_base or base_url + # The managed gateway only proxies MANAGED_OPENAI_TTS_MODELS — same + # coercion text_to_speech applies server-side. + if is_managed and not config_base and model not in tts_tool_openai.MANAGED_OPENAI_TTS_MODELS: + model = tts_tool_openai.DEFAULT_OPENAI_MODEL + speed_default = tts_config.get("speed", 1.0) if isinstance(tts_config, dict) else 1.0 + try: + speed = float(oai.get("speed", speed_default)) + except (TypeError, ValueError): + speed = 1.0 + return _direct(TTS_WIRE_OPENAI, "openai", base_url, api_key, model, + voice=oai.get("voice") or tts_tool_openai.DEFAULT_OPENAI_VOICE, speed=speed) + if provider == "elevenlabs": + api_key = tts._resolve_provider_key("ELEVENLABS_API_KEY", "elevenlabs") + if not api_key: + return _relay("no credentials") + el = _section(tts_config, "elevenlabs") + return _direct(TTS_WIRE_ELEVENLABS, "elevenlabs", + str(el.get("base_url") or "https://api.elevenlabs.io/v1").rstrip("/"), + api_key, el.get("model_id") or tts_tool_providers.DEFAULT_ELEVENLABS_MODEL_ID, + voice=el.get("voice_id") or tts_tool_providers.DEFAULT_ELEVENLABS_VOICE_ID, speed=None) + if provider == "deepinfra": + api_key = tts._resolve_provider_key("DEEPINFRA_API_KEY", "deepinfra") + if not api_key: + return _relay("no credentials") + from hermes_cli.models import deepinfra_base_url + di = _section(tts_config, "deepinfra") + model = _deepinfra_model(di, "tts") + if not model: + return _relay("no deepinfra tts model") + return _direct(TTS_WIRE_OPENAI, "deepinfra", deepinfra_base_url(di), api_key, model, + voice=di.get("voice") or "af_bella", speed=None) + # edge / minimax / xai / mistral / gemini / neutts / kittentts / piper: server-host-only + # engines or wire shapes the desktop doesn't speak yet; the relay path serves them. + return _relay(f"provider {provider!r} has no client wire") + + +def resolve_client_voice_config() -> Dict[str, Any]: + """Resolve both directions for the CURRENT profile scope. + + Callers scope the profile via ``hermes_constants.set_hermes_home_override`` + (the web server's ``_config_profile_scope``) before calling — identical to + how ``/api/audio/transcribe`` scopes ``transcribe_recording``. + """ + if not _client_direct_enabled(): + disabled = _relay("voice.client_direct disabled") + return {"stt": disabled, "tts": disabled} + out: Dict[str, Any] = {} + for key, resolver in (("stt", _resolve_stt_client_config), ("tts", _resolve_tts_client_config)): + try: + out[key] = resolver() + except Exception: + logger.exception("client voice-config %s resolution failed", key.upper()) + out[key] = _relay("resolution error") + return out diff --git a/tools/voice_live.py b/tools/voice_live.py new file mode 100644 index 0000000000000000000000000000000000000000..b9ab6f78639aa7adc7b08f8b416894d68d21e0c8 --- /dev/null +++ b/tools/voice_live.py @@ -0,0 +1,186 @@ +"""GPT-Live voice chat mode: the full-duplex voice frontend that delegates to Hermes. + +``voice.voice_chat_mode: gpt-live`` replaces the chained STT → turn → TTS loop with ONE +full-duplex voice model (OpenAI ``gpt-live-1``) that owns the microphone and the speaker and +delegates every real request to Hermes as its *client-delegation* backend. Hermes stays the +agent: whatever model/provider the session has selected answers, with the full toolset. + +Division of labour (the Live API has no tools of its own in client mode): + +* the desktop renderer holds the WebRTC media session (mic in, speech out) and the data channel; +* this module resolves WHICH credentials/voice/persona to use and performs the one server-side + step the API requires — exchanging the browser's SDP offer for an answer with the project key + (``POST /v1/live/sessions``), so the key never reaches the client; +* the renderer turns each ``session.delegation.created`` into a normal ``prompt.submit`` on the + active session (surface ``voice-live``) and streams the reply back as + ``session.commentary.append`` — Hermes' answer is what the voice speaks. + +Vendor contract: https://developers.openai.com/api/docs/guides/live (+ live-delegation, +voice-webrtc). Billing is $0.05/min of session time on the OpenAI key, separate from the +Hermes turn. +""" + +from __future__ import annotations + +import json +import logging +import urllib.error +import urllib.request +from typing import Any, Dict, Optional + +logger = logging.getLogger(__name__) + +GPT_LIVE_MODE = "gpt-live" +CHAINED_MODE = "chained" +DEFAULT_LIVE_MODEL = "gpt-live-1" +DEFAULT_LIVE_VOICE = "marin" +DEFAULT_LIVE_BASE_URL = "https://api.openai.com/v1" +# Voices the vendor lists for gpt-live-1 (live-conversations guide) plus the realtime defaults it +# accepts; free text stays allowed for custom voices. +GPT_LIVE_VOICES = ( + "marin", "cedar", "quartz", "ripple", "vesper", "willow", "stone", "gleam", "meridian", + "bossa", "tempo", "beacon", "delta", "cinder", +) + +# Persona for the voice layer. Short on purpose: the live model has a small context window and +# the vendor guide asks for role + style + a labelled delegation policy, nothing more. The +# backend (Hermes) carries the real instructions, tools and memory. +LIVE_PERSONA = ( + "You are Hermes, a calm and friendly voice assistant. Speak naturally at an unhurried pace. " + "Be clear and direct, not overly cheerful. If the user is frustrated, acknowledge it briefly " + "and focus on the next helpful step.\n\n" + "Backchannel policy: Use moderate backchannels. Acknowledge naturally without competing with " + "the main response.\n\n" + "Interruption policy: Stop speaking when the user interrupts. Listen to what they say.\n\n" + "Delegation policy:\n" + "Backend tools:\n" + "- Hermes agent: a full AI agent with tools — it can run commands, read and edit files, " + "browse the web, search, remember things across sessions, schedule tasks, and reason " + "carefully about anything. It is the one who actually does work and knows facts.\n\n" + "Delegate to the backend when:\n" + "- The user asks a question that needs facts, current information, or careful reasoning.\n" + "- The user asks you to do, check, find, make, fix, run or remember anything.\n" + "- A correction changes work already requested.\n\n" + "Do not delegate to the backend when:\n" + "- The user greets you, makes small talk, or asks you to repeat a result already provided.\n" + "- You need a brief clarification to understand the request.\n\n" + "Delegate before giving an answer that depends on backend work. Do not guess the result " + "while waiting; say briefly that you are checking, then wait for the result." +) + +# Per-turn note prepended to the MODEL INPUT (never the byte-stable system prompt) when a turn +# arrives from the live voice layer. Same seam as the HUD note. +VOICE_LIVE_TURN_NOTE = ( + "[Note: this message is a delegation from a live spoken conversation. The text is a voice " + "transcript (it may contain mis-hearings, hesitations and later corrections; use the latest " + "intent). Your reply will be spoken aloud by a voice model that paraphrases it: answer in plain " + "conversational sentences, keep it short (a few sentences unless the user asked for detail), no " + "markdown, no lists, no code blocks, no URLs read out character by character. Do the work with " + "your tools as usual; only the final facts need to be spoken. Do not claim an action succeeded " + "before it actually did.]" +) + + +def voice_live_turn_note(context: str = "") -> str: + """The per-turn note plus, when the client sent one, the recent spoken exchange the delegation + refers to (the user's last words alone are often "yes" or "Thursday, not Friday").""" + context = context.strip() + if not context: + return VOICE_LIVE_TURN_NOTE + return f"{VOICE_LIVE_TURN_NOTE}\n[Recent spoken conversation, newest last:\n{context}]" + + +def _voice_section() -> Dict[str, Any]: + try: + from hermes_cli.config import load_config + voice = load_config().get("voice") + except Exception: + return {} + return voice if isinstance(voice, dict) else {} + + +def _live_section(voice: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + section = (voice if voice is not None else _voice_section()).get("gpt_live") + return section if isinstance(section, dict) else {} + + +def voice_chat_mode(voice: Optional[Dict[str, Any]] = None) -> str: + """``chained`` (default) or ``gpt-live``. Accepts the underscore spelling too.""" + raw = (voice if voice is not None else _voice_section()).get("voice_chat_mode") + mode = str(raw or CHAINED_MODE).strip().lower().replace("_", "-") + return GPT_LIVE_MODE if mode in {GPT_LIVE_MODE, "gptlive", "live"} else CHAINED_MODE + + +def _resolve_credentials(live: Dict[str, Any]) -> tuple[str, str]: + """``(api_key, base_url)`` — ``voice.gpt_live.api_key`` first, else the same OpenAI audio + chain the STT/TTS providers use (``VOICE_TOOLS_OPENAI_KEY`` → ``OPENAI_API_KEY`` → pool). + + The Nous-managed audio proxy does not carry ``/live/sessions``; this mode is direct-key only. + """ + from tools.tool_backend_helpers import resolve_openai_audio_api_key + api_key = str(live.get("api_key") or "").strip() or resolve_openai_audio_api_key() + base_url = str(live.get("base_url") or DEFAULT_LIVE_BASE_URL).strip().rstrip("/") + return api_key, base_url + + +def live_instructions(live: Optional[Dict[str, Any]] = None) -> str: + extra = str((live if live is not None else _live_section()).get("instructions") or "").strip() + return f"{LIVE_PERSONA}\n\n{extra}" if extra else LIVE_PERSONA + + +def resolve_gpt_live_status() -> Dict[str, Any]: + """Non-secret readiness verdict for the client: which mode is selected and whether GPT-Live + can start (a key resolves). Never returns the key.""" + voice = _voice_section() + mode = voice_chat_mode(voice) + live = _live_section(voice) + api_key, _base = _resolve_credentials(live) + return { + "mode": mode, + "available": bool(api_key), + "reason": None if api_key else "no OpenAI API key (set OPENAI_API_KEY or voice.gpt_live.api_key)", + "model": str(live.get("model") or DEFAULT_LIVE_MODEL), + "voice": str(live.get("voice") or DEFAULT_LIVE_VOICE), + } + + +def build_session_config(history: Optional[list] = None) -> Dict[str, Any]: + """The ``session`` object for ``POST /v1/live/sessions`` (client delegation, WebRTC — the + transport negotiates the audio format, so none is set).""" + live = _live_section() + config: Dict[str, Any] = { + "model": str(live.get("model") or DEFAULT_LIVE_MODEL), + "instructions": live_instructions(live), + "audio": {"output": {"voice": str(live.get("voice") or DEFAULT_LIVE_VOICE)}}, + "delegation": {"type": "client"}, + } + if history: + config["input"] = history + return config + + +def create_webrtc_session(sdp_offer: str, history: Optional[list] = None) -> Dict[str, Any]: + """Exchange the renderer's SDP offer for the Live session answer. + + Returns the vendor response ``{"session": {"id": ...}, "transport": {"type": "webrtc", + "sdp": ...}}``. Raises ``ValueError`` for a missing key and ``RuntimeError`` (with the vendor + status/detail) for a rejected request. + """ + live = _live_section() + api_key, base_url = _resolve_credentials(live) + if not api_key: + raise ValueError("GPT-Live needs an OpenAI API key (OPENAI_API_KEY or voice.gpt_live.api_key)") + body = json.dumps({ + "session": build_session_config(history), + "transport": {"type": "webrtc", "sdp": sdp_offer}, + }).encode("utf-8") + req = urllib.request.Request( + f"{base_url}/live/sessions", data=body, method="POST", + headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=30) as resp: + return json.loads(resp.read().decode("utf-8")) + except urllib.error.HTTPError as exc: + detail = exc.read().decode("utf-8", "replace")[:600] + logger.warning("GPT-Live session creation failed: %s %s", exc.code, detail) + raise RuntimeError(f"GPT-Live session creation failed ({exc.code}): {detail}") from exc diff --git a/tools/voice_mode.py b/tools/voice_mode.py new file mode 100644 index 0000000000000000000000000000000000000000..b420132774ff14a9f710ffffcc8f8c719514fbe2 --- /dev/null +++ b/tools/voice_mode.py @@ -0,0 +1,1581 @@ +"""Voice Mode -- push-to-talk recording and playback for the CLI. + +Capture via sounddevice, WAV via stdlib wave, STT via tools.transcription_tools, +playback via sounddevice or system players. Optional deps: ``uv sync --extra voice``. +""" + +import logging +import math +import os +import platform +import shlex +import shutil +import subprocess +import sys +from collections import deque +from contextlib import suppress +from pathlib import Path +import tempfile +import threading +import time +import wave +from typing import Any, Callable, Dict, List, Optional + +logger = logging.getLogger(__name__) + +from tools.voice_mode_transcript import _voice_config, is_voice_stop_phrase, is_whisper_hallucination +from hermes_constants import is_termux as _is_termux_environment + +# ── Recording parameters ── +SAMPLE_RATE = 16000 # Whisper native rate +CHANNELS = 1 +DTYPE = "int16" +SAMPLE_WIDTH = 2 # bytes per sample (int16) +SILENCE_RMS_THRESHOLD = 200 # RMS below this = silence (int16 range 0-32767) +SILENCE_DURATION_SECONDS = 3.0 # continuous silence before auto-stop +_TEMP_DIR = os.path.join(tempfile.gettempdir(), "hermes_voice") + + +# ── Lazy audio imports ── +# Never imported at module level: crashes headless environments (SSH, Docker, +# WSL, no PortAudio). + +def _import_audio(): + """Lazy-import (sounddevice, numpy); raises ImportError/OSError when unavailable.""" + import sounddevice as sd + import numpy as np + return sd, np + + +def _sounddevice_output_allowed() -> bool: + """False on macOS: PortAudio/CoreAudio OUTPUT init triggers a kTCCServiceMediaLibrary + prompt, so output goes through ``afplay`` there. Input (recording) is unaffected. + + Returns False on macOS: importing/initializing sounddevice (PortAudio/CoreAudio) for output triggers a + kTCCServiceMediaLibrary permission prompt, even though playback needs no media-library access. This does + NOT affect audio *input* (recording), which legitimately needs microphone permission. See PR #62601 / + #13291. + """ + return platform.system() != "Darwin" + + +def _play_int16_via_tempfile(audio, sample_rate: int) -> None: + """Play int16 mono PCM via a temp WAV + play_audio_file (macOS: afplay, no TCC prompt).""" + tmp_path = None + try: + tmp = tempfile.NamedTemporaryFile(suffix=".wav", delete=False) + tmp_path = tmp.name + _write_wav_frames(tmp, audio.tobytes(), sample_rate) + play_audio_file(tmp_path) + except Exception as e: + logger.debug("Tone tempfile playback failed: %s", e) + finally: + _unlink_quietly(tmp_path) + + +def _write_wav_frames(dest, frames: bytes, sample_rate: int) -> None: + """Write raw 16-bit mono PCM *frames* as a WAV to *dest* (path or file object).""" + with wave.open(dest, "wb") as wf: + wf.setnchannels(CHANNELS) + wf.setsampwidth(SAMPLE_WIDTH) + wf.setframerate(sample_rate) + wf.writeframes(frames) + + +def _unlink_quietly(path: Optional[str]) -> None: + """Best-effort unlink; missing/undeletable files are ignored.""" + if path: + with suppress(OSError): + os.unlink(path) + + +def _audio_available() -> bool: + try: + _import_audio() + return True + except (ImportError, OSError): + return False + + +def _rms(np, data) -> float: + return float(np.sqrt(np.mean(data.astype(np.float64) ** 2))) + + +def _default_input_samplerate(sd) -> int: + """Default input device rate, else the Whisper-friendly SAMPLE_RATE.""" + with suppress(Exception): + info = sd.query_devices(None, "input") + rate = info.get("default_samplerate") if isinstance(info, dict) else getattr(info, "default_samplerate", None) + if isinstance(rate, (int, float)) and rate > 0: + return int(round(rate)) + return SAMPLE_RATE + + +# ── Environment detection ── +def _voice_capture_install_hint() -> str: + # sounddevice imports but PortAudio's shared library is missing — a pip install can't fix that; point at + # the system package instead of misreporting missing Python packages (#18432). + if _is_termux_environment(): + return "pkg install python-numpy portaudio && python -m pip install sounddevice" + # Inside a venv a bare `pip install` may hit whichever Python the shell + # resolves first (macOS: often a Rosetta system Python) — use the venv's pip. + with suppress(Exception): + if sys.prefix != getattr(sys, "base_prefix", sys.prefix): + pip_in_venv = Path(sys.prefix) / "bin" / "pip" + if pip_in_venv.exists(): + return f"{pip_in_venv} install sounddevice numpy" + return "pip install sounddevice numpy" + + +def _portaudio_missing_message() -> str: + """sounddevice imports but PortAudio's .so is missing — pip can't fix that.""" + hint = (" Termux: pkg install portaudio" if _is_termux_environment() + else " Linux: sudo apt-get install libportaudio2\n macOS: brew install portaudio") + return f"PortAudio system library not found -- install it first:\n{hint}\nThen retry /voice on." + + +_TERMUX_APP_MISSING_WARNING = ( + "Termux:API Android app is not installed. Install/update the Termux:API app to use termux-microphone-record." +) + + +def _termux_microphone_command() -> Optional[str]: + return shutil.which("termux-microphone-record") if _is_termux_environment() else None + + +def _run_quiet(cmd: List[str], *, timeout: float, check: bool) -> subprocess.CompletedProcess: + """subprocess.run with captured, utf-8-decoded output and no stdin.""" + return subprocess.run( + cmd, capture_output=True, text=True, encoding='utf-8', errors='replace', + timeout=timeout, check=check, stdin=subprocess.DEVNULL) + + +# `pm list packages` is canonical, but on some ROMs `pm` isn't on Termux's PATH +# while `cmd package` is, and on others `pm` returns nothing for the calling +# user even when the app is present — so both are tried. +_TERMUX_API_PACKAGE_PROBES = ( + ("pm", "list", "packages", "com.termux.api"), + ("cmd", "package", "list", "packages", "com.termux.api"), +) + + +def _termux_api_app_installed() -> bool: + """True iff the Termux:API Android app is installed. + + A probe reporting ``package:com.termux.api`` is authoritative. If EVERY probe + is inconclusive (binary missing, denied, timeout, non-zero exit) trust the + ``termux-microphone-record`` binary on PATH: a false negative blocks ``/voice + on``, a false positive only surfaces a precise runtime error. + """ + if not _is_termux_environment(): + return False + inconclusive = False + for cmd in _TERMUX_API_PACKAGE_PROBES: + try: + result = _run_quiet(list(cmd), timeout=5, check=False) + except (OSError, subprocess.TimeoutExpired): + result = None + if result is None or result.returncode != 0: + inconclusive = True + continue + if "package:com.termux.api" in (result.stdout or "").lower(): + return True + if inconclusive and shutil.which("termux-microphone-record") is not None: + logger.debug( + "Termux package-manager probes inconclusive; trusting " + "termux-microphone-record binary on PATH (issue #31015).") + return True + return False + + +def _termux_voice_capture_available() -> bool: + return _termux_microphone_command() is not None and _termux_api_app_installed() + + +def _pulse_socket_candidates() -> List[str]: + """Socket paths a PulseAudio/PipeWire client would try by default.""" + env = os.environ.get + # PULSE_SERVER may be "unix:/path", "unix:/path;..." or a bare path. + parts = [p.strip() for p in env('PULSE_SERVER', '').split(';')] + candidates = [p[len('unix:'):] for p in parts if p.startswith('unix:')] + if env('PULSE_RUNTIME_PATH'): + candidates.append(os.path.join(env('PULSE_RUNTIME_PATH'), 'native')) + if env('XDG_RUNTIME_DIR'): + candidates += [os.path.join(env('XDG_RUNTIME_DIR'), 'pulse', 'native'), + os.path.join(env('XDG_RUNTIME_DIR'), 'pipewire-0')] + return [c for c in candidates if c] + + +def _pulse_socket_reachable() -> bool: + """True if a PulseAudio/PipeWire socket on disk accepts a connection (a stale socket of + a dead server does not count). Covers a local sound server without PULSE_SERVER set. + + Covers the common case where a sound server runs locally (e.g. on a remote SSH host) without + ``PULSE_SERVER``/``PIPEWIRE_REMOTE`` being set -- the client just connects to the default socket under + the runtime dir. We look at ``PULSE_SERVER`` unix paths, ``PULSE_RUNTIME_PATH``, and ``XDG_RUNTIME_DIR`` + for a ``pulse/native`` or ``pipewire-0`` socket (issue #35622). + """ + import socket + import stat + for path in _pulse_socket_candidates(): + try: + if not stat.S_ISSOCK(os.stat(path).st_mode): + continue + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock: + sock.settimeout(0.5) + sock.connect(path) + return True + except OSError: + continue + return False + + +def _probe_audio_libraries(warnings: List[str], notices: List[str], *, has_forwarded_audio: bool, + termux_mic_cmd: Optional[str], termux_app_installed: bool) -> None: + """Import sounddevice and query devices; append the outcome to warnings/notices. + + Host audio forwarding or Termux:API capture downgrade "no devices" / "query + failed" to notices — in WSL with PulseAudio the query can fail yet audio works. + """ + termux_capture = bool(termux_mic_cmd and termux_app_installed) + + def outcome(termux_notice, warning, *, forwarded_notice="", import_failed=False): + if forwarded_notice and has_forwarded_audio: + notices.append(forwarded_notice) + elif termux_capture: + notices.append(termux_notice) + elif import_failed and termux_mic_cmd and not termux_app_installed: + warnings.append(_TERMUX_APP_MISSING_WARNING) + else: + warnings.append(warning) + + try: + sd, _ = _import_audio() + except ImportError: + return outcome("Termux:API microphone recording available (sounddevice not required)", + f"Audio libraries not installed ({_voice_capture_install_hint()})", import_failed=True) + except OSError: + return outcome("Termux:API microphone recording available (PortAudio not required)", + _portaudio_missing_message(), import_failed=True) + try: + if sd.query_devices(): + return + outcome("No PortAudio devices detected, but Termux:API microphone capture is available", + "No audio input/output devices detected", + forwarded_notice="No PortAudio devices detected but host audio forwarding is configured -- continuing") + except Exception: + outcome("PortAudio device query failed, but Termux:API microphone capture is available", + "Audio subsystem error (PortAudio cannot query devices)", + forwarded_notice="Audio device query failed but host audio forwarding is configured -- continuing") + + +def detect_audio_environment() -> dict: + """Return ``{'available', 'warnings' (hard-fail, block voice), 'notices' (informational)}``. + + SSH, containers and WSL normally have no audio devices, but a reachable sound + server (PulseAudio/PipeWire socket or forwarding env vars) is honored. + """ + warnings, notices = [], [] + termux_mic_cmd = _termux_microphone_command() + termux_app_installed = _termux_api_app_installed() + has_forwarded_audio = bool( + os.environ.get('PULSE_SERVER') or os.environ.get('PIPEWIRE_REMOTE') or _pulse_socket_reachable()) + + def report(notice: str, warning: str) -> None: + (notices if has_forwarded_audio else warnings).append(notice if has_forwarded_audio else warning) + + # SSH detection -- normally no audio devices, but honor a reachable sound server (PulseAudio/PipeWire + # socket or forwarding env vars), which works fine over SSH (issue #35622). + if any(os.environ.get(v) for v in ('SSH_CLIENT', 'SSH_TTY', 'SSH_CONNECTION')): + report("Running over SSH with a reachable PulseAudio/PipeWire sound server", + "Running over SSH -- no audio devices available.\n" + " If a sound server (PulseAudio/PipeWire) is running on this host,\n" + " point Hermes at it, e.g.:\n" + " export XDG_RUNTIME_DIR=/run/user/$(id -u)\n" + " # or: export PULSE_SERVER=unix:$XDG_RUNTIME_DIR/pulse/native") + + # Docker/Podman container detection — honor host audio forwarding. When the user mounts a + # PulseAudio/PipeWire socket into the container and points PULSE_SERVER / PIPEWIRE_REMOTE at it, audio + # works fine (issue #21203). Only block when no forwarding is configured. + from hermes_constants import is_container + if is_container(): + report("Running inside container (Docker/Podman/LXC) with host audio forwarding", + "Running inside container (Docker/Podman/LXC) -- no audio devices.\n" + " Forward host audio with one of (substitute $XDG_RUNTIME_DIR for your runtime dir,\n" + " typically /run/user/$UID):\n" + " PulseAudio: -v $XDG_RUNTIME_DIR/pulse/native:$XDG_RUNTIME_DIR/pulse/native \\\n" + " -e PULSE_SERVER=unix:$XDG_RUNTIME_DIR/pulse/native\n" + " PipeWire: -e PIPEWIRE_REMOTE=$XDG_RUNTIME_DIR/pipewire-0") + + # WSL: the PowerShell/Media.SoundPlayer fallback only covers OUTPUT, so when + # it is all that's available downgrade to a notice (recording guidance stays + # visible, TTS-only usage isn't blocked). + if _is_wsl2_env(): + if has_forwarded_audio: + notices.append("Running in WSL with a reachable PulseAudio/PipeWire sound server") + elif _wsl_powershell_tts_available(): + notices.append( + "Running in WSL without a PulseAudio bridge -- TTS playback " + "will use the PowerShell/Media.SoundPlayer fallback. " + "Voice INPUT (recording) still requires a PulseAudio bridge:\n" + " 1. Set PULSE_SERVER=unix:/mnt/wslg/PulseServer\n" + " 2. Create ~/.asoundrc pointing ALSA at PulseAudio\n" + " 3. Verify with: arecord -d 3 /tmp/test.wav && aplay /tmp/test.wav") + else: + warnings.append( + "Running in WSL -- audio requires a forwarded sound server.\n" + " PulseAudio: export PULSE_SERVER=unix:/mnt/wslg/PulseServer\n" + " PipeWire: export PIPEWIRE_REMOTE=$XDG_RUNTIME_DIR/pipewire-0\n" + " Then verify: arecord -d 3 /tmp/test.wav && aplay /tmp/test.wav") + + _probe_audio_libraries(warnings, notices, has_forwarded_audio=has_forwarded_audio, + termux_mic_cmd=termux_mic_cmd, termux_app_installed=termux_app_installed) + return {"available": not warnings, "warnings": warnings, "notices": notices} + + +# ── Audio cues (beep tones) ── +_DEFAULT_BEEP_VOLUME = 0.3 + + +def _get_beep_volume() -> float: + """``voice.beep_volume`` clamped to 0.0-1.0; 0.3 when missing/invalid.""" + raw = _voice_config().get("beep_volume", _DEFAULT_BEEP_VOLUME) + try: + volume = float(raw) + except (TypeError, ValueError): + return _DEFAULT_BEEP_VOLUME + if isinstance(raw, bool) or volume < 0.0 or volume > 1.0 or math.isnan(volume): + return _DEFAULT_BEEP_VOLUME + return volume + + +def _sd_play_blocking(sd, audio, sample_rate: int, *, timeout: float, blocksize: int = 0) -> None: + """``sd.play`` then poll until idle or *timeout* (``sd.wait()`` has no timeout and + hangs forever if the device stalls).""" + sd.play(audio, samplerate=sample_rate, blocksize=blocksize) + deadline = time.monotonic() + timeout + while sd.get_stream() and sd.get_stream().active and time.monotonic() < deadline: + time.sleep(0.01) + sd.stop() + + +def play_beep(frequency: int = 880, duration: float = 0.12, count: int = 1) -> None: + """Play *count* short beeps of *frequency* Hz, *duration* s each. Synthesized with + numpy only (no sounddevice import => no macOS TCC prompt); macOS output via afplay.""" + try: + import numpy as np + except ImportError: + return + try: + samples_per_beep = int(SAMPLE_RATE * duration) + gap = np.zeros(int(SAMPLE_RATE * 0.06), dtype=np.int16) # 60ms between beeps + beep_volume = _get_beep_volume() + parts = [] + for i in range(count): + t = np.linspace(0, duration, samples_per_beep, endpoint=False) + tone = np.sin(2 * np.pi * frequency * t) + fade_len = min(int(SAMPLE_RATE * 0.01), samples_per_beep // 4) # avoid clicks + tone[:fade_len] *= np.linspace(0, 1, fade_len) + tone[-fade_len:] *= np.linspace(1, 0, fade_len) + parts.append((tone * beep_volume * 32767).astype(np.int16)) + if i < count - 1: + parts.append(gap) + audio = np.concatenate(parts) + if not _sounddevice_output_allowed(): + _play_int16_via_tempfile(audio, SAMPLE_RATE) + return + try: + sd, _ = _import_audio() + except (ImportError, OSError): + return + _sd_play_blocking(sd, audio, SAMPLE_RATE, timeout=2.0) + except Exception as e: + logger.debug("Beep playback failed: %s", e) + + +# ── Thinking sound — calm ambient "blub blub" while the agent works ── +# Minutes of silent tool use reads as "it died". Scaled by voice.beep_volume, gated +# by voice.thinking_sound (default on); the host's *should_play* callback decides +# when blips are allowed, using the output ref-count below as its signal. + +_audio_output_active_count = 0 +_audio_output_lock = threading.Lock() + + +def mark_audio_output_active(active: bool) -> None: + """Ref-count real audio output; playback paths bracket with (True)/(False) so + ``is_audio_output_active()`` means speech is leaving the speakers RIGHT NOW — + unlike per-turn TTS-done events, which stay 'busy' while waiting for text.""" + global _audio_output_active_count + with _audio_output_lock: + _audio_output_active_count = max(0, _audio_output_active_count + (1 if active else -1)) + + +def is_audio_output_active() -> bool: + """True while TTS/file audio is actually playing on the speakers.""" + with _audio_output_lock: + return _audio_output_active_count > 0 + + +_thinking_lock = threading.Lock() +_thinking_stop: Optional[threading.Event] = None + + +def thinking_sound_enabled() -> bool: + """Config gate: ``voice.thinking_sound`` (default True).""" + try: + from utils import is_truthy_value + return is_truthy_value(_voice_config().get("thinking_sound", True), default=True) + except Exception: + return True + + +def _synth_thinking_blip(np, frequency: float) -> "Any": + """One soft 'blub': short sine with a downward glide and a click-free envelope.""" + duration = 0.16 + n = int(SAMPLE_RATE * duration) + t = np.linspace(0, duration, n, endpoint=False) + glide = np.linspace(1.0, 0.72, n) # water-drop feel: freq → 0.72*freq + phase = 2 * np.pi * np.cumsum(frequency * glide) / SAMPLE_RATE + tone = 0.8 * np.sin(phase) + 0.2 * np.sin(phase / 2.0) # octave-down softens harmonics + attack = int(0.02 * SAMPLE_RATE) + env = np.ones(n) + env[:attack] = np.linspace(0.0, 1.0, attack) + env *= np.exp(-t * 14.0) + volume = _get_beep_volume() * 0.5 # deliberately quieter than the beeps + return (tone * env * volume * 32767).astype(np.int16) + + +def _thinking_sound_loop(stop: threading.Event, should_play) -> None: + """Daemon loop: alternating-pitch blips every ~0.8-1.2s until *stop*; skips (without + stopping) while *should_play* is False. macOS exits immediately: sounddevice output + is TCC-gated and per-second afplay churn is worse than silence.""" + if not _sounddevice_output_allowed(): + return + try: + sd, np = _import_audio() + except (ImportError, OSError): + return + import random + blips = [_synth_thinking_blip(np, p) for p in (392.0, 329.6)] # G4 / E4 + i = 0 + while not stop.is_set(): + try: + if should_play is None or should_play(): + blip = blips[i % len(blips)] + i += 1 + sd.play(blip, samplerate=SAMPLE_RATE) + stop.wait(len(blip) / SAMPLE_RATE + 0.02) + sd.stop() + except Exception as e: + logger.debug("Thinking sound blip failed: %s", e) + return + stop.wait(0.8 + random.random() * 0.4) + + +def start_thinking_sound(should_play=None) -> bool: + """Start the ambient thinking sound (idempotent); *should_play* is polled before each + blip. True when running (or already running), False when disabled/unavailable.""" + global _thinking_stop + if not thinking_sound_enabled(): + return False + with _thinking_lock: + if _thinking_stop is not None and not _thinking_stop.is_set(): + return True + stop = threading.Event() + _thinking_stop = stop + threading.Thread(target=_thinking_sound_loop, args=(stop, should_play), + daemon=True, name="voice-thinking-sound").start() + return True + + +def stop_thinking_sound() -> None: + """Stop the ambient thinking sound instantly (idempotent).""" + global _thinking_stop + with _thinking_lock: + stop, _thinking_stop = _thinking_stop, None + if stop is not None: + stop.set() + + +# ── Recorders ── +def _new_recording_path(ext: str) -> str: + """Timestamped ``recording_*.<ext>`` path under _TEMP_DIR (created on demand).""" + os.makedirs(_TEMP_DIR, exist_ok=True) + return os.path.join(_TEMP_DIR, f"recording_{time.strftime('%Y%m%d_%H%M%S')}.{ext}") + + +class _RecorderBase: + """Lock, recording flag, start time and live RMS shared by both recorder backends.""" + + def __init__(self) -> None: + self._lock = threading.Lock() + self._recording, self._start_time, self._current_rms = False, 0.0, 0 + + @property + def is_recording(self) -> bool: + return self._recording + + @property + def elapsed_seconds(self) -> float: + return time.monotonic() - self._start_time if self._recording else 0.0 + + @property + def current_rms(self) -> int: + """Current input RMS level (0-32767), updated each audio chunk.""" + return self._current_rms + + +class TermuxAudioRecorder(_RecorderBase): + """Recorder backend that uses Termux:API microphone capture commands.""" + + supports_silence_autostop = False + + def __init__(self) -> None: + super().__init__() + self._recording_path: Optional[str] = None + + def start(self, on_silence_stop=None) -> None: + del on_silence_stop # Termux:API does not expose live silence callbacks. + mic_cmd = _termux_microphone_command() + if not mic_cmd: + raise RuntimeError( + "Termux voice capture requires the termux-api package and app.\n" + "Install with: pkg install termux-api\n" + "Then install/update the Termux:API Android app.") + if not _termux_api_app_installed(): + raise RuntimeError( + "Termux voice capture requires the Termux:API Android app.\n" + "Install/update the Termux:API app, then retry /voice on.") + with self._lock: + if self._recording: + return + self._recording_path = _new_recording_path("aac") + command = [mic_cmd, "-f", self._recording_path, "-l", "0", "-e", "aac", + "-r", str(SAMPLE_RATE), "-c", str(CHANNELS)] + try: + _run_quiet(command, timeout=15, check=True) + except subprocess.CalledProcessError as e: + details = (e.stderr or e.stdout or str(e)).strip() + raise RuntimeError(f"Termux microphone start failed: {details}") from e + except Exception as e: + raise RuntimeError(f"Termux microphone start failed: {e}") from e + with self._lock: + self._start_time, self._recording, self._current_rms = time.monotonic(), True, 0 + logger.info("Termux voice recording started") + + def _stop_termux_recording(self) -> None: + mic_cmd = _termux_microphone_command() + if mic_cmd: + _run_quiet([mic_cmd, "-q"], timeout=15, check=False) + + def _reset_state(self) -> tuple: + """Clear recording state under the lock; return (was_recording, path, started_at).""" + with self._lock: + was_recording, path, started_at = self._recording, self._recording_path, self._start_time + self._recording, self._recording_path, self._current_rms = False, None, 0 + return was_recording, path, started_at + + def stop(self) -> Optional[str]: + was_recording, path, started_at = self._reset_state() + if not was_recording: + return None + self._stop_termux_recording() + if not path or not os.path.isfile(path): + return None + if time.monotonic() - started_at < 0.3 or os.path.getsize(path) <= 0: # sub-0.3s taps / empty + _unlink_quietly(path) + return None + logger.info("Termux voice recording stopped: %s", path) + return path + + def cancel(self) -> None: + _, path, _ = self._reset_state() + with suppress(Exception): + self._stop_termux_recording() + _unlink_quietly(path) + logger.info("Termux voice recording cancelled") + + def shutdown(self) -> None: + self.cancel() + + +class AudioRecorder(_RecorderBase): + """Thread-safe sounddevice.InputStream recorder: ``start(on_silence_stop=cb)`` ... + ``stop()`` -> WAV path or None; ``cancel()`` discards. With a callback the recording + auto-stops after ``silence_duration`` seconds of silence following speech.""" + + supports_silence_autostop = True + + def __init__(self) -> None: + super().__init__() + self._stream: Any = None + self._frames: List[Any] = [] + self._sample_rate: int = SAMPLE_RATE + self._on_silence_stop = None + self._silence_threshold: int = SILENCE_RMS_THRESHOLD + self._silence_duration: float = SILENCE_DURATION_SECONDS + self._min_speech_duration: float = 0.3 # seconds above threshold to confirm speech + self._max_dip_tolerance: float = 0.3 # max dip before resetting a speech attempt + self._max_wait: float = 15.0 # seconds to wait for speech before auto-stop + # Hard cap, wired from voice.max_recording_seconds by the CLI before each recording; 0 = none. + self._max_recording_seconds: float = 0.0 + self._peak_rms: int = 0 # for the speech-presence check in stop() + self._reset_detection_state() + + def _reset_detection_state(self) -> None: + self._has_spoken = False + # speech attempt / its dip / silence run / sustained resume after silence / resume dip + self._speech_start = self._dip_start = self._silence_start = 0.0 + self._resume_start = self._resume_dip_start = 0.0 + + def _max_duration_reached(self, elapsed: float) -> bool: + """``voice.max_recording_seconds`` cap elapsed (<= 0 / unset disables it).""" + cap = self._max_recording_seconds + return bool(cap and cap > 0 and elapsed >= cap) + + def _track_speech(self, rms: int, now: float) -> None: + """Advance the speech/dip trackers for one block. Speech is confirmed after + ``_min_speech_duration`` above threshold, tolerating dips < ``_max_dip_tolerance`` + (micro-pauses); afterwards only SUSTAINED resumed speech resets the silence timer.""" + if rms > self._silence_threshold: + self._dip_start = 0.0 + if self._speech_start == 0.0: + self._speech_start = now + elif not self._has_spoken and now - self._speech_start >= self._min_speech_duration: + self._has_spoken = True + logger.debug("Speech confirmed (%.2fs above threshold)", now - self._speech_start) + if not self._has_spoken: + self._silence_start = 0.0 + else: + # Resumed speech mirrors initial detection: track, tolerate dips, confirm. + self._resume_dip_start = 0.0 + if self._resume_start == 0.0: + self._resume_start = now + elif now - self._resume_start >= self._min_speech_duration: + self._silence_start = 0.0 + self._resume_start = 0.0 + elif self._has_spoken: + if self._resume_start > 0: # dip-tolerant resume reset + if self._resume_dip_start == 0.0: + self._resume_dip_start = now + elif now - self._resume_dip_start >= self._max_dip_tolerance: + self._resume_start = 0.0 + self._resume_dip_start = 0.0 + elif self._speech_start > 0: + # Speech attempt dipped; a long enough dip is genuine silence. + if self._dip_start == 0.0: + self._dip_start = now + elif now - self._dip_start >= self._max_dip_tolerance: + logger.debug("Speech attempt reset (dip lasted %.2fs)", now - self._dip_start) + self._speech_start = 0.0 + self._dip_start = 0.0 + + def _should_auto_stop(self, rms: int, now: float) -> bool: + """Spoke then silent for ``_silence_duration``; no speech for ``_max_wait``; + or the hard cap elapsed (independent of speech).""" + elapsed = now - self._start_time + if self._has_spoken and rms <= self._silence_threshold: + if self._silence_start == 0.0: + self._silence_start = now + elif now - self._silence_start >= self._silence_duration: + logger.info("Silence detected (%.1fs), auto-stopping", self._silence_duration) + return True + elif not self._has_spoken and elapsed >= self._max_wait: + logger.info("No speech within %.0fs, auto-stopping", self._max_wait) + return True + if self._max_duration_reached(elapsed): + logger.info("Max recording length reached (%.0fs), auto-stopping", self._max_recording_seconds) + return True + return False + + def _fire_silence_callback(self) -> None: + """Invoke ``on_silence_stop`` once, in a daemon thread.""" + with self._lock: + cb, self._on_silence_stop = self._on_silence_stop, None # fire only once + if not cb: + return + + def _safe_cb(): + try: + cb() + except Exception as e: + logger.error("Silence callback failed: %s", e, exc_info=True) + threading.Thread(target=_safe_cb, daemon=True).start() + + def _on_audio_block(self, np, indata) -> None: + self._frames.append(indata.copy()) + rms = int(_rms(np, indata)) + self._current_rms = rms + self._peak_rms = max(self._peak_rms, rms) + if self._on_silence_stop is None: + return + now = time.monotonic() + self._track_speech(rms, now) + if self._should_auto_stop(rms, now): + self._fire_silence_callback() + + def _ensure_stream(self) -> None: + """Create the InputStream once and keep it alive (between recordings the callback + discards chunks): re-opening an InputStream hangs on macOS CoreAudio.""" + if self._stream is not None: + return + sd, np = _import_audio() + + def _callback(indata, frames, time_info, status): # noqa: ARG001 + if status: + logger.debug("sounddevice status: %s", status) + if self._recording: + self._on_audio_block(np, indata) + + stream = None + for attempt in range(2): + try: # may block on CoreAudio (first call only) + stream = sd.InputStream(samplerate=self._sample_rate, channels=CHANNELS, dtype=DTYPE, + callback=_callback) + stream.start() + break + except Exception as e: + with suppress(Exception): + stream.close() + stream = None + # PortAudio paTimedOut (-9987): a cold host-API bridge (WSLg ALSA->Pulse + # with a SUSPENDED RDP source) missed the 1 s thread-start window. The + # failed open itself wakes the bridge, so one immediate retry succeeds + # where the user's second key press would have (#109303). + if attempt or "timed out" not in str(e).lower(): + raise RuntimeError( + f"Failed to open audio input stream: {e}. " + "Check that a microphone is connected and accessible.") from e + logger.info("Audio input stream start timed out; retrying once") + self._stream = stream + + def start(self, on_silence_stop=None) -> None: + """Start capturing; *on_silence_stop* is invoked (daemon thread, no args) when + silence follows speech. Raises ``RuntimeError`` if sounddevice/numpy are missing.""" + try: + sd, _ = _import_audio() + except OSError as e: + raise RuntimeError(_portaudio_missing_message()) from e + except ImportError as e: + raise RuntimeError( + "Voice mode requires sounddevice and numpy.\n" + f"Install with: {sys.executable} -m pip install sounddevice numpy") from e + with self._lock: + if self._recording: + return + self._frames = [] + self._start_time = time.monotonic() + self._reset_detection_state() + self._peak_rms = 0 + self._current_rms = 0 + self._on_silence_stop = on_silence_stop + self._sample_rate = _default_input_samplerate(sd) + self._ensure_stream() + with self._lock: + self._recording = True + logger.info("Voice recording started (rate=%d, channels=%d)", self._sample_rate, CHANNELS) + + def _close_stream_with_timeout(self, timeout: float = 3.0) -> None: + """Close the stream with a timeout to prevent CoreAudio hangs.""" + if self._stream is None: + return + stream, self._stream = self._stream, None + + def _do_close(): + with suppress(Exception): + stream.stop() + stream.close() + + t = threading.Thread(target=_do_close, daemon=True) + t.start() + clock = __import__("time") # real clock even when tests patch this module's ``time`` + deadline = clock.monotonic() + timeout + while t.is_alive() and clock.monotonic() < deadline: # short joins keep Ctrl+C responsive + t.join(timeout=0.1) + if t.is_alive(): + logger.warning("Audio stream close timed out after %.1fs — forcing ahead", timeout) + + def stop(self) -> Optional[str]: + """Stop recording (stream stays alive) and return the WAV path, or None if unusable.""" + with self._lock: + if not self._recording: + return None + self._recording, self._current_rms = False, 0 + if not self._frames: + return None + _, np = _import_audio() + audio_data = np.concatenate(self._frames, axis=0) + self._frames = [] + logger.info("Voice recording stopped (%.1fs, %d samples)", + time.monotonic() - self._start_time, len(audio_data)) + if len(audio_data) < int(self._sample_rate * 0.3): + logger.debug("Recording too short (%d samples), discarding", len(audio_data)) + return None + # Peak RMS, not the average (which trailing silence dilutes). + if self._peak_rms < SILENCE_RMS_THRESHOLD: + logger.info("Recording too quiet (peak RMS=%d < %d), discarding", + self._peak_rms, SILENCE_RMS_THRESHOLD) + return None + return self._write_wav(audio_data, sample_rate=self._sample_rate) + + def _discard(self) -> None: + with self._lock: + self._recording, self._frames, self._on_silence_stop, self._current_rms = False, [], None, 0 + + def cancel(self) -> None: + """Stop recording and discard all captured audio (stream stays alive).""" + self._discard() + logger.info("Voice recording cancelled") + + def shutdown(self) -> None: + """Release the audio stream. Call when voice mode is disabled.""" + self._discard() + self._close_stream_with_timeout() # outside the lock: avoids deadlock with the callback + logger.info("AudioRecorder shut down") + + @staticmethod + def _write_wav(audio_data, *, sample_rate: int = SAMPLE_RATE) -> str: + """Write numpy int16 audio to a WAV file; returns the path.""" + wav_path = _new_recording_path("wav") + _write_wav_frames(wav_path, audio_data.tobytes(), sample_rate) + logger.info("WAV written: %s (%d bytes)", wav_path, os.path.getsize(wav_path)) + return wav_path + + +def create_audio_recorder() -> AudioRecorder | TermuxAudioRecorder: + """Return the best recorder backend for the current environment.""" + return TermuxAudioRecorder() if _termux_voice_capture_available() else AudioRecorder() + + +# ── STT dispatch ── +def transcribe_recording(wav_path: str, model: Optional[str] = None) -> Dict[str, Any]: + """Transcribe a WAV via ``transcribe_audio()``, filtering Whisper hallucinations; + returns ``{success, transcript[, error]}``.""" + from tools.transcription_common import MAX_FILE_SIZE + from tools.transcription_tools import transcribe_audio + + result = transcribe_audio(wav_path, model=model, source="voice_mode") + # Only chunk when the provider itself reports "File too large" — local + # providers have no upload cap and never return this error. + if not result.get("success") and "File too large" in result.get("error", ""): + result = _transcribe_wav_in_chunks(wav_path, model=model, max_file_size=MAX_FILE_SIZE) + # A configured stop phrase always survives: "bye"/"okay" overlap the + # hallucination blocklist, and swallowing them would make "bye" fail to end the chat. + if result.get("success"): + raw_transcript = result.get("transcript", "") + if is_whisper_hallucination(raw_transcript) and not is_voice_stop_phrase(raw_transcript): + logger.info("Filtered Whisper hallucination: %r", result["transcript"]) + return {"success": True, "transcript": "", "filtered": True} + # no_speech = heard no words, not a failure: re-listen quietly instead of + # surfacing "Transcription failed". + if result.get("no_speech"): + return {"success": True, "transcript": "", "no_speech": True} + return result + + +def _transcribe_wav_in_chunks(wav_path: str, *, model: Optional[str], max_file_size: int) -> Dict[str, Any]: + """Split an oversized WAV into provider-sized chunks and join transcripts.""" + from tools.transcription_tools import transcribe_audio + + chunk_paths, transcripts = [], [] + try: + chunk_paths = _split_wav_for_transcription(wav_path, max_file_size=max_file_size) + if not chunk_paths: + return {"success": False, "transcript": "", "error": "No audio chunks were created"} + logger.info("Transcribing oversized WAV in %d chunks: %s", len(chunk_paths), wav_path) + for index, chunk_path in enumerate(chunk_paths, start=1): + result = transcribe_audio(chunk_path, model=model, source="voice_mode") + if not result.get("success"): + error = result.get("error", "Unknown transcription error") + return {"success": False, "transcript": "", + "error": f"Chunk {index}/{len(chunk_paths)} failed: {error}"} + transcript = result.get("transcript", "").strip() + if transcript and not is_whisper_hallucination(transcript): + transcripts.append(transcript) + return {"success": True, "transcript": " ".join(transcripts).strip(), + "provider": result.get("provider"), "chunks": len(chunk_paths)} + except Exception as e: + logger.error("Chunked transcription failed for %s: %s", wav_path, e, exc_info=True) + return {"success": False, "transcript": "", "error": f"Chunked transcription failed: {e}"} + finally: + for chunk_path in chunk_paths: + _unlink_quietly(chunk_path) + + +def _split_wav_for_transcription(wav_path: str, *, max_file_size: int) -> List[str]: + """Write WAV chunks small enough to pass the shared STT file-size gate.""" + os.makedirs(_TEMP_DIR, exist_ok=True) + chunk_paths: List[str] = [] + with wave.open(wav_path, "rb") as source: + params = source.getparams() + block_align = max(1, params.nchannels * params.sampwidth) + max_data_bytes = max_file_size - 64 * 1024 # header reserve + if max_data_bytes < block_align: + raise ValueError("STT max_file_size is too small for WAV chunking") + frames_per_chunk = max(1, max_data_bytes // block_align) + index = 0 + while True: + frames = source.readframes(frames_per_chunk) + if not frames: + break + index += 1 + with tempfile.NamedTemporaryFile( + prefix=f"{os.path.splitext(os.path.basename(wav_path))[0]}_chunk{index:03d}_", + suffix=".wav", dir=_TEMP_DIR, delete=False) as temp: + chunk_path = temp.name + try: + with wave.open(chunk_path, "wb") as chunk: + chunk.setparams(params._replace(nframes=0)) + chunk.writeframes(frames) + chunk_paths.append(chunk_path) + except Exception: + _unlink_quietly(chunk_path) + raise + return chunk_paths + + +# ── Audio playback (interruptable) ── +_active_playback: Optional[subprocess.Popen] = None # so stop_playback can interrupt it +_playback_lock = threading.Lock() + + +def _set_active_playback(proc) -> None: + global _active_playback + with _playback_lock: + _active_playback = proc + + +def stop_playback() -> None: + """Interrupt the currently playing audio (if any).""" + global _active_playback + with _playback_lock: + proc = _active_playback + _active_playback = None + if proc and proc.poll() is None: + with suppress(Exception): + proc.terminate() + logger.info("Audio playback interrupted") + with suppress(Exception): # also stop sounddevice playback if active + sd, _ = _import_audio() + sd.stop() + + +def _is_wsl2_env() -> bool: + """True inside WSL (Microsoft kernel signature in /proc/version); False on any error. + Module-level so tests can patch it instead of ``builtins.open``.""" + try: + with open("/proc/version", encoding="utf-8", errors="replace") as _fv: + return "microsoft" in _fv.read().lower() + except OSError: + return False + + +def _wsl_powershell_tts_available() -> bool: + """WSL2 PowerShell TTS fallback usable. OUTPUT only (Media.SoundPlayer on the host) — + recording still needs a PulseAudio bridge, so callers keep surfacing that guidance.""" + return bool(_is_wsl2_env() and shutil.which("powershell.exe") and shutil.which("ffmpeg")) + + +def play_audio_file(file_path: str) -> bool: + """Play an audio file; True on success. WAV via ``sounddevice.play()`` when allowed, + else system players: afplay (macOS), WSL2 PowerShell bridge, ffplay, aplay (Linux). + Interruptible via ``stop_playback()``.""" + mark_audio_output_active(True) # ref-count real speaker output for the whole call + try: + return _play_audio_file_impl(file_path) + finally: + mark_audio_output_active(False) + + +def _play_wav_via_sounddevice(file_path: str) -> bool: + """Play a WAV through sounddevice; False when unavailable/failed (caller falls through).""" + try: + sd, np = _import_audio() + with wave.open(file_path, "rb") as wf: + frames = wf.readframes(wf.getnframes()) + audio_data = np.frombuffer(frames, dtype=np.int16) + sample_rate = wf.getframerate() + # WSLg RDP audio needs a warmup to avoid crackling: the RDP channel takes + # ~100 ms to stabilise and the small default blocksize worsens + # clock-adjustment jitter (microsoft/wslg#1257). + blocksize = 0 # default (auto) + if _is_wsl2_env(): + fade_samples = int(0.1 * sample_rate) + audio_float = audio_data.astype(np.float64) + audio_float[:fade_samples] *= np.linspace(0.0, 1.0, fade_samples, dtype=np.float64) + audio_data = np.concatenate([ + np.zeros(int(0.1 * sample_rate), dtype=np.int16), audio_float.astype(np.int16), + np.zeros(int(0.05 * sample_rate), dtype=np.int16)]) + blocksize = 4096 + _sd_play_blocking(sd, audio_data, sample_rate, + timeout=len(audio_data) / sample_rate + 2.0, blocksize=blocksize) + return True + except (ImportError, OSError): + return False + except Exception as e: + logger.debug("sounddevice playback failed: %s", e) + return False + + +def _wsl_powershell_player_cmd(file_path: str) -> Optional[List[str]]: + """WSL2 PowerShell fallback player command, or None. Without a PulseAudio bridge + ffplay/aplay have no device, but Media.SoundPlayer on the host does: convert to a + uniquely-named WAV in Windows %TEMP% (concurrent TTS must not collide), play, always + delete, and re-raise the ORIGINAL exit status past the cleanup (rm -f exits 0).""" + if not (shutil.which("powershell.exe") and shutil.which("ffmpeg") and _is_wsl2_env()): + return None + try: + import uuid + + def _out(cmd): + return subprocess.check_output(cmd, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL, + timeout=3).decode(errors="replace").strip() + + win_tmp_wsl = _out(["wslpath", "-u", _out(["cmd.exe", "/c", "echo %TEMP%"])]) + if not win_tmp_wsl: + return None + wsl_wav = os.path.join(win_tmp_wsl, f"hermes-tts-{uuid.uuid4().hex[:8]}.wav") + win_wav = _out(["wslpath", "-w", wsl_wav]) + if not win_wav: + return None + win_wav_safe = win_wav.replace("'", "''") + ps_script = f"(New-Object Media.SoundPlayer '{win_wav_safe}').PlaySync()" + ps_cmd = " && ".join([ + shlex.join(["ffmpeg", "-i", file_path, "-f", "wav", wsl_wav, "-loglevel", "quiet", "-y"]), + shlex.join(["powershell.exe", "-NoProfile", "-Command", ps_script])]) + # /bin/sh full path so the which(cmd[0]) check in the player loop passes. + return ["/bin/sh", "-c", f"( {ps_cmd} ); rc=$?; {shlex.join(['rm', '-f', wsl_wav])}; exit $rc"] + except Exception: + return None # WSL path resolution failed; fall through to ffplay/aplay + + +def _system_player_candidates(file_path: str) -> List[List[str]]: + """Ordered system-player commands for this platform.""" + system = platform.system() + players: List[List[str]] = [["afplay", file_path]] if system == "Darwin" else [] + ps_cmd = _wsl_powershell_player_cmd(file_path) if system == "Linux" else None + if ps_cmd: + players.append(ps_cmd) + players.append(["ffplay", "-nodisp", "-autoexit", "-loglevel", "quiet", file_path]) + if system == "Linux": + players.append(["aplay", "-q", file_path]) + return players + + +def _run_system_player(cmd: List[str]) -> bool: + """Run one player to completion (interruptible via stop_playback).""" + proc = None + try: + # Sibling of the TTS/STT credential scrub: players must not inherit tokens/keys. + # See #56332, #70342. + from tools.environments.local import hermes_subprocess_env + proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL, + env=hermes_subprocess_env(inherit_credentials=False)) + _set_active_playback(proc) + proc.wait(timeout=300) + rc = proc.returncode + if rc == 0: + return True + # e.g. WSL ffplay/aplay with no audio device — fall through to the next player. + logger.debug("System player %s exited with code %d, trying next", cmd[0], rc) + except subprocess.TimeoutExpired: + logger.warning("System player %s timed out, killing process", cmd[0]) + if proc is not None: + proc.kill() + proc.wait() + except Exception as e: + logger.debug("System player %s failed: %s", cmd[0], e) + finally: + _set_active_playback(None) + return False + + +def _play_audio_file_impl(file_path: str) -> bool: + if not os.path.isfile(file_path): + logger.warning("Audio file not found: %s", file_path) + return False + # macOS skips sounddevice output (TCC media-library prompt); afplay handles all formats. + if file_path.endswith(".wav") and _sounddevice_output_allowed() and _play_wav_via_sounddevice(file_path): + return True + for cmd in _system_player_candidates(file_path): + if shutil.which(cmd[0]) and _run_system_player(cmd): + return True + logger.warning("No audio player available for %s", file_path) + return False + + +# ── Barge-in — detect the user speaking over TTS playback ── +# Public API kept from main: the per-playback barge monitor (rolling-floor VAD). No in-tree +# caller since full_duplex_listen took over the voice path, but plugins may import it. +def listen_for_speech( + should_stop: Callable[[], bool], + threshold: Optional[int] = None, + sustained_ms: int = 300, + calibration_ms: int = 400, + capture: bool = False, + on_trigger: Optional[Callable[[], None]] = None, + pre_roll_ms: int = 1200, + endpoint_silence_ms: int = 1250, + max_utterance_ms: int = 30_000, +): + """Block until sustained speech is heard on the mic, or *should_stop*. + + Barge-in monitor: run in a side thread while TTS is playing. Without + *capture* it returns ``True`` when the user started talking (cut playback). + With ``capture=True`` it ALSO records the interruption — a rolling + *pre_roll_ms* buffer means the utterance is kept from its first syllable, + not from the moment detection tripped — and keeps rolling until the user + goes quiet for *endpoint_silence_ms*, then returns the WAV path (or + ``None`` if speech never tripped). *on_trigger* fires at the moment of + detection so the caller can stop playback while capture continues. + + The noise floor is calibrated from the first *calibration_ms* of input — + playback is already audible then, so speaker bleed is baked into the + floor and only louder-than-playback speech trips the trigger. Requiring + *sustained_ms* of consecutive above-threshold blocks filters out coughs, + keyboard thumps, and playback transients. + """ + try: + sd, np = _import_audio() + except (ImportError, OSError): + return None if capture else False + + from collections import deque + + block = int(SAMPLE_RATE * 0.03) # 30ms blocks + calib_blocks = max(1, calibration_ms // 30) + trip_blocks = max(1, sustained_ms // 30) + endpoint_blocks = max(1, endpoint_silence_ms // 30) + max_blocks = max(1, max_utterance_ms // 30) + + # Rolling floor window: continuously tracks TTS speaker-bleed volume + # throughout playback, not just the first calibration_ms. This is the + # key fix for false barge-in — a one-shot calibration freezes a floor + # from the opening TTS passage, but later louder passages exceed the + # stale floor and false-trigger. The rolling window keeps the floor + # current so only genuinely louder-than-playback speech trips the VAD. + floor_window: "deque[float]" = deque(maxlen=max(calib_blocks, 100)) # ~3s rolling + pre_roll: deque = deque(maxlen=max(1, pre_roll_ms // 30)) + consecutive = 0 + min_floor = 0.0 # baseline from initial calibration; floor never drops below this + block_idx = 0 # block counter for diagnostic logging + + try: + with sd.InputStream(samplerate=SAMPLE_RATE, channels=1, dtype="int16", blocksize=block) as stream: + while not should_stop(): + data, _ = stream.read(block) + rms = float(np.sqrt(np.mean(data.astype(np.float64) ** 2))) + if capture: + pre_roll.append(data.copy()) + block_idx += 1 + + # Wait for at least calib_blocks before evaluating. During + # the initial warmup we always feed the window so calibration + # has data to work with. + if len(floor_window) < calib_blocks: + floor_window.append(rms) + continue + + # Lock a minimum floor from the initial calibration samples. + # During inter-sentence pauses the rolling window can flush + # with near-silence, collapsing the 90th-percentile floor + # toward zero and false-triggering on the next rising + # sentence. min_floor keeps the trigger from ever dropping + # below the baseline TTS playback level established during + # the initial calibration_ms window. + # + # If the grace period ended during an inter-sentence gap the + # calibration samples near-silence. Locking a near-zero + # floor sets the trigger so low that TTS blocks exceed it, + # are excluded from the rolling window (rms >= trigger), and + # the floor freezes — guaranteeing a false trigger the moment + # TTS resumes. Clamp min_floor to SILENCE_RMS_THRESHOLD * 2 + # (400 RMS) so the 8x multiplier yields a trigger of at least + # (500-2000 RMS) stays below it and feeds the rolling window, + # while genuine speech (3000-8000 RMS) can still trip it. + if min_floor == 0.0 and len(floor_window) >= calib_blocks: + _pct90 = float(np.percentile(list(floor_window), 90)) + min_floor = max(_pct90, SILENCE_RMS_THRESHOLD * 2) + else: + _pct90 = float(np.percentile(list(floor_window), 90)) + + # Use the 90th percentile of the ROLLING window for the + # noise floor so the trigger reflects the loudest parts of + # recent playback — not a frozen snapshot from TTS onset. + _floor = max(_pct90, min_floor) + # 8.0x multiplier: TTS speaker bleed has wide + # volume variation between sentences and within sentences. + # At 5x, louder TTS passages exceed the trigger, get + # excluded from the floor window, and create a low-stale + # floor that false-triggers on the next loud passage. + # 8x gives enough headroom for TTS dynamics to stay below + # the trigger and get absorbed into the rolling floor. + trigger = max(float(threshold or SILENCE_RMS_THRESHOLD * 2), _floor * 8.0) + # Ceiling: never let the trigger exceed 4000 RMS, otherwise + # a very loud TTS passage would push the trigger so high + # that genuine speech (which is typically 3000–8000 RMS) + # couldn't trip it. + trigger = min(trigger, 4000.0) + + # Only feed the floor window with blocks that are NOT above + # the current trigger — speech blocks would inflate the floor + # and make the trigger unreachable. + if rms < trigger: + floor_window.append(rms) + + consecutive = consecutive + 1 if rms >= trigger else 0 + if consecutive > 0: + logger.debug( + "VAD above-trigger: block=%d rms=%.0f floor=%.0f trigger=%.0f " + "consec=%d/%d min_floor=%.0f window_len=%d", + block_idx, rms, _floor, trigger, consecutive, + trip_blocks, min_floor, len(floor_window), + ) + if consecutive < trip_blocks: + continue + + # Tripped — the user is talking over playback. + logger.info( + "VAD TRIPPED: block=%d rms=%.0f floor=%.0f trigger=%.0f " + "consec=%d min_floor=%.0f — cutting TTS playback", + block_idx, rms, _floor, trigger, consecutive, min_floor, + ) + if on_trigger: + try: + on_trigger() + except Exception as e: + logger.debug("Barge-in trigger callback failed: %s", e) + if not capture: + return True + + # Keep rolling until the user goes quiet. Playback is stopped + # now, so plain silence endpointing (recorder threshold) works. + frames: List[Any] = list(pre_roll) + quiet = 0 + for _ in range(max_blocks): + data, _ = stream.read(block) + frames.append(data.copy()) + rms = float(np.sqrt(np.mean(data.astype(np.float64) ** 2))) + quiet = quiet + 1 if rms < SILENCE_RMS_THRESHOLD else 0 + if quiet >= endpoint_blocks: + break + return AudioRecorder._write_wav(np.concatenate(frames, axis=0)) + except Exception as e: + logger.debug("Barge-in listener failed: %s", e) + return None if capture else False + + +# ── Full-duplex agent-turn listener ── +# One listener for the WHOLE agent turn (armed at utterance submit, disarmed when +# response + TTS are done): calibrates against the QUIET room at turn start, +# holds that baseline through playback (never speaker bleed), trips on a windowed +# majority of blocks — so the user can interject during generation, not just TTS. +# Speaker bleed at the mic is a few hundred RMS (~1000-1400 loud/close); direct +# speech is 3000-8000; a quiet-room floor is typically 50-300. +PLAYBACK_MIN_TRIGGER = 1500.0 # min trigger while TTS flows: bleed alone never trips +TRIGGER_CEILING = 4000.0 # a noisy room must never push the trigger past normal speech +DEFAULT_BARGE_MULTIPLIER = 3.0 # over the quiet floor: 300 * 3 = 900 vs 3000+ speech + + +def _vad_log(msg: str) -> None: + """VAD diagnostic: logger.debug, plus stderr when HERMES_VOICE_DEBUG=1 (live tuning).""" + logger.debug(msg) + if os.environ.get("HERMES_VOICE_DEBUG", "").strip() == "1": + with suppress(Exception): + print(f"[voice-vad] {msg}", file=sys.stderr, flush=True) + + +def _capture_until_quiet(stream, np, block: int, pre_roll, *, endpoint_blocks: int, max_blocks: int) -> str: + """After a trip, read until *endpoint_blocks* of quiet (or *max_blocks*) and write + pre-roll + capture to a WAV. Playback was cut by the trigger, so silence endpointing works.""" + frames: List[Any] = list(pre_roll) + quiet = 0 + for _ in range(max_blocks): + data, _ = stream.read(block) + frames.append(data.copy()) + quiet = quiet + 1 if _rms(np, data) < SILENCE_RMS_THRESHOLD else 0 + if quiet >= endpoint_blocks: + break + return AudioRecorder._write_wav(np.concatenate(frames, axis=0)) + + +class _BargeDetector: + """Per-block barge-in state machine behind ``full_duplex_listen``.""" + + def __init__(self, np, *, mult: float, calib_blocks: int, trip_blocks: int, grace_blocks: int) -> None: + self._np, self.mult, self.calib_blocks, self.grace_blocks = np, mult, calib_blocks, grace_blocks + self.trip_needed = max(1, int(round(trip_blocks * 0.8))) + self.ambient: deque = deque(maxlen=100) # ~3s of quiet-phase RMS + self.recent_above: deque = deque(maxlen=trip_blocks) + self.quiet_floor = float(SILENCE_RMS_THRESHOLD) + self.floor_locked = self.playing_prev = self.playback_seen = False + self.grace_remaining = self.block_idx = 0 + self.blocks_since_playback = 10_000 + + def _floor(self) -> tuple: + """(pct90, floor): 90th percentile of the quiet window; floor never below the silence threshold.""" + pct90 = float(self._np.percentile(list(self.ambient), 90)) if self.ambient else float(SILENCE_RMS_THRESHOLD) + return pct90, max(pct90, float(SILENCE_RMS_THRESHOLD)) + + def _calibrate(self, rms: float, playing: bool) -> bool: + """Lock the floor from the first calib_blocks: the listener arms at utterance + submit, before any TTS exists, so they sample the quiet room — NOT bleed.""" + if not playing: + self.ambient.append(rms) + if len(self.ambient) >= self.calib_blocks or playing: + pct90, self.quiet_floor = self._floor() + self.floor_locked = True + _vad_log(f"calibrated quiet floor={self.quiet_floor:.0f} " + f"(pct90={pct90:.0f}, {len(self.ambient)} blocks, mult={self.mult:g})") + return self.floor_locked + + def _track_playback(self, playing: bool) -> None: + """Grace only when playback starts after a real gap (>=1s), so inter-sentence + flapping of the audio-active flag can't chain windows and swallow an interjection.""" + if playing and not self.playing_prev: + if not self.playback_seen or self.blocks_since_playback > 33: + self.grace_remaining = self.grace_blocks + _vad_log(f"playback started (block={self.block_idx}) — grace {self.grace_blocks * 30}ms") + self.playback_seen = True + self.playing_prev = playing + self.blocks_since_playback = 0 if playing else self.blocks_since_playback + 1 + + def feed(self, rms: float, playing: bool) -> Optional[str]: + """Consume one 30ms block; return the phase name when speech trips, else None.""" + self.block_idx += 1 + if not self.floor_locked and not self._calibrate(rms, playing): + return None + self._track_playback(playing) + # Trigger: quiet baseline x multiplier, phase-clamped. + trigger = max(self.quiet_floor * self.mult, + PLAYBACK_MIN_TRIGGER if playing else float(SILENCE_RMS_THRESHOLD) * 2) + trigger = min(trigger, TRIGGER_CEILING) + # Track ambient drift ONLY while nothing plays (never absorb bleed) and the block isn't speech. + if not playing and rms < trigger: + self.ambient.append(rms) + _, self.quiet_floor = self._floor() + above = rms >= trigger + if above and self.grace_remaining > 0: + _vad_log(f"grace suppression: block={self.block_idx} rms={rms:.0f} " + f"trigger={trigger:.0f} ({self.grace_remaining} blocks left)") + above = False + if self.grace_remaining > 0: + self.grace_remaining -= 1 + self.recent_above.append(above) + phase = "playback" if playing else "generation" + if rms >= trigger * 0.5: + _vad_log(f"block={self.block_idx} rms={rms:.0f} floor={self.quiet_floor:.0f} " + f"trigger={trigger:.0f} above={above} " + f"window={sum(self.recent_above)}/{self.trip_needed} phase={phase}") + if not (above and sum(self.recent_above) >= self.trip_needed): + return None + _vad_log(f"TRIPPED ({phase}): block={self.block_idx} rms={rms:.0f} floor={self.quiet_floor:.0f} " + f"trigger={trigger:.0f} window={sum(self.recent_above)}/{len(self.recent_above)}") + return phase + + +def full_duplex_listen( + should_stop: Callable[[], bool], is_playing: Optional[Callable[[], bool]] = None, + on_trigger: Optional[Callable[[str], None]] = None, multiplier: Optional[float] = None, + sustained_ms: int = 300, calibration_ms: int = 450, grace_ms: int = 500, pre_roll_ms: int = 1200, + endpoint_silence_ms: int = 1250, max_utterance_ms: int = 30_000, +) -> Optional[str]: + """Listen across an ENTIRE agent turn; return the captured interruption WAV path. + + Phase per 30ms block from *is_playing* (usually ``is_audio_output_active``): + ``generation`` — first *calibration_ms* of quiet room set the floor, trigger = + floor x *multiplier*; ``playback`` — floor HELD, trigger clamped up to + ``PLAYBACK_MIN_TRIGGER``, *grace_ms* after playback start suppresses onset + transients. Trip = >=80% of the last *sustained_ms* blocks above trigger (so + intra-word dips don't reset). Then ``on_trigger(phase)`` fires and capture runs + from the *pre_roll_ms* buffer until *endpoint_silence_ms* of quiet. ``None`` + when *should_stop* ends the turn without speech. + """ + try: + sd, np = _import_audio() + except (ImportError, OSError): + return None + block = int(SAMPLE_RATE * 0.03) # 30ms blocks + endpoint_blocks = max(1, endpoint_silence_ms // 30) + detector = _BargeDetector( + np, mult=float(multiplier) if multiplier else DEFAULT_BARGE_MULTIPLIER, + calib_blocks=max(1, calibration_ms // 30), trip_blocks=max(1, sustained_ms // 30), + grace_blocks=max(0, grace_ms // 30)) + pre_roll: deque = deque(maxlen=max(1, pre_roll_ms // 30)) + try: + with sd.InputStream(samplerate=SAMPLE_RATE, channels=1, dtype="int16", blocksize=block) as stream: + while not should_stop(): + data, _ = stream.read(block) + pre_roll.append(data.copy()) + playing = bool(is_playing()) if is_playing is not None else False + phase = detector.feed(_rms(np, data), playing) + if phase is None: + continue + if on_trigger: + try: + on_trigger(phase) + except Exception as e: + logger.debug("full-duplex trigger callback failed: %s", e) + return _capture_until_quiet(stream, np, block, pre_roll, endpoint_blocks=endpoint_blocks, + max_blocks=max(1, max_utterance_ms // 30)) + except Exception as e: + logger.debug("Full-duplex listener failed: %s", e) + return None + + +# ── Requirements check ── +def _check_plugin_stt_provider(provider: str) -> bool: + """True when *provider* resolves to an available STT plugin.""" + key = (provider or "").lower().strip() + if not key or key == "none": + return False + try: + from agent.transcription_registry import get_provider + from hermes_cli.plugins import _ensure_plugins_discovered + _ensure_plugins_discovered() + plugin_provider = get_provider(key) + if plugin_provider is None: + # Match the transcription dispatcher: long-lived processes may need + # one refresh after plugins or configuration change. + _ensure_plugins_discovered(force=True) + plugin_provider = get_provider(key) + except Exception as exc: # noqa: BLE001 - discovery failure is non-fatal + logger.debug("STT plugin requirements check skipped for '%s': %s", key, exc) + return False + try: + return plugin_provider is not None and bool(plugin_provider.is_available()) + except Exception as exc: # noqa: BLE001 - plugins must not break status + logger.warning( + "STT plugin provider '%s' is_available() raised during requirements " + "check: %s - treating as unavailable", key, exc, exc_info=True) + return False + + +# STT providers handled natively by tools.transcription_tools -> status label. +_NATIVE_STT_LABELS = { + "local": "local faster-whisper", + "local_command": "local command", + "groq": "Groq", + "openai": "OpenAI", + "mistral": "Mistral Voxtral", + "xai": "xAI Grok STT", + "elevenlabs": "ElevenLabs Scribe", +} + + +def check_voice_requirements() -> Dict[str, Any]: + """Check voice mode requirements: ``{available, audio_available, stt_available, + missing_packages, details, environment}``.""" + from tools.transcription_tools import ( + _get_provider, _load_stt_config, _resolve_command_stt_provider_config, is_stt_enabled) + stt_config = _load_stt_config() + stt_enabled = is_stt_enabled(stt_config) + stt_provider = _get_provider(stt_config) + stt_label = None # "OK (...)" once a native / command / plugin provider resolves + if stt_provider in _NATIVE_STT_LABELS: + stt_label = f"OK ({_NATIVE_STT_LABELS[stt_provider]})" + elif stt_enabled and _resolve_command_stt_provider_config(stt_provider, stt_config) is not None: + stt_label = f"OK (command: {stt_provider})" + elif stt_enabled and _check_plugin_stt_provider(stt_provider): + stt_label = f"OK (plugin: {stt_provider})" + stt_available = stt_enabled and stt_label is not None + + termux_capture = _termux_voice_capture_available() + has_audio = _audio_available() or termux_capture + env_check = detect_audio_environment() + details = [ + "Audio capture: OK (Termux:API microphone)" if termux_capture + else "Audio capture: OK" if has_audio + else f"Audio capture: MISSING ({_voice_capture_install_hint()})", + "STT provider: DISABLED in config (stt.enabled: false)" if not stt_enabled + else f"STT provider: {stt_label}" if stt_label + else ("STT provider: MISSING (uv pip install faster-whisper — " + "`pip install faster-whisper` also works if pip is on PATH, " + "or set GROQ_API_KEY / VOICE_TOOLS_OPENAI_KEY)"), + ] + details += [f"Environment: {w}" for w in env_check["warnings"]] + details += [f"Environment: {n}" for n in env_check.get("notices", [])] + return { + "available": has_audio and stt_available and env_check["available"], + "audio_available": has_audio, + "stt_available": stt_available, + "missing_packages": [] if has_audio else ["sounddevice", "numpy"], + "details": "\n".join(details), + "environment": env_check, + } + + +# ── Temp file cleanup ── +def cleanup_temp_recordings(max_age_seconds: int = 3600) -> int: + """Remove ``recording_*.wav`` temp files older than *max_age_seconds*; returns the count.""" + if not os.path.isdir(_TEMP_DIR): + return 0 + deleted, now = 0, time.time() + for entry in os.scandir(_TEMP_DIR): + if entry.is_file() and entry.name.startswith("recording_") and entry.name.endswith(".wav"): + with suppress(OSError): + if now - entry.stat().st_mtime > max_age_seconds: + os.unlink(entry.path) + deleted += 1 + if deleted: + logger.debug("Cleaned up %d old voice recordings", deleted) + return deleted + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. +import difflib # noqa: F401,E402 +import re # noqa: F401,E402 + +WHISPER_HALLUCINATIONS = { + "thank you.", + "thank you", + "thanks for watching.", + "thanks for watching", + "subscribe to my channel.", + "subscribe to my channel", + "like and subscribe.", + "like and subscribe", + "please subscribe.", + "please subscribe", + "thank you for watching.", + "thank you for watching", + "bye.", + "bye", + "you", + "the end.", + "the end", + # Non-English hallucinations (common on silence) + "продолжение следует", + "продолжение следует...", + "sous-titres", + "sous-titres réalisés par la communauté d'amara.org", + "sottotitoli creati dalla comunità amara.org", + "untertitel von stephanie geiges", + "amara.org", + "www.mooji.org", + "ご視聴ありがとうございました", +} + + +_PLUGIN_COMPAT_LAZY = { + 'DEFAULT_TTS_ECHO_SIMILARITY_THRESHOLD': ('tools.voice_mode_transcript', 'DEFAULT_TTS_ECHO_SIMILARITY_THRESHOLD'), + 'DEFAULT_VOICE_STOP_PHRASES': ('tools.voice_mode_transcript', 'DEFAULT_VOICE_STOP_PHRASES'), + 'MIN_FRAGMENT_LENGTH_FOR_ECHO': ('tools.voice_mode_transcript', 'MIN_FRAGMENT_LENGTH_FOR_ECHO'), + 'is_tts_echo': ('tools.voice_mode_transcript', 'is_tts_echo'), + 'voice_stop_hint': ('tools.voice_mode_transcript', 'voice_stop_hint'), +} + + +def __getattr__(name): # PEP 562 — lazy so no import cycles + target = _PLUGIN_COMPAT_LAZY.get(name) + if target is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + import importlib + from hermes_cli.plugin_compat import warn_once + warn_once(__name__, name, *target) + return getattr(importlib.import_module(target[0]), target[1]) +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/wake_word.py b/tools/wake_word.py new file mode 100644 index 0000000000000000000000000000000000000000..940c161479dec665dc165af4d0c9eee4e0e051ae --- /dev/null +++ b/tools/wake_word.py @@ -0,0 +1,839 @@ +"""Wake-word ("Hey Hermes") detection — hands-free session trigger. + +One always-on hotword listener shared by CLI, TUI and desktop GUI (a single owner, +gated by ``wake_surface_enabled``). Engines live in :mod:`tools.wake_word_engines`; +this module owns config, the capture loop and the process-wide listener singleton. +Capture reuses voice mode's 16 kHz mono int16 ``sounddevice`` path on a daemon +thread; callers ``pause()`` while a voice turn holds the mic and ``resume()`` once +idle (two input streams on one device is unreliable cross-platform). +""" + +from __future__ import annotations + +import logging +import os +import queue +import sys +import threading +import time +from contextlib import suppress +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Callable, Dict, Optional + +from tools.wake_word_engines import _Engine, _OpenWakeWordEngine, _PorcupineEngine, _SherpaKwsEngine, _sub + +logger = logging.getLogger(__name__) + +SAMPLE_RATE = 16000 # 16 kHz mono int16 — Whisper-native and what every engine expects. + +# Minimum gap between two wake fires, so one "hey hermes" can't retrigger across +# several frames while the caller is still reacting. +_FIRE_COOLDOWN_SECONDS = 2.0 +_START_TIMEOUT_SECONDS = 5.0 + +# Ambient-speech rejection: N consecutive over-threshold frames before firing +# (a stray phoneme spikes one frame; a real phrase holds several). +_DEFAULT_CONFIRMATION_FRAMES = 3 + +# Dead-mic detection: an int16 stream whose peak stays at/below _SILENCE_PEAK for +# this many consecutive seconds is flagged silent (desktop push-to-talk and the +# backend listener capture differently, so one can work while the other is all zeros). +_SILENCE_PEAK = 10 +_SILENCE_ALERT_SECONDS = 10 + +# provider alias -> (engine class name on this module, lazy_deps feature). +# Unknown providers probe as openwakeword but fail to build. +_PROVIDERS: Dict[str, tuple[str, str]] = { + "porcupine": ("_PorcupineEngine", "wake.porcupine"), + **{k: ("_SherpaKwsEngine", "wake.sherpa") for k in ("sherpa", "sherpa-onnx", "kws", "open")}, + **{k: ("_OpenWakeWordEngine", "wake.openwakeword") for k in ("openwakeword", "oww", "local")}, +} + + +class WakeWordInUse(RuntimeError): + """Raised when another surface or process owns the wake-word listener.""" + + +# ── Config ── + +# capture: "local" (PortAudio on the backend host), "client" (desktop/TUI streams int16 +# frames via wake.feed), or "auto" (local when a device exists, else client). +_DEFAULTS: Dict[str, Any] = { + "enabled": False, "surface": "auto", "input_device": None, "capture": "auto", + "provider": "openwakeword", "phrase": "hey hermes", "sensitivity": 0.6, + "confirmation_frames": _DEFAULT_CONFIRMATION_FRAMES, "start_new_session": True, +} + +# Bundled "hey hermes" model (tools/wakewords/) — the default; alias names resolve +# to it, not to an openWakeWord built-in. +_BUNDLED_MODEL_NAME = "hey_hermes" +_BUNDLED_MODEL_ALIASES = frozenset({"", "hey_hermes", "hey hermes", "hermes"}) + + +def _bundled_wakeword_path(framework: str = "onnx") -> str: + """Path to the shipped hey_hermes model (.onnx/.tflite) for ``framework``.""" + ext = "tflite" if str(framework).strip().lower() == "tflite" else "onnx" + return os.path.join(os.path.dirname(__file__), "wakewords", f"{_BUNDLED_MODEL_NAME}.{ext}") + + +def _is_macos_arm64() -> bool: + import platform + return sys.platform == "darwin" and platform.machine() == "arm64" + + +def default_inference_framework() -> str: + """tflite on macOS ARM64, onnx elsewhere: openWakeWord's ONNX embedding model + scores near-zero on Apple Silicon — the detector arms but never fires.""" + return "tflite" if _is_macos_arm64() else "onnx" + + +_warned_onnx_coerced = False + + +def resolve_inference_framework(cfg: Dict[str, Any]) -> str: + """Effective openWakeWord backend: explicit ``openwakeword.inference_framework`` or + the platform default. Explicit ``onnx`` on macOS ARM64 is provably dead, so it is + coerced to tflite with a one-time warning (a pre-fix pin must not stay deaf).""" + global _warned_onnx_coerced + + framework = str(_sub(cfg, "openwakeword").get("inference_framework") or "").strip().lower() + if not framework: + return default_inference_framework() + if framework == "onnx" and _is_macos_arm64(): + if not _warned_onnx_coerced: + _warned_onnx_coerced = True + logger.warning("wake: openwakeword.inference_framework='onnx' is set but ONNX's " + "embedding model never fires on macOS ARM64 (openWakeWord #336) — " + "using tflite instead. Set inference_framework to '' (auto) or " + "'tflite' in config.yaml to silence this.") + return "tflite" + return framework + + +def ensure_tflite_runtime() -> bool: + """Make ``import tflite_runtime.interpreter`` resolve, returning success. openWakeWord hardcodes + that import but only declares ``tflite-runtime`` on Linux; on macOS the wheel is ``ai-edge-litert``, + so alias it in-process (site-packages untouched).""" + try: + import tflite_runtime.interpreter # noqa: F401 + return True + except ImportError: + pass + try: + from ai_edge_litert import interpreter as _litert # type: ignore[import-not-found] + except ImportError: + return False + import types + pkg = types.ModuleType("tflite_runtime") + pkg.__path__ = [] # type: ignore[attr-defined] # mark as package + sys.modules.setdefault("tflite_runtime", pkg) + sys.modules["tflite_runtime.interpreter"] = _litert + logger.debug("wake word: bridged tflite_runtime -> ai_edge_litert") + return True + + +def load_wake_word_config() -> Dict[str, Any]: + """Return the ``wake_word`` config section, shape-guarded to a dict.""" + cfg = None + with suppress(Exception): + from hermes_cli.config import load_config + cfg = load_config().get("wake_word") + return cfg if isinstance(cfg, dict) else {} + + +def _get(cfg: Dict[str, Any], key: str) -> Any: + val = cfg.get(key) + return _DEFAULTS.get(key) if val is None else val + + +def _clamped(cfg: Dict[str, Any], key: str, cast, lo, hi): + """Numeric config value via ``cast``, defaulting on junk, clamped to lo..hi.""" + try: + n = cast(_get(cfg, key)) + except (TypeError, ValueError): + n = cast(_DEFAULTS[key]) + return min(max(n, lo), hi) + + +def _provider(cfg: Dict[str, Any]) -> str: + return str(_get(cfg, "provider")).strip().lower() or "openwakeword" + + +def _input_device(cfg: Dict[str, Any]) -> int | str | None: + """Configured PortAudio input selector, preserving indices and names.""" + raw = _get(cfg, "input_device") + return None if isinstance(raw, bool) else raw if raw is None or isinstance(raw, int) else (str(raw).strip() or None) + + +def _sensitivity(cfg: Dict[str, Any]) -> float: + return _clamped(cfg, "sensitivity", float, 0.0, 1.0) + + +def _confirmation_frames(cfg: Dict[str, Any]) -> int: + """Consecutive over-threshold frames required to fire, clamped 1..10 (1 = single-frame).""" + return _clamped(cfg, "confirmation_frames", int, 1, 10) + + +def wake_phrase(cfg: Optional[Dict[str, Any]] = None) -> str: + """Human-facing wake phrase label (purely cosmetic; engine keys detection).""" + cfg = cfg if cfg is not None else load_wake_word_config() + return str(_get(cfg, "phrase")) or "hey hermes" + + +def resolve_capture_mode(cfg: Optional[Dict[str, Any]] = None, *, prefer_client: bool = False, + force_local: bool = False) -> str: + """Return ``local`` or ``client`` capture mode for this arm. ``prefer_client`` is set by remote + desktop; ``force_local`` keeps CLI/TUI on the process mic. Under ``auto`` a working backend input + always wins; client is the fallback only for a preferring surface with no usable backend mic — + CLI/TUI stay local so status reports the real requirement rather than a path nothing will feed.""" + cfg = cfg if cfg is not None else load_wake_word_config() + if force_local: + return "local" + raw = str(_get(cfg, "capture") or "auto").strip().lower() + if raw in ("client", "remote", "external"): + return "client" + return "client" if raw != "local" and prefer_client and not _local_input_device_ready() else "local" + + +def _input_channels(info: Any) -> int: + ch = info.get("max_input_channels") if isinstance(info, dict) else getattr(info, "max_input_channels", 0) + return int(ch or 0) + + +def _local_input_device_ready() -> bool: + """True when PortAudio is importable and at least one input device exists.""" + try: + sd, _ = _import_audio() + devices = sd.query_devices() + if isinstance(devices, dict): + return _input_channels(devices) > 0 + # Also accept a resolvable default input (some hosts list devices oddly). + return (any(_input_channels(d) > 0 for d in devices) + or _input_channels(sd.query_devices(None, "input")) > 0) + except Exception: + return False + + +def wake_surface_enabled(surface: str, cfg: Optional[Dict[str, Any]] = None) -> bool: + """Should ``surface`` (cli/tui/gui) host the listener? True when enabled and the configured + surface is ``auto`` or this one; ``auto`` only makes it eligible — the lock admits one claimant.""" + cfg = cfg if cfg is not None else load_wake_word_config() + want = str(_get(cfg, "surface")).strip().lower() or "auto" + return bool(cfg.get("enabled")) and want in ("auto", surface.strip().lower()) + + +# ── Multi-profile phrase enrollment (open-vocabulary routing) ── + +def _active_profile_name() -> str: + with suppress(Exception): + from hermes_cli.profiles import get_active_profile_name + return get_active_profile_name() or "default" + return "default" + + +def enrolled_profile_phrases() -> Dict[str, str]: + """Map ``profile name -> wake phrase`` for every wake-enabled profile, reading each profile's own + ``config.yaml`` raw (``load_config()`` targets only the ACTIVE profile). Phrase defaults to + ``"hey <profile>"``; the sherpa engine listens for all and routes to the match. Unreadable → skipped.""" + phrases: Dict[str, str] = {} + with suppress(Exception): + from hermes_cli.config import read_user_config_raw + from hermes_cli.profiles import get_profile_dir, list_profiles + for info in list_profiles(): + name = getattr(info, "name", None) or str(info) + with suppress(Exception): + wc = read_user_config_raw(Path(get_profile_dir(name)) / "config.yaml").get("wake_word") or {} + if isinstance(wc, dict) and wc.get("enabled"): + phrase = str(wc.get("phrase") or f"hey {name}").strip() + if phrase: + phrases[name] = phrase + return phrases + + +# ── Audio capture (lazy — never import sounddevice at module load) ── + +def _import_audio(): + import numpy as np + import sounddevice as sd + return sd, np + + +def _audio_available() -> bool: + with suppress(ImportError, OSError): + return bool(_import_audio()) + return False + + +def _describe_input_device(selector: int | str | None, sd=None) -> Dict[str, Any]: + """Resolve a PortAudio selector into JSON-safe diagnostics (``InputStream`` stays the + authority on whether the device actually opens). Imports sounddevice unless ``sd`` is given.""" + details: Dict[str, Any] = {"selector": selector} + try: + sd = sd or _import_audio()[0] + info = sd.query_devices(selector, "input") + except Exception as e: + details["error"] = str(e) + return details + if not isinstance(info, dict): + return details + if info.get("name"): + details["name"] = str(info["name"]) + for key, out_key, cast in (("max_input_channels", "max_input_channels", int), + ("default_samplerate", "default_samplerate", float), ("hostapi", "hostapi_index", int)): + if isinstance(info.get(key), (int, float)): + details[out_key] = cast(info[key]) + if "hostapi_index" in details: + with suppress(Exception): + hostapi = sd.query_hostapis(details["hostapi_index"]) + if isinstance(hostapi, dict) and hostapi.get("name"): + details["hostapi"] = str(hostapi["name"]) + return details + + +def _resample_audio_frame(np, frame, output_length: int): + """Convert one native-rate capture block to an exact engine frame.""" + source = np.asarray(frame, dtype=np.float64).reshape(-1) + if source.size == output_length: + return np.asarray(frame, dtype=np.int16).reshape(-1) + if source.size == 0: + return np.zeros(output_length, dtype=np.int16) + if source.size > output_length: + # Average each source window when reducing (matches the desktop wake capture + # path) so speech energy is retained instead of decimated. + edges = np.linspace(0, source.size, output_length + 1, dtype=np.int64) + values = np.add.reduceat(source, edges[:-1]) / np.diff(edges) + else: + # Unusual low-rate devices: interpolate up to the 16 kHz frame size. + source_positions = np.arange(source.size, dtype=np.float64) + values = np.interp(np.linspace(0, source.size - 1, output_length), source_positions, source) + return np.rint(values).clip(-32768, 32767).astype(np.int16) + + +def silent_audio_hint(details: Dict[str, Any]) -> str: + """Platform-specific remediation for an armed stream delivering silence.""" + if sys.platform == "darwin": + return ("Microphone delivers only silence. Grant the Hermes backend " + "microphone access in System Settings > Privacy & Security > " + "Microphone, then toggle the wake word.") + fix = ("Set wake_word.input_device to a different PortAudio input device" + if sys.platform == "win32" else "Check the selected input device") + selector = details.get("selector") + label = str(details.get("name") or "").strip() or ("system default" if selector is None else str(selector)) + hostapi = str(details.get("hostapi") or "").strip() + label = f"{label} ({hostapi})" if hostapi else label + return f"Microphone delivers only silence from {label}. {fix}, then toggle the wake word." + + +# ── Engines (implementations live in tools.wake_word_engines) ── + +def _build_engine(cfg: Dict[str, Any]) -> _Engine: + provider = _provider(cfg) + if provider not in _PROVIDERS: + raise ValueError(f"Unknown wake_word provider: {provider!r}") + return globals()[_PROVIDERS[provider][0]](cfg) + + +# ── Requirements probe (for /wake status + enable path) ── + +def _stt_ready() -> bool: + """Is a speech-to-text provider configured and enabled? (A wake without STT arms the + mic but every utterance dies at transcription — same bar as ``check_voice_requirements``.)""" + with suppress(Exception): + from tools.transcription_tools import _get_provider, _load_stt_config, is_stt_enabled + stt_config = _load_stt_config() + return is_stt_enabled(stt_config) and _get_provider(stt_config) != "none" + return False + + +def _tts_ready() -> bool: + """Can the configured TTS provider run (or install at first use)? PROBE, not an installer: + ``check_tts_requirements`` lazily pip-installs the SDK, which froze wake.status polls for a whole + pip run. Uninstalled deps count as ready iff lazy installs are allowed; pip is never touched here.""" + try: + from tools.tts_tool import _get_provider, _load_tts_config, check_tts_requirements + provider = _get_provider(_load_tts_config()) + feature = f"tts.{provider}" if provider in ("edge", "elevenlabs", "mistral") else None + if feature is not None: + from tools import lazy_deps + if not lazy_deps.is_available(feature): + return lazy_deps._allow_lazy_installs() + return bool(check_tts_requirements()) + except Exception: + return False + + +def check_wake_word_requirements(cfg: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + """Report whether wake-word detection can run, with a remediation hint.""" + cfg = cfg if cfg is not None else load_wake_word_config() + provider = _provider(cfg) + from tools import lazy_deps + feature = _PROVIDERS.get(provider, ("", "wake.openwakeword"))[1] + deps_ok = lazy_deps.is_available(feature) + lazy_ok = lazy_deps._allow_lazy_installs() + # The audio probe imports sounddevice + numpy — packages the lazy installer would + # fetch — so only trust it once deps are installed; on a fresh install the engine + # constructors' ``lazy_deps.ensure()`` + stream-open surface any real audio problem. + audio_ok = _audio_available() if deps_ok else False + # Loop is wake → record → STT → agent → TTS; without either end the mic hears you + # and nothing perceptible happens — refuse with a hint. + stt_ok, tts_ok = _stt_ready(), _tts_ready() + # tflite needs a runtime openWakeWord doesn't declare off Linux; report it as a + # remediation instead of arming a detector that can't fire. + tflite_ok = (feature != "wake.openwakeword" or resolve_inference_framework(cfg) != "tflite" + or ensure_tflite_runtime() or lazy_deps.is_available("wake.openwakeword.tflite") or lazy_ok) + key_ok = provider != "porcupine" or bool((os.getenv("PORCUPINE_ACCESS_KEY") or "").strip()) + capture_mode = resolve_capture_mode(cfg) + missing = " and ".join(n for n, ok in (("speech-to-text", stt_ok), ("text-to-speech", tts_ok)) if not ok) + + # Ordered remediation ladder: first true predicate wins. + ladder = ( + (not key_ok, lambda: "Set PORCUPINE_ACCESS_KEY (free key at https://console.picovoice.ai)."), + (not deps_ok and not lazy_ok, lambda: lazy_deps.feature_install_command(feature) or ""), + (not tflite_ok, + lambda: "The wake word needs the tflite runtime on this Mac: pip install ai-edge-litert"), + (deps_ok and not audio_ok and capture_mode == "local", + lambda: "Microphone capture needs sounddevice + numpy and a working audio device."), + (bool(missing), lambda: (f"Wake word needs {missing} configured — run `hermes tools` " + f"(Voice section) or see the voice-mode docs.")), + ) + hint = next((make() for cond, make in ladder if cond), "") + + # Client capture needs deps (engine) but not a server-side PortAudio device. + if capture_mode == "client": + mic_ok = deps_ok or lazy_ok + else: + mic_ok = (deps_ok and audio_ok) or (not deps_ok and lazy_ok) + if deps_ok and not audio_ok and not hint: + hint = ("No local microphone on this backend. Remote desktop can stream " + "the client mic — set wake_word.capture: client or use a desktop " + "build with client-capture wake support.") + + return { + "available": key_ok and stt_ok and tts_ok and tflite_ok and mic_ok, "provider": provider, + "deps_available": deps_ok, "audio_available": audio_ok, + "local_input_available": _local_input_device_ready() if deps_ok else False, + "capture": capture_mode, "access_key_set": key_ok, "stt_available": stt_ok, "tts_available": tts_ok, + "phrase": wake_phrase(cfg), "hint": hint, + } + + +# ── Detector ── + +@dataclass +class _Capture: + """One armed audio source: a PortAudio stream (local) or the feed queue (client).""" + + stream: Any = None # sounddevice.InputStream, None in client mode + queue: Any = None # client-capture frame queue, None in local mode + np: Any = None + rate: int = SAMPLE_RATE + frame_length: int = 1280 # samples per read at ``rate`` + + def read(self): + """One raw block; None when no client frame arrived within 250 ms. Stream errors propagate.""" + if self.stream is not None: + return self.stream.read(self.frame_length)[0] + with suppress(Exception): + return self.queue.get(timeout=0.25) + return None + + def close(self) -> None: + with suppress(Exception): + if self.stream is not None: + self.stream.stop() + self.stream.close() + + +class WakeWordDetector: + """Background hotword listener; fires ``on_wake()`` when the phrase is heard. The engine is built + once and kept across pause/resume — only the stream + reader thread cycle, so mic toggles are cheap.""" + + def __init__(self, engine: _Engine, on_wake: Callable[[], None], cooldown: float = _FIRE_COOLDOWN_SECONDS, + on_failure: Optional[Callable[["WakeWordDetector"], None]] = None, + input_device: int | str | None = None, external_audio: bool = False): + self.engine, self.on_wake, self.cooldown, self.on_failure = engine, on_wake, cooldown, on_failure + self.input_device, self.external_audio = input_device, bool(external_audio) + self.input_device_details: Dict[str, Any] = ( + {"selector": "client", "name": "client capture", "hostapi": "remote"} + if self.external_audio else {"selector": input_device}) + self._thread: Optional[threading.Thread] = None + self._stop, self._callback_inflight = threading.Event(), threading.Event() + self._lock, self._last_fire = threading.Lock(), 0.0 + # Client-capture PCM queue (int16 mono frames). Local mode ignores this. + self._audio_q: "queue.Queue[Any]" = queue.Queue(maxsize=64) + # True when the stream is open but every frame is (near-)silence, so status + # surfaces can tell "armed" from "deaf". + self.audio_silent, self._silent_frames = False, 0 + + @property + def running(self) -> bool: + t = self._thread + return t is not None and t.is_alive() + + def feed(self, pcm_int16) -> None: + """Enqueue one int16 mono frame (or raw bytes) for client capture. Short frames are + zero-padded to ``engine.frame_length``, long ones split; on overflow the oldest is dropped.""" + if not self.external_audio: + return + try: + import numpy as np + except Exception: + return + if isinstance(pcm_int16, (bytes, bytearray, memoryview)): + arr = np.frombuffer(pcm_int16, dtype=np.int16) + else: + arr = np.asarray(pcm_int16, dtype=np.int16).reshape(-1) + fl = int(self.engine.frame_length) + if fl <= 0: + return + for offset in range(0, int(arr.shape[0]), fl): + chunk = arr[offset : offset + fl] + if chunk.shape[0] < fl: + chunk = np.pad(chunk, (0, fl - chunk.shape[0])) + try: + self._audio_q.put_nowait(chunk) + except Exception: + # Drop oldest on overflow so we stay real-time + with suppress(Exception): + self._audio_q.get_nowait() + with suppress(Exception): + self._audio_q.put_nowait(chunk) + + def start(self) -> None: + """Open the mic (or client feeder) and begin listening. Idempotent.""" + with self._lock: + if self.running: + return + self._stop.clear() + ready = threading.Event() + startup_errors: list[BaseException] = [] + self._thread = threading.Thread(target=self._run, args=(ready, startup_errors), + daemon=True, name="wake-word") + self._thread.start() + if not ready.wait(_START_TIMEOUT_SECONDS): + self._halt_thread() + raise TimeoutError("Timed out while opening the wake-word microphone.") + if startup_errors: + self._halt_thread() + raise RuntimeError("Failed to open the wake-word microphone.") from startup_errors[0] + + # pause/resume keep the engine; stop tears it down. + def pause(self) -> None: + self._halt_thread() + + def resume(self) -> None: + self.start() + + def stop(self) -> None: + self._halt_thread() + self.engine.close() + + def _halt_thread(self) -> None: + with self._lock: + self._stop.set() + t = self._thread + if t is not None and t is not threading.current_thread(): + t.join(timeout=2.0) + if self._thread is t: + self._thread = None + + def _dispatch_wake(self) -> None: + try: + self.on_wake() + except Exception as e: + logger.warning("wake word callback failed: %s", e) + finally: + self._callback_inflight.clear() + + def _open_capture(self, frame_length: int) -> _Capture: + """Open the audio source; raises on any local-mic failure.""" + if self.external_audio: + with suppress(Exception): # drain stale frames from a previous arm + while True: + self._audio_q.get_nowait() + logger.info("wake word: client-capture mode (frame=%d, rate=%d) — waiting for wake.feed", + frame_length, SAMPLE_RATE) + return _Capture(queue=self._audio_q, frame_length=frame_length) + + try: + sd, np = _import_audio() + except (ImportError, OSError) as e: + logger.error("wake word: audio libraries unavailable: %s", e) + raise + details = self.input_device_details = _describe_input_device(self.input_device, sd) + # Capture at the device's native rate when PortAudio reports one; frames are resampled to the engine. + cap, rate = _Capture(np=np), details.get("default_samplerate") + if isinstance(rate, (int, float)) and not isinstance(rate, bool) and rate > 0: + with suppress(OverflowError, ValueError): + cap.rate = int(round(rate)) + cap.frame_length = max(1, int(round(frame_length * cap.rate / SAMPLE_RATE))) + logger.info("wake word: opening microphone device=%s selector=%r hostapi=%s " + "default_rate=%s capture_rate=%d engine_rate=%d", details.get("name") or "system default", + self.input_device, details.get("hostapi") or "unknown", + details.get("default_samplerate") or "unknown", cap.rate, SAMPLE_RATE) + try: + cap.stream = sd.InputStream(device=self.input_device, samplerate=cap.rate, channels=1, + dtype="int16", blocksize=cap.frame_length) + cap.stream.start() + except Exception as e: + logger.error("wake word: failed to open microphone: %s", e) + raise + return cap + + def _note_silence(self, frame, silent_alert_frames: int) -> None: + """Track consecutive near-zero frames; flag/unflag ``audio_silent``. ``frame`` is None when + no client frame arrived (counts as silence for status, but is never logged as a dead mic).""" + try: + peak = 0 if frame is None or not len(frame) else int(abs(frame).max()) + except Exception: + peak = _SILENCE_PEAK + 1 + if peak <= _SILENCE_PEAK: + self._silent_frames += 1 + if self._silent_frames == silent_alert_frames: + self.audio_silent = True + if frame is not None: + logger.warning("wake word: mic delivers only silence (peak<=%d for %ds); %s", + _SILENCE_PEAK, _SILENCE_ALERT_SECONDS, + silent_audio_hint(self.input_device_details)) + elif self._silent_frames: + if self.audio_silent: + logger.info("wake word: mic audio detected — stream healthy") + self._silent_frames, self.audio_silent = 0, False + + def _fire(self) -> None: + """Honor the cooldown, then run ``on_wake`` on its own thread (once).""" + now = time.monotonic() + if now - self._last_fire < self.cooldown: + logger.debug("wake word: detection within cooldown — ignored") + return + self._last_fire = now + logger.info("wake word: phrase detected — firing callback") + if not self._callback_inflight.is_set(): + self._callback_inflight.set() + threading.Thread(target=self._dispatch_wake, daemon=True, name="wake-word-callback").start() + + def _run(self, ready: threading.Event, startup_errors: list[BaseException]) -> None: + frame_length = self.engine.frame_length + try: + cap = self._open_capture(frame_length) + except Exception as e: + startup_errors.append(e) + ready.set() + return + # Drop buffered audio/feature state so a resume right after a voice turn can't + # re-fire on audio captured before the pause (wake → voice → resume → wake loop). + with suppress(Exception): + self.engine.reset() + logger.info("wake word: listening (frame=%d, rate=%d, external=%s)", + frame_length, SAMPLE_RATE, self.external_audio) + ready.set() + failed = False + silent_alert_frames = max(1, int(_SILENCE_ALERT_SECONDS * SAMPLE_RATE / max(1, frame_length))) + try: + while not self._stop.is_set(): + try: + data = cap.read() + except Exception as e: + logger.warning("wake word: stream read error: %s", e) + failed = not self._stop.is_set() + break + if data is None: # no client frames yet — counts as silence for status + self._note_silence(None, silent_alert_frames) + continue + frame = data[:, 0] if getattr(data, "ndim", 1) == 2 else data + if cap.rate != SAMPLE_RATE: + frame = _resample_audio_frame(cap.np, frame, frame_length) + self._note_silence(frame, silent_alert_frames) + try: + if self.engine.process(frame): + self._fire() + except Exception as e: + logger.debug("wake word: engine error: %s", e) + finally: + cap.close() + logger.info("wake word: stream closed") + if failed and self.on_failure is not None: + self.on_failure(self) + + +# ── Process-wide singleton (mirrors hermes_cli.voice's continuous API) ── + +_detector: Optional[WakeWordDetector] = None +_detector_owner: object | None = None +_detector_file_lock = None +_detector_lock = threading.Lock() + + +def _lock_path() -> Path: + from hermes_constants import get_default_hermes_root + return get_default_hermes_root() / "runtime" / "wake-word.lock" + + +def _flock(handle, acquire: bool) -> None: + """Non-blocking exclusive lock (or unlock) of one byte / whole file, per OS.""" + if os.name == "nt": + import msvcrt + if acquire: # msvcrt needs at least one byte to lock + handle.seek(0, os.SEEK_END) + if handle.tell() == 0: + handle.write(b"\0") + handle.flush() + handle.seek(0) + msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK if acquire else msvcrt.LK_UNLCK, 1) + else: + import fcntl + fcntl.flock(handle.fileno(), (fcntl.LOCK_EX | fcntl.LOCK_NB) if acquire else fcntl.LOCK_UN) + + +def _acquire_machine_lock(path: Optional[Path] = None): + """Acquire the cross-process microphone lease, or raise WakeWordInUse.""" + lock_path = path or _lock_path() + lock_path.parent.mkdir(parents=True, exist_ok=True) + handle = open(lock_path, "a+b") + try: + _flock(handle, True) + except OSError as e: # BlockingIOError is an OSError: lock held elsewhere + handle.close() + raise WakeWordInUse("Wake-word microphone is already owned.") from e + return handle + + +def _release_machine_lock(handle) -> None: + if handle is None: + return + try: + _flock(handle, False) + except OSError: + pass + finally: + handle.close() + + +def _teardown_locked(close: Callable[[], None]) -> None: + """Forget the singleton and run ``close``, always releasing the machine lease (caller holds the lock).""" + global _detector, _detector_owner, _detector_file_lock + lock_handle = _detector_file_lock + _detector = _detector_owner = _detector_file_lock = None + try: + close() + finally: + _release_machine_lock(lock_handle) + + +def _owned_detector(owner: object) -> Optional[WakeWordDetector]: + """The armed detector iff ``owner`` holds the lease (caller holds the lock).""" + return _detector if _detector is not None and _detector_owner is owner else None + + +def _detector_failed(detector: WakeWordDetector) -> None: + """Release ownership if the active microphone stream dies unexpectedly.""" + with _detector_lock: + if _detector is detector: + _teardown_locked(detector.engine.close) + + +def start_listening(on_wake: Callable[[], None], *, owner: object, config: Optional[Dict[str, Any]] = None, + external_audio: bool = False) -> WakeWordDetector: + """Claim, build, and start the detector. Idempotent for the same owner; a different owner + (or process) gets :class:`WakeWordInUse`. Raises if engine construction fails (missing deps / + access key / model) — callers should probe :func:`check_wake_word_requirements` first.""" + if owner is None: + raise ValueError("wake-word owner must not be None") + + global _detector, _detector_owner, _detector_file_lock + with _detector_lock: + if _detector is not None: + if _detector_owner is not owner: + raise WakeWordInUse("Wake-word microphone is already owned.") + _detector.on_wake = on_wake + _detector.resume() + return _detector + _detector_file_lock = _acquire_machine_lock() + try: + cfg = config if config is not None else load_wake_word_config() + _detector = WakeWordDetector(_build_engine(cfg), on_wake, on_failure=_detector_failed, + input_device=_input_device(cfg), external_audio=external_audio) + _detector_owner = owner + _detector.start() + return _detector + except Exception: + with suppress(Exception): + _teardown_locked(_detector.stop if _detector is not None else lambda: None) + raise + + +def _owned_call(owner: object, action: Optional[Callable[[WakeWordDetector], None]] = None) -> bool: + """Under the lock, True iff ``owner`` holds the lease; also runs ``action(detector)`` when given.""" + with _detector_lock: + det = _owned_detector(owner) + if det is None: + return False + if action is not None: + action(det) + return True + + +def owns_listener(owner: object) -> bool: + return _owned_call(owner) + + +def pause_listening(*, owner: object) -> bool: + """Release the microphone only when ``owner`` holds the lease.""" + return _owned_call(owner, WakeWordDetector.pause) + + +def resume_listening(*, owner: object) -> bool: + """Re-open the microphone only when ``owner`` holds the lease.""" + return _owned_call(owner, WakeWordDetector.resume) + + +def stop_listening(*, owner: object) -> bool: + """Fully stop the detector only when ``owner`` holds the lease.""" + return _owned_call(owner, lambda det: _teardown_locked(det.stop)) + + +def _current_detector() -> Optional[WakeWordDetector]: + with _detector_lock: + return _detector + + +def is_listening() -> bool: + return (det := _current_detector()) is not None and det.running + + +def audio_is_silent() -> bool: + """True when the armed stream opens fine but delivers only silence (dead mic), so + detection can never fire; status shows "listening but the microphone appears silent".""" + return (det := _current_detector()) is not None and det.audio_silent + + +def get_input_device_status(cfg: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + """Return configured/active PortAudio input diagnostics for status UIs.""" + if (det := _current_detector()) is not None: + return dict(det.input_device_details) + return _describe_input_device(_input_device(cfg if cfg is not None else load_wake_word_config())) + + +def get_last_match() -> Optional[tuple[str, str]]: + """(matched phrase, profile) of the most recent wake fire when the engine reports + per-phrase matches (sherpa multi-profile routing); None otherwise.""" + return None if (det := _current_detector()) is None else getattr(det.engine, "last_match", None) + + +def feed_audio(*, owner: object, pcm_int16) -> bool: + """Push client-captured PCM into ``owner``'s armed detector; True when accepted.""" + with _detector_lock: + det = _owned_detector(owner) + if det is None or not det.external_audio: + return False + det.feed(pcm_int16) + return True + + +def detector_frame_info() -> Dict[str, Any]: + """Sample rate + frame length for client capture streamers.""" + if (det := _current_detector()) is None: + return {"sample_rate": SAMPLE_RATE, "frame_length": 1280} + return {"sample_rate": SAMPLE_RATE, "external_audio": bool(det.external_audio), + "frame_length": int(getattr(det.engine, "frame_length", 1280) or 1280)} diff --git a/tools/wake_word_engines.py b/tools/wake_word_engines.py new file mode 100644 index 0000000000000000000000000000000000000000..2a9e623433db3b87ce74ec97e553d359c97096c4 --- /dev/null +++ b/tools/wake_word_engines.py @@ -0,0 +1,271 @@ +"""Wake-word hotword engines (openWakeWord / sherpa-onnx KWS / Porcupine). + +All three run fully on-device. Config, platform probes and sensitivity accessors +live in :mod:`tools.wake_word`; engines read them lazily through that module (import cycle). +""" + +from __future__ import annotations + +import logging +import os +from contextlib import suppress +from pathlib import Path +from typing import Any, Dict, Optional + +logger = logging.getLogger("tools.wake_word") + + +def _ww(): + from tools import wake_word + return wake_word + + +def _ensure_dep(feature: str) -> None: + from tools import lazy_deps + lazy_deps.ensure(feature, prompt=False) + + +class _Engine: + """Minimal hotword-engine contract: feed int16 frames, get a bool. Subclasses set ``feature`` + (lazy_deps name, ensured before ``_build``) and their own ``cfg`` sub-section ``section``.""" + + feature: str = "" + section: str = "" + frame_length: int = 1280 # 80 ms at 16 kHz + + #: (matched phrase, profile name) of the most recent fire. Multi-phrase engines + #: (sherpa) set this for profile routing; single-phrase engines leave it None. + last_match: Optional[tuple[str, str]] = None + + def __init__(self, cfg: Dict[str, Any]): + _ensure_dep(self.feature) + self._build(cfg, _sub(cfg, self.section), _ww()) + + def _build(self, cfg: Dict[str, Any], sub: Dict[str, Any], ww) -> None: + raise NotImplementedError + + def process(self, frame) -> bool: # frame: 1-D int16 ndarray + raise NotImplementedError + + def reset(self) -> None: + """Clear any internal audio/feature buffer (called on every (re)start).""" + + def close(self) -> None: + """Release engine resources (called once on stop).""" + + +def _looks_like_path(value: str) -> bool: + return os.sep in value or value.endswith((".onnx", ".tflite", ".ppn")) or os.path.exists(value) + + +def _sub(cfg: Dict[str, Any], key: str) -> Dict[str, Any]: + sub = cfg.get(key) + return sub if isinstance(sub, dict) else {} + + +class _OpenWakeWordEngine(_Engine): + """openWakeWord — free, local ONNX/tflite hotword detection. Scores one ~80 ms frame at a time; + ``sensitivity`` IS the raw 0..1 threshold (higher = stricter). A real utterance holds the score + high across frames while a stray phoneme spikes one, so ``confirmation_frames`` hits are required.""" + + feature, section = "wake.openwakeword", "openwakeword" + frame_length = 1280 # openWakeWord recommends 80 ms frames. + + def _build(self, cfg, sub, ww) -> None: + import openwakeword + from openwakeword.model import Model + model_ref = str(sub.get("model") or ww._BUNDLED_MODEL_NAME).strip() + framework = self._usable_framework(ww.resolve_inference_framework(cfg)) + self._threshold = ww._sensitivity(cfg) + self._confirm_needed = ww._confirmation_frames(cfg) + self._confirm_streak = 0 + # Default (or explicit "hey_hermes") → the bundled model; built-in names / paths as-is. + if model_ref.lower() in ww._BUNDLED_MODEL_ALIASES: + model_ref = ww._bundled_wakeword_path(framework) + # download_models() also fetches the shared feature models (melspectrogram + + # embedding) needed for ANY model, so a custom path must call it too. + try: + openwakeword.utils.download_models([model_ref]) + except Exception as e: # pragma: no cover - network/path dependent + logger.debug("openwakeword model download skipped: %s", e) + self._model = Model(wakeword_models=[model_ref], inference_framework=framework) + self._labels = list(self._model.models.keys()) + + @staticmethod + def _usable_framework(framework: str) -> str: + """Refuse openWakeWord's silent tflite→onnx downgrade: without a tflite runtime it falls back + to onnx, which on macOS ARM64 never fires (armed but deaf). Install + bridge the runtime first + (gate lives here because dep specs can't carry PEP 508 markers); on that Mac raise instead.""" + ww = _ww() + if framework != "tflite" or ww.ensure_tflite_runtime(): + return framework + try: + _ensure_dep("wake.openwakeword.tflite") + except Exception as e: + logger.debug("wake word: tflite runtime install failed: %s", e) + if ww.ensure_tflite_runtime(): + return framework + if ww._is_macos_arm64(): + raise RuntimeError("The wake word needs the tflite backend on this Mac, but its " + "runtime is missing. Install it with: pip install ai-edge-litert") + logger.warning("wake word: no tflite runtime available — falling back to onnx") + return "onnx" + + def process(self, frame) -> bool: + hit = any(score >= self._threshold for score in self._model.predict(frame).values()) + self._confirm_streak = self._confirm_streak + 1 if hit else 0 + if self._confirm_streak < self._confirm_needed: + return False + self._confirm_streak = 0 + return True + + def reset(self) -> None: + # Clears openWakeWord's rolling feature buffer so stale audio captured before a + # pause can't re-fire the moment we resume. + self._confirm_streak = 0 + with suppress(Exception): + self._model.reset() + + def close(self) -> None: + self.reset() + + +# sherpa-onnx open-vocabulary KWS model: small streaming zipformer transducer (English, +# GigaSpeech), downloaded once under HERMES_HOME. Keywords are tokenized at RUNTIME. +_SHERPA_KWS_MODEL_URL = ( + "https://github.com/k2-fsa/sherpa-onnx/releases/download/kws-models/" + "sherpa-onnx-kws-zipformer-gigaspeech-3.3M-2024-01-01.tar.bz2" +) +_SHERPA_KWS_MODEL_DIR = "sherpa-onnx-kws-zipformer-gigaspeech-3.3M-2024-01-01" + + +def _sherpa_model_root() -> Path: + from hermes_constants import get_hermes_home + return get_hermes_home() / "cache" / "wakewords" + + +def _ensure_sherpa_model(root: Optional[Path] = None) -> Path: + """Download + unpack the sherpa KWS model once; return its directory.""" + root = root or _sherpa_model_root() + target = root / _SHERPA_KWS_MODEL_DIR + if (target / "tokens.txt").exists(): + return target + import tarfile + import urllib.request + root.mkdir(parents=True, exist_ok=True) + archive = root / f"{_SHERPA_KWS_MODEL_DIR}.tar.bz2" + logger.info("wake word: downloading sherpa KWS model (one-time, ~13 MB)") + urllib.request.urlretrieve(_SHERPA_KWS_MODEL_URL, archive) # noqa: S310 + with tarfile.open(archive, "r:bz2") as tf: + tf.extractall(root, filter="data") + archive.unlink(missing_ok=True) + if not (target / "tokens.txt").exists(): + raise RuntimeError(f"sherpa KWS model unpack failed: {target}") + return target + + +class _SherpaKwsEngine(_Engine): + """sherpa-onnx open-vocabulary keyword spotting — any typed phrase, zero training. ``wake_word.phrase`` + is BPE-tokenized at runtime against the model's vocabulary: DETECTION config, not a cosmetic label.""" + + feature, section = "wake.sherpa", "sherpa" + frame_length = 1280 # streaming zipformer accepts any chunk; match capture path. + + def _build(self, cfg, sub, ww) -> None: + import sherpa_onnx + import tempfile + from sherpa_onnx import text2token + model_dir = str(sub.get("model_dir") or "").strip() + d = Path(model_dir) if model_dir else _ensure_sherpa_model() + if not (d / "tokens.txt").exists(): + raise RuntimeError(f"sherpa KWS model not found at {d}") + + # Phrase set: this profile's phrase plus — with profile routing on — every other + # wake-enabled profile's phrase, so ONE listener can wake any profile. + phrase = str(ww._get(cfg, "phrase") or "hey hermes").strip() + phrase_map: Dict[str, str] = {phrase: ww._active_profile_name()} + if bool(cfg.get("profile_routing", True)): + for prof, p in ww.enrolled_profile_phrases().items(): + phrase_map.setdefault(p.strip(), prof) + phrases = list(phrase_map) + tokens = text2token([p.upper() for p in phrases], tokens=str(d / "tokens.txt"), tokens_type="bpe", + bpe_model=str(d / "bpe.model")) + # sherpa keyword entries reject spaces in the @display-name; underscore them and + # map display → profile for match routing. + self._display_to_profile: Dict[str, str] = {} + kw = tempfile.NamedTemporaryFile(mode="w", suffix=".txt", prefix="hermes-kws-", delete=False, + encoding="utf-8") + for p, toks in zip(phrases, tokens): + display = p.upper().replace(" ", "_") + self._display_to_profile[display] = phrase_map[p] + kw.write(" ".join(toks) + f" @{display}\n") + kw.close() + self._keywords_file = kw.name + + # Shared 0..1 sensitivity → sherpa keywords_threshold. 0.5 lands on sherpa's + # recommended 0.25; a stricter 0.35 missed ~12% of true positives in live TTS + # matrix tests while 0.25 held zero false fires. + threshold = 0.05 + 0.4 * ww._sensitivity(cfg) + + def _model_file(part: str) -> str: + hits = sorted(d.glob(f"{part}-*[!8].onnx")) + if not hits: + raise RuntimeError(f"sherpa KWS model file missing: {d}/{part}-*[!8].onnx") + return str(hits[0]) + + self._spotter = sherpa_onnx.KeywordSpotter( + tokens=str(d / "tokens.txt"), encoder=_model_file("encoder"), decoder=_model_file("decoder"), + joiner=_model_file("joiner"), keywords_file=self._keywords_file, keywords_threshold=threshold, + num_threads=1, + ) + self._stream = self._spotter.create_stream() + + def process(self, frame) -> bool: + import numpy as np + self._stream.accept_waveform(_ww().SAMPLE_RATE, np.asarray(frame, dtype=np.float32) / 32768.0) + fired = False + while self._spotter.is_ready(self._stream): + self._spotter.decode_stream(self._stream) + result = self._spotter.get_result(self._stream) + if result: + fired, display = True, str(result) + self.last_match = (display.replace("_", " ").lower(), + self._display_to_profile.get(display, "")) + self._spotter.reset_stream(self._stream) # one utterance must not fire repeatedly + return fired + + def reset(self) -> None: + # Fresh stream drops buffered audio/decoder state (pause → resume must not re-fire). + with suppress(Exception): + self._stream = self._spotter.create_stream() + + def close(self) -> None: + with suppress(OSError): + os.unlink(self._keywords_file) + + +class _PorcupineEngine(_Engine): + """Picovoice Porcupine — premium, on-device, needs an access key.""" + + feature, section = "wake.porcupine", "porcupine" + + def _build(self, cfg, sub, ww) -> None: + import pvporcupine + access_key = (os.getenv("PORCUPINE_ACCESS_KEY") or "").strip() + if not access_key: + raise RuntimeError("Porcupine wake word requires PORCUPINE_ACCESS_KEY " + "(get a free key at https://console.picovoice.ai).") + keyword = str(sub.get("keyword") or "jarvis").strip() + # Porcupine's `sensitivities` runs the OPPOSITE way to our shared knob (higher = + # looser); invert so "higher = stricter" holds for every engine. + kwargs: Dict[str, Any] = {"access_key": access_key, "sensitivities": [1.0 - ww._sensitivity(cfg)]} + kwargs["keyword_paths" if _looks_like_path(keyword) else "keywords"] = [keyword] + self._porcupine = pvporcupine.create(**kwargs) + self.frame_length = self._porcupine.frame_length + + def process(self, frame) -> bool: + return self._porcupine.process(frame) >= 0 # pvporcupine wants a plain sequence of int16 + + def close(self) -> None: + with suppress(Exception): + self._porcupine.delete() diff --git a/tools/web_tools.py b/tools/web_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..a94cfc7534d1d87197be6c6a77d050b50421084f --- /dev/null +++ b/tools/web_tools.py @@ -0,0 +1,547 @@ +#!/usr/bin/env python3 +"""Generic web_search / web_extract tools over pluggable backends. + +Backend is selected during ``hermes tools`` (``web.backend`` in config.yaml; per +capability via ``web.search_backend`` / ``web.extract_backend``). Every vendor +implementation lives in ``plugins/web/<vendor>/provider.py`` and registers with +``agent.web_search_registry``; this module owns selection, safety gates, +caching, keyless rescue, and the truncate-and-store result pipeline. +Debug: ``WEB_TOOLS_DEBUG=true`` writes ``logs/web_tools_debug_<UUID>.json``. +""" + +import json +import logging +import os +from typing import List, Any, Optional +# Per-vendor client cache slots; plugins read/write these via tools.web_tools (tests reset them to None). +_firecrawl_client = _firecrawl_client_config = _parallel_client = _async_parallel_client = _exa_client = None + +from plugins.web.firecrawl.provider import _is_tool_gateway_ready, check_firecrawl_api_key +from tools.debug_helpers import DebugSession +from tools.tool_backend_helpers import NOUS_MANAGED_PROVIDER, selection_exists +from tools.url_safety import async_is_safe_url +from tools.web_tools_rescue import _rescue_eligible, _rescue_search +from tools.web_tools_truncate import _effective_char_limit, _trim_results, _truncate_results, convert_base64_images_to_links +from tools.web_tools_extract import ( + _extract_safe_urls, _merge_in_order, _no_provider_error, _resolve_extract_provider, _result_entry, + _strict_selection_error, _validate_extract_urls, +) + +logger = logging.getLogger(__name__) + + +# ─── Backend Selection ──────────────────────────────────────────────────────── + +def _env_value(name: str) -> str: + """Resolve ``name`` via the config-aware env layer (``hermes config set`` values), then process env. + + Mirrors the SearXNG provider's ``_searxng_url()`` so that values set through Hermes' config/.env layer + (``hermes config set``, ``hermes tools``) are honored here too — not just raw process-env exports. + Without this, a config-only ``SEARXNG_URL`` (or any provider key) leaves the backend auto-detect cascade + and ``check_web_api_key()`` blind to it. See #34290. + """ + try: + from hermes_cli.config import get_env_value + val = get_env_value(name) + except Exception: + val = None + return ((os.getenv(name, "") if val is None else val) or "").strip() + + +def _has_env(name: str) -> bool: + return bool(_env_value(name)) + + +def _load_web_config() -> dict: + """Load the ``web:`` section from config.yaml; always a dict (a null section yields ``{}``).""" + try: + from hermes_cli.config import load_config + return load_config().get("web") or {} + except Exception: + return {} + + +def _configured_backend(key: str = "backend") -> str: + """Lower-cased, stripped ``web.<key>`` value ("" when unset/null).""" + return (_load_web_config().get(key) or "").lower().strip() + + +def _registry_call(func_name: str, default, *args): + """``agent.web_search_registry.<func_name>(*args)``, or *default* if it raised (registry never fatal).""" + try: + import agent.web_search_registry as registry_mod + return getattr(registry_mod, func_name)(*args) + except Exception as exc: # noqa: BLE001 — registry optional; never fatal + logger.debug("web provider registry %s%r failed: %s", func_name, args, exc) + return default + + +def _registered_web_provider(backend: str): + """Plugin-registered web provider by name, or ``None``.""" + return _registry_call("get_provider", None, backend) if backend else None + + +def _list_registered_web_providers(): + """All plugin-registered web providers (empty list on failure).""" + return _registry_call("list_providers", []) + + +def _probe(provider, method: str, context: str = "") -> Optional[bool]: + """``bool(provider.<method>())``, or ``None`` if it raised (a broken provider is unavailable; *context* is + appended to the debug log line, e.g. " during readiness check").""" + try: + return bool(getattr(provider, method)()) + except Exception as exc: # noqa: BLE001 — a broken provider is "unavailable" + name = getattr(provider, "name", provider) + logger.debug("web provider %r.%s() raised%s: %s", name, method, context, exc) + return None + + +def _get_backend() -> str: + """Shared web backend name. A stored ``web.backend`` is returned as-is — no availability probe, no + fallback — so a broken selection surfaces the vendor's honest error rather than silently rerouting. + Autodetect runs ONLY when no web selection has ever been stored.""" + configured = _configured_backend() + if configured: + # "nous" (managed subscription) is serviced by firecrawl, routed through the managed Tool Gateway. + return "firecrawl" if configured == NOUS_MANAGED_PROVIDER else configured + if selection_exists("web"): + # Selection exists (use_gateway / per-capability keys) but no shared name: firecrawl, no ladder. + return "firecrawl" + + # Never-configured install. Explicit user credentials beat the managed-gateway probe (a Nous OAuth + # token's tier may not grant web access; the gateway then fails at runtime with no fallback). + # Free tiers trail paid. + backend_candidates = ( + ("tavily", _has_env("TAVILY_API_KEY")), ("perplexity", _has_env("PERPLEXITY_API_KEY")), + ("exa", _has_env("EXA_API_KEY")), + ("parallel", _has_env("PARALLEL_API_KEY")), ("keenable", _has_env("KEENABLE_API_KEY")), + ("firecrawl", _has_env("FIRECRAWL_API_KEY") or _has_env("FIRECRAWL_API_URL")), + ("firecrawl", _is_tool_gateway_ready()), ("searxng", _has_env("SEARXNG_URL")), + ("brave-free", _has_env("BRAVE_SEARCH_API_KEY")), ("ddgs", _ddgs_package_importable()), + ) + for backend, available in backend_candidates: + if available: + return backend + + # Plugin-contributed providers (built-ins are covered above); probe the held object directly. + for provider in _list_registered_web_providers(): + if provider.name not in _LEGACY_WEB_BACKENDS and _probe(provider, "is_available"): + return provider.name + + # Keyless free tier — strictly last so it never pre-empts a keyed backend. Discovery must run + # first: reachable from contexts that haven't loaded plugins (subprocess runs, delegate children). + try: + _ensure_web_plugins_loaded() + from agent.web_search_registry import _keyless_preference, _keyless_tier_enabled + if _keyless_tier_enabled(): + for name in _keyless_preference(): + provider = _registered_web_provider(name) + if provider is not None and _probe(provider, "is_keyless_available"): + return name + except Exception as exc: # noqa: BLE001 — registry optional; never fatal + logger.debug("keyless fallback walk failed: %s", exc) + + return "firecrawl" # default (backward compat) + + +def _get_search_backend() -> str: + """Backend for web_search: ``web.search_backend`` (strict, no probe) > ``web.backend`` > autodetect.""" + return _configured_backend("search_backend") or _get_backend() + + +def _get_extract_backend() -> str: + """Backend for web_extract: ``web.extract_backend`` (strict, no probe) > ``web.backend`` > autodetect.""" + return _configured_backend("extract_backend") or _get_backend() + + +def _ddgs_package_importable() -> bool: + """ddgs is the only backend gated on package presence; single symbol so tests can patch it.""" + try: + import ddgs # noqa: F401 + return True + except ImportError: + return False + + +def _xai_available() -> bool: + # Cheap probe only (env var OR auth.json OAuth): resolve_xai_http_credentials() may hit the network. + try: + from tools.xai_http import has_xai_credentials + return has_xai_credentials() + except Exception: + return False + + +# Built-in backends -> cheap availability probes; any other name is a plugin provider resolved via the +# registry's ``is_available()``. Lambdas so test patches of module-level helpers (_ddgs_package_importable, +# check_firecrawl_api_key) are honored at call time. ``xai`` is probed via has_xai_credentials(), not a +# registered provider, though the registry's _LEGACY_PREFERENCE omits it — drop it if xai ever registers. +_BUILTIN_AVAILABILITY = { + "exa": lambda: _has_env("EXA_API_KEY"), + "parallel": lambda: _has_env("PARALLEL_API_KEY"), + "keenable": lambda: _has_env("KEENABLE_API_KEY"), + "firecrawl": lambda: check_firecrawl_api_key(), + "tavily": lambda: _has_env("TAVILY_API_KEY") + or any(_configured_backend(k) == "tavily" for k in ("backend", "search_backend", "extract_backend")), + "perplexity": lambda: _has_env("PERPLEXITY_API_KEY"), + "searxng": lambda: _has_env("SEARXNG_URL"), + "brave-free": lambda: _has_env("BRAVE_SEARCH_API_KEY"), + "ddgs": lambda: _ddgs_package_importable(), + "xai": _xai_available, +} +_LEGACY_WEB_BACKENDS = frozenset(_BUILTIN_AVAILABILITY) + + +def _is_backend_available(backend: str) -> bool: + """True when *backend* is usable — the single availability chokepoint. Non-legacy names delegate to the + registered provider's ``is_available()`` (unregistered names fall through); built-ins use cheap probes. + + For plugin-registered backends (any name outside :data:`_LEGACY_WEB_BACKENDS`), availability is + delegated to the provider's ``is_available()`` via the web_search_registry. This is the single + chokepoint through which ``_get_backend``, ``_get_capability_backend``, and ``check_web_api_key`` all + resolve availability — fixing custom-provider discovery for every caller at once (issues #28651, #31873, + #32698). Built-in backends keep their cheap hardcoded probes below. + """ + backend = (backend or "").lower().strip() + provider = None if backend in _LEGACY_WEB_BACKENDS else _registered_web_provider(backend) + if provider is not None: + return _probe(provider, "is_available") or False + probe = _BUILTIN_AVAILABILITY.get(backend) + return probe() if probe else False + + +# ─── Firecrawl Client ──────────────────────────────────────────────────────── After PR #25182, the +# firecrawl client, lazy SDK proxy, dual-auth config resolution, response normalizers, and +# check_firecrawl_api_key() all live in plugins.web.firecrawl.provider. +def _web_requires_env() -> list[str]: + """Tool-registry metadata env vars for the web backends. Gateway vars are always listed: gating them + on ``managed_nous_tools_enabled()`` cost a synchronous portal HTTP refresh at every CLI startup. + Contract: set var -> tool sees it; extras are harmless for the not-logged-in.""" + return [ + "EXA_API_KEY", "PARALLEL_API_KEY", "TAVILY_API_KEY", "PERPLEXITY_API_KEY", "KEENABLE_API_KEY", "FIRECRAWL_API_KEY", + "FIRECRAWL_API_URL", "FIRECRAWL_GATEWAY_URL", "TOOL_GATEWAY_DOMAIN", "TOOL_GATEWAY_SCHEME", + "TOOL_GATEWAY_USER_TOKEN", + ] + +_debug = DebugSession("web_tools", env_var="WEB_TOOLS_DEBUG") + + +# ─── Dispatch ───────────────────────────────────────────────────────────────── + +# ─── Exa / Parallel inline helpers — moved into plugins ────────────────────── After PR #25182, the exa +# client + search/extract and parallel client + search/extract helpers all live in their respective plugins: +# - plugins/web/exa/provider.py - plugins/web/parallel/provider.py Both plugins register through +# agent.web_search_registry and the dispatchers in this file resolve them via get_active_*_provider(). +def _ensure_web_plugins_loaded() -> None: + """Idempotently run plugin discovery so the web registry is populated. Dispatch is reachable from contexts + that never triggered discovery (subprocess agent runs, delegate children, scripts); without it a + configured backend yields a misleading "No web ... provider" error. + + Every bundled web provider (brave-free, ddgs, searxng, exa, parallel, tavily, firecrawl, keenable) + registers itself via ``plugins/web/<vendor>/__init__.py`` during plugin discovery. Tool dispatch can be + reached from contexts that haven't already triggered discovery — subprocess agent runs, delegate + children, standalone scripts, certain test paths — and without it the registry is empty and + ``get_provider('firecrawl')`` returns ``None`` even when the user has ``web.extract_backend: firecrawl`` + configured and ``FIRECRAWL_API_KEY`` set. See #27580. + """ + try: + from hermes_cli.plugins import _ensure_plugins_discovered + _ensure_plugins_discovered() + except Exception as exc: # noqa: BLE001 + # Warning, not debug: a broken plugin import is otherwise invisible. + logger.warning("Web plugin discovery failed (non-fatal): %s", exc) + + +def _finish_debug(call_name: str, debug_call_data: dict, error_msg: Optional[str] = None) -> Optional[str]: + """Log the call into the debug session; with *error_msg*, record it and return its ``tool_error`` envelope.""" + if error_msg is not None: + logger.debug("%s", error_msg) + debug_call_data["error"] = error_msg + _debug.log_call(call_name, debug_call_data) + _debug.save() + return None if error_msg is None else tool_error(error_msg) + + +def web_search_tool(query: str, limit: int = 5) -> str: + """Search the web via the configured backend. + + Returns a JSON string ``{"success": bool, "data": {"web": [{"title", "url", "description", "position"}, + ...]}}`` (metadata only — use web_extract_tool for page content) or ``{"success": false, "error": ...}``. + """ + try: + limit = min(max(int(limit), 1), 100) + except (TypeError, ValueError): + limit = 5 + debug_call_data = { + "parameters": {"query": query, "limit": limit}, "error": None, "results_count": 0, + "original_response_size": 0, "final_response_size": 0, + } + + try: + from tools.interrupt import is_interrupted + if is_interrupted(): + return tool_error("Interrupted", success=False) + # Sync only — every provider's search() is sync. + _ensure_web_plugins_loaded() + from agent.web_search_registry import get_active_search_provider, get_provider as _wsp_get_provider + backend = _get_search_backend() + provider = _wsp_get_provider(backend) if backend else None + if provider is None or not provider.supports_search(): + if provider is None and backend and selection_exists("web"): + error_text = debug_call_data["error"] = _strict_selection_error("search", backend) + _finish_debug("web_search_tool", debug_call_data) + return json.dumps({"success": False, "error": error_text}, indent=2, ensure_ascii=False) + # Never-configured install: legacy availability-walked autodetect. + provider = get_active_search_provider() + + if provider is None: + fallback = "No web search provider configured. Run `hermes tools` to set one up." + response_data = {"success": False, "error": _no_provider_error("search", fallback)} + else: + logger.info("Web search via %s: '%s' (limit: %d)", provider.name, query, limit) + response_data = _memoized_search(provider, query, limit) + + debug_call_data["results_count"] = len(response_data.get("data", {}).get("web", [])) + result_json = json.dumps(response_data, indent=2, ensure_ascii=False) + debug_call_data["final_response_size"] = len(result_json) + _finish_debug("web_search_tool", debug_call_data) + return result_json + except Exception as e: + return _finish_debug("web_search_tool", debug_call_data, f"Error searching web: {str(e)}") + + +def _memoized_search(provider, query: str, limit: int) -> dict: + """TTL memo + single-flight around the paid vendor call (tools/web_result_cache.py); sits after every + safety/config check. The provider is asked for the BUCKETED count so near-identical limits share an entry; + the caller's count is sliced out. Only successful, non-rescued responses are cached — caching a rescue + would make the one-shot ring fallback sticky for a whole TTL.""" + from tools.web_result_cache import bucket_limit, search_memo, slice_search_response + + def _paid_search() -> tuple[dict, bool]: + fetch_limit = bucket_limit(limit) + try: + resp = provider.search(query, fetch_limit) + except Exception as exc: # noqa: BLE001 — candidate for rescue + if not _rescue_eligible(provider): + raise + return _rescue_search(provider.name, str(exc), query, fetch_limit), True + if not resp.get("success") and _rescue_eligible(provider): + return _rescue_search(provider.name, str(resp.get("error", "")), query, fetch_limit), True + return resp, False + + response_data = search_memo.lookup(provider.name, query, limit) + if response_data is None: + with search_memo.flight_lock(provider.name, query, limit): + # Re-check inside the lock: a concurrent identical call may have stored. + response_data = search_memo.lookup(provider.name, query, limit) + if response_data is None: + response_data, was_rescued = _paid_search() + if not was_rescued: + search_memo.store(provider.name, query, limit, response_data) + return slice_search_response(response_data, limit) + + +async def web_extract_tool(urls: List[Any], format: str = None, char_limit: Optional[int] = None) -> str: + """Extract clean page content (no LLM) from URLs via the configured backend. + + Pages over ``char_limit`` (default web.extract_char_limit or 15000) are head+tail truncated with a footer + pointing at the stored full text; inline base64 images become ``[IMAGE: alt]``. URLs carrying secrets are + refused before any fetch; private-network URLs are blocked per entry. Returns JSON ``{"results": [...]}``. + """ + normalized_urls, normalized_indices, invalid_urls, blocked = _validate_extract_urls(urls) + if blocked is not None: + return blocked + debug_call_data = { + "parameters": {"urls": normalized_urls, "format": format, "char_limit": char_limit}, "error": None, + "pages_extracted": 0, "pages_truncated": 0, "original_response_size": 0, "final_response_size": 0, + "truncation_metrics": [], "processing_applied": [], + } + + try: + logger.info("Extracting content from %d URL(s)", len(normalized_urls)) + # SSRF protection — filter private/internal URLs before any backend. + safe_urls, safe_indices, ssrf_blocked = [], [], {} + for index, url in zip(normalized_indices, normalized_urls): + if await async_is_safe_url(url): + safe_urls.append(url) + safe_indices.append(index) + else: + ssrf_blocked[index] = _result_entry( + url, "Blocked: URL targets a private or internal network address" + ) + + results = [] + if safe_urls: + backend = _get_extract_backend() + _ensure_web_plugins_loaded() + provider, error_json = _resolve_extract_provider(backend) + if error_json is not None: + return error_json + results = await _extract_safe_urls(provider, safe_urls, format) + # Reconstruct input order across invalid, blocked, and provider entries (providers preserve + # the order of the safe URL list they receive). + if invalid_urls or ssrf_blocked: + fixed = {**ssrf_blocked, **invalid_urls} + results = _merge_in_order(len(urls), fixed, safe_indices, safe_urls, results) + + logger.info("Extracted content from %d pages", len(results)) + debug_call_data["pages_extracted"] = len(results) + debug_call_data["original_response_size"] = len(json.dumps({"results": results})) + debug_call_data["processing_applied"].append("truncate_and_store") + _truncate_results(results, _effective_char_limit(char_limit), debug_call_data) + trimmed = _trim_results(results) + result_json = ( + json.dumps({"results": trimmed}, indent=2, ensure_ascii=False) if trimmed + else tool_error("Content was inaccessible or not found") + ) + # Belt-and-suspenders sweep of the serialized JSON: a provider may tuck a base64 blob in metadata. + cleaned_result = convert_base64_images_to_links(result_json) + debug_call_data["final_response_size"] = len(cleaned_result) + debug_call_data["processing_applied"].append("base64_image_conversion") + _finish_debug("web_extract_tool", debug_call_data) + return cleaned_result + except Exception as e: + return _finish_debug("web_extract_tool", debug_call_data, f"Error extracting content: {str(e)}") + + +def _provider_is_ready(provider) -> bool: + """True when *provider* is keyed-available OR keyless-capable, without raising. + + ``get_active_*_provider()`` returns an explicitly configured backend even when ``is_available()`` is + False (so dispatch can emit a precise error), so readiness gates (tool check_fn, ``hermes doctor``) + must probe for real. Keyless mode (Exa/Parallel free tier) is a working state, not a misconfig. + + See #78412. + """ + if provider is None: + return False + ready = _probe(provider, "is_available", " during readiness check") + if ready is None: # broken provider == not ready; don't try the keyless probe + return False + return bool(ready or _probe(provider, "is_keyless_available", " during readiness check")) + + +def check_web_api_key() -> bool: + """``check_fn`` gate for web_search / web_extract: is any web backend available? + + A plugin-registered provider reporting ``is_available()`` must light the tools up even with no + built-in credentials; resolution funnels through :func:`_is_backend_available`. + + See #28651, #31873. + """ + # Boolean OR over configured + built-ins — probe order is irrelevant here. + candidates = [c for c in (_configured_backend(),) if c] + list(_LEGACY_WEB_BACKENDS) + if any(_is_backend_available(backend) for backend in candidates): + return True + # Plugin path. Discovery must run first: check_fn fires at tool-registration time, before any dispatch. + try: + _ensure_web_plugins_loaded() + from agent.web_search_registry import get_active_search_provider, get_active_extract_provider + return _provider_is_ready(get_active_search_provider()) or _provider_is_ready( + get_active_extract_provider() + ) + except Exception as exc: # noqa: BLE001 — registry optional; never fatal + logger.debug("web provider registry availability check failed: %s", exc) + return False + + +# ─── Registry ───────────────────────────────────────────────────────────────── +from tools.registry import registry, tool_error + +WEB_SEARCH_SCHEMA = { + "name": "web_search", + "description": "Search the web for information. Returns up to 5 results by default with titles, URLs, and descriptions. The query is passed through to the configured backend, so operators such as site:domain, filetype:pdf, intitle:word, -term, and \"exact phrase\" may work when the backend supports them.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "The search query to look up on the web. You may include backend-supported operators such as site:example.com, filetype:pdf, intitle:word, -term, or \"exact phrase\"." + }, + "limit": { + "type": "integer", + "description": "Maximum number of results to return. Defaults to 5.", + "minimum": 1, + "maximum": 100, + "default": 5 + } + }, + "required": ["query"] + } +} + +WEB_EXTRACT_SCHEMA = { + "name": "web_extract", + "description": "Extract content from web page URLs. Returns clean page content in markdown/text (no LLM summarization — fast). Also works with PDF URLs (arxiv papers, documents) — pass the PDF link directly. Pages within the char budget (default 15000) return whole; larger pages return a head+tail window with a footer telling you the full text's saved file path and the read_file call to page through the omitted middle. Inline images appear as [IMAGE: alt] placeholders; real image URLs are kept as links. If a URL fails or times out, use the browser tool instead.", + "parameters": { + "type": "object", + "properties": { + "urls": { + "type": "array", + "items": {"type": "string"}, + "description": "List of URLs to extract content from (max 5 URLs per call)", + "maxItems": 5 + }, + "char_limit": { + "type": "integer", + "description": "Optional per-page character budget sent back (default 15000). Pages larger than this are head+tail truncated with the full text stored to disk. Raise it when you need more of a long page inline.", + "minimum": 2000 + } + }, + "required": ["urls"] + } +} + +registry.register( + name="web_search", toolset="web", schema=WEB_SEARCH_SCHEMA, + handler=lambda args, **kw: web_search_tool(args.get("query", ""), limit=args.get("limit", 5)), + check_fn=check_web_api_key, requires_env=_web_requires_env(), emoji="🔍", + max_result_size_chars=100_000, +) +registry.register( + name="web_extract", toolset="web", schema=WEB_EXTRACT_SCHEMA, + handler=lambda args, **kw: web_extract_tool( + args.get("urls", [])[:5] if isinstance(args.get("urls"), list) else [], "markdown", + char_limit=args.get("char_limit"), + ), + check_fn=check_web_api_key, requires_env=_web_requires_env(), is_async=True, emoji="📄", + max_result_size_chars=100_000, +) + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. +from typing import Dict # noqa: F401,E402 +from typing import TYPE_CHECKING # noqa: F401,E402 +import asyncio # noqa: F401,E402 +import httpx # noqa: F401,E402 +import re # noqa: F401,E402 +import sys # noqa: F401,E402 + + +_PLUGIN_COMPAT_LAZY = { + 'DEFAULT_EXTRACT_CHAR_LIMIT': ('tools.web_tools_truncate', 'DEFAULT_EXTRACT_CHAR_LIMIT'), + 'Firecrawl': ('plugins.web.firecrawl.provider', 'Firecrawl'), + 'MAX_STORED_TEXT_CHARS': ('tools.web_tools_truncate', 'MAX_STORED_TEXT_CHARS'), + 'build_vendor_gateway_url': ('tools.managed_tool_gateway', 'build_vendor_gateway_url'), + 'managed_nous_tools_enabled': ('tools.tool_backend_helpers', 'managed_nous_tools_enabled'), + 'normalize_url_for_request': ('tools.url_safety', 'normalize_url_for_request'), + 'nous_tool_gateway_unavailable_message': ('tools.tool_backend_helpers', 'nous_tool_gateway_unavailable_message'), + 'prefers_gateway': ('tools.tool_backend_helpers', 'prefers_gateway'), + 'resolve_managed_tool_gateway': ('tools.managed_tool_gateway', 'resolve_managed_tool_gateway'), + 'sensitive_query_param_name': ('tools.url_safety', 'sensitive_query_param_name'), +} + + +def __getattr__(name): # PEP 562 — lazy so no import cycles + target = _PLUGIN_COMPAT_LAZY.get(name) + if target is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + import importlib + from hermes_cli.plugin_compat import warn_once + warn_once(__name__, name, *target) + return getattr(importlib.import_module(target[0]), target[1]) +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/web_tools_rescue.py b/tools/web_tools_rescue.py new file mode 100644 index 0000000000000000000000000000000000000000..ade3332eccadfe51951346a092a60dbe4a2a90bf --- /dev/null +++ b/tools/web_tools_rescue.py @@ -0,0 +1,120 @@ +"""One-shot keyless-ring rescue for failed keyed/configured web calls. + +Stateless by design: a rescue routes THIS call through the free-tier ring (plugins/web/keyless_mcp.py); +the next web_search/web_extract call attempts the chosen backend again. Callers must never cache a +rescue-served response, or the one-shot rescue becomes sticky for a whole TTL. Logs under the origin +(tools.web_tools) logger. +""" + +import logging + +logger = logging.getLogger("tools.web_tools") + +# Ring vendor -> env var holding its paid key (keyed mode ⇒ eligible for rescue). +_RING_KEY_VARS = { + "exa": "EXA_API_KEY", "parallel": "PARALLEL_API_KEY", + "firecrawl": "FIRECRAWL_API_KEY", "keenable": "KEENABLE_API_KEY", +} + + +def _keyless_rescue_enabled() -> bool: + """``web.keyless_rescue`` (default on), implicitly off when the keyless tier is disabled.""" + from tools.web_tools import _load_web_config + if not _load_web_config().get("keyless_rescue", True): + return False + try: + from agent.web_search_registry import _keyless_tier_enabled + return _keyless_tier_enabled() + except Exception as exc: # noqa: BLE001 — registry optional + logger.debug("keyless rescue tier check failed: %s", exc) + return False + + +def _rescue_eligible(provider) -> bool: + """True when a failed call on *provider* should get a one-shot rescue. + + Eligible: a keyed/configured path — any non-ring backend, or a ring vendor in keyed mode. A ring + vendor already in keyless mode is NOT eligible: its failure means the ring was already walked. + """ + if not _keyless_rescue_enabled() or provider is None: + return False + try: + from plugins.web.keyless_mcp import _KEYLESS_RING, use_keyless + name = getattr(provider, "name", "") + if name not in _KEYLESS_RING: + return True + from agent.web_search_provider import get_provider_env + key_var = _RING_KEY_VARS.get(name, "") + return not use_keyless(name, get_provider_env(key_var) if key_var else "") + except Exception as exc: # noqa: BLE001 — rescue is best-effort + logger.debug("rescue eligibility check failed: %s", exc) + return False + + +def _rescue_search(provider_name: str, original_error: str, query: str, limit: int) -> dict: + """Rescue a failed search via the ring; annotate the result with the original failure.""" + from plugins.web.keyless_mcp import search_with_failover + logger.warning( + "web_search backend '%s' failed (%s); one-shot keyless rescue", + provider_name, (original_error or "")[:200], + ) + rescued = search_with_failover(provider_name, query, limit) + if rescued.get("success"): + rescued.setdefault("data", {}).update( + rescued_from=provider_name, + backend_error=( + f"Configured backend '{provider_name}' failed this call " + f"({(original_error or 'unknown error')[:300]}); result served by the keyless free tier. " + f"The next call will use '{provider_name}' again." + ), + ) + return rescued + # Ring also failed: the ORIGINAL error names the user's setup, so lead with it. + return { + "success": False, + "error": ( + f"{original_error or 'search failed'} " + f"(keyless rescue also failed: {rescued.get('error', 'unknown')})" + ), + } + + +def _policy_blocked_result(result: dict) -> bool: + """True for a website-policy refusal — intentional, never rescued (it would fetch blocked content).""" + error = str(result.get("error") or "").lower() + return bool(result.get("blocked_by_policy")) or "blocked by website policy" in error + + +def _rescue_extract(provider_name: str, urls: list, results: list) -> list: + """Rescue a whole-batch extract failure via the ring. + + Only genuine failures are re-fetched; policy-blocked entries are preserved verbatim. If the provider + broke url/result order parity, every entry is treated as rescueable and the ring's list replaces the + batch wholesale. + """ + from plugins.web.keyless_mcp import extract_with_failover + + parity = len(results) == len(urls) + rescue_idx = [i for i, r in enumerate(results) if not parity or not _policy_blocked_result(r)] + if not rescue_idx: + return results # every failure is an intentional policy block + + rescue_urls = [urls[i] for i in rescue_idx] if parity else list(urls) + errors = (results[i].get("error") for i in rescue_idx if results[i].get("error")) + original_error = next(errors, "extract failed") + logger.warning( + "web_extract backend '%s' failed all %d URL(s) (%s); one-shot keyless rescue", + provider_name, len(rescue_urls), (original_error or "")[:200], + ) + rescued = extract_with_failover(provider_name, list(rescue_urls)) + if rescued and all(r.get("error", "") for r in rescued): + return results # rescue also failed everywhere: keep original errors + for r in rescued: + meta = None if r.get("error") else r.setdefault("metadata", {}) + if isinstance(meta, dict): + meta["rescued_from"] = provider_name + meta["backend_error"] = (original_error or "")[:300] + if parity and len(rescued) == len(rescue_idx): + replacements = dict(zip(rescue_idx, rescued)) + return [replacements.get(i, r) for i, r in enumerate(results)] + return rescued diff --git a/tools/website_policy.py b/tools/website_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..be0af25fd35dcc31f1c9821f091d2c5681366083 --- /dev/null +++ b/tools/website_policy.py @@ -0,0 +1,198 @@ +"""Website access policy helpers for URL-capable tools. + +Loads a user-managed website blocklist (``security.website_blocklist`` in ~/.hermes/config.yaml plus +optional shared list files) without the heavier CLI config stack. The parsed policy is cached with a +short TTL so config edits take effect quickly without re-parsing YAML on every URL check. +""" + +from __future__ import annotations + +import fnmatch +import logging +import threading +import time +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple +from urllib.parse import urlparse + +from hermes_constants import get_hermes_home +from tools.url_safety import _normalize_hostname as _normalize_host + +logger = logging.getLogger(__name__) + +_DEFAULT_WEBSITE_BLOCKLIST = {"enabled": False, "domains": [], "shared_files": []} + +# Without this cache a 50-URL extract would mean 51 YAML parses of config.yaml. +_CACHE_TTL_SECONDS = 30.0 +_cache_lock = threading.Lock() +_cached_policy: Optional[Dict[str, Any]] = None +_cached_policy_path: Optional[str] = None +_cached_policy_time: float = 0.0 + + +class WebsitePolicyError(Exception): + """Raised when a website policy file is malformed.""" + + +def _normalize_rule(rule: Any) -> Optional[str]: + """Reduce a rule (bare host, URL, or ``host/path``) to a lowercase host; None for blanks/comments.""" + if not isinstance(rule, str) or not (value := rule.strip().lower()) or value.startswith("#"): + return None + if "://" in value: + parsed = urlparse(value) + value = parsed.netloc or parsed.path + return value.split("/", 1)[0].strip().rstrip(".").removeprefix("www.") or None + + +def _iter_blocklist_file_rules(path: Path) -> List[str]: + """Rules from a shared blocklist file; missing/unreadable files warn and yield nothing rather than + raising — a bad file path must not disable all web tools.""" + try: + raw = path.read_text(encoding="utf-8") + except FileNotFoundError: + logger.warning("Shared blocklist file not found (skipping): %s", path) + return [] + except (OSError, UnicodeDecodeError) as exc: + logger.warning("Failed to read shared blocklist file %s (skipping): %s", path, exc) + return [] + return [rule for rule in map(_normalize_rule, raw.splitlines()) if rule] + + +def _require_mapping(value: Any, label: str) -> Dict[str, Any]: + """``None`` (empty YAML section) counts as an empty mapping; other non-dicts are errors.""" + if value is not None and not isinstance(value, dict): + raise WebsitePolicyError(f"{label} must be a mapping") + return value or {} + + +def _load_policy_config(config_path: Path) -> Dict[str, Any]: + if not config_path.exists(): + return dict(_DEFAULT_WEBSITE_BLOCKLIST) + try: + import yaml + except ImportError: + logger.debug("PyYAML not installed — website blocklist disabled") + return dict(_DEFAULT_WEBSITE_BLOCKLIST) + try: + config = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {} + except yaml.YAMLError as exc: + raise WebsitePolicyError(f"Invalid config YAML at {config_path}: {exc}") from exc + except OSError as exc: + raise WebsitePolicyError(f"Failed to read config file {config_path}: {exc}") from exc + if not isinstance(config, dict): + raise WebsitePolicyError("config root must be a mapping") + security = _require_mapping(config.get("security", {}), "security") + website_blocklist = _require_mapping(security.get("website_blocklist", {}), "security.website_blocklist") + return {**_DEFAULT_WEBSITE_BLOCKLIST, **website_blocklist} + + +def _require_type(policy: Dict[str, Any], key: str, kind: type, default: Any) -> Any: + """Typed policy field; ``None``/empty list values are coerced to ``[]`` for lists only.""" + value = policy.get(key, default) + if kind is list: + value = value or [] + if not isinstance(value, kind): + kind_name = "boolean" if kind is bool else "list" + raise WebsitePolicyError(f"security.website_blocklist.{key} must be a {kind_name}") + return value + + +def load_website_blocklist(config_path: Optional[Path] = None) -> Dict[str, Any]: + """Parsed website blocklist policy (``{"enabled", "rules"}``); cached for ``_CACHE_TTL_SECONDS`` for + the default config path only — an explicit ``config_path`` (tests) bypasses and never populates it.""" + global _cached_policy, _cached_policy_path, _cached_policy_time + default_path = get_hermes_home() / "config.yaml" + resolved_path = str(config_path or default_path) + now = time.monotonic() + if config_path is None: + with _cache_lock: + fresh = _cached_policy_path == resolved_path and (now - _cached_policy_time) < _CACHE_TTL_SECONDS + if _cached_policy is not None and fresh: + return _cached_policy + config_path = config_path or default_path + policy = _load_policy_config(config_path) + domains = map(_normalize_rule, _require_type(policy, "domains", list, [])) + pairs: List[Tuple[str, str]] = [(p, "config") for p in domains if p] + shared_files = _require_type(policy, "shared_files", list, []) + enabled = _require_type(policy, "enabled", bool, True) + for shared_file in shared_files: + if not isinstance(shared_file, str) or not shared_file.strip(): + continue + path = Path(shared_file).expanduser() + path = path if path.is_absolute() else (get_hermes_home() / path).resolve() + pairs += [(normalized, str(path)) for normalized in _iter_blocklist_file_rules(path)] + # dict.fromkeys dedupes (pattern, source) while keeping first-seen order. + result = {"enabled": enabled, "rules": [{"pattern": p, "source": s} for p, s in dict.fromkeys(pairs)]} + if config_path == default_path: # explicit paths are tests — never cache them + with _cache_lock: + _cached_policy, _cached_policy_path, _cached_policy_time = result, resolved_path, now + return result + + +def _match_host_against_rule(host: str, pattern: str) -> bool: + """``*.example.com`` rules glob-match; bare hosts match exactly or as a parent domain.""" + if not host or not pattern: + return False + if pattern.startswith("*."): + return fnmatch.fnmatch(host, pattern) + return host == pattern or host.endswith(f".{pattern}") + + +def _extract_host_from_urlish(url: str) -> str: + """Host of ``url``; schemeless inputs (``example.com/x``) are retried as ``//url``.""" + parsed = urlparse(url) + host = _normalize_host(parsed.hostname or parsed.netloc) + if not host and "://" not in url: + parsed = urlparse(f"//{url}") + host = _normalize_host(parsed.hostname or parsed.netloc) + return host + + +def check_website_access(url: str, config_path: Optional[Path] = None) -> Optional[Dict[str, str]]: + """``None`` if the URL is allowed by the blocklist policy, else block metadata (host/rule/source/message). + + Fails open on policy errors (warn + ``None``) so a config typo can't break all web tools — except with + an explicit ``config_path`` (tests), where errors propagate. + """ + # Fast path: cached policy disabled/empty → no YAML read, no host extraction. + if config_path is None: + with _cache_lock: + if _cached_policy is not None and not _cached_policy.get("enabled"): + return None + host = _extract_host_from_urlish(url) + if not host: + return None + try: + policy = load_website_blocklist(config_path) + except WebsitePolicyError as exc: + if config_path is not None: + raise + logger.warning("Website policy config error (failing open): %s", exc) + return None + except Exception as exc: + logger.warning("Unexpected error loading website policy (failing open): %s", exc) + return None + if not policy.get("enabled"): + return None + for rule in policy.get("rules", []): + pattern, source = rule.get("pattern", ""), rule.get("source", "config") + if _match_host_against_rule(host, pattern): + logger.info("Blocked URL %s — matched rule '%s' from %s", url, pattern, source) + return { + "url": url, "host": host, "rule": pattern, "source": source, + "message": f"Blocked by website policy: '{host}' matched rule '{pattern}' from {source}", + } + return None + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. + +def invalidate_cache() -> None: + """Force the next ``check_website_access`` call to re-read config.""" + global _cached_policy + with _cache_lock: + _cached_policy = None +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/working_diff.py b/tools/working_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..534da92c987a953c8b5f21a022dffa823d623852 --- /dev/null +++ b/tools/working_diff.py @@ -0,0 +1,96 @@ +"""Working-tree git diff collection shared by the CLI and gateway ``/diff``. + +Surface-agnostic so the CLI (colored terminal) and gateway (fenced, truncated +messages) render the same data. Modes: ``working`` (unstaged + untracked), +``staged`` (``git diff --cached``), ``all`` (everything since HEAD plus untracked). +Untracked files are folded in via ``git diff --no-index /dev/null <file>`` so +brand-new files show as additions instead of being invisible. +""" + +from __future__ import annotations + +import os +import shutil +import subprocess +from contextlib import suppress +from typing import Dict, List + +from hermes_cli._subprocess_compat import harden_git_argv, noninteractive_git_env + +_GIT_TIMEOUT = 15 +_MAX_UNTRACKED_FILES = 50 # sanity cap so a node_modules explosion can't hang us + +_MODE_ARGS = { + "working": ["diff"], + "staged": ["diff", "--cached"], + "all": ["diff", "HEAD"], +} +VALID_MODES = tuple(_MODE_ARGS) + + +def _run(args: List[str], cwd: str, timeout: int = _GIT_TIMEOUT): + """Run git, returning (returncode, stdout). Never raises on git failure. Hardened against a + malicious repo's ``.git/config`` (GHSA-7x36-8jrh-v4pw): ``noninteractive_git_env`` disables + fsmonitor/hooks/pager/editor/credential sinks and ``harden_git_argv`` appends ``--no-ext-diff + --no-textconv`` to diff-rendering subcommands so attribute-scoped drivers can't execute either.""" + proc = subprocess.run( + ["git", "-c", "core.quotePath=false", *harden_git_argv(args)], + cwd=cwd, capture_output=True, text=True, timeout=timeout, encoding="utf-8", errors="replace", + stdin=subprocess.DEVNULL, env=noninteractive_git_env(), + ) + return proc.returncode, proc.stdout + + +def _untracked_files(cwd: str) -> List[str]: + code, out = _run(["ls-files", "--others", "--exclude-standard"], cwd) + return [line for line in out.splitlines() if line.strip()] if code == 0 else [] + + +def _untracked_diff(cwd: str, files: List[str]) -> str: + """Render untracked files as new-file diffs via ``git diff --no-index``.""" + chunks: List[str] = [] + for rel in files[:_MAX_UNTRACKED_FILES]: + with suppress(subprocess.TimeoutExpired, OSError): + # --no-index exits 1 when files differ — the success path, so the code is ignored. + _, out = _run(["diff", "--no-index", "--", os.devnull, rel], cwd) + if out.strip(): + chunks.append(out.rstrip("\n")) + if len(files) > _MAX_UNTRACKED_FILES: + chunks.append(f"... ({len(files) - _MAX_UNTRACKED_FILES} more untracked files not shown)") + return "\n".join(chunks) + + +def collect_working_diff(cwd: str, mode: str = "working", paths: List[str] | None = None) -> Dict: + """Collect a git diff of the working directory: ``{"success", "stat", "diff", "untracked", "empty"}`` + on success or ``{"success": False, "error": ...}`` when git is unavailable / not a repo. ``paths`` + restricts the diff to pathspecs (passed verbatim); untracked files are then skipped.""" + if mode not in _MODE_ARGS: + return {"success": False, "error": f"Unknown mode '{mode}'. Use: {', '.join(VALID_MODES)}"} + if not shutil.which("git"): + return {"success": False, "error": "git is not installed or not on PATH."} + try: + code, _ = _run(["rev-parse", "--is-inside-work-tree"], cwd, timeout=5) + except (subprocess.TimeoutExpired, OSError) as e: + return {"success": False, "error": f"git failed: {e}"} + if code != 0: + return {"success": False, "error": "Not a git repository."} + + base_args = _MODE_ARGS[mode] + pathspec = ["--", *paths] if paths else [] + try: + _, stat_out = _run([*base_args, "--stat", *pathspec], cwd) + _, diff_out = _run([*base_args, *pathspec], cwd, timeout=_GIT_TIMEOUT * 2) + untracked = _untracked_files(cwd) if mode in ("working", "all") and not paths else [] + untracked_diff = _untracked_diff(cwd, untracked) if untracked else "" + except subprocess.TimeoutExpired: + return {"success": False, "error": "git diff timed out."} + except OSError as e: + return {"success": False, "error": f"git failed: {e}"} + + stat, diff = stat_out.strip(), diff_out.strip() + if untracked_diff: + diff = f"{diff}\n{untracked_diff}".strip() + result = {"success": True, "stat": stat, "diff": diff, "untracked": untracked} + if not stat and not diff and not untracked: + result["empty"] = True + return result diff --git a/tools/write_approval.py b/tools/write_approval.py new file mode 100644 index 0000000000000000000000000000000000000000..39c9a4cda86a5b6d84491db7d26acbdd24e4601a --- /dev/null +++ b/tools/write_approval.py @@ -0,0 +1,287 @@ +#!/usr/bin/env python3 +"""Write-approval gate + pending store for memory and skill writes. + +A per-subsystem boolean ``write_approval`` gates the agent's cross-session writes — +**memory** (MEMORY.md / USER.md) and **skills** (SKILL.md + files) — from either +origin (**foreground** turn or **background_review** fork). ``false`` (default) +writes freely; ``true`` never commits directly: it prompts inline (memory, +interactive CLI only) or **stages** the write under +``<HERMES_HOME>/pending/{memory,skills}/<id>.json`` for out-of-band review. +""" + +from __future__ import annotations + +import difflib +import json +import logging +import re +import time +import uuid +from contextlib import suppress +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, List, Optional + +from hermes_constants import get_hermes_home +from utils import atomic_json_write + +logger = logging.getLogger(__name__) + +# Subsystem identifiers +MEMORY = "memory" +SKILLS = "skills" +_SUBSYSTEMS = (MEMORY, SKILLS) + +# Per-subsystem config key. Intentionally a single boolean with no "block all writes" +# state — to disable a subsystem use its own enable flag (e.g. ``memory.memory_enabled``). +CONFIG_KEY = "write_approval" +_TRUTHY_STRINGS = frozenset({"on", "true", "yes", "1", "approve", "enabled"}) + + +# --- Config resolution --- + +def write_approval_enabled(subsystem: str) -> bool: + """Read ``<subsystem>.write_approval``; any unset/invalid value means gate off.""" + if subsystem not in _SUBSYSTEMS: + return False + try: + from hermes_cli.config import load_config, cfg_get + return _normalize_enabled(cfg_get(load_config(), subsystem, CONFIG_KEY, default=False)) + except Exception: + return False + + +def _normalize_enabled(value: Any) -> bool: + """Coerce a config value to bool; unknown → False (gate off). The string branch + covers hand-edited configs (YAML already parses bare on/off/yes/no).""" + if isinstance(value, bool): + return value + return isinstance(value, str) and value.strip().lower() in _TRUTHY_STRINGS + + +# --- Pending store (file-backed) --- + +def _pending_path(subsystem: str, pending_id: str) -> Path: + return get_hermes_home() / "pending" / subsystem / f"{pending_id}.json" + + +def _pending_files(subsystem: str) -> list: + d = _pending_path(subsystem, "").parent + return list(d.glob("*.json")) if d.exists() else [] + + +def stage_write(subsystem: str, payload: Dict[str, Any], *, summary: str, origin: str) -> Dict[str, Any]: + """Persist a pending write and return its record (``id`` + metadata). ``payload`` is the exact + kwargs to replay the write on approval; ``origin`` is ``foreground`` or ``background_review``. + Best-effort: on disk failure it logs and still returns a record — the write is lost, which is + the safe failure for an approval gate (nothing silently committed).""" + pid = uuid.uuid4().hex[:8] + record = { + "id": pid, "subsystem": subsystem, "action": payload.get("action", ""), + "summary": (summary or "").strip(), "origin": origin or "foreground", + "created_at": time.time(), "payload": payload, + } + try: + atomic_json_write(_pending_path(subsystem, pid), record) + except Exception as e: # pragma: no cover - disk failure path + logger.error("Failed to stage pending %s write: %s", subsystem, e, exc_info=True) + return record + + +def list_pending(subsystem: str) -> List[Dict[str, Any]]: + """Return all pending records for ``subsystem``, oldest first.""" + records: List[Dict[str, Any]] = [] + for p in _pending_files(subsystem): + try: + records.append(json.loads(p.read_text(encoding="utf-8"))) + except Exception: + logger.warning("Skipping unreadable pending record: %s", p) + records.sort(key=lambda r: r.get("created_at", 0)) + return records + + +def get_pending(subsystem: str, pending_id: str) -> Optional[Dict[str, Any]]: + """Return a single pending record by id, or None.""" + path = _pending_path(subsystem, pending_id) + if not path.exists(): + return None + with suppress(Exception): + return json.loads(path.read_text(encoding="utf-8")) + return None + + +def discard_pending(subsystem: str, pending_id: str) -> bool: + """Delete a pending record. Returns True if it existed.""" + try: + path = _pending_path(subsystem, pending_id) + if path.exists(): + path.unlink() + return True + except Exception as e: # pragma: no cover + logger.error("Failed to discard pending %s/%s: %s", subsystem, pending_id, e) + return False + + +def pending_count(subsystem: str) -> int: + """Cheap count of pending records (for notification badges).""" + d = _pending_path(subsystem, "").parent + if not d.exists(): + return 0 + with suppress(Exception): + return sum(1 for _ in d.glob("*.json")) + return 0 + + +# --- Write origin --- + +def current_origin() -> str: + """``foreground`` or ``background_review`` — reuses the skill-provenance ContextVar + the background review fork sets; foreground turns leave it at the default.""" + with suppress(Exception): + from tools.skill_provenance import get_current_write_origin + return get_current_write_origin() + return "foreground" + + +# --- Gate decision --- + +@dataclass(slots=True, kw_only=True) +class GateDecision: + """Result of evaluating the write gate; exactly one flag is True. ``allow``: do the real write; + ``blocked``: user denied the inline prompt (``message`` says why); ``stage``: caller must + ``stage_write`` the payload (``message`` is the user-facing "staged for approval" note).""" + + allow: bool = False + blocked: bool = False + stage: bool = False + message: str = "" + + +def _staged(subsystem: str) -> GateDecision: + where = "/skills pending" if subsystem == SKILLS else "/memory pending" + return GateDecision(stage=True, message=(f"Staged for approval ({subsystem}.write_approval is on). " + f"Not yet saved — review with {where}.")) + + +def evaluate_gate(subsystem: str, *, inline_summary: str = "", inline_detail: str = "") -> GateDecision: + """Decide what to do with a pending write: gate off → allow; gate on + skills (any origin) or + background → stage; gate on + memory + foreground → inline prompt when an interactive channel + exists, else stage. The gate only ever delays a write, never silently refuses it; ``blocked`` + is produced only when the user actively denies the inline prompt.""" + if not write_approval_enabled(subsystem): + return GateDecision(allow=True) + # Skills are too big to review inline; a background write runs in a daemon thread with no user. + if subsystem == SKILLS or current_origin() == "background_review": + return _staged(subsystem) + granted = _prompt_inline_memory_approval(inline_summary, inline_detail) + if granted is None: + return _staged(MEMORY) + if granted: + return GateDecision(allow=True) + return GateDecision(blocked=True, message="Memory write denied by user. The change was not saved.") + + +def _prompt_inline_memory_approval(summary: str, detail: str) -> Optional[bool]: + """Prompt inline for a memory write: True approved, False denied, None → stage. Uses the per-thread + CLI approval callback (``tools.terminal_tool.set_approval_callback``) directly, not + ``prompt_dangerous_approval``: that wrapper falls back to ``input()`` (deadlock-prone under + prompt_toolkit; silent deny in gateway sessions) and turns callback errors into a deny, whereas + here a missing channel or failed prompt must stage instead. + + See #15216. + """ + try: + from tools.terminal_tool import _get_approval_callback + except Exception: + return None + callback = _get_approval_callback() + if callback is None: + return None + header = summary.strip() or "Save to memory?" + try: + choice = callback(detail.strip() or header, f"Save to memory: {header}", allow_permanent=False) + except Exception as e: + logger.error("Inline memory approval prompt failed: %s", e) + return None + # unknown outcome → stage rather than drop + return {"once": True, "session": True, "deny": False}.get(choice) + + +# --- Skill-specific helpers (gist + diff for the review affordances) --- + +_GIST_TEMPLATES = {"write_file": "write {file_path} in '{name}'", "remove_file": "remove {file_path} from '{name}'", + "delete": "delete skill '{name}'"} + + +def skill_gist(action: str, name: str, *, content: str = "", file_path: str = "", + old_string: str = "", new_string: str = "") -> str: + """One-line heuristic gist (no model call) for a pending skill write: create/edit use + the frontmatter ``description:``; patch/write_file describe the size of the change.""" + if action in {"create", "edit"} and content: + desc = _frontmatter_description(content) + size = f"{len(content) // 1024 + 1} KB" if len(content) >= 1024 else f"{len(content)} chars" + return f"{'create' if action == 'create' else 'rewrite'} '{name}'{f' — {desc}' if desc else ''} ({size})" + if action == "patch": + removed = old_string.count("\n") + 1 if old_string else 0 + added = new_string.count("\n") + 1 if new_string else 0 + return f"patch '{name}' {file_path or 'SKILL.md'} (+{added}/-{removed} lines)" + return _GIST_TEMPLATES.get(action, "{action} '{name}'").format(action=action, name=name, file_path=file_path) + + +def _frontmatter_description(content: str) -> str: + """Extract the ``description:`` value from SKILL.md YAML frontmatter (≤140 chars).""" + m = re.search(r"^description:\s*(.+)$", content, re.MULTILINE) + return m.group(1).strip().strip("'\"")[:140] if m else "" + + +def _find_skill_path(name: str) -> Optional[Path]: + """Directory of an installed skill, or None if unknown / lookup unavailable.""" + try: + from tools.skill_manager_tool import _find_skill + except Exception: + return None + # Only the import is guarded (as on main); a lookup failure propagates. + found = _find_skill(name) + return found["path"] if found else None + + +def skill_pending_diff(record: Dict[str, Any]) -> str: + """Full content (create) or unified diff vs. the on-disk skill (edit/patch/write_file), + rendered by /skills diff <id> on surfaces that can show it.""" + payload = record.get("payload", {}) + action = payload.get("action", "") + name = payload.get("name", "") + if action == "create": + return payload.get("content") or "" + if action not in {"edit", "patch", "write_file"}: + return {"remove_file": f"remove file: {payload.get('file_path')} from skill '{name}'", + "delete": f"delete skill '{name}'"}.get(action, f"({action} on '{name}')") + + # patch/write_file target a file inside the skill; edit always targets SKILL.md. + target_label, current = "SKILL.md", "" + skill_dir = _find_skill_path(name) + if skill_dir: + if action != "edit": + target_label = payload.get("file_path") or "SKILL.md" + with suppress(Exception): + p = skill_dir / target_label + current = p.read_text(encoding="utf-8") if p.exists() else "" + + if action == "patch": + old_s, new_s = payload.get("old_string") or "", payload.get("new_string") or "" + new = current.replace(old_s, new_s) if current else f"(patch {old_s!r} → {new_s!r})" + else: + new = payload.get("content" if action == "edit" else "file_content") or "" + diff = difflib.unified_diff(current.splitlines(keepends=True), new.splitlines(keepends=True), + fromfile=f"a/{target_label}", tofile=f"b/{target_label}") + return "".join(diff) or "(no textual change)" + + +# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- +# Names external plugins imported from this module before the Sep 2026 decomposition. +# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does). +# The whole block is removed by reverting the commit that added it. + +def is_background() -> bool: + return current_origin() == "background_review" +# ---- END PLUGIN-COMPAT ---- diff --git a/tools/x_search_tool.py b/tools/x_search_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..d57f819350e6d7e13a92ad6e4c5bc0ecc8c1a189 --- /dev/null +++ b/tools/x_search_tool.py @@ -0,0 +1,343 @@ +#!/usr/bin/env python3 +"""X Search tool backed by xAI's built-in ``x_search`` Responses API tool. + +Registers when either xAI credential path is available (``XAI_API_KEY`` or ``hermes auth add +xai-oauth``). At call time an explicit ``XAI_API_KEY`` wins (``prefer_api_key=True``): x_search +is API-metered and the subscription OAuth bearer answers ``/v1/responses`` without citations. +Date filters are validated client-side so malformed windows fail fast instead of burning a +billable call. Results carry ``degraded``: True when a narrowing filter was active AND xAI +returned no citations in either channel (answer came from model knowledge, not the X index). +""" + +from __future__ import annotations + +import json +import logging +import time +from datetime import date, datetime, timezone +from typing import Any, Dict, List, Optional, Tuple + +import requests + +from tools.registry import registry, tool_error +from tools.xai_http import DEFAULT_XAI_BASE_URL, hermes_xai_user_agent, resolve_xai_http_credentials + +logger = logging.getLogger(__name__) + +DEFAULT_X_SEARCH_MODEL = "grok-4.5" +DEFAULT_X_SEARCH_TIMEOUT_SECONDS = 180 +DEFAULT_X_SEARCH_RETRIES = 2 +X_SEARCH_REASONING_EFFORTS = ("low", "medium", "high", "xhigh") +MAX_HANDLES = 10 + + +def _load_x_search_config() -> Dict[str, Any]: + try: + from hermes_cli.config import load_config + return load_config().get("x_search", {}) or {} + except Exception: + return {} + + +def _get_x_search_reasoning_effort() -> Optional[str]: + raw_value = _load_x_search_config().get("reasoning_effort") + effort = str(raw_value).strip().lower() if raw_value is not None else "" + if effort and effort not in X_SEARCH_REASONING_EFFORTS: + allowed = ", ".join(X_SEARCH_REASONING_EFFORTS) + raise ValueError(f"x_search.reasoning_effort must be one of: {allowed} (got {raw_value!r})") + return effort or None + + +def _get_x_search_int(key: str, default: int, floor: int) -> int: + try: + return max(floor, int(_load_x_search_config().get(key, default))) + except Exception: + return default + + +def _resolve_xai_bearer() -> Tuple[str, str, str]: + """Return ``(api_key, base_url, source)``; ``source`` is ``"xai-oauth"`` or ``"xai"``. Raises RuntimeError + when no credential is usable (expiry between registration and call -> clean tool error, not a 401). + + x_search is API-index access: when a subscription OAuth credential is configured alongside a paid + ``XAI_API_KEY``, the OAuth path authorizes but answers ``/v1/responses`` in a degraded Grok explanatory + mode with no citations, while the API key returns real posts (#88040). Pass ``prefer_api_key=True`` so + the shared resolver checks the explicit API key first — same root cause as the TTS fix for #87045 + (#87081) — keeping OAuth as the fallback when no API key is configured. + """ + creds = resolve_xai_http_credentials(prefer_api_key=True) + api_key = str(creds.get("api_key") or "").strip() + if not api_key: + raise RuntimeError( + "No xAI credentials available. Run `hermes auth add xai-oauth` " + "to sign in with your SuperGrok subscription, or set XAI_API_KEY." + ) + base_url = str(creds.get("base_url") or DEFAULT_XAI_BASE_URL).strip().rstrip("/") + return api_key, base_url, str(creds.get("provider") or "xai") + + +def check_x_search_requirements() -> bool: + """True when xAI credentials resolve to a non-empty bearer (OAuth auto-refreshed).""" + return bool(str(resolve_xai_http_credentials().get("api_key") or "").strip()) + + +def _normalize_handles(handles: Optional[List[str]], field_name: str) -> List[str]: + cleaned = [h for h in (str(handle or "").strip().lstrip("@") for handle in handles or []) if h] + if len(cleaned) > MAX_HANDLES: + raise ValueError(f"{field_name} supports at most {MAX_HANDLES} handles") + return cleaned + + +def _parse_iso_date(value: str, field_name: str) -> Optional[date]: + """Strict YYYY-MM-DD or None for blank (xAI silently accepts malformed dates and returns no citations).""" + raw = value.strip() + if not raw: + return None + try: + return datetime.strptime(raw, "%Y-%m-%d").date() + except ValueError as exc: + raise ValueError(f"{field_name} must be YYYY-MM-DD (got {raw!r})") from exc + + +def _validate_date_range(from_date: str, to_date: str) -> None: + """Both parse as YYYY-MM-DD; from <= to; from not after today UTC (to may be in the future).""" + parsed_from, parsed_to = _parse_iso_date(from_date, "from_date"), _parse_iso_date(to_date, "to_date") + if parsed_from and parsed_to and parsed_from > parsed_to: + raise ValueError( + f"from_date ({parsed_from.isoformat()}) must be on or before to_date ({parsed_to.isoformat()})" + ) + today_utc = datetime.now(timezone.utc).date() + if parsed_from is not None and parsed_from > today_utc: + raise ValueError( + f"from_date ({parsed_from.isoformat()}) is in the future; " + f"X Search only indexes past posts (today UTC is {today_utc.isoformat()})" + ) + + +def _message_contents(payload: Dict[str, Any]): + for item in payload.get("output", []) or []: + if item.get("type") == "message": + yield from item.get("content", []) or [] + + +def _extract_response_text(payload: Dict[str, Any]) -> str: + output_text = str(payload.get("output_text") or "").strip() + if output_text: + return output_text + contents = (c for c in _message_contents(payload) if c.get("type") in {"output_text", "text"}) + parts = (str(c.get("text") or "").strip() for c in contents) + return "\n\n".join(p for p in parts if p).strip() + + +def _extract_inline_citations(payload: Dict[str, Any]) -> List[Dict[str, Any]]: + return [ + { + "url": a.get("url", ""), "title": a.get("title", ""), + "start_index": a.get("start_index"), "end_index": a.get("end_index"), + } + for content in _message_contents(payload) + for a in content.get("annotations", []) or [] + if a.get("type") == "url_citation" + ] + + +def _http_error_message(exc: requests.HTTPError) -> str: + response = getattr(exc, "response", None) + if response is None: + return str(exc) + try: + payload = response.json() + except Exception: + payload = None + if not isinstance(payload, dict): + text = str(getattr(response, "text", "") or "").strip() + return text[:500] if text else str(exc) + code = str(payload.get("code") or "").strip() + message = str(payload.get("error") or "").strip() or str(payload) + return (f"{code}: {message}" if code and code not in message else message) or str(exc) + + +def _error_json(error: str, exc: BaseException) -> str: + body = {"success": False, "provider": "xai", "tool": "x_search", "error": error} + return json.dumps({**body, "error_type": type(exc).__name__}, ensure_ascii=False) + + +def _post_with_retries(url: str, headers: Dict[str, str], payload: Dict[str, Any]) -> requests.Response: + """POST with retries on 5xx / timeout / connection errors; re-raises the last failure.""" + timeout_seconds = _get_x_search_int("timeout_seconds", DEFAULT_X_SEARCH_TIMEOUT_SECONDS, 30) + max_retries = _get_x_search_int("retries", DEFAULT_X_SEARCH_RETRIES, 0) + for attempt in range(max_retries + 1): + try: + response = requests.post(url, headers=headers, json=payload, timeout=timeout_seconds) + response.raise_for_status() + return response + except requests.HTTPError as e: + status_code = getattr(getattr(e, "response", None), "status_code", None) + if status_code is None or status_code < 500 or attempt >= max_retries: + raise + kind, detail = "upstream", _http_error_message(e) + except (requests.ReadTimeout, requests.ConnectionError) as e: + if attempt >= max_retries: + raise + kind, detail = "transient", e + logger.warning("x_search %s failure on attempt %s/%s: %s", kind, attempt + 1, max_retries + 1, detail) + time.sleep(min(5.0, 1.5 * (attempt + 1))) + raise RuntimeError("x_search request did not return a response") + + +def _build_x_search_tool_def( + allowed_x_handles, excluded_x_handles, from_date: str, to_date: str, + enable_image_understanding: bool, enable_video_understanding: bool, +) -> Tuple[Dict[str, Any], List[str]]: + """Return ``(tool_def, active_filters)``; raises ValueError on invalid filters.""" + allowed = _normalize_handles(allowed_x_handles, "allowed_x_handles") + excluded = _normalize_handles(excluded_x_handles, "excluded_x_handles") + if allowed and excluded: + raise ValueError("allowed_x_handles and excluded_x_handles cannot be used together") + _validate_date_range(from_date, to_date) + + tool_def: Dict[str, Any] = {"type": "x_search"} + active_filters: List[str] = [] + filters = (("allowed_x_handles", allowed), ("excluded_x_handles", excluded), + ("from_date", from_date.strip()), ("to_date", to_date.strip())) + for key, value in filters: + if value: + tool_def[key] = value + active_filters.append(key) + if enable_image_understanding: + tool_def["enable_image_understanding"] = True + if enable_video_understanding: + tool_def["enable_video_understanding"] = True + return tool_def, active_filters + + +def x_search_tool( + query: str, + allowed_x_handles: Optional[List[str]] = None, + excluded_x_handles: Optional[List[str]] = None, + from_date: str = "", + to_date: str = "", + enable_image_understanding: bool = False, + enable_video_understanding: bool = False, +) -> str: + if not query or not query.strip(): + return tool_error("query is required for x_search") + try: + api_key, base_url, source = _resolve_xai_bearer() + except RuntimeError as exc: + return tool_error(str(exc)) + try: + tool_def, active_filters = _build_x_search_tool_def( + allowed_x_handles, excluded_x_handles, from_date, to_date, + enable_image_understanding, enable_video_understanding, + ) + reasoning_effort = _get_x_search_reasoning_effort() + except ValueError as exc: + return tool_error(str(exc)) + + try: + payload = { + "model": str(_load_x_search_config().get("model") or "").strip() or DEFAULT_X_SEARCH_MODEL, + "input": [{"role": "user", "content": query.strip()}], + "tools": [tool_def], + "store": False, + } + if reasoning_effort: + payload["reasoning"] = {"effort": reasoning_effort} + headers = { + "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", + "User-Agent": hermes_xai_user_agent(), + } + data = _post_with_retries(f"{base_url}/responses", headers, payload).json() + citations = list(data.get("citations") or []) + inline_citations = _extract_inline_citations(data) + # xAI returns 200 with a synthesized answer even when no posts match the narrowing + # filters; with both citation channels empty the answer came from training data. + degraded = bool(active_filters) and not citations and not inline_citations + result = { + "success": True, "provider": "xai", "credential_source": source, "tool": "x_search", + "model": payload["model"], "query": query.strip(), "answer": _extract_response_text(data), + "citations": citations, "inline_citations": inline_citations, "degraded": degraded, + "degraded_reason": ( + f"no citations returned despite filters: {', '.join(active_filters)}" if degraded else None + ), + } + return json.dumps(result, ensure_ascii=False) + except requests.HTTPError as e: + logger.error("x_search failed: %s", e, exc_info=True) + return _error_json(_http_error_message(e), e) + except requests.ReadTimeout as e: + logger.error("x_search timed out: %s", e, exc_info=True) + timeout = _get_x_search_int("timeout_seconds", DEFAULT_X_SEARCH_TIMEOUT_SECONDS, 30) + return _error_json(f"xAI x_search timed out after {timeout} seconds", e) + except Exception as e: + logger.error("x_search failed: %s", e, exc_info=True) + return _error_json(str(e), e) + + +X_SEARCH_SCHEMA = { + "name": "x_search", + "description": ( + "Search X (Twitter) posts, profiles, and threads using xAI's built-in " + "X Search tool. Read-only discovery only: use this for current " + "discussion, reactions, or claims on public X rather than general web " + "pages. Do not use it to post, reply, like, DM, upload media, delete, " + "or inspect the user's authenticated X account — those require a " + "separate authenticated X API surface outside this tool. Available " + "when xAI credentials are configured (SuperGrok OAuth or XAI_API_KEY)." + ), + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "What to look up on X.", + }, + "allowed_x_handles": { + "type": "array", + "items": {"type": "string"}, + "description": "Optional list of X handles to include exclusively (max 10).", + }, + "excluded_x_handles": { + "type": "array", + "items": {"type": "string"}, + "description": "Optional list of X handles to exclude (max 10).", + }, + "from_date": { + "type": "string", + "description": "Optional start date in YYYY-MM-DD format.", + }, + "to_date": { + "type": "string", + "description": "Optional end date in YYYY-MM-DD format.", + }, + "enable_image_understanding": { + "type": "boolean", + "description": "Whether xAI should analyze images attached to matching X posts.", + "default": False, + }, + "enable_video_understanding": { + "type": "boolean", + "description": "Whether xAI should analyze videos attached to matching X posts.", + "default": False, + }, + }, + "required": ["query"], + }, +} + + +def _handle_x_search(args, **kw): + return x_search_tool( + args.get("query", ""), args.get("allowed_x_handles"), args.get("excluded_x_handles"), + args.get("from_date", ""), args.get("to_date", ""), + bool(args.get("enable_image_understanding", False)), + bool(args.get("enable_video_understanding", False)), + ) + + +registry.register( + name="x_search", toolset="x_search", schema=X_SEARCH_SCHEMA, handler=_handle_x_search, + check_fn=check_x_search_requirements, requires_env=["XAI_API_KEY"], emoji="🐦", + max_result_size_chars=100_000, +)