diff --git a/AGENTS.md b/AGENTS.md index e89c819844e6a..6737b92a98d3d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -240,7 +240,7 @@ hermes-agent/ ├── agent/ # Agent internals (provider adapters, memory, caching, compression, etc.) ├── hermes_cli/ # CLI subcommands, setup wizard, plugins loader, skin engine ├── tools/ # Tool implementations — auto-discovered via tools/registry.py -│ └── environments/ # Terminal backends (local, docker, ssh, modal, daytona, singularity) +│ └── environments/ # Terminal backends (local, docker, ssh, modal, daytona, singularity, tenki) ├── gateway/ # Messaging gateway — run.py + session.py + platforms/ │ ├── platforms/ # Adapter per platform (telegram, discord, slack, whatsapp, │ │ # homeassistant, signal, matrix, mattermost, email, sms, @@ -491,18 +491,18 @@ The dashboard embeds the real `hermes --tui` — **not** a rewrite. See `hermes ### Electron Desktop Chat App (`apps/desktop/`) -A **separate** chat surface from both the classic CLI and the dashboard's embedded TUI. It is an Electron + React + nanostore renderer (`@assistant-ui/react`) that talks to a `tui_gateway` backend over JSON-RPC (`requestGateway(method, params)`). The WebSocket/JSON-RPC transport lives in the framework-agnostic `apps/shared` package (`@hermes/shared` — `JsonRpcGatewayClient` + WS URL helpers), which the web dashboard (`web/`) also consumes; **desktop has no build/runtime dependency on the dashboard frontend** — it spawns a headless `hermes serve` backend server (the same gateway `dashboard` serves, minus the browser UI). `dashboard` and `serve` share `cmd_dashboard`/`start_server` but are independent surfaces — neither launches the other. The one exception is a backward-compat *fallback*: `serve` is newer, so the desktop spawn (`electron/backend-command.cjs` + `backendSupportsServe()` in `main.cjs`) detects whether the resolved runtime registers `serve` and, only when it does not (an older managed install / PATH `hermes` the app hasn't updated yet), rewrites the argv to the legacy `dashboard --no-open`. Without that, a new app against an un-upgraded runtime would crash on an unknown subcommand and brick every mid-upgrade user. It does NOT embed `hermes --tui` — it has its own composer, transcript, and slash-command pipeline. Route desktop bugs to the `hermes-desktop-app-work` skill, not `hermes-dashboard-work`. +A **separate** chat surface from both the classic CLI and the dashboard's embedded TUI. It is an Electron + React + nanostore renderer (`@assistant-ui/react`) that talks to a `tui_gateway` backend over JSON-RPC (`requestGateway(method, params)`). The WebSocket/JSON-RPC transport lives in the framework-agnostic `apps/shared` package (`@hermes/shared` — `JsonRpcGatewayClient` + WS URL helpers), which the web dashboard (`web/`) also consumes; **desktop has no build/runtime dependency on the dashboard frontend** — it spawns a headless `hermes serve` backend server (the same gateway `dashboard` serves, minus the browser UI entirely: `serve` sets `headless_backend=True`, so `cmd_dashboard` skips `_build_web_ui` AND exports `HERMES_SERVE_HEADLESS=1` so `mount_spa()` disables the SPA even if a stray `web_dist/` exists — only the JSON-RPC/WS/API surface is reachable). `dashboard` and `serve` share `cmd_dashboard`/`start_server` but are independent surfaces — neither launches the other. The one exception is a backward-compat *fallback*: `serve` is newer, so the desktop spawn (`electron/backend-command.ts` + `backendSupportsServe()` in `electron/main.ts`) detects whether the resolved runtime registers `serve` and, only when it does not (an older managed install / PATH `hermes` the app hasn't updated yet), rewrites the argv to the legacy `dashboard --no-open`. Without that, a new app against an un-upgraded runtime would crash on an unknown subcommand and brick every mid-upgrade user. It does NOT embed `hermes --tui` — it has its own composer, transcript, and slash-command pipeline. For scoped Desktop architecture, state, resolver, transport, and testing rules, read `apps/desktop/AGENTS.md`. **Slash commands in the desktop app are curated client-side, then dispatched to the backend.** The pipeline: - **Backend already provides everything.** `tui_gateway/server.py` `commands.catalog` (empty-query list) and `complete.slash` (typed-query completions) both include built-in commands, user `quick_commands`, AND skill-derived commands (`scan_skill_commands()` / `get_skill_commands()`). The desktop app does not need a new RPC to see skills. -- **The renderer curates via `apps/desktop/src/lib/desktop-slash-commands.ts`.** This is the load-bearing file. It holds `DESKTOP_COMMANDS` (the ~19 built-ins shown in the palette) plus block-lists for terminal-only / messaging-only / picker-owned / settings-owned / advanced commands that should NOT clutter the desktop popover. +- **The renderer curates via `apps/desktop/src/lib/desktop-slash-commands.ts`.** This is the load-bearing file. It holds `DESKTOP_COMMAND_SPECS` (the built-ins and their Desktop surfaces) plus `NO_DESKTOP_SURFACE` block-lists for terminal-only / messaging-only / picker-owned / settings-owned / advanced commands that should NOT clutter the desktop popover. - `isDesktopSlashCommand(name)` — gates **execution**. Returns true for built-ins AND for any non-built-in (skill / quick command), so typed extension commands run. - `isDesktopSlashSuggestion(name)` — gates **discovery/completion**. Used by BOTH completion paths in `app/chat/composer/hooks/use-slash-completions.ts` (empty-query catalog filter + typed-query `complete.slash` filter) and by `filterDesktopCommandsCatalog`. - `isDesktopSlashExtensionCommand(name)` — true when the command is NOT a known Hermes built-in (i.e. a skill or user quick command). Both suggestion and catalog-filter paths allow extensions through so skill commands surface in the palette. (Added when fixing "skill commands missing from the desktop slash palette" — the curated allow-list was silently dropping every skill/quick command from completions even though they executed fine when typed.) -- **Dispatch** lives in `app/session/hooks/use-prompt-actions.ts` (`runSlash`): built-ins that the desktop owns (`/skin`, `/help`, `/new`, …) are handled locally or via `commands.catalog`; everything else goes to `slash.exec`, falling back to `command.dispatch` (which the gateway resolves into skill / alias / exec directives). A skill command resolves to `{type: "skill", message}` and is submitted as a normal prompt. +- **Dispatch** lives in `app/session/hooks/use-prompt-actions/slash.ts` (`runSlash`): built-ins that the desktop owns (`/skin`, `/help`, `/new`, …) are handled locally or via `commands.catalog`; everything else goes to `slash.exec`, falling back to `command.dispatch` (which the gateway resolves into skill / alias / exec directives). A skill command resolves to `{type: "skill", message}` and is submitted as a normal prompt. -**Rule:** the desktop slash palette's curation is about hiding noise (terminal-only / messaging-only built-ins), NOT about hiding user-activated extensions. Skill commands and `quick_commands` are extensions the backend surfaces — they belong in completions. If you tighten `desktop-slash-commands.ts`, keep `isDesktopSlashExtensionCommand` flowing into both the suggestion and catalog-filter paths. Tests: `apps/desktop/src/lib/desktop-slash-commands.test.ts` (run via the repo-root `vitest`, since `apps/desktop` resolves deps from the root workspace install). +**Rule:** the desktop slash palette's curation is about hiding noise (terminal-only / messaging-only built-ins), NOT about hiding user-activated extensions. Skill commands and `quick_commands` are extensions the backend surfaces — they belong in completions. If you tighten `desktop-slash-commands.ts`, keep `isDesktopSlashExtensionCommand` flowing into both the suggestion and catalog-filter paths. Tests: from `apps/desktop`, run `npx vitest run src/lib/desktop-slash-commands.test.ts` (workspace dependencies are installed at the repo root). --- diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index bad33481c745e..d2a6c43979cb0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -109,7 +109,7 @@ A well-built third-party-product plugin can clear automated review and still be | Requirement | Notes | |-------------|-------| | **Git** | With the `git-lfs` extension installed | -| **Python 3.11+** | uv will install it if missing | +| **Python 3.11–3.13** | uv will install it if missing | | **uv** | Fast Python package manager ([install](https://docs.astral.sh/uv/)) | | **Node.js 20+** | Optional — needed for browser tools and WhatsApp bridge (matches root `package.json` engines) | @@ -257,7 +257,7 @@ hermes-agent/ │ ├── skill_tools.py # Skill search, load, manage │ └── environments/ # Terminal execution backends │ ├── base.py # BaseEnvironment ABC -│ ├── local.py, docker.py, ssh.py, singularity.py, modal.py, daytona.py +│ ├── local.py, docker.py, ssh.py, singularity.py, modal.py, daytona.py, tenki.py │ ├── gateway/ # Messaging gateway │ ├── run.py # GatewayRunner — platform lifecycle, message routing, cron diff --git a/agent/prompt_builder.py b/agent/prompt_builder.py index 06e9b5a94456b..ceaa2a6a958bc 100644 --- a/agent/prompt_builder.py +++ b/agent/prompt_builder.py @@ -7,6 +7,7 @@ import json import logging import os +import sys import threading import contextvars from collections import OrderedDict @@ -17,6 +18,8 @@ from agent.runtime_cwd import resolve_agent_cwd from agent.skill_utils import ( + EXCLUDED_SKILL_DIRS, + SKILL_SUPPORT_DIRS, extract_skill_conditions, extract_skill_description, get_all_skills_dirs, @@ -25,6 +28,7 @@ parse_frontmatter, skill_matches_environment, skill_matches_platform, + skill_matches_platform_list, ) from utils import atomic_json_write @@ -743,6 +747,17 @@ def format_steer_marker(steer_text: str) -> str: "or 'all'). Do not promise the user that a deliver='origin' or " "default-deliver cron job will message them in this session." ), + "desktop": ( + "You are chatting inside the Hermes desktop app — a graphical chat " + "surface, not a terminal. Use markdown freely: it renders with full " + "GitHub flavor (tables, code blocks with syntax highlighting, math " + "via $...$, task lists, blockquote callouts). " + "You can deliver files natively — include MEDIA:/absolute/path/to/file " + "in your response. Images (.png, .jpg, .webp) appear inline, audio and " + "video play inline, and other files arrive as download links. You can " + "also include image URLs in markdown format ![alt](url) and they " + "render inline as photos." + ), "sms": ( "You are communicating via SMS. Keep responses concise and use plain text " "only — no markdown, no formatting. SMS messages are limited to ~1600 " @@ -1139,22 +1154,6 @@ def build_environment_hints() -> str: f"`uname -a && whoami && pwd`." ) - # Hermes desktop GUI — any agent running under the desktop app should know - # it. HERMES_DESKTOP marks the backend powering the chat; HERMES_DESKTOP_TERMINAL - # marks a hermes launched in the embedded terminal pane. Both set by main.cjs. - _truthy = ("1", "true", "yes") - _in_desktop = (os.getenv("HERMES_DESKTOP") or "").strip().lower() in _truthy - _in_desktop_term = (os.getenv("HERMES_DESKTOP_TERMINAL") or "").strip().lower() in _truthy - if _in_desktop or _in_desktop_term: - _desktop_hint = "Runtime surface: you're running inside the Hermes desktop GUI app." - if _in_desktop_term: - _desktop_hint += ( - " You're in its embedded terminal pane, beside the GUI chat — the user can " - "select your output (⌥-drag on macOS, Shift-drag elsewhere) and press " - "⌘/Ctrl+L to send it to the chat composer." - ) - hints.append(_desktop_hint) - if is_wsl(): hints.append(WSL_ENVIRONMENT_HINT) @@ -1288,13 +1287,26 @@ def clear_skills_system_prompt_cache(*, clear_snapshot: bool = False) -> None: def _build_skills_manifest(skills_dir: Path) -> dict[str, list[int]]: """Build an mtime/size manifest of all SKILL.md and DESCRIPTION.md files.""" manifest: dict[str, list[int]] = {} - for filename in ("SKILL.md", "DESCRIPTION.md"): - for path in iter_skill_index_files(skills_dir, filename): + skills_dir_str = str(skills_dir) + base = os.path.join(skills_dir_str, "") + prefix_len = len(base) + for root, dirs, files in os.walk(skills_dir_str, followlinks=True): + has_skill_md = "SKILL.md" in files + dirs[:] = [ + d + for d in dirs + if d not in EXCLUDED_SKILL_DIRS + and not (has_skill_md and d in SKILL_SUPPORT_DIRS) + ] + for filename in ("SKILL.md", "DESCRIPTION.md"): + if filename not in files: + continue + path = os.path.join(root, filename) try: - st = path.stat() + st = os.stat(path) except OSError: continue - manifest[str(path.relative_to(skills_dir))] = [st.st_mtime_ns, st.st_size] + manifest[path[prefix_len:]] = [st.st_mtime_ns, st.st_size] return manifest @@ -1426,6 +1438,22 @@ def _skill_should_show( return True +def _current_session_platform_hint() -> str: + """Return the active platform without importing the gateway package on CLI startup.""" + platform = os.environ.get("HERMES_PLATFORM") or os.environ.get("HERMES_SESSION_PLATFORM") + if platform: + return platform + + session_context = sys.modules.get("gateway.session_context") + get_session_env = getattr(session_context, "get_session_env", None) if session_context else None + if get_session_env is None: + return "" + try: + return get_session_env("HERMES_SESSION_PLATFORM") or "" + except Exception: + return "" + + def build_skills_system_prompt( available_tools: "set[str] | None" = None, available_toolsets: "set[str] | None" = None, @@ -1460,15 +1488,10 @@ def build_skills_system_prompt( # ── Layer 1: in-process LRU cache ───────────────────────────────── # Include the resolved platform so per-platform disabled-skill lists # produce distinct cache entries (gateway serves multiple platforms). - from gateway.session_context import get_session_env - _platform_hint = ( - os.environ.get("HERMES_PLATFORM") - or get_session_env("HERMES_SESSION_PLATFORM") - or "" - ) + _platform_hint = _current_session_platform_hint() disabled = get_disabled_skill_names(_platform_hint or None) cache_key = ( - str(skills_dir.resolve()), + str(skills_dir), tuple(str(d) for d in external_dirs), tuple(sorted(str(t) for t in (available_tools or set()))), tuple(sorted(str(ts) for ts in (available_toolsets or set()))), @@ -1497,7 +1520,7 @@ def build_skills_system_prompt( category = entry.get("category") or "general" frontmatter_name = entry.get("frontmatter_name") or skill_name platforms = entry.get("platforms") or [] - if not skill_matches_platform({"platforms": platforms}): + if not skill_matches_platform_list(platforms): continue if frontmatter_name in disabled or skill_name in disabled: continue diff --git a/cli-config.yaml.example b/cli-config.yaml.example index 8b0769ead3a77..fd426419a69b0 100644 --- a/cli-config.yaml.example +++ b/cli-config.yaml.example @@ -306,8 +306,34 @@ terminal: # daytona_image: "nikolaik/python-nodejs:python3.11-nodejs20" # container_disk: 10240 # Daytona max is 10GB per sandbox -# -# --- Container resource limits (docker, singularity, modal, daytona -- ignored for local/ssh) --- +# ----------------------------------------------------------------------------- +# OPTION 7: Tenki cloud execution +# Commands run in Tenki cloud sandboxes, created on demand +# Great for: On-demand cloud compute, isolated ephemeral sandboxes +# Requires: pip install tenki-sandbox, plus `tenki login` or the +# TENKI_AUTH_TOKEN / TENKI_API_KEY env var +# ----------------------------------------------------------------------------- +# terminal: +# backend: "tenki" +# cwd: "/home/tenki" # Path INSIDE the sandbox +# timeout: 180 +# lifetime_seconds: 300 +# container_persistent: false # Tenki default: terminate sandboxes on cleanup +# tenki_image: "" # Optional image/template; blank uses Tenki default +# tenki_api_endpoint: "https://api.tenki.cloud" +# tenki_workspace_id: "" # Blank falls back to Tenki CLI config +# tenki_project_id: "" # Blank falls back to Tenki CLI config +# tenki_name_prefix: "hermes" +# tenki_allow_inbound: false +# tenki_allow_outbound: true +# tenki_max_duration: 3600 # Max sandbox lifetime in seconds +# tenki_idle_timeout: 0 # Auto-pause after idle seconds (0 = disabled) +# tenki_pause_retention: 0 # Retention for paused sandboxes (0 = disabled) +# tenki_sync_hermes_home: false # Opt-in sync of selected ~/.hermes files +# tenki_forward_env: [] # Env vars to forward (e.g. GITHUB_TOKEN) + +# +# --- Container resource limits (docker, singularity, modal, daytona, tenki -- ignored for local/ssh) --- # These settings apply to all container backends. They control the resources # allocated to the sandbox and whether its filesystem persists across sessions. container_cpu: 1 # CPU cores @@ -409,8 +435,14 @@ compression: # Trigger compression at this % of model's context limit (default: 0.50 = 50%) # Lower values = more aggressive compression, higher values = compress later + # Models with context windows below 512K are floored at 0.75 (raise-only) so + # compaction doesn't fire with half the window still free; set above 0.75 to override. threshold: 0.50 - + + # Existing Codex gpt-5.5 behavior: raise Hermes' compaction trigger to 85% + # for the ChatGPT Codex OAuth route. Set false to opt back down to threshold. + codex_gpt55_autoraise: true + # Fraction of the threshold to preserve as recent tail (default: 0.20 = 20%) # e.g. 20% of 50% threshold = 10% of total context kept as recent messages. # Summary output is separately capped at 12K tokens (Gemini output limit). @@ -422,6 +454,14 @@ compression: # compression of older turns. protect_last_n: 20 + # Codex app-server (codex CLI runtime) thread-compaction mode. The codex + # agent owns the real thread context on this runtime, so Hermes' summarizer + # cannot shrink it — compaction goes through the app server instead. + # native = let Codex decide when to compact its own thread (default) + # hermes = let Hermes threshold trigger Codex thread/compact/start + # off = Hermes will not auto-trigger compaction; Codex may still compact natively + codex_app_server_auto: native + # Number of non-system messages to protect at the head of the transcript, in # ADDITION to the system prompt (which is always implicitly protected). # Head messages are NEVER summarized — they survive every compression @@ -834,6 +874,11 @@ platform_toolsets: # priority_mode: prepend # priority: # - my_plugin_command +# webhook: +# extra: +# # Route scripts default to a 30 second timeout. Scripts must live under +# # the active profile's scripts directory and receive webhook JSON on stdin. +# script_timeout_seconds: 30 # # Discord-specific settings (config.yaml top-level, not under platforms:): # @@ -1380,3 +1425,50 @@ updates: # # This is a CREDENTIAL: prefer setting HERMES_DASHBOARD_OIDC_CLIENT_SECRET # # in ~/.hermes/.env over putting it here in config.yaml. # # client_secret: "" + +# ============================================================================= +# External secret sources +# ============================================================================= +# Pull provider credentials from external secret managers at process startup +# instead of storing them in ~/.hermes/.env. Only the manager's bootstrap +# credential (e.g. BWS_ACCESS_TOKEN / OP_SERVICE_ACCOUNT_TOKEN) lives in .env +# (or your shell / desktop session); everything else rotates centrally. +# Failures never block startup — Hermes warns once and continues with +# whatever .env already had. +# +# Multiple sources can be enabled at once: +# - "mapped" sources (explicit VAR -> ref bindings, e.g. 1Password's env: +# map) beat "bulk" sources (whole-project dumps like Bitwarden BSM) +# - within a shape, the first source to claim a var wins; later claims +# are skipped with a startup warning (never a silent clobber) +# - a source's override_existing lets it beat .env/shell values, but +# never another secret source's claim +# Docs: https://hermes-agent.nousresearch.com/docs/user-guide/secrets/ +# +# secrets: +# # Optional explicit ordering of enabled sources. +# # sources: [onepassword, bitwarden] +# +# # ---- Bitwarden Secrets Manager (bws CLI) -------------------------------- +# bitwarden: +# enabled: false +# access_token_env: BWS_ACCESS_TOKEN # bootstrap token, sourced from .env +# project_id: "" # UUID of the BSM project to sync +# server_url: "" # "" = US Cloud; EU/self-hosted URL otherwise +# cache_ttl_seconds: 300 # 0 disables caching +# override_existing: true # BSM values win over existing env +# auto_install: true # lazy-download bws into ~/.hermes/bin +# +# # ---- 1Password (op CLI) ------------------------------------------------- +# onepassword: +# enabled: false +# # Map env-var names to op:// secret references. Each is resolved with a +# # single `op read` at startup. +# env: +# OPENAI_API_KEY: "op://Private/OpenAI/api key" +# ANTHROPIC_API_KEY: "op://Private/Anthropic/credential" +# account: "" # op --account shorthand; "" = default +# service_account_token_env: OP_SERVICE_ACCOUNT_TOKEN # headless auth; unset = desktop session +# binary_path: "" # "" = resolve op via PATH; else absolute path +# cache_ttl_seconds: 300 # 0 disables BOTH cache layers +# override_existing: true # resolved values win over existing env diff --git a/cli.py b/cli.py index c3f438690a28e..fe5c0910a7414 100644 --- a/cli.py +++ b/cli.py @@ -334,11 +334,15 @@ def _resolve_prefill_messages_file(config: Dict[str, Any]) -> str: return "" -def _parse_reasoning_config(effort: str) -> dict | None: - """Parse a reasoning effort level into an OpenRouter reasoning config dict.""" +def _parse_reasoning_config(effort) -> dict | None: + """Parse a reasoning effort level into an OpenRouter reasoning config dict. + + Accepts the raw config value (string or YAML boolean — ``false``/``off`` + parse as thinking disabled, see parse_reasoning_effort). + """ from hermes_constants import parse_reasoning_effort result = parse_reasoning_effort(effort) - if effort and effort.strip() and result is None: + if effort and str(effort).strip() and result is None: logger.warning("Unknown reasoning_effort '%s', using default (medium)", effort) return result @@ -401,6 +405,21 @@ def load_cli_config() -> Dict[str, Any]: "singularity_image": "docker://nikolaik/python-nodejs:python3.11-nodejs20", "modal_image": "nikolaik/python-nodejs:python3.11-nodejs20", "daytona_image": "nikolaik/python-nodejs:python3.11-nodejs20", + "tenki_image": "", + # Blank so the TENKI_API_ENDPOINT / TENKI_API_URL and Tenki CLI + # fallbacks in resolve_tenki_api_endpoint() stay reachable; a + # non-blank default here is bridged as explicit and would mask them. + "tenki_api_endpoint": "", + "tenki_workspace_id": "", + "tenki_project_id": "", + "tenki_name_prefix": "hermes", + "tenki_allow_inbound": False, + "tenki_allow_outbound": True, + "tenki_max_duration": 3600, + "tenki_idle_timeout": 0, + "tenki_pause_retention": 0, + "tenki_sync_hermes_home": False, + "tenki_forward_env": [], "docker_volumes": [], # host:container volume mounts for Docker backend "docker_mount_cwd_to_workspace": False, # explicit opt-in only; default off for sandbox isolation }, @@ -451,7 +470,9 @@ def load_cli_config() -> Dict[str, Any]: "resume_max_assistant_chars": 200, "resume_max_assistant_lines": 3, "resume_skip_tool_only": True, - "show_reasoning": False, + # Live reasoning display default ON — keep in sync with + # hermes_cli/config.py DEFAULT_CONFIG (display.show_reasoning). + "show_reasoning": True, "reasoning_full": False, "streaming": True, "busy_input_mode": "interrupt", @@ -503,6 +524,7 @@ def load_cli_config() -> Dict[str, Any]: # overwrite env vars that were already set by .env -- only a user's config # file should be authoritative. _file_has_terminal_config = False + file_config: dict[str, Any] = {} # Load from file if exists if config_path.exists(): @@ -537,6 +559,8 @@ def load_cli_config() -> Dict[str, Any]: if key == "model": continue # Already handled above if key in file_config: + if isinstance(defaults[key], dict) and file_config[key] is None: + continue if isinstance(defaults[key], dict) and isinstance(file_config[key], dict): defaults[key].update(file_config[key]) else: @@ -560,7 +584,7 @@ def load_cli_config() -> Dict[str, Any]: logger.warning("Failed to load cli-config.yaml: %s", e) # Expand ${ENV_VAR} references in config values before bridging to env vars. - from hermes_cli.config import _expand_env_vars + from hermes_cli.config import _deep_merge, _expand_env_vars, _normalize_terminal_backend_defaults defaults = _expand_env_vars(defaults) # Managed scope: overlay administrator-pinned values LAST so they win over @@ -573,7 +597,11 @@ def load_cli_config() -> Dict[str, Any]: # normalization, leaf-merge) and is fail-open. from hermes_cli import managed_scope + managed_config = managed_scope.load_managed_config() defaults = managed_scope.apply_managed_overlay(defaults) + raw_terminal_defaults_source = file_config + if managed_config: + raw_terminal_defaults_source = _deep_merge(raw_terminal_defaults_source, managed_config) # Apply terminal config to environment variables (so terminal_tool picks them up) terminal_config = defaults.get("terminal", {}) @@ -583,6 +611,9 @@ def load_cli_config() -> Dict[str, Any]: # Accept both, with "backend" taking precedence (it's the documented key). if "backend" in terminal_config: terminal_config["env_type"] = terminal_config["backend"] + + defaults = _normalize_terminal_backend_defaults(defaults, raw_terminal_defaults_source) + terminal_config = defaults.get("terminal", {}) # CWD resolution for CLI/TUI. The gateway has its own config bridge in # gateway/run.py but may lazily import cli.py (triggering this code). @@ -609,12 +640,24 @@ def load_cli_config() -> Dict[str, Any]: "singularity_image": "TERMINAL_SINGULARITY_IMAGE", "modal_image": "TERMINAL_MODAL_IMAGE", "daytona_image": "TERMINAL_DAYTONA_IMAGE", + "tenki_image": "TERMINAL_TENKI_IMAGE", + "tenki_api_endpoint": "TERMINAL_TENKI_API_ENDPOINT", + "tenki_workspace_id": "TERMINAL_TENKI_WORKSPACE_ID", + "tenki_project_id": "TERMINAL_TENKI_PROJECT_ID", + "tenki_name_prefix": "TERMINAL_TENKI_NAME_PREFIX", + "tenki_allow_inbound": "TERMINAL_TENKI_ALLOW_INBOUND", + "tenki_allow_outbound": "TERMINAL_TENKI_ALLOW_OUTBOUND", + "tenki_max_duration": "TERMINAL_TENKI_MAX_DURATION", + "tenki_idle_timeout": "TERMINAL_TENKI_IDLE_TIMEOUT", + "tenki_pause_retention": "TERMINAL_TENKI_PAUSE_RETENTION", + "tenki_sync_hermes_home": "TERMINAL_TENKI_SYNC_HERMES_HOME", + "tenki_forward_env": "TERMINAL_TENKI_FORWARD_ENV", # SSH config "ssh_host": "TERMINAL_SSH_HOST", "ssh_user": "TERMINAL_SSH_USER", "ssh_port": "TERMINAL_SSH_PORT", "ssh_key": "TERMINAL_SSH_KEY", - # Container resource config (docker, singularity, modal, daytona -- ignored for local/ssh) + # Container resource config (docker, singularity, modal, daytona, tenki -- ignored for local/ssh) "container_cpu": "TERMINAL_CONTAINER_CPU", "container_memory": "TERMINAL_CONTAINER_MEMORY", "container_disk": "TERMINAL_CONTAINER_DISK", @@ -623,6 +666,7 @@ def load_cli_config() -> Dict[str, Any]: "docker_env": "TERMINAL_DOCKER_ENV", "docker_extra_args": "TERMINAL_DOCKER_EXTRA_ARGS", "docker_mount_cwd_to_workspace": "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", + "docker_network": "TERMINAL_DOCKER_NETWORK", "docker_run_as_host_user": "TERMINAL_DOCKER_RUN_AS_HOST_USER", "docker_persist_across_processes": "TERMINAL_DOCKER_PERSIST_ACROSS_PROCESSES", "docker_orphan_reaper": "TERMINAL_DOCKER_ORPHAN_REAPER", @@ -1103,6 +1147,19 @@ def _run_cleanup(*, notify_session_finalize: bool = True): ) try: if _active_agent_ref and hasattr(_active_agent_ref, 'shutdown_memory_provider'): + # A /new shortly before exit leaves its end→switch boundary task + # (old-session extraction, LLM-bound) queued on the memory + # manager's serialized worker. shutdown_all()'s drain only waits + # ~5s and cancels queued tasks, so give pending work a bounded + # head start via the manager's own barrier — otherwise a + # "/new then quit" silently drops the old session's extraction. + # The 30s exit watchdog remains the hard backstop. + _mm = getattr(_active_agent_ref, '_memory_manager', None) + if _mm is not None and hasattr(_mm, 'flush_pending'): + try: + _mm.flush_pending(timeout=10) + except Exception: + pass # Forward the agent's own transcript so memory providers' # ``on_session_end`` hooks see the real conversation instead of # an empty list (#15165). ``_session_messages`` is set on @@ -3703,7 +3760,7 @@ def __init__( # bell_on_complete: play terminal bell (\a) when agent finishes a response self.bell_on_complete = CLI_CONFIG["display"].get("bell_on_complete", False) # show_reasoning: display model thinking/reasoning before the response - self.show_reasoning = CLI_CONFIG["display"].get("show_reasoning", False) + self.show_reasoning = CLI_CONFIG["display"].get("show_reasoning", True) # reasoning_full: when reasoning display is on, print the post-response # recap box uncollapsed instead of clamping to the first 10 lines. self.reasoning_full = CLI_CONFIG["display"].get("reasoning_full", False) @@ -3731,8 +3788,9 @@ def __init__( # streaming: stream tokens to the terminal as they arrive (display.streaming in config.yaml) self.streaming_enabled = CLI_CONFIG["display"].get("streaming", False) - # show_timestamps: prefix user and assistant labels with [HH:MM] + # show_timestamps: prefix user and assistant labels with timestamps self.show_timestamps = CLI_CONFIG["display"].get("timestamps", False) + self.timestamp_format = CLI_CONFIG["display"].get("timestamp_format", "%H:%M") self.final_response_markdown = str( CLI_CONFIG["display"].get("final_response_markdown", "strip") ).strip().lower() or "strip" @@ -4839,6 +4897,12 @@ def _pet_flash(self, state: str, secs: float = 1.6) -> None: self._pet_event = state self._pet_event_until = time.monotonic() + secs + def _on_reaction(self, kind: str) -> None: + """User affection (ily / <3 / good bot), core-detected — the pet's share + of the vibe signal that plays hearts on the TUI/desktop. Flash a celebrate.""" + if kind == "vibe": + self._pet_flash("jump") + def _pet_react_turn_end(self) -> None: """Flash the end-of-turn beat: failed on error, jump on a finished plan, else wave.""" if not self._pet_enabled: @@ -5475,7 +5539,7 @@ def _flush_reasoning_preview(self, *, force: bool = False) -> None: def _format_submitted_user_message_preview(self, user_input: str) -> str: """Format the submitted user-message scrollback preview.""" ts_suffix = ( - f" [dim]{datetime.now().strftime('%H:%M')}[/]" + f" [dim]{datetime.now().strftime(getattr(self, 'timestamp_format', '%H:%M'))}[/]" if getattr(self, "show_timestamps", False) else "" ) lines = user_input.split("\n") @@ -5776,7 +5840,7 @@ def _emit_stream_text(self, text: str) -> None: except (ValueError, IndexError): self._stream_text_ansi = "" if self.show_timestamps: - label = f"{label} {datetime.now().strftime('%H:%M')}" + label = f"{label} {datetime.now().strftime(getattr(self, 'timestamp_format', '%H:%M'))}" w = self._scrollback_box_width() fill = w - 2 - HermesCLI._status_bar_display_width(label) _cprint(f"\n{_ACCENT}╭─{label}{'─' * max(fill - 1, 0)}╮{_RST}") @@ -5831,6 +5895,33 @@ def _flush_table_buf() -> None: line = _strip_markdown_syntax(line) _emit_one(line) + # Force-flush long partial lines so a response that opens with a + # long paragraph paints as tokens arrive instead of staying blank + # until the first newline (TTFT perception fix — the reasoning box + # has done this at 80 chars since day one; the response box never + # did). Wrap at the terminal's visible width so we only ever emit + # text that would have line-broken at that point anyway; the + # remainder stays buffered as the logical line's continuation. + # Table-shaped partials are exempt — they need the whole block for + # realignment (see the table side-buffer above). + if ( + self._stream_buf + and not self._in_stream_table + and not self._stream_buf.lstrip().startswith("|") + ): + wrap_w = max(40, _terminal_width_for_streaming()) + while len(self._stream_buf) >= wrap_w: + cut = self._stream_buf.rfind(" ", 0, wrap_w) + if cut <= 0: + cut = wrap_w # single unbreakable run — hard wrap + chunk, self._stream_buf = ( + self._stream_buf[:cut], + self._stream_buf[cut:].lstrip(" "), + ) + if self.final_response_markdown == "strip": + chunk = _strip_markdown_syntax(chunk) + _emit_one(chunk) + def _flush_stream(self) -> None: """Emit any remaining partial line from the stream buffer and close the box.""" # If we're still inside a "reasoning block" at end-of-stream, it was @@ -6815,7 +6906,7 @@ def _ts_suffix(message: dict) -> str: return "" try: from datetime import datetime - return f" [{datetime.fromtimestamp(float(ts)).strftime('%H:%M')}]" + return f" [{datetime.fromtimestamp(float(ts)).strftime(getattr(self, 'timestamp_format', '%H:%M'))}]" except (ValueError, OSError, TypeError): return "" @@ -6921,17 +7012,69 @@ def _discard_session_if_empty(self, session_id: Optional[str]) -> bool: ) return False + def _launch_session_boundary_memory_flush( + self, + history_snapshot: list, + *, + session_id: Optional[str] = None, + ) -> Optional[list]: + """Stage old-session memory extraction so /new stays responsive. + + The context-engine ``on_session_end`` boundary is delivered + synchronously here: it is cheap (local state clear, no LLM call) and + ordering-sensitive — it must land before ``reset_session_state()`` + rebinds the engine to the new session. + + The memory-provider half (LLM-bound extraction, seconds) is NOT run + here. The returned snapshot is handed by ``new_session()`` to + ``MemoryManager.commit_session_boundary_async`` as a single + end→switch task on the manager's serialized background worker, so + extraction can never race the provider rebinding (providers key off + internal ``_session_id`` state — a late ``on_session_end`` after + ``on_session_switch`` would misattribute the old transcript to the + new session). + + Returns the history snapshot to queue, or ``None`` when there is + nothing to extract (no agent / empty history / no memory manager). + """ + agent = getattr(self, "agent", None) + if not agent or not history_snapshot: + return None + + engine = getattr(agent, "context_compressor", None) + if engine is not None and hasattr(engine, "on_session_end"): + try: + engine.on_session_end(session_id or "", history_snapshot) + except Exception: + logger.debug( + "Context engine on_session_end failed at /new boundary", + exc_info=True, + ) + + # No provider extraction to queue when no memory manager is + # configured — new_session() falls back to the inline switch path. + if getattr(agent, "_memory_manager", None) is None: + return None + return history_snapshot + def new_session(self, silent=False, title=None): """Start a fresh session with a new session ID and cleared agent state.""" + old_session_id = self.session_id + _boundary_snapshot = None if self.agent and self.conversation_history: - # Trigger memory extraction on the old session before session_id rotates. - self.agent.commit_memory_session(self.conversation_history) + # Deliver the context-engine boundary synchronously and get back + # the history snapshot for the deferred provider extraction — + # queued below (after rotation) so /new never blocks on the + # LLM-bound extraction call. + _boundary_snapshot = self._launch_session_boundary_memory_flush( + list(self.conversation_history), + session_id=old_session_id, + ) self._notify_session_boundary("on_session_finalize") elif self.agent: # First session or empty history — still finalize the old session self._notify_session_boundary("on_session_finalize") - old_session_id = self.session_id if self._session_db and old_session_id: # Flush any un-persisted messages from the current turn to the # old session *before* rotating. /new can be called mid-turn @@ -7019,15 +7162,29 @@ def new_session(self, silent=False, title=None): # per-session state (_session_turns, _turn_counter, _document_id). # Fires BEFORE the plugin on_session_reset hook (shell hooks only # see the new id; Python providers see the transition). See #6672. + # + # When the old session has history, end-of-session extraction + # (LLM-bound, seconds) and this switch are queued as ONE task on + # the memory manager's serialized worker — end strictly before + # switch, without blocking /new (#16454). With no history there + # is nothing to extract; switch inline as before. try: _mm = getattr(self.agent, "_memory_manager", None) if _mm is not None: - _mm.on_session_switch( - self.session_id, - parent_session_id=old_session_id or "", - reset=True, - reason="new_session", - ) + if _boundary_snapshot: + _mm.commit_session_boundary_async( + _boundary_snapshot, + new_session_id=self.session_id, + parent_session_id=old_session_id or "", + reason="new_session", + ) + else: + _mm.on_session_switch( + self.session_id, + parent_session_id=old_session_id or "", + reset=True, + reason="new_session", + ) except Exception: pass self._notify_session_boundary("on_session_reset") @@ -7039,7 +7196,6 @@ def new_session(self, silent=False, title=None): print("(^_^)v New session started!") - def _consume_pending_resume_selection(self, text: str) -> bool: """Resolve a bare numeric reply that follows a bare ``/resume`` prompt. @@ -7810,6 +7966,7 @@ def _apply_model_switch_result(self, result, persist_global: bool) -> None: api_key=result.api_key or self.api_key or "", model_info=mi, config_context_length=getattr(self.agent, "_config_context_length", None) if self.agent else None, + custom_providers=getattr(self.agent, "_custom_providers", None) if self.agent else None, ) if ctx: _cprint(f" Context: {ctx:,} tokens") @@ -8118,6 +8275,7 @@ def _handle_model_switch(self, cmd_original: str): api_key=result.api_key or self.api_key or "", model_info=mi, config_context_length=getattr(self.agent, "_config_context_length", None) if self.agent else None, + custom_providers=getattr(self.agent, "_custom_providers", None) if self.agent else None, ) if ctx: _cprint(f" Context: {ctx:,} tokens") @@ -8886,7 +9044,39 @@ def process_command(self, command: str) -> bool: ) # Check for skill slash commands (/gif-search, /axolotl, etc.) elif base_cmd in skill_commands: - user_instruction = cmd_original[len(base_cmd):].strip() + rest = cmd_original[len(base_cmd):].strip() + # Stacked slash-skill invocations: `/skill-a /skill-b do XYZ` + # loads every leading skill (up to 5), not just the first. + # Inspired by Claude Code v2.1.199. + from agent.skill_commands import ( + build_stacked_skill_invocation_message, + split_stacked_skill_commands, + ) + extra_keys, user_instruction = split_stacked_skill_commands(rest) + if extra_keys: + stacked_result = build_stacked_skill_invocation_message( + [base_cmd, *extra_keys], + user_instruction, + task_id=self.session_id, + ) + if stacked_result: + msg, loaded_names, missing = stacked_result + print( + f"\n⚡ Loading {len(loaded_names)} stacked skills: " + f"{', '.join(loaded_names)}" + ) + if missing: + ChatConsole().print( + f"[yellow]Skipped missing skills: {', '.join(missing)}[/]" + ) + if hasattr(self, '_pending_input'): + self._pending_input.put(msg) + else: + ChatConsole().print( + f"[bold red]Failed to load stacked skills for {base_cmd}[/]" + ) + return True + user_instruction = rest msg = build_skill_invocation_message( base_cmd, user_instruction, task_id=self.session_id ) @@ -10012,8 +10202,8 @@ def _billing_poll_charge(self, state, charge_id, amount): _time.sleep(interval) # Past the cap with no terminal state = timeout (not an error). - print(f" 🟡 Still processing after 5 minutes — this is a timeout, not a " - f"failure. Check /billing or the portal shortly.") + print(" 🟡 Still processing after 5 minutes — this is a timeout, not a " + "failure. Check /billing or the portal shortly.") self._billing_portal_hint(state) def _billing_render_charge_failed(self, state, reason): @@ -11528,13 +11718,15 @@ def _sudo_password_callback(self) -> str: return "" def _approval_callback(self, command: str, description: str, - *, allow_permanent: bool = True) -> str: + *, allow_permanent: bool = True, + smart_denied: bool = False) -> str: """ Prompt for dangerous command approval through the prompt_toolkit UI. Called from the agent thread. Shows a selection UI similar to clarify - with choices: once / session / always / deny. When allow_permanent - is False (tirith warnings present), the 'always' option is hidden. + with choices: once / session / always / deny. Smart DENY owner + overrides show only once / deny. When allow_permanent is False for + another reason (for example tirith), only 'always' is hidden. Long commands also get a 'view' option so the full command can be expanded before deciding. @@ -11551,7 +11743,11 @@ def _approval_callback(self, command: str, description: str, self._approval_state = { "command": command, "description": description, - "choices": self._approval_choices(command, allow_permanent=allow_permanent), + "choices": self._approval_choices( + command, + allow_permanent=allow_permanent, + smart_denied=smart_denied, + ), "selected": 0, "response_queue": response_queue, } @@ -11597,9 +11793,13 @@ def _approval_callback(self, command: str, description: str, _cprint(f"\n{_DIM} ⏱ Timeout — denying command{_RST}") return "deny" - def _approval_choices(self, command: str, *, allow_permanent: bool = True) -> list[str]: + def _approval_choices(self, command: str, *, allow_permanent: bool = True, + smart_denied: bool = False) -> list[str]: """Return approval choices for a dangerous command prompt.""" - choices = ["once", "session", "always", "deny"] if allow_permanent else ["once", "session", "deny"] + if smart_denied: + choices = ["once", "deny"] + else: + choices = ["once", "session", "always", "deny"] if allow_permanent else ["once", "session", "deny"] if len(command) > 70: choices.append("view") return choices @@ -12112,7 +12312,7 @@ def display_callback(sentence: str): w = self._scrollback_box_width(getattr(self.console, "width", 80)) label = " ⚕ Hermes " if self.show_timestamps: - label = f"{label}{datetime.now().strftime('%H:%M')} " + label = f"{label}{datetime.now().strftime(getattr(self, 'timestamp_format', '%H:%M'))} " fill = w - 2 - HermesCLI._status_bar_display_width(label) _cprint(f"\n{_ACCENT}╭─{label}{'─' * max(fill - 1, 0)}╮{_RST}") _cprint(f"{_STREAM_PAD}{sentence.rstrip()}") @@ -12676,19 +12876,27 @@ def _persist_active_session_before_close(self): except (Exception, KeyboardInterrupt) as e: logger.debug("Could not persist active CLI session before close: %s", e) - def _print_exit_summary(self): - """Print session resume info on exit, similar to Claude Code.""" - # Clear the screen + scrollback before printing the summary so the - # live bottom chrome (status bar, input box, separator rules) and the - # rest of the session transcript don't get stranded above the exit - # summary (#38252). By this point app.run() has returned and - # prompt_toolkit has restored terminal modes, so writing raw escapes - # to stdout is safe. ESC[3J clears scrollback, ESC[2J clears the - # visible screen, ESC[H homes the cursor — so the summary prints at a - # clean top-left. Falls back to the platform clear command if stdout - # isn't a TTY-capable stream. Honors NO_COLOR/dumb terminals by - # skipping silently when there's no real console. - self._clear_terminal_on_exit() + def _print_exit_summary(self, clear_screen: bool = True): + """Print session resume info on exit, similar to Claude Code. + + Args: + clear_screen: When True (default), clear the terminal screen and + scrollback before printing the summary. This is appropriate for + interactive TUI teardown (#38252). Single-query (-q) mode should + pass False to preserve the printed answer (#53009). + """ + if clear_screen: + # Clear the screen + scrollback before printing the summary so the + # live bottom chrome (status bar, input box, separator rules) and the + # rest of the session transcript don't get stranded above the exit + # summary (#38252). By this point app.run() has returned and + # prompt_toolkit has restored terminal modes, so writing raw escapes + # to stdout is safe. ESC[3J clears scrollback, ESC[2J clears the + # visible screen, ESC[H homes the cursor — so the summary prints at a + # clean top-left. Falls back to the platform clear command if stdout + # isn't a TTY-capable stream. Honors NO_COLOR/dumb terminals by + # skipping silently when there's no real console. + self._clear_terminal_on_exit() print() msg_count = len(self.conversation_history) if msg_count > 0: @@ -13018,6 +13226,29 @@ def run(self): except Exception: pass + # Pre-import the agent runtime off-thread during the same idle window. + # The first turn otherwise pays ~1.5s of module imports on the + # time-to-first-token critical path: `import run_agent` (~0.9s, + # deferred by the lazy AIAgent wrapper above) plus the OpenAI SDK + # (~0.6s, deferred until client construction). Python's import lock + # makes this safe: if the user submits before the warm finishes, the + # main thread simply blocks on the remaining import work instead of + # redoing it. Skipped when agent startup is explicitly deferred + # (Termux) — that path defers heavy work on purpose. + if os.environ.get("HERMES_DEFER_AGENT_STARTUP") != "1": + def _prewarm_agent_runtime() -> None: + try: + import run_agent # noqa: F401 (imports model_tools + tool registry) + import openai # noqa: F401 + except Exception: + logger.debug("agent runtime pre-import failed", exc_info=True) + + threading.Thread( + target=_prewarm_agent_runtime, + name="agent-runtime-prewarm", + daemon=True, + ).start() + # Redaction opt-out warning (#17691): ON by default, loud when off. # The redactor snapshots its state at import time so any toggle now # won't affect the running process — we just want the operator to @@ -14990,8 +15221,17 @@ def process_loop(): # and watch pattern matches) while agent is idle. try: from tools.process_registry import process_registry - for _evt, _synth in process_registry.drain_notifications(): + from tools.approval import get_current_session_key + _drain_sk = get_current_session_key(default="") + for _evt, _synth in process_registry.drain_notifications(session_key=_drain_sk): + from tools.async_delegation import ( + claim_event_delivery, complete_event_delivery, + ) + _claim = claim_event_delivery(_evt, "cli-idle") + if _claim is None: + continue self._pending_input.put(_synth) + complete_event_delivery(_evt, _claim) except Exception: pass continue @@ -15153,7 +15393,14 @@ def _restart_recording(): try: from tools.process_registry import process_registry for _evt, _synth in process_registry.drain_notifications(): + from tools.async_delegation import ( + claim_event_delivery, complete_event_delivery, + ) + _claim = claim_event_delivery(_evt, "cli-post-turn") + if _claim is None: + continue self._pending_input.put(_synth) + complete_event_delivery(_evt, _claim) except Exception: pass # Non-fatal — don't break the main loop @@ -16077,7 +16324,7 @@ def _signal_handler_q(signum, frame): # banner, doesn't depend on the welcome banner being shown. cli._show_security_advisories() cli.chat(query, images=single_query_images or None) - cli._print_exit_summary() + cli._print_exit_summary(clear_screen=False) finally: _finalize_single_query(cli) return diff --git a/gateway/run.py b/gateway/run.py index ed257607fe806..c0779e0740795 100644 --- a/gateway/run.py +++ b/gateway/run.py @@ -54,6 +54,7 @@ # preserving the established test-patch surface. from agent.account_usage import fetch_account_usage, render_account_usage_lines from agent.async_utils import safe_schedule_threadsafe +from agent.conversation_loop import INTERRUPT_WAITING_FOR_MODEL_PREFIX from agent.i18n import t from hermes_cli.config import cfg_get from hermes_cli.fallback_config import get_fallback_chain @@ -67,6 +68,7 @@ _AGENT_CACHE_IDLE_TTL_SECS = 3600.0 # evict agents idle for >1h _PLATFORM_CONNECT_TIMEOUT_SECS_DEFAULT = 30.0 _ADAPTER_DISCONNECT_TIMEOUT_SECS_DEFAULT = 5.0 +_GATEWAY_PROXY_SSE_BUFFER_MAX_CHARS = 16 * 1024 * 1024 _TELEGRAM_COMMAND_MENTION_RE = re.compile(r"(? str: return redact_sensitive_text(str(cmd or ""), force=True) +def _format_exec_approval_fallback( + command: str, + description: str, + command_prefix: str, + *, + allow_permanent: bool = True, + smart_denied: bool = False, +) -> str: + """Render the text fallback from approval capabilities, not platform names.""" + cmd_preview = command[:200] + "..." if len(command) > 200 else command + heading = "⚠️ **Dangerous command requires approval:**" + if smart_denied: + heading = "⚠️ **Smart DENY — owner override for one operation:**" + + choices = [f"Reply `{command_prefix}approve` to execute this one operation"] + if not smart_denied: + choices.append( + f"`{command_prefix}approve session` to approve this pattern for the session" + ) + if allow_permanent: + choices.append(f"`{command_prefix}approve always` to approve permanently") + choices.append(f"`{command_prefix}deny` to cancel") + return ( + f"{heading}\n```\n{cmd_preview}\n```\nReason: {description}\n\n" + + ", ".join(choices[:-1]) + f", or {choices[-1]}." + ) + + def _gateway_provider_error_reply(text: str) -> str: """Map raw provider/API errors to a short user-safe Telegram reply.""" if _GATEWAY_AUTH_ERROR_RE.search(text): @@ -424,6 +454,11 @@ def _sanitize_gateway_final_response(platform: Any, text: str) -> str: if _gateway_surface_passes_raw_text(platform): return text + # Cancellation metadata, not assistant prose. ACP/TUI already suppress + # this sentinel; chat surfaces should too (#7921). + if str(text).strip().startswith(INTERRUPT_WAITING_FOR_MODEL_PREFIX): + return "" + redacted = _redact_gateway_user_facing_secrets(str(text)) if _looks_like_gateway_provider_error(redacted): return _gateway_provider_error_reply(redacted) @@ -715,7 +750,12 @@ def _is_fresh_gateway_interruption( ) -def _build_replay_entry(role: str, content: Any, msg: Dict[str, Any]) -> Dict[str, Any]: +def _build_replay_entry( + role: str, + content: Any, + msg: Dict[str, Any], + preserve_timestamp: bool = False, +) -> Dict[str, Any]: """Build a replay entry for a non-tool-calling message, preserving the assistant fields the agent's API builders rely on for multi-turn fidelity. @@ -723,13 +763,20 @@ def _build_replay_entry(role: str, content: Any, msg: Dict[str, Any]) -> Dict[st be unit-tested in isolation. Mirrors the ``_ASSISTANT_REPLAY_FIELDS`` contract above. + ``preserve_timestamp``: when True, copy the source row's ``timestamp`` + onto the replay entry. Currently only user messages need this — the + stale-dangerous-confirmation stripper in ``agent/replay_cleanup.py`` + reads the timestamp to decide whether a confirmation is too old to + replay safely. Assistant/tool messages are not timestamp-stripped in + the same way, so we keep the existing default of dropping it. + Empty values: most fields are dropped when falsy (matching the original PR #2974 behaviour) since an empty list/string for those carries no information. The exception is ``reasoning_content``: DeepSeek/Kimi thinking-mode replay treats an empty string as a meaningful sentinel that ``_copy_reasoning_content_for_api`` upgrades to a single space. - Dropping it here would make the gateway send no ``reasoning_content`` at - all on the next turn, which can cause HTTP 400 from strict thinking + Dropping it here would make the gateway send no ``reasoning_content`` + at all on the next turn, which can cause HTTP 400 from strict thinking providers. """ entry: Dict[str, Any] = {"role": role, "content": content} @@ -745,6 +792,10 @@ def _build_replay_entry(role: str, content: Any, msg: Dict[str, Any]) -> Dict[st elif not _rval: continue entry[_rkey] = _rval + if preserve_timestamp: + ts = msg.get("timestamp") + if ts: + entry["timestamp"] = ts return entry @@ -860,7 +911,12 @@ def _build_gateway_agent_history( if msg.get("mirror"): mirror_src = msg.get("mirror_source", "another session") content = f"[Delivered from {mirror_src}] {content}" - entry = _build_replay_entry(role, content, msg) + # Preserve the timestamp on user messages so the + # stale-dangerous-confirmation stripper in agent/replay_cleanup.py + # can read it. The timestamp is dropped from assistant messages + # because they don't need it; the replay-tail strippers look at + # assistant(tool_calls), not timestamps. + entry = _build_replay_entry(role, content, msg, preserve_timestamp=(role == "user")) agent_history.append(entry) # Strip interrupted tool-call tails so the LLM doesn't re-execute @@ -874,6 +930,15 @@ def _build_gateway_agent_history( # on resume and loops the restart forever (#49201). agent_history = _strip_dangling_tool_call_tail(agent_history) + # Strip stale dangerous-confirmation text in user messages (#59607). + # A high-risk confirmation phrase (e.g. "confirm forced restart") that + # is older than the expiry window must not be replayed to the model, + # otherwise an unrelated follow-up message can be interpreted as a + # fresh confirmation and trigger the destructive action a second time. + agent_history = _strip_stale_dangerous_confirmations( + agent_history, now=time.time() + ) + observed_context = "\n".join(observed_group_context).strip() or None return agent_history, observed_context @@ -971,6 +1036,8 @@ def _last_transcript_timestamp(history: Optional[List[Dict[str, Any]]]) -> Any: is_interrupted_tool_result as _is_interrupted_tool_result, strip_interrupted_tool_tails as _strip_interrupted_tool_tails, strip_dangling_tool_call_tail as _strip_dangling_tool_call_tail, + strip_stale_dangerous_confirmations as _strip_stale_dangerous_confirmations, + is_dangerous_confirmation as _is_dangerous_confirmation, ) @@ -1260,7 +1327,7 @@ def _clear_planned_restart_notification() -> None: sys.path.insert(0, str(Path(__file__).parent.parent)) # Resolve Hermes home directory (respects HERMES_HOME override) -from hermes_constants import get_hermes_home +from hermes_constants import get_hermes_home, get_hermes_home_override from utils import atomic_json_write, atomic_yaml_write, base_url_host_matches, is_truthy_value _hermes_home = get_hermes_home() @@ -1356,6 +1423,8 @@ def _current_max_iterations() -> int: "wecom_callback", "bluebubbles", "sms", + "whatsapp_cloud", + "line", }) @@ -1415,7 +1484,7 @@ def _profile_runtime_scope(profile_home: "Path"): with open(_config_path, encoding="utf-8") as _f: _cfg = _yaml.safe_load(_f) or {} # Expand ${ENV_VAR} references before bridging to env vars. - from hermes_cli.config import _expand_env_vars + from hermes_cli.config import _expand_env_vars, _normalize_terminal_backend_defaults _cfg = _expand_env_vars(_cfg) # Managed scope: overlay administrator-pinned values BEFORE bridging to # env vars, so a managed timezone / redact_secrets / max_turns / terminal @@ -1428,6 +1497,7 @@ def _profile_runtime_scope(profile_home: "Path"): _cfg = managed_scope.apply_managed_overlay(_cfg) except Exception: pass + _cfg = _normalize_terminal_backend_defaults(_cfg, _cfg) # Top-level simple values (fallback only — don't override .env) for _key, _val in _cfg.items(): if isinstance(_val, (str, int, float, bool)) and _key not in os.environ: @@ -1436,6 +1506,9 @@ def _profile_runtime_scope(profile_home: "Path"): # config.yaml overrides .env for these since it's the documented config path. _terminal_cfg = _cfg.get("terminal", {}) if _terminal_cfg and isinstance(_terminal_cfg, dict): + _terminal_backend = str( + _terminal_cfg.get("backend") or os.environ.get("TERMINAL_ENV") or "" + ).strip().lower() _terminal_env_map = { "backend": "TERMINAL_ENV", "cwd": "TERMINAL_CWD", @@ -1447,6 +1520,18 @@ def _profile_runtime_scope(profile_home: "Path"): "singularity_image": "TERMINAL_SINGULARITY_IMAGE", "modal_image": "TERMINAL_MODAL_IMAGE", "daytona_image": "TERMINAL_DAYTONA_IMAGE", + "tenki_image": "TERMINAL_TENKI_IMAGE", + "tenki_api_endpoint": "TERMINAL_TENKI_API_ENDPOINT", + "tenki_workspace_id": "TERMINAL_TENKI_WORKSPACE_ID", + "tenki_project_id": "TERMINAL_TENKI_PROJECT_ID", + "tenki_name_prefix": "TERMINAL_TENKI_NAME_PREFIX", + "tenki_allow_inbound": "TERMINAL_TENKI_ALLOW_INBOUND", + "tenki_allow_outbound": "TERMINAL_TENKI_ALLOW_OUTBOUND", + "tenki_max_duration": "TERMINAL_TENKI_MAX_DURATION", + "tenki_idle_timeout": "TERMINAL_TENKI_IDLE_TIMEOUT", + "tenki_pause_retention": "TERMINAL_TENKI_PAUSE_RETENTION", + "tenki_sync_hermes_home": "TERMINAL_TENKI_SYNC_HERMES_HOME", + "tenki_forward_env": "TERMINAL_TENKI_FORWARD_ENV", "ssh_host": "TERMINAL_SSH_HOST", "ssh_user": "TERMINAL_SSH_USER", "ssh_port": "TERMINAL_SSH_PORT", @@ -1459,6 +1544,7 @@ def _profile_runtime_scope(profile_home: "Path"): "docker_env": "TERMINAL_DOCKER_ENV", "docker_extra_args": "TERMINAL_DOCKER_EXTRA_ARGS", "docker_mount_cwd_to_workspace": "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", + "docker_network": "TERMINAL_DOCKER_NETWORK", "docker_run_as_host_user": "TERMINAL_DOCKER_RUN_AS_HOST_USER", "docker_persist_across_processes": "TERMINAL_DOCKER_PERSIST_ACROSS_PROCESSES", "docker_orphan_reaper": "TERMINAL_DOCKER_ORPHAN_REAPER", @@ -1474,10 +1560,16 @@ def _profile_runtime_scope(profile_home: "Path"): # Only bridge explicit absolute paths from config.yaml. if _cfg_key == "cwd" and str(_val) in {".", "auto", "cwd"}: continue - # Expand shell tilde in cwd so subprocess.Popen never - # receives a literal "~/" which the kernel rejects. + # Expand shell tilde in local/container cwd so subprocess.Popen + # never receives a literal "~/" which the kernel rejects. + # SSH cwd is interpreted by the remote shell, so preserve + # "~" / "~/..." for the SSH backend instead of expanding it + # to the Hermes host/container HOME (often /opt/data). Shared + # predicate with terminal_tool so the two sites can't drift. if _cfg_key == "cwd" and isinstance(_val, str): - _val = os.path.expanduser(_val) + from tools.terminal_tool import _is_ssh_remote_tilde_cwd + if not _is_ssh_remote_tilde_cwd(_terminal_backend, _val.strip()): + _val = os.path.expanduser(_val) if isinstance(_val, (list, dict)): os.environ[_env_var] = json.dumps(_val) else: @@ -1553,6 +1645,16 @@ def _profile_runtime_scope(profile_home: "Path"): os.environ["HERMES_GATEWAY_BUSY_TEXT_MODE"] = str(_display_cfg["busy_text_mode"]) if "busy_ack_enabled" in _display_cfg: os.environ["HERMES_GATEWAY_BUSY_ACK_ENABLED"] = str(_display_cfg["busy_ack_enabled"]) + # This process-level env var is documented as an override for + # service managers, so preserve it when already set. Other display + # bridges stay config-authoritative for backwards compatibility. + if ( + "busy_steer_ack_enabled" in _display_cfg + and "HERMES_GATEWAY_BUSY_STEER_ACK_ENABLED" not in os.environ + ): + os.environ["HERMES_GATEWAY_BUSY_STEER_ACK_ENABLED"] = str( + _display_cfg["busy_steer_ack_enabled"] + ) # Timezone: bridge config.yaml → HERMES_TIMEZONE env var. _tz_cfg = _cfg.get("timezone", "") if _tz_cfg and isinstance(_tz_cfg, str): @@ -1651,13 +1753,27 @@ def _profile_runtime_scope(profile_home: "Path"): # Set terminal working directory for messaging platforms. # config.yaml terminal.cwd is the canonical source (bridged to TERMINAL_CWD -# by the config bridge above). When it's unset or a placeholder, default -# to home directory. MESSAGING_CWD is accepted as a backward-compat -# fallback (deprecated — the warning above tells users to migrate). +# by the config bridge above). Placeholder values are resolved per-backend — +# see gateway/cwd_placeholder.py for the three-case contract (local vs docker +# mount-off vs docker mount-on). MESSAGING_CWD is a backward-compat fallback. +from gateway.cwd_placeholder import CWD_PLACEHOLDERS, resolve_placeholder_terminal_cwd + _configured_cwd = os.environ.get("TERMINAL_CWD", "") -if not _configured_cwd or _configured_cwd in {".", "auto", "cwd"}: - _fallback = os.getenv("MESSAGING_CWD") or str(Path.home()) - os.environ["TERMINAL_CWD"] = _fallback +if not _configured_cwd or _configured_cwd in CWD_PLACEHOLDERS: + _resolved_cwd = resolve_placeholder_terminal_cwd( + configured_cwd=_configured_cwd, + terminal_backend=os.environ.get("TERMINAL_ENV", ""), + messaging_cwd=os.getenv("MESSAGING_CWD"), + docker_mount_cwd_to_workspace=os.getenv( + "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", "false" + ).lower() + in {"true", "1", "yes"}, + home_fallback=str(Path.home()), + ) + if _resolved_cwd is None: + os.environ.pop("TERMINAL_CWD", None) + else: + os.environ["TERMINAL_CWD"] = _resolved_cwd from gateway.config import ( ChannelOverride, @@ -1669,6 +1785,7 @@ def _profile_runtime_scope(profile_home: "Path"): load_gateway_config, ) from gateway.session import ( + AsyncSessionStore, SessionStore, SessionSource, SessionContext, @@ -1686,8 +1803,10 @@ def _profile_runtime_scope(profile_home: "Path"): EphemeralReply, MessageEvent, MessageType, + _prefix_within_utf16_limit, _reply_anchor_for_event, merge_pending_message_event, + utf16_len, ) from gateway.restart import ( DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT, @@ -1847,6 +1966,23 @@ def _resolve_runtime_agent_kwargs_for_provider(provider: str) -> dict: } +def _credential_pool_for_provider(provider: Optional[str]): + """Return the live credential pool for a provider id (e.g. ``custom:hyper``).""" + if not provider or not str(provider).strip(): + return None + try: + return _resolve_runtime_agent_kwargs_for_provider(str(provider).strip()).get( + "credential_pool" + ) + except Exception: + logger.debug( + "Failed to resolve credential pool for provider=%s", + provider, + exc_info=True, + ) + return None + + def _try_resolve_fallback_provider() -> dict | None: """Attempt to resolve credentials from the fallback_model/fallback_providers config.""" from hermes_cli.runtime_provider import resolve_runtime_provider @@ -2209,6 +2345,14 @@ def _teams_pipeline_plugin_enabled() -> bool: return "teams_pipeline" in enabled or "teams-pipeline" in enabled +def _gateway_config_home() -> Path: + """Return the Hermes home that gateway config reads should use.""" + override = get_hermes_home_override() + if override: + return Path(override) + return _hermes_home + + def _load_gateway_config() -> dict: """Load and parse ~/.hermes/config.yaml, returning {} on any error. @@ -2220,7 +2364,8 @@ def _load_gateway_config() -> dict: gateway honors administrator-pinned values — neither read_raw_config nor a direct yaml.safe_load carries the managed merge on its own. Fail-open. """ - config_path = _hermes_home / 'config.yaml' + config_home = _gateway_config_home() + config_path = config_home / 'config.yaml' raw: dict = {} used_canonical = False try: @@ -2519,7 +2664,22 @@ def _normalize_empty_agent_response( ) api_calls = int(agent_result.get("api_calls", 0) or 0) - if api_calls > 0 and not agent_result.get("interrupted"): + if agent_result.get("interrupted"): + # An interrupted run that did work (api_calls > 0) is the drain of a + # run the user deliberately stopped or steered — its silence is + # intentional, and any queued/interrupting message is delivered by + # the recursive drain inside _run_agent before this result is seen. + # An interrupted run with ZERO api_calls never processed the user's + # message at all: it was killed at the top of the tool loop by an + # interrupt flag left over from a recent /stop (#44212). Pure + # silence there swallows a real user message, so surface it. + if api_calls == 0: + return ( + "⚠️ Your message was interrupted before processing started " + "(likely by a recent /stop). Please send it again." + ) + return response + if api_calls > 0: if agent_result.get("partial"): err = agent_result.get("error", "processing incomplete") return f"⚠️ Processing stopped: {str(err)[:200]}. Try again." @@ -2735,6 +2895,10 @@ def __init__(self, config: Optional[GatewayConfig] = None): key, max_active_age=_bg_max_age_seconds, ), ) + # One enforced loop-side boundary for the synchronous SessionStore. + # Sync helpers keep using ``session_store`` directly; async gateway + # handlers call this facade and await every operation. + self._async_session_store = AsyncSessionStore(self.session_store) self.delivery_router = DeliveryRouter(self.config) self._running = False self._gateway_loop: Optional[asyncio.AbstractEventLoop] = None @@ -2828,6 +2992,15 @@ def __init__(self, config: Optional[GatewayConfig] = None): # cannot grow unbounded over a long-running gateway lifetime. self._session_sources: "OrderedDict[str, SessionSource]" = OrderedDict() self._session_sources_max = 512 + # Completion delivery is intentionally lifecycle-scoped. This closes + # duplicate queue/watcher races inside one gateway without pretending + # the adapter call and a persistence write can be exactly-once across + # a process crash. Any durable async-delegation replay state remains + # owned by tools.async_delegation, not a parallel gateway ledger. + self._completion_delivery_lock = threading.Lock() + self._completion_deliveries_inflight: set[tuple[str, str, object]] = set() + self._completion_deliveries_delivered: "OrderedDict[tuple[str, str, object], None]" = OrderedDict() + self._completion_delivery_retention = 2048 # Cache AIAgent instances per session to preserve prompt caching. # Without this, a new AIAgent is created per message, rebuilding the @@ -2965,9 +3138,15 @@ def __init__(self, config: Optional[GatewayConfig] = None): except Exception as exc: logger.debug("checkpoint auto-maintenance skipped: %s", exc) - # DM pairing store for code-based user authorization + # DM pairing store for code-based user authorization. + # ``pairing_store`` stays as the global/default store for the + # ``hermes pairing`` CLI and any caller without a profile context. + # ``pairing_stores`` is the per-profile map used by + # ``authz_mixin._is_user_authorized`` to route checks to the right + # whitelist (one per profile in multiplex mode). from gateway.pairing import PairingStore self.pairing_store = PairingStore() + self.pairing_stores: Dict[str, "PairingStore"] = {} # Event hook system from gateway.hooks import HookRegistry @@ -3643,8 +3822,13 @@ def _resolve_session_agent_runtime( "base_url": override.get("base_url"), "api_mode": override.get("api_mode"), "max_tokens": override.get("max_tokens"), + "credential_pool": override.get("credential_pool"), } if override_runtime.get("api_key"): + if override_runtime.get("credential_pool") is None: + override_runtime["credential_pool"] = _credential_pool_for_provider( + override.get("provider") + ) logger.debug( "Session model override (fast): session=%s config_model=%s -> override_model=%s provider=%s", resolved_session_key or "", model, override_model, @@ -3951,6 +4135,48 @@ def _request_clean_exit(self, reason: str) -> None: def _running_agent_count(self) -> int: return len(self._running_agents) + def _active_work_count(self) -> int: + """All agent work the gateway must expose and drain as one total.""" + return ( + self._running_agent_count() + + self._active_cron_job_count() + + self._active_api_run_count() + ) + + def _active_cron_job_count(self) -> int: + """Count of cron jobs currently executing, from the cron scheduler's + own in-flight tracking (``cron.scheduler._running_job_ids``). + + Cron jobs run through a standalone ``AIAgent`` on the scheduler's own + thread pool (``cron/scheduler.py::run_job``), entirely outside + ``self._running_agents`` — the dict every OTHER active-work check on + this class (``_running_agent_count``, ``_drain_active_agents``) reads. + Without this, the shutdown drain is structurally blind to in-flight + cron work: it can report ``active_at_start=0`` and proceed straight + to killing tool subprocesses while a cron job's terminal command is + still running (#60432). Best-effort: returns 0 if the cron module + can't be imported (e.g. a minimal test double for this class). + """ + try: + from cron.scheduler import get_running_job_ids + return len(get_running_job_ids()) + except Exception: + return 0 + + def _active_api_run_count(self) -> int: + """Count API-server work that is outside ``_running_agents``. + + The primary API server owns the sole HTTP listener. Secondary multiplex + profiles cannot create an ``api_server`` adapter because it binds a port, + so only the primary registry is a supported source of this work. + """ + try: + adapter = getattr(self, "adapters", {}).get(Platform.API_SERVER) + helper = getattr(adapter, "active_agent_work_count", None) + return max(0, int(helper())) if callable(helper) else 0 + except Exception: + return 0 + # ── scale-to-zero idle detection / dormant-quiesce (Phase 0) ────────────── # The gateway-side BEHAVIOUR that consumes the relay scale-to-zero primitives # (gateway-gateway Phase 5). Pure logic lives in gateway/scale_to_zero.py; the @@ -4338,7 +4564,7 @@ def _update_runtime_status(self, gateway_state: Optional[str] = None, exit_reaso gateway_state=gateway_state, exit_reason=exit_reason, restart_requested=self._restart_requested, - active_agents=self._running_agent_count(), + active_agents=self._active_work_count(), ) except Exception: pass @@ -4361,7 +4587,7 @@ def _persist_active_agents(self) -> None: """ try: from gateway.status import write_runtime_status - write_runtime_status(active_agents=self._running_agent_count()) + write_runtime_status(active_agents=self._active_work_count()) except Exception: pass @@ -4388,7 +4614,7 @@ def _enter_external_drain(self) -> None: logger.info( "External drain ENGAGED (.drain_request.json present) — refusing " "new turns; %d in-flight turn(s) will finish. Process stays up.", - self._running_agent_count(), + self._active_work_count(), ) # Flip the persisted lifecycle state so /api/status.gateway_busy / # gateway_drainable track the drain. Preserve active_agents (the @@ -4439,6 +4665,10 @@ async def _drain_control_watcher(self, interval: float = 1.0) -> None: try: if drain_requested(): self._enter_external_drain() + # API and cron work live outside messaging's + # _running_agents map. Refresh the aggregate while an + # external caller polls this reversible drain state. + self._persist_active_agents() else: self._exit_external_drain() except asyncio.CancelledError: @@ -4638,14 +4868,17 @@ def _load_reasoning_config() -> dict | None: """Load reasoning effort from config.yaml. Reads agent.reasoning_effort from config.yaml. Valid: "none", - "minimal", "low", "medium", "high", "xhigh". Returns None to use + "minimal", "low", "medium", "high", "xhigh", "max", "ultra". Returns None to use default (medium). """ from hermes_constants import parse_reasoning_effort cfg = _load_gateway_runtime_config() - effort = str(cfg_get(cfg, "agent", "reasoning_effort", default="") or "").strip() + # Keep the raw value — coercing with ``or ""`` turns a YAML boolean + # False (``reasoning_effort: false``/``off``/``no``) into "", silently + # re-enabling thinking for users who explicitly disabled it. + effort = cfg_get(cfg, "agent", "reasoning_effort", default="") result = parse_reasoning_effort(effort) - if effort and effort.strip() and result is None: + if effort and str(effort).strip() and result is None: logger.warning("Unknown reasoning_effort '%s', using default (medium)", effort) return result @@ -4856,6 +5089,74 @@ def _load_fallback_model() -> list | None: pass return None + def _refresh_fallback_model(self) -> list | None: + """Re-read fallback_providers from disk for the next agent create/reuse. + + Cron already does this per job via ``get_fallback_chain``; the gateway + previously froze ``self._fallback_model`` at process start, so a chain + configured (or changed) after ``hermes gateway`` was running never + reached messaging sessions even though the same process's cron jobs + fell back correctly. Fixes #60955. + + A TRANSIENT read/parse failure (user mid-edit of config.yaml with a + non-atomic write) keeps the last known-good chain instead of wiping a + cached agent's working fallback for that turn. Only a successful read + that genuinely lacks the key clears the chain. + """ + try: + import yaml as _y + cfg_path = _hermes_home / "config.yaml" + if not cfg_path.exists(): + self._fallback_model = None + return self._fallback_model + with open(cfg_path, encoding="utf-8") as _f: + cfg = _y.safe_load(_f) or {} + except Exception: + # Transient failure — keep last known-good chain. + logger.debug( + "fallback_providers refresh: config.yaml read failed; " + "keeping last known-good chain", exc_info=True, + ) + return self._fallback_model + self._fallback_model = get_fallback_chain(cfg) or None + return self._fallback_model + + @staticmethod + def _apply_fallback_chain_to_agent(agent: Any, chain: list | None) -> None: + """Keep a cached agent's fallback chain aligned with current config. + + Skips rewrite while a cooldown is holding the agent on an already- + activated fallback provider — ``restore_primary_runtime`` owns that + turn-scoped lifecycle. When primary is active (or cooldown expired), + replace the chain so mid-uptime ``fallback_providers`` edits take + effect without requiring a gateway restart (#60955). + """ + if agent is None: + return + new_chain = list(chain or []) + rate_limited_until = getattr(agent, "_rate_limited_until", 0) or 0 + if ( + getattr(agent, "_fallback_activated", False) + and rate_limited_until > time.monotonic() + ): + return + old_chain = list(getattr(agent, "_fallback_chain", []) or []) + agent._fallback_chain = new_chain + agent._fallback_model = new_chain[0] if new_chain else None + if not getattr(agent, "_fallback_activated", False): + agent._fallback_index = 0 + # A config edit signals the user changed something — drop the + # session-scoped unavailability memo so re-configured entries + # (e.g. credentials added mid-uptime for a previously-failing + # provider) get retried instead of staying suppressed for the + # cached agent's lifetime. Only on actual content change, so + # the per-message no-op refresh keeps the memo's rate-limiting + # benefit (#60955). + if new_chain != old_chain: + unavailable = getattr(agent, "_unavailable_fallback_keys", None) + if unavailable: + unavailable.clear() + def _snapshot_running_agents(self) -> Dict[str, Any]: return { session_key: agent @@ -4954,7 +5255,7 @@ def _agent_has_active_subagents(running_agent: Any) -> bool: except Exception: return False - def _session_has_compression_in_flight(self, session_key: str) -> bool: + async def _session_has_compression_in_flight(self, session_key: str) -> bool: """Return True when a compression lock is held for this session's id. Context compression is interrupt-protected (#23975) but gateway @@ -4962,28 +5263,43 @@ def _session_has_compression_in_flight(self, session_key: str) -> bool: the pre-rotation parent while compression is mid-flight, producing orphaned compression siblings (#56391). Callers demote interrupt to queue when this returns True. + + Both blocking sources — the ``session_store`` lock + JSON load, and the + SQLite ``get_compression_lock_holder`` SELECT — are offloaded to a + worker thread so a large state.db never freezes the event loop (#5). """ session_store = getattr(self, "session_store", None) if not session_key or session_store is None: return False try: - with session_store._lock: # noqa: SLF001 — snapshot entry under lock - session_store._ensure_loaded_locked() # noqa: SLF001 - entry = session_store._entries.get(session_key) # noqa: SLF001 - session_id = getattr(entry, "session_id", None) if entry is not None else None - if not session_id: - return False + session_id = await asyncio.to_thread( + self._lookup_session_id_under_store_lock, session_store, session_key + ) except Exception: return False + if not session_id: + return False session_db = getattr(self, "_session_db", None) if session_db is None: return False - db = getattr(session_db, "_db", session_db) + raw_db = getattr(session_db, "_db", session_db) try: - return bool(db.get_compression_lock_holder(str(session_id))) + holder = await asyncio.to_thread( + raw_db.get_compression_lock_holder, str(session_id) + ) + return bool(holder) except Exception: return False + @staticmethod + def _lookup_session_id_under_store_lock(session_store, session_key: str): + """Sync helper run in the thread pool: read session_id under the store lock.""" + # noqa: SLF001 — intentional private access; runs off the event loop. + with session_store._lock: # noqa: SLF001 + session_store._ensure_loaded_locked() # noqa: SLF001 + entry = session_store._entries.get(session_key) # noqa: SLF001 + return getattr(entry, "session_id", None) if entry is not None else None + # Hard cap on per-session pending follow-ups for busy_input_mode=queue # (and the draining/steer-fallback/subagent-demotion paths that share # this entry point). Without a cap, a stuck agent + a rapid-fire user @@ -5132,7 +5448,7 @@ async def _handle_active_session_busy_message(self, event: MessageEvent, session "Approval response via plain text: session=%s verb=%s args=%r", session_key, _verb, _normalized_args, ) - _adapter = self.adapters.get(event.source.platform) + _adapter = self._adapter_for_source(event.source) if _adapter and _reply: _text, _eph_ttl = _adapter._unwrap_ephemeral(_reply) if _text: @@ -5206,7 +5522,7 @@ async def _handle_active_session_busy_message(self, event: MessageEvent, session effective_mode = "queue" demoted_for_compression = ( effective_mode == "interrupt" - and self._session_has_compression_in_flight(session_key) + and await self._session_has_compression_in_flight(session_key) ) if demoted_for_compression: logger.info( @@ -5272,20 +5588,44 @@ async def _handle_active_session_busy_message(self, event: MessageEvent, session logger.debug("Busy ack suppressed for session %s", session_key) return True # input still processed, just no ack sent - # Debounce: only send an acknowledgment once every 30 seconds per session - # to avoid spamming the user when they send multiple messages quickly + # Debounce before consulting config-heavy display settings. Rapid + # follow-ups should be processed but should not trigger another config + # read just to discover that no ack will be sent. _BUSY_ACK_COOLDOWN = 30 now = time.time() last_ack = self._busy_ack_ts.get(session_key, 0) if now - last_ack < _BUSY_ACK_COOLDOWN: return True # interrupt sent (if not queue), ack already delivered recently + from gateway.display_config import resolve_display_setting + platform_key = _platform_config_key(event.source.platform) + + # In steer mode the user's text has already been injected into the + # active run. Some mobile chat setups want that steering to be silent, + # like STT transcript echo suppression: keep the behavior, drop only + # the confirmation bubble. + if is_steer_mode: + steer_ack_env = os.environ.get("HERMES_GATEWAY_BUSY_STEER_ACK_ENABLED") + if steer_ack_env is not None: + steer_ack_enabled = steer_ack_env.strip().lower() in {"1", "true", "yes", "on"} + else: + steer_ack_enabled = bool( + resolve_display_setting( + _load_gateway_config(), + platform_key, + "busy_steer_ack_enabled", + True, + ) + ) + if not steer_ack_enabled: + logger.debug("Busy steer ack suppressed for session %s", session_key) + return True + self._busy_ack_ts[session_key] = now # Build a status-rich acknowledgment. Mobile chat defaults keep this # terse; detailed iteration/tool state is still available in logs and # can be opted in per platform via display.platforms..busy_ack_detail. - from gateway.display_config import resolve_display_setting status_parts = [] busy_ack_detail_enabled = bool( resolve_display_setting( @@ -5394,18 +5734,36 @@ async def _handle_active_session_busy_message(self, event: MessageEvent, session async def _drain_active_agents(self, timeout: float) -> tuple[Dict[str, Any], bool]: snapshot = self._snapshot_running_agents() last_active_count = self._running_agent_count() + last_cron_count = self._active_cron_job_count() + last_api_count = self._active_api_run_count() last_status_at = 0.0 def _maybe_update_status(force: bool = False) -> None: - nonlocal last_active_count, last_status_at + nonlocal last_active_count, last_cron_count, last_api_count, last_status_at now = asyncio.get_running_loop().time() active_count = self._running_agent_count() - if force or active_count != last_active_count or (now - last_status_at) >= 1.0: + cron_count = self._active_cron_job_count() + api_count = self._active_api_run_count() + if ( + force + or active_count != last_active_count + or cron_count != last_cron_count + or api_count != last_api_count + or (now - last_status_at) >= 1.0 + ): self._update_runtime_status("draining") last_active_count = active_count + last_cron_count = cron_count + last_api_count = api_count last_status_at = now - if not self._running_agents: + # Cron jobs run on the scheduler's own thread pool, outside + # ``self._running_agents`` — fold their in-flight count into the + # same wait/timeout this method already applies to chat sessions, + # or a cron job's tool work gets killed with zero warning the + # instant it's the only active thing running (#60432). + # API-server / desk sessions have the same structural gap (#63529). + if not self._running_agents and last_cron_count == 0 and last_api_count == 0: _maybe_update_status(force=True) return snapshot, False @@ -5414,10 +5772,21 @@ def _maybe_update_status(force: bool = False) -> None: return snapshot, True deadline = asyncio.get_running_loop().time() + timeout - while self._running_agents and asyncio.get_running_loop().time() < deadline: + while ( + ( + self._running_agents + or self._active_cron_job_count() + or self._active_api_run_count() + ) + and asyncio.get_running_loop().time() < deadline + ): _maybe_update_status() await asyncio.sleep(0.1) - timed_out = bool(self._running_agents) + timed_out = ( + bool(self._running_agents) + or bool(self._active_cron_job_count()) + or bool(self._active_api_run_count()) + ) _maybe_update_status(force=True) return snapshot, timed_out @@ -5455,7 +5824,7 @@ async def _notify_active_sessions_of_shutdown(self) -> None: source = None try: if getattr(self, "session_store", None) is not None: - self.session_store._ensure_loaded() + await self.async_session_store._ensure_loaded() entry = self.session_store._entries.get(session_key) source = getattr(entry, "origin", None) if entry else None except Exception as e: @@ -6225,7 +6594,7 @@ async def _drain_startup_restore_queue(self) -> int: while queue: event = queue.pop(0) source = getattr(event, "source", None) - adapter = self.adapters.get(source.platform) if source is not None else None + adapter = self._adapter_for_source(source) if adapter is None: logger.debug( "Dropping startup-restore queued message: adapter unavailable for %s", @@ -6331,7 +6700,7 @@ def _schedule_resume_pending_sessions(self, platform=None) -> int: continue source = entry.origin - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter is None: logger.debug( "Skipping auto-resume for %s: adapter not ready for %s", @@ -6725,7 +7094,7 @@ async def start(self) -> bool: pass else: try: - suspended = self.session_store.suspend_recently_active() + suspended = await self.async_session_store.suspend_recently_active() if suspended: logger.info("Marked %d in-flight session(s) as resumable from previous run", suspended) except Exception as e: @@ -7286,13 +7655,13 @@ async def _process_handoff(self, row: Dict[str, Any]) -> None: # Make sure there's an entry in the session_store for this key. If # the home channel has never been used, get_or_create_session # creates one; switch_session then re-points it. - self.session_store.get_or_create_session(dest_source) + await self.async_session_store.get_or_create_session(dest_source) # Re-bind the destination key to the CLI session_id. switch_session # ends the prior session in SQLite and reopens the CLI session under # the new key. The CLI's transcript becomes the active one for the # gateway from this moment on. - switched = self.session_store.switch_session(session_key, cli_session_id) + switched = await self.async_session_store.switch_session(session_key, cli_session_id) if switched is None: raise RuntimeError( f"could not switch session key {session_key} → {cli_session_id}" @@ -7369,13 +7738,13 @@ async def _session_expiry_watcher(self, interval: int = 300): _MAX_FINALIZE_RETRIES = 3 while self._running: try: - self.session_store._ensure_loaded() + await self.async_session_store._ensure_loaded() # Collect expired sessions first, then log a single summary. _expired_entries = [] for key, entry in list(self.session_store._entries.items()): if entry.expiry_finalized: continue - if not self.session_store._is_session_expired(entry): + if not await self.async_session_store._is_session_expired(entry): continue _expired_entries.append((key, entry)) @@ -7442,20 +7811,24 @@ async def _session_expiry_watcher(self, interval: int = 300): self._set_session_reasoning_override(key, None) if hasattr(self, "_pending_model_notes"): self._pending_model_notes.pop(key, None) + # Clear per-session model cache so a resumed turn + # resolves from current config, not a stale fallback + # cached before the session went idle (mirrors /new + # and the compression-exhausted auto-reset, #58403). + _lrm = getattr(self, "_last_resolved_model", None) + if _lrm is not None: + _lrm.pop(key, None) _pending_approvals = getattr(self, "_pending_approvals", None) if isinstance(_pending_approvals, dict): _pending_approvals.pop(key, None) _update_prompt_pending = getattr(self, "_update_prompt_pending", None) if isinstance(_update_prompt_pending, dict): _update_prompt_pending.pop(key, None) - with self.session_store._lock: - entry.expiry_finalized = True - # Session finalization is a conversation boundary — - # drop the persisted /model override too so a later - # message doesn't rehydrate it after the in-memory - # override was popped above. - entry.model_override = None - self.session_store._save() + # Persist the finalized flag to sessions.json AND + # state.db (single write-path, #9006) — also drops + # the persisted /model override, since finalization + # is a conversation boundary. + await self.async_session_store.set_expiry_finalized(entry) logger.debug( "Session expiry finalized for %s", entry.session_id, @@ -7470,9 +7843,9 @@ async def _session_expiry_watcher(self, interval: int = 300): "Marking as finalized to prevent infinite retry loop.", failures, entry.session_id, e, ) - with self.session_store._lock: - entry.expiry_finalized = True - self.session_store._save() + await self.async_session_store.set_expiry_finalized( + entry, clear_model_override=False + ) _finalize_failures.pop(entry.session_id, None) else: logger.debug( @@ -7523,7 +7896,7 @@ async def _session_expiry_watcher(self, interval: int = 300): getattr(self.config, "session_store_max_age_days", 0) or 0 ) if _max_age > 0: - _pruned = self.session_store.prune_old_entries(_max_age) + _pruned = await self.async_session_store.prune_old_entries(_max_age) if _pruned: logger.info( "SessionStore prune: dropped %d stale entries", @@ -7784,6 +8157,27 @@ def _kill_tool_subprocesses(phase: str) -> None: ) except Exception as _e: logger.debug("process_registry.kill_all (%s) error: %s", phase, _e) + try: + # Any cron job still dispatched at this instant just had + # its tool subprocess killed above (kill_all() has no + # per-job-ID targeting — it's a global sweep). Its agent + # thread is still alive in this process and may go on to + # produce a plausible-looking final response from the + # now-truncated tool output; mark the run interrupted so + # the scheduler can never report that as success (#60432). + # No-op when no cron job is in flight. + from cron.scheduler import mark_running_jobs_interrupted + _interrupted = mark_running_jobs_interrupted( + f"Gateway shutdown ({phase}) killed the job's tool " + "subprocess before the run finished." + ) + if _interrupted: + logger.warning( + "Shutdown (%s): marked %d in-flight cron job(s) interrupted: %s", + phase, len(_interrupted), ", ".join(_interrupted), + ) + except Exception as _e: + logger.debug("mark_running_jobs_interrupted (%s) error: %s", phase, _e) try: from tools.async_delegation import interrupt_all as _interrupt_async _async_n = _interrupt_async(reason=f"gateway shutdown ({phase})") @@ -7836,7 +8230,7 @@ def _phase_elapsed() -> float: if _agent is _AGENT_PENDING_SENTINEL: continue try: - self.session_store.mark_resume_pending( + await self.async_session_store.mark_resume_pending( _sk, "restart_timeout" if self._restart_requested else "shutdown_timeout", ) @@ -7844,16 +8238,24 @@ def _phase_elapsed() -> float: except Exception as _e: logger.debug("pre-drain mark_resume_pending failed for %s: %s", _sk, _e) + _cron_at_start = self._active_cron_job_count() + _api_at_start = self._active_api_run_count() _drain_started_at = time.monotonic() active_agents, timed_out = await self._drain_active_agents(timeout) logger.info( "Shutdown phase: drain done at +%.2fs (drain took %.2fs, " - "timed_out=%s, active_at_start=%d, active_now=%d)", + "timed_out=%s, active_at_start=%d, active_now=%d, " + "cron_at_start=%d, cron_now=%d, " + "api_at_start=%d, api_now=%d)", _phase_elapsed(), time.monotonic() - _drain_started_at, timed_out, len(active_agents), self._running_agent_count(), + _cron_at_start, + self._active_cron_job_count(), + _api_at_start, + self._active_api_run_count(), ) if not timed_out: @@ -7863,7 +8265,7 @@ def _phase_elapsed() -> float: for _sk in _pre_drain_keys: if _sk not in self._running_agents: try: - self.session_store.clear_resume_pending(_sk) + await self.async_session_store.clear_resume_pending(_sk) except Exception as _e: logger.debug( "clear_resume_pending after drain failed for %s: %s", @@ -7872,9 +8274,13 @@ def _phase_elapsed() -> float: if timed_out: logger.warning( - "Gateway drain timed out after %.1fs with %d active agent(s); interrupting remaining work.", + "Gateway drain timed out after %.1fs with %d active agent(s), " + "%d in-flight cron job(s), and %d api_server run(s); " + "interrupting remaining work.", timeout, self._running_agent_count(), + self._active_cron_job_count(), + self._active_api_run_count(), ) # Mark forcibly-interrupted sessions as resume_pending BEFORE # interrupting the agents. This preserves each session's @@ -7904,7 +8310,7 @@ def _phase_elapsed() -> float: if _agent is _AGENT_PENDING_SENTINEL: continue try: - self.session_store.mark_resume_pending(_sk, _resume_reason) + await self.async_session_store.mark_resume_pending(_sk, _resume_reason) except Exception as _e: logger.debug( "mark_resume_pending failed for %s: %s", @@ -8217,6 +8623,13 @@ async def _start_secondary_profile_adapters(self) -> int: try: from gateway.status import write_runtime_status served = [active] + sorted(self._profile_adapters.keys()) + # Per-profile PairingStores so authz_mixin can route pairing + # checks to the right whitelist. The active profile gets a store + # at its HERMES_HOME; additional served profiles get one under + # profiles//pairing/. See gateway.pairing.PairingStore. + for name in served: + if name and name not in self.pairing_stores: + self.pairing_stores[name] = PairingStore(profile=name) write_runtime_status(served_profiles=served) except Exception: logger.debug("could not record served_profiles", exc_info=True) @@ -8334,6 +8747,11 @@ def _adapter_credential_fingerprint(adapter: Any) -> Optional[str]: if isinstance(val, str) and val.strip(): token = val.strip() break + if not token: + config = getattr(adapter, "config", None) + val = getattr(config, "token", None) + if isinstance(val, str) and val.strip(): + token = val.strip() if not token: return None import hashlib @@ -8498,7 +8916,7 @@ def check( async def _deliver_platform_notice(self, source, content: str) -> None: """Deliver a setup/operational notice using platform-specific privacy rules.""" - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if not adapter: return @@ -8973,7 +9391,7 @@ async def _handle_message(self, event: MessageEvent) -> Optional[str]: has_media = bool(getattr(event, "media_urls", None)) if not queued_text and not has_media: return "Usage: /queue " - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter: queued_event = MessageEvent( text=queued_text, @@ -8994,7 +9412,7 @@ async def _handle_message(self, event: MessageEvent) -> Optional[str]: timestamp=event.timestamp, ) self._enqueue_fifo(_quick_key, queued_event, adapter) - depth = self._queue_depth(_quick_key, adapter=self.adapters.get(source.platform)) + depth = self._queue_depth(_quick_key, adapter=self._adapter_for_source(source)) if depth <= 1: return "Queued for the next turn." return f"Queued for the next turn. ({depth} queued)" @@ -9011,7 +9429,7 @@ async def _handle_message(self, event: MessageEvent) -> Optional[str]: running_agent = self._running_agents.get(_quick_key) if running_agent is _AGENT_PENDING_SENTINEL: # Agent hasn't started yet — queue as turn-boundary fallback. - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter: queued_event = MessageEvent( text=steer_text, @@ -9033,7 +9451,7 @@ async def _handle_message(self, event: MessageEvent) -> Optional[str]: return f"⏩ Steer queued — arrives after the next tool call: '{preview}'" return "Steer rejected (empty payload)." # Running agent is missing or lacks steer() — fall back to queue. - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter: queued_event = MessageEvent( text=steer_text, @@ -9158,7 +9576,7 @@ async def _handle_message(self, event: MessageEvent) -> Optional[str]: if event.message_type == MessageType.PHOTO: logger.debug("PRIORITY photo follow-up for session %s — queueing without interrupt", _quick_key) - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter: merge_pending_message_event(adapter._pending_messages, _quick_key, event) return None @@ -9179,7 +9597,7 @@ async def _handle_message(self, event: MessageEvent) -> Optional[str]: time.time() - _started_at, _quick_key, ) - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter: if self._busy_input_mode == "queue": self._enqueue_fifo(_quick_key, event, adapter) @@ -9202,7 +9620,7 @@ async def _handle_message(self, event: MessageEvent) -> Optional[str]: return EphemeralReply("⚡ Force-stopped. The agent was still starting — session unlocked.") # Queue the message so it will be picked up after the # agent starts. - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter: merge_pending_message_event( adapter._pending_messages, @@ -9257,6 +9675,22 @@ async def _handle_message(self, event: MessageEvent) -> Optional[str]: ) self._queue_or_replace_pending_event(_quick_key, event) return None + # #56391 — Compression protection (PRIORITY path). Same + # rationale as ``_handle_active_session_busy_message``: context + # compression is interrupt-protected (#23975), but an interrupt + # here starts a new turn against the pre-rotation parent + # session while the still-running compression later rotates + # the id out from under it, forking orphaned compression + # siblings. Demote to queue semantics so the follow-up waits + # for the in-flight compression + rotation to land. + if await self._session_has_compression_in_flight(_quick_key): + logger.info( + "PRIORITY interrupt demoted to queue for session %s " + "because context compression is in flight (#56391)", + _quick_key, + ) + self._queue_or_replace_pending_event(_quick_key, event) + return None logger.debug("PRIORITY interrupt for session %s", _quick_key) running_agent.interrupt(event.text) # NOTE: self._pending_messages was write-only (never consumed). @@ -9290,7 +9724,7 @@ async def _handle_message(self, event: MessageEvent) -> Optional[str]: if isinstance(quick_commands, dict) and command in quick_commands: qcmd = quick_commands[command] if qcmd.get("type") == "alias": - target = qcmd.get("target", "").strip() + target = (qcmd.get("target") or "").strip() if target: target = target if target.startswith("/") else f"/{target}" target_command = target.lstrip("/") @@ -9441,7 +9875,7 @@ async def _do_reset(): else "Learning a skill from this conversation…" ) try: - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter: _ack_meta = self._thread_metadata_for_source(source) await adapter.send(str(source.chat_id), _ack, metadata=_ack_meta) @@ -9495,7 +9929,7 @@ async def _do_reset(): _ack = getattr(_blueprint_result, "text", "") or "" if _ack: try: - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter: _ack_meta = self._thread_metadata_for_source(source) await adapter.send(str(source.chat_id), _ack, metadata=_ack_meta) @@ -9702,7 +10136,7 @@ async def _do_undo(): else: return f"Quick command '/{command}' has no command defined." elif qcmd.get("type") == "alias": - target = qcmd.get("target", "").strip() + target = (qcmd.get("target") or "").strip() if target: target = target if target.startswith("/") else f"/{target}" target_command = target.lstrip("/") @@ -9748,8 +10182,15 @@ async def _do_undo(): bundle_key = resolve_bundle_command_key(command) if bundle_key is not None: user_instruction = event.get_command_args().strip() + # Pass the platform explicitly: bundle skill loading + # bypasses get_skill_commands()' scan-time disabled + # filter, and the gateway serves multiple platforms in + # one process, so env-var platform resolution can't be + # trusted here. Mirrors the stacked-skill gate (#58888). + _bundle_plat = source.platform.value if source.platform else None bundle_result = build_bundle_invocation_message( - bundle_key, user_instruction, task_id=_quick_key + bundle_key, user_instruction, task_id=_quick_key, + platform=_bundle_plat, ) if bundle_result: msg, _loaded, missing = bundle_result @@ -9788,12 +10229,60 @@ async def _do_undo(): f"Enable it with: `hermes skills config`" ) user_instruction = event.get_command_args().strip() - msg = build_skill_invocation_message( - cmd_key, user_instruction, task_id=_quick_key - ) - if msg: - event.text = msg - # Fall through to normal message processing with skill content + # Stacked slash-skill invocations: `/skill-a /skill-b do + # XYZ` loads every leading skill (up to 5), not just the + # first. Inspired by Claude Code v2.1.199. Mirrors CLI. + try: + from agent.skill_commands import ( + build_stacked_skill_invocation_message as _build_stacked, + split_stacked_skill_commands, + ) + extra_keys, stacked_instruction = ( + split_stacked_skill_commands(user_instruction) + ) + except Exception: + _build_stacked = None + extra_keys, stacked_instruction = [], user_instruction + if extra_keys and _plat: + # split_stacked_skill_commands() only resolves that + # each extra token is a KNOWN skill command — like + # get_skill_commands() itself, it has no per-platform + # view. Re-check every stacked skill (not just the + # leading one above) against the same disabled list, + # or a skill an operator disabled for this platform + # still gets its full content loaded via the stack. + from agent.skill_utils import get_disabled_skill_names as _get_plat_disabled + _plat_disabled = _get_plat_disabled(platform=_plat) + _disabled_extra = [ + skill_cmds.get(k, {}).get("name", "") + for k in extra_keys + if skill_cmds.get(k, {}).get("name", "") in _plat_disabled + ] + if _disabled_extra: + return ( + f"The **{', '.join(_disabled_extra)}** skill(s) in this " + f"stacked invocation are disabled for {_plat}.\n" + f"Enable them with: `hermes skills config`" + ) + if extra_keys and _build_stacked is not None: + stacked_result = _build_stacked( + [cmd_key, *extra_keys], + stacked_instruction, + task_id=_quick_key, + ) + if stacked_result: + msg, _loaded, _missing = stacked_result + event.text = msg + # Fall through to normal message processing + else: + return f"Failed to load stacked skills for /{command}." + else: + msg = build_skill_invocation_message( + cmd_key, user_instruction, task_id=_quick_key + ) + if msg: + event.text = msg + # Fall through to normal message processing with skill content else: # Not an active skill — check if it's a known-but-disabled or # uninstalled skill and give actionable guidance. @@ -9901,7 +10390,7 @@ async def _do_undo(): # on error. Let the user drive the next turn. if _final_text.strip(): try: - session_entry = self.session_store.get_or_create_session(source) + session_entry = await self.async_session_store.get_or_create_session(source) except Exception: session_entry = None if session_entry is not None: @@ -9959,6 +10448,7 @@ async def _prepare_inbound_message_text( event: MessageEvent, source: SessionSource, history: List[Dict[str, Any]], + session_key: Optional[str] = None, ) -> Optional[str]: """Prepare inbound event text for the agent. @@ -9977,10 +10467,10 @@ async def _prepare_inbound_message_text( message_text = event.text or "" _group_sessions_per_user = getattr(self.config, "group_sessions_per_user", True) _thread_sessions_per_user = getattr(self.config, "thread_sessions_per_user", False) - # Use the same helper every other call site uses so the write key here - # matches the consume key at the run_conversation site — even if the - # session store overrides build_session_key's default behavior. - session_key = self._session_key_for_source(source) + # Prefer the already resolved session key from the caller so this write + # key matches the consume key at the run_conversation site. Fall back + # to deriving it here for tests and legacy standalone callers. + session_key = session_key or self._session_key_for_source(source) # Reset only this session's per-call buffer; other sessions may be # concurrently preparing multimodal turns on the same runner. self._consume_pending_native_image_paths(session_key) @@ -10031,7 +10521,10 @@ async def _prepare_inbound_message_text( if image_paths: # Decide routing: native (attach pixels) vs text (vision_analyze # pre-run + prepend description). See agent/image_routing.py. - _img_mode = self._decide_image_input_mode() + _img_mode = self._decide_image_input_mode( + source=source, + session_key=session_key, + ) if _img_mode == "native": # Defer attachment to the run_conversation call site. pending_native = getattr(self, "_pending_native_image_paths_by_session", None) @@ -10058,11 +10551,12 @@ async def _prepare_inbound_message_text( message_text, audio_paths, ) - # Echo each successful transcript back to the user immediately, - # before the agent loop runs. Lets the user verify STT quality - # in real-time and see the raw whisper output verbatim. - if _successful_transcripts: - _echo_adapter = self.adapters.get(source.platform) + # Echo each successful transcript back to the user immediately + # when configured. Lets users verify STT quality in real-time, + # while allowing quiet STT for users who only want the agent to + # receive the transcription. + if _successful_transcripts and self._should_echo_stt_transcripts(): + _echo_adapter = self._adapter_for_source(source) _echo_meta = self._thread_metadata_for_source(source, self._reply_anchor_for_event(event)) if _echo_adapter: for _tx in _successful_transcripts: @@ -10212,8 +10706,10 @@ async def _prepare_inbound_message_text( from agent.model_metadata import get_model_context_length_async _msg_cwd = os.environ.get("TERMINAL_CWD", os.path.expanduser("~")) - _msg_runtime = _resolve_runtime_agent_kwargs() _msg_config_ctx = None + _msg_cfg = None + _msg_model_cfg = {} + _msg_custom_providers = [] try: _msg_cfg = _load_gateway_config() _msg_model_cfg = _msg_cfg.get("model", {}) @@ -10221,13 +10717,57 @@ async def _prepare_inbound_message_text( _msg_raw_ctx = _msg_model_cfg.get("context_length") if _msg_raw_ctx is not None: _msg_config_ctx = int(_msg_raw_ctx) + try: + from hermes_cli.config import get_compatible_custom_providers + + _msg_custom_providers = get_compatible_custom_providers(_msg_cfg) + except Exception: + _msg_custom_providers = _msg_cfg.get("custom_providers") or [] except Exception: pass + # Resolve the session's actual model/provider/base_url the + # same way the hygiene compression block does (~11080). + # GatewayRunner has no self._model/self._base_url attrs + # (that was copy-pasted from HermesCLI, which does carry + # self.model/self.base_url), so using them here always raised + # AttributeError, silently caught below, meaning this feature + # never ran. + _msg_model, _msg_runtime = self._resolve_session_agent_runtime( + source=source, + session_key=session_key, + user_config=_msg_cfg, + ) + _msg_base_url = _msg_runtime.get("base_url") or "" + # A global model.context_length belongs to the configured + # model, not a session /model or channel override. Prefer a + # matching per-custom-provider model limit when available. + _msg_configured_model = ( + _msg_model_cfg.get("default") or _msg_model_cfg.get("model") + if isinstance(_msg_model_cfg, dict) + else _msg_model_cfg + ) + if _msg_model != _msg_configured_model: + _msg_config_ctx = None + if _msg_custom_providers and _msg_base_url: + try: + from hermes_cli.config import get_custom_provider_context_length + + _msg_custom_ctx = get_custom_provider_context_length( + model=_msg_model, + base_url=_msg_base_url, + custom_providers=_msg_custom_providers, + ) + if _msg_custom_ctx: + _msg_config_ctx = _msg_custom_ctx + except Exception: + pass _msg_ctx_len = await get_model_context_length_async( - self._model, - base_url=self._base_url or _msg_runtime.get("base_url") or "", + _msg_model, + base_url=_msg_base_url, api_key=_msg_runtime.get("api_key") or "", config_context_length=_msg_config_ctx, + provider=_msg_runtime.get("provider") or "", + custom_providers=_msg_custom_providers, ) _ctx_result = await preprocess_context_references_async( message_text, @@ -10236,7 +10776,7 @@ async def _prepare_inbound_message_text( allowed_root=_msg_cwd, ) if _ctx_result.blocked: - _adapter = self.adapters.get(source.platform) + _adapter = self._adapter_for_source(source) if _adapter: await _adapter.send( source.chat_id, @@ -10246,10 +10786,35 @@ async def _prepare_inbound_message_text( if _ctx_result.expanded: message_text = _ctx_result.message except Exception as exc: - logger.debug("@ context reference expansion failed: %s", exc) + logger.warning("@ context reference expansion failed: %s", exc) + logger.debug("@ context reference expansion failure detail", exc_info=True) return message_text + async def _prepare_profile_scoped_inbound_message_text( + self, + *, + event: MessageEvent, + source: SessionSource, + history: List[Dict[str, Any]], + session_key: Optional[str] = None, + ) -> Optional[str]: + """Run inbound preprocessing under the routed profile when multiplexed.""" + if getattr(getattr(self, "config", None), "multiplex_profiles", False): + with _profile_runtime_scope(self._resolve_profile_home_for_source(source)): + return await self._prepare_inbound_message_text( + event=event, + source=source, + history=history, + session_key=session_key, + ) + return await self._prepare_inbound_message_text( + event=event, + source=source, + history=history, + session_key=session_key, + ) + def _consume_pending_native_image_paths(self, session_key: str) -> List[str]: pending_native = getattr(self, "_pending_native_image_paths_by_session", None) if not pending_native: @@ -10277,6 +10842,15 @@ def _cache_session_source(self, session_key: str, source) -> None: except Exception: pass + @property + def async_session_store(self) -> AsyncSessionStore: + """Return the single async facade for this runner's SessionStore.""" + facade = getattr(self, "_async_session_store", None) + if facade is None or facade._store is not self.session_store: + facade = AsyncSessionStore(self.session_store) + self._async_session_store = facade + return facade + def _get_cached_session_source(self, session_key: str): if not session_key: return None @@ -10320,8 +10894,48 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g except Exception: pass - session_entry = self.session_store.get_or_create_session(source) + session_entry = await self.async_session_store.get_or_create_session(source) session_key = session_entry.session_key + pinned_session_id = str( + (getattr(event, "metadata", None) or {}).get("gateway_session_id") or "" + ).strip() + if pinned_session_id and pinned_session_id != session_entry.session_id: + # Fail closed (#55578): the spawning session may have ENDED since + # dispatch (user /new-reset, compression rotation whose parent was + # closed). switch_session() re-opens ended sessions, so pinning + # blindly would RESURRECT a conversation the user explicitly + # ended and inject into it — the same illicit-revival class as + # the ws_orphan_reap loop (#60609). A completion whose spawning + # session is dead is dropped from injection; the subagent's + # output remains in the delegation records. + pinned_row = None + try: + if self._session_db is not None: + # AsyncSessionDB already offloads to a thread. + pinned_row = await self._session_db.get_session(pinned_session_id) + except Exception: + pinned_row = None + if pinned_row is None or pinned_row.get("ended_at"): + logger.warning( + "Async-delegation completion pinned to session %s, which is " + "%s — dropping injection instead of resurrecting it " + "(#55578 fail-closed; result remains in the delegation " + "records).", + pinned_session_id, + "unknown" if pinned_row is None else "ended", + ) + return + prior_session_id = session_entry.session_id + switched = await self.async_session_store.switch_session(session_key, pinned_session_id) + if switched is not None: + session_entry = switched + logger.info( + "Pinned async-delegation completion to spawning session %s " + "(was %s) for routing key %s (#57498)", + pinned_session_id, + prior_session_id, + session_key, + ) self._cache_session_source(session_key, source) if await asyncio.to_thread(self._is_telegram_topic_lane, source): try: @@ -10362,7 +10976,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g # lane session is ended cleanly. Mutating session_entry in # place here created a split-brain state where the JSON # index pointed at one id but code downstream used another. - switched = self.session_store.switch_session(session_key, bound_session_id) + switched = await self.async_session_store.switch_session(session_key, bound_session_id) if switched is not None: session_entry = switched # If the stored binding pointed at a parent, rewrite it to the @@ -10393,6 +11007,13 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g self._set_session_reasoning_override(session_key, None) if hasattr(self, "_pending_model_notes"): self._pending_model_notes.pop(session_key, None) + # Clear per-session model cache so the fresh session resolves + # from current config, not a stale fallback cached before the + # auto-reset (mirrors /new and the compression-exhausted + # auto-reset, #58403). + _lrm = getattr(self, "_last_resolved_model", None) + if _lrm is not None: + _lrm.pop(session_key, None) # Evict the cached agent so the fresh session does not inherit the # previous conversation's context_compressor._previous_summary — # the cache is keyed on the stable session_key, so an auto-reset @@ -10470,7 +11091,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g and platform_name not in policy.notify_exclude_platforms ) if should_notify: - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter: if reset_reason == "suspended": reason_text = "previous session was stopped or interrupted" @@ -10488,7 +11109,9 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g f"Adjust reset timing in config.yaml under session_reset." ) try: - session_info = self._format_session_info() + session_info = await asyncio.to_thread( + self._reset_notice_session_info, source + ) if session_info: notice = f"{notice}\n\n{session_info}" except Exception: @@ -10541,7 +11164,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g logger.warning("[Gateway] Failed to auto-load skill(s) %s: %s", _skill_names, e) # Load conversation history from transcript - history = self.session_store.load_transcript(session_entry.session_id) + history = await self.async_session_store.load_transcript(session_entry.session_id) # ----------------------------------------------------------------- # Session hygiene: auto-compress pathologically large transcripts @@ -10732,14 +11355,22 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g user_config=_hyg_data if isinstance(_hyg_data, dict) else None, ) if _hyg_runtime.get("api_key"): + # Pass the FULL transcript (tool results included). + # Filtering to user/assistant-only starved the + # compressor: tool results are usually the bulk of + # the context, _prune_old_tool_results never saw + # them, and short filtered histories tripped the + # protect-first/last early-return so nothing was + # compressed at all (#3854). The agent loop passes + # its full message list to _compress_context — the + # gateway now matches. _hyg_msgs = [ - {"role": m.get("role"), "content": m.get("content")} - for m in history - if m.get("role") in {"user", "assistant"} - and m.get("content") + m for m in history + if m.get("role") in {"user", "assistant", "tool"} ] if len(_hyg_msgs) >= 4: + _hyg_session_db = getattr(self._session_db, "_db", self._session_db) _hyg_agent = AIAgent( **_hyg_runtime, model=_hyg_model, @@ -10748,15 +11379,31 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g skip_memory=True, enabled_toolsets=["memory"], session_id=session_entry.session_id, - session_db=getattr(self._session_db, "_db", self._session_db), + session_db=_hyg_session_db, ) try: - # The hygiene agent rotates the session - # forward to a continuation id that becomes - # the gateway session's live row. It must - # never finalize on close() — close() would - # end the newly rotated session the gateway - # entry now points at. + # Gateway hygiene runs before the user turn + # starts and already owns the session binding. + # Prefer in-place compaction here: it archives + # old rows under the same session id instead of + # minting a continuation child that then has to + # be published back to SessionStore/topic + # bindings. If no SessionDB is available, + # compress_context leaves this flag false and + # the guard below preserves the transcript. + _hyg_agent.compression_in_place = True + _bind_hyg_state = getattr( + getattr(_hyg_agent, "context_compressor", None), + "bind_session_state", + None, + ) + if callable(_bind_hyg_state): + _bind_hyg_state( + _hyg_session_db, + session_entry.session_id, + ) + # It must never finalize on close() — close() + # would end the live gateway session row. _hyg_agent._end_session_on_close = False _hyg_agent._print_fn = lambda *a, **kw: None @@ -10780,7 +11427,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g ) if _hyg_rotated: session_entry.session_id = _hyg_new_sid - self.session_store._save() + await self.async_session_store._save() await asyncio.to_thread( self._sync_telegram_topic_binding, source, session_entry, @@ -10788,17 +11435,27 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g ) # Only rewrite the transcript when rotation produced - # a NEW session id OR in-place compaction succeeded. + # a NEW session id. In-place compaction does NOT + # need a rewrite: archive_and_compact() has already + # soft-archived the previous active rows and inserted + # the compacted messages as the new active set inside + # _compress_context(). Calling rewrite_transcript() + # after in-place compaction would invoke + # replace_messages(active_only=False) which DELETEs + # ALL rows — including the archived turns that + # archive_and_compact() deliberately preserved + # (silent data loss, #61145). + # # The danger this guards against (mirrors the - # /compress fix #44794/#39704): the hygiene agent is - # built WITHOUT a session_db, so _compress_context - # cannot rotate — if it also wasn't in-place, the - # session_id is unchanged for a FAILURE reason, and an - # unconditional rewrite_transcript() would DELETE the - # original messages and replace them with only the - # compressed summary (permanent data loss, #21301). - if _hyg_rotated or _hyg_in_place: - self.session_store.rewrite_transcript( + # /compress fix #44794/#39704): if _compress_context + # returns a summary but neither rotates nor completes + # archive_and_compact(), the session_id is unchanged + # for a FAILURE reason, and an unconditional + # rewrite_transcript() would DELETE the original + # messages and replace them with only the compressed + # summary (permanent data loss, #21301). + if _hyg_rotated: + await self.async_session_store.rewrite_transcript( session_entry.session_id, _compressed ) # Reset stored token count — transcript rewritten @@ -10808,6 +11465,16 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g _new_tokens = estimate_messages_tokens_rough( _compressed ) + elif _hyg_in_place: + # archive_and_compact() already persisted the + # compacted transcript inside _compress_context. + # Reset counts to match the new active set. + session_entry.last_prompt_tokens = 0 + history = _compressed + _new_count = len(_compressed) + _new_tokens = estimate_messages_tokens_rough( + _compressed + ) else: # No rewrite happened — transcript preserved # unchanged, so the post-compression counts equal @@ -10858,7 +11525,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g "configuration." ) try: - _adapter = self.adapters.get(source.platform) + _adapter = self._adapter_for_source(source) if _adapter and source.chat_id: await _adapter.send(source.chat_id, _warn_msg, metadata=_hyg_meta) except Exception as _werr: @@ -10882,7 +11549,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g "check `auxiliary.compression.model` in config.yaml." ) try: - _adapter = self.adapters.get(source.platform) + _adapter = self._adapter_for_source(source) if _adapter and source.chat_id: await _adapter.send(source.chat_id, _aux_msg, metadata=_hyg_meta) except Exception as _werr: @@ -10905,7 +11572,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g ) # First-message onboarding -- only on the very first interaction ever - if not history and not self.session_store.has_any_sessions(): + if not history and not await self.async_session_store.has_any_sessions(): # Default first-contact note: a brief self-introduction. _intro_note = ( "\n\n[System note: This is the user's very first message ever. " @@ -10990,10 +11657,11 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g # attachments (documents, audio, etc.) are not sent to the vision # tool even when they appear in the same message. # ----------------------------------------------------------------- - message_text = await self._prepare_inbound_message_text( + message_text = await self._prepare_profile_scoped_inbound_message_text( event=event, source=source, history=history, + session_key=session_key, ) if message_text is None: return @@ -11038,7 +11706,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g # event so deferred post-delivery callbacks can be released by the # same run that registered them. self._bind_adapter_run_generation( - self.adapters.get(source.platform), + self._adapter_for_source(source), session_key, run_generation, ) @@ -11078,7 +11746,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g # Stop persistent typing indicator now that the agent is done try: - _typing_adapter = self.adapters.get(source.platform) + _typing_adapter = self._adapter_for_source(source) if _typing_adapter and hasattr(_typing_adapter, "stop_typing"): await _typing_adapter.stop_typing(source.chat_id) except Exception: @@ -11090,7 +11758,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g _quick_key or "?", run_generation, ) - _stale_adapter = self.adapters.get(source.platform) + _stale_adapter = self._adapter_for_source(source) if getattr(type(_stale_adapter), "pop_post_delivery_callback", None) is not None: _stale_adapter.pop_post_delivery_callback( _quick_key, @@ -11148,7 +11816,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g if session_key and _should_clear_resume_pending_after_turn(agent_result): self._clear_restart_failure_count(session_key) try: - self.session_store.clear_resume_pending(session_key) + await self.async_session_store.clear_resume_pending(session_key) except Exception as _e: logger.debug( "clear_resume_pending failed for %s: %s", @@ -11170,8 +11838,8 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g if agent_result.get("session_id") and agent_result["session_id"] != session_entry.session_id: if session_entry.session_id == _run_start_session_id: session_entry.session_id = agent_result["session_id"] - self.session_store._save() - self.session_store._record_gateway_session_peer( + await self.async_session_store._save() + await self.async_session_store._record_gateway_session_peer( session_entry.session_id, session_key, source, @@ -11369,12 +12037,17 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g "Auto-resetting session %s after compression exhaustion.", session_entry.session_id, ) - new_entry = self.session_store.reset_session(session_key) + new_entry = await self.async_session_store.reset_session(session_key) self._evict_cached_agent(session_key) self._session_model_overrides.pop(session_key, None) self._set_session_reasoning_override(session_key, None) if hasattr(self, "_pending_model_notes"): self._pending_model_notes.pop(session_key, None) + # Clear per-session model cache so the post-reset turn + # resolves from current config, not a stale fallback. + _lrm = getattr(self, "_last_resolved_model", None) + if _lrm is not None: + _lrm.pop(session_key, None) if new_entry is not None: # Drop the stale reference to the bloated compressed child and # re-point the Telegram topic binding at the fresh session. @@ -11408,7 +12081,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g pass # Skip all transcript writes — don't grow a broken session elif not history: tool_defs = agent_result.get("tools", []) - self.session_store.append_to_transcript( + await self.async_session_store.append_to_transcript( session_entry.session_id, { "role": "session_meta", @@ -11462,7 +12135,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g # after transient failures). #47237 _skip_persist = ( event.message_id - and self.session_store.has_platform_message_id( + and await self.async_session_store.has_platform_message_id( session_entry.session_id, str(event.message_id) ) ) @@ -11473,7 +12146,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g event.message_id, session_entry.session_id, ) else: - self.session_store.append_to_transcript( + await self.async_session_store.append_to_transcript( session_entry.session_id, _user_entry, skip_db=agent_persisted, @@ -11499,13 +12172,13 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g } if event.message_id: _user_entry["message_id"] = str(event.message_id) - self.session_store.append_to_transcript( + await self.async_session_store.append_to_transcript( session_entry.session_id, _user_entry, skip_db=agent_persisted, ) if response: - self.session_store.append_to_transcript( + await self.async_session_store.append_to_transcript( session_entry.session_id, {"role": "assistant", "content": response, "timestamp": ts}, skip_db=agent_persisted, @@ -11530,7 +12203,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g ): entry["message_id"] = str(event.message_id) _user_msg_id_attached = True - self.session_store.append_to_transcript( + await self.async_session_store.append_to_transcript( session_entry.session_id, entry, skip_db=agent_persisted, ) @@ -11538,7 +12211,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g # Token counts and model are now persisted by the agent directly. # Keep only last_prompt_tokens here for context-window tracking and # compression decisions. - self.session_store.update_session( + await self.async_session_store.update_session( session_entry.session_key, last_prompt_tokens=agent_result.get("last_prompt_tokens", 0), ) @@ -11595,7 +12268,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g # users see the agent "stop responding without explanation." if agent_result.get("already_sent") and not agent_result.get("failed"): if response: - _media_adapter = self.adapters.get(source.platform) + _media_adapter = self._adapter_for_source(source) if _media_adapter: await self._deliver_media_from_response( response, event, _media_adapter, @@ -11606,7 +12279,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g # still surface the runtime metadata on the final reply. if _footer_line: try: - _foot_adapter = self.adapters.get(source.platform) + _foot_adapter = self._adapter_for_source(source) if _foot_adapter: await _foot_adapter.send( source.chat_id, @@ -11622,7 +12295,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g except Exception as e: # Stop typing indicator on error too try: - _err_adapter = self.adapters.get(source.platform) + _err_adapter = self._adapter_for_source(source) if _err_adapter and hasattr(_err_adapter, "stop_typing"): await _err_adapter.stop_typing(source.chat_id) except Exception: @@ -11638,7 +12311,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g if 'message_text' in locals() and message_text is not None and session_entry is not None: _already_persisted = False try: - _recent_transcript = self.session_store.load_transcript(session_entry.session_id) + _recent_transcript = await self.async_session_store.load_transcript(session_entry.session_id) except Exception: _recent_transcript = [] for _msg in reversed(_recent_transcript[-10:]): @@ -11666,7 +12339,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g } if getattr(event, "message_id", None): _user_entry["message_id"] = str(event.message_id) - self.session_store.append_to_transcript( + await self.async_session_store.append_to_transcript( session_entry.session_id, _user_entry, ) @@ -11724,6 +12397,26 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g # Restore session context variables to their pre-handler state self._clear_session_env(_session_env_tokens) + def _reset_notice_session_info(self, source: SessionSource) -> str: + """Session-info block for the auto-reset notice, profile-scoped. + + When multiplexing, resolve model/provider/context inside the profile + serving ``source`` — otherwise the banner advertises the base config's + model while the session actually runs on the profile's (#59003). + Mirrors ``_run_agent``'s gating so single-profile gateways never + enter the scope. + + Call via ``asyncio.to_thread`` from async handlers: under the scope, + resolution can do blocking work (credential refresh, context-length + HTTP probes) that must not run on the event loop. The scope is entered + inside this method, so contextvars behave correctly in the worker + thread. + """ + if getattr(getattr(self, "config", None), "multiplex_profiles", False): + with _profile_runtime_scope(self._resolve_profile_home_for_source(source)): + return self._format_session_info() + return self._format_session_info() + def _format_session_info(self) -> str: """Resolve current model config and return a formatted info block. @@ -12101,7 +12794,7 @@ def _goal_max_turns_from_config(self) -> int: except Exception: return 20 - def _get_goal_manager_for_event(self, event: "MessageEvent"): + async def _get_goal_manager_for_event(self, event: "MessageEvent"): """Return a GoalManager bound to the session for this gateway event. Returns ``(manager, session_entry)`` or ``(None, None)`` if the @@ -12113,7 +12806,7 @@ def _get_goal_manager_for_event(self, event: "MessageEvent"): logger.debug("goal manager unavailable: %s", exc) return None, None try: - session_entry = self.session_store.get_or_create_session(event.source) + session_entry = await self.async_session_store.get_or_create_session(event.source) except Exception as exc: logger.debug("goal manager: session lookup failed: %s", exc) return None, None @@ -12127,7 +12820,7 @@ def _get_goal_manager_for_event(self, event: "MessageEvent"): async def _send_goal_status_notice(self, source: Any, message: str) -> None: """Send a /goal judge status line back to the originating chat/thread.""" - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if not adapter: logger.debug("goal continuation: no adapter for %s", getattr(source, "platform", None)) return @@ -12154,7 +12847,7 @@ async def _defer_goal_status_notice_after_delivery(self, source: Any, message: s exactly this boundary; when unavailable, fall back to direct awaited delivery rather than silently dropping the notice. """ - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if not adapter: logger.debug("goal continuation: no adapter for %s", getattr(source, "platform", None)) return @@ -12252,7 +12945,7 @@ async def _post_turn_goal_continuation( # Enqueue via the adapter's FIFO so a user message already in # flight preempts the continuation naturally. try: - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) _quick_key = self._session_key_for_source(source) if adapter and _quick_key: cont_event = MessageEvent( @@ -12285,7 +12978,7 @@ def _get_guild_id(event: MessageEvent) -> Optional[int]: async def _handle_voice_channel_join(self, event: MessageEvent) -> str: """Join the user's current Discord voice channel.""" - adapter = self.adapters.get(event.source.platform) + adapter = self._adapter_for_source(event.source) if not hasattr(adapter, "join_voice_channel"): return "Voice channels are not supported on this platform." @@ -12342,7 +13035,7 @@ async def _handle_voice_channel_join(self, event: MessageEvent) -> str: async def _handle_voice_channel_leave(self, event: MessageEvent) -> str: """Leave the Discord voice channel.""" - adapter = self.adapters.get(event.source.platform) + adapter = self._adapter_for_source(event.source) guild_id = self._get_guild_id(event) if not guild_id or not hasattr(adapter, "leave_voice_channel"): @@ -12536,6 +13229,10 @@ def _should_send_voice_reply( return True + def _should_echo_stt_transcripts(self) -> bool: + """Return whether inbound voice/STT transcripts should be echoed to chat.""" + return bool(getattr(self.config, "stt_echo_transcripts", True)) + async def _send_voice_reply(self, event: MessageEvent, text: str) -> None: """Generate TTS audio and send as a voice message before the text reply.""" import uuid as _uuid @@ -12572,7 +13269,7 @@ async def _send_voice_reply(self, event: MessageEvent, text: str) -> None: logger.warning("Auto voice reply TTS failed: %s", result.get("error")) return - adapter = self.adapters.get(event.source.platform) + adapter = self._adapter_for_source(event.source) # If connected to a voice channel, play there instead of sending a file guild_id = self._get_guild_id(event) @@ -12750,7 +13447,7 @@ async def _run_background_task( media_urls = media_urls or [] media_types = media_types or [] - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if not adapter: logger.warning("No adapter for platform %s in background task %s", source.platform, task_id) return @@ -12830,7 +13527,8 @@ def run_sync(): chat_type=source.chat_type, thread_id=source.thread_id, session_db=getattr(self._session_db, "_db", self._session_db), - fallback_model=self._fallback_model, + # Reload from disk — do not reuse the startup snapshot (#60955). + fallback_model=self._refresh_fallback_model(), ) try: return agent.run_conversation( @@ -12945,7 +13643,7 @@ def run_sync(): async def _get_telegram_topic_capabilities(self, source: SessionSource) -> dict: """Read Telegram private-topic capability flags via Bot API getMe.""" - adapter = self.adapters.get(source.platform) if getattr(self, "adapters", None) else None + adapter = self._adapter_for_source(source) bot = getattr(adapter, "_bot", None) if bot is None or not hasattr(bot, "get_me"): return {"checked": False} @@ -12973,7 +13671,7 @@ def _field(name: str): async def _ensure_telegram_system_topic(self, source: SessionSource) -> None: """Create/pin the managed System topic after /topic activation when possible.""" - adapter = self.adapters.get(source.platform) if getattr(self, "adapters", None) else None + adapter = self._adapter_for_source(source) if adapter is None or not source.chat_id: return @@ -13014,7 +13712,7 @@ async def _ensure_telegram_system_topic(self, source: SessionSource) -> None: async def _send_telegram_topic_setup_image(self, source: SessionSource) -> None: """Send the bundled BotFather Threads Settings screenshot when available.""" - adapter = self.adapters.get(source.platform) if getattr(self, "adapters", None) else None + adapter = self._adapter_for_source(source) if adapter is None or not source.chat_id or not hasattr(adapter, "send_image_file"): return image_path = Path(__file__).resolve().parent / "assets" / "telegram-botfather-threads-settings.jpg" @@ -13041,6 +13739,91 @@ def _sanitize_telegram_topic_title(self, title: str) -> str: cleaned = cleaned[:117].rstrip() + "..." return cleaned + def _is_discord_auto_thread_lane(self, source: SessionSource) -> bool: + """Return True only for Discord threads Hermes just auto-created.""" + return ( + source.platform == Platform.DISCORD + and source.chat_type == "thread" + and bool(getattr(source, "auto_thread_created", False)) + and bool(source.thread_id) + and bool(getattr(source, "auto_thread_initial_name", None)) + ) + + def _sanitize_discord_thread_title(self, title: str) -> str: + """Return a Discord-safe semantic thread title from a session title. + + Discord thread names are capped at 100 characters measured in UTF-16 + code units (emoji count double), so truncate with the UTF-16 helpers + rather than Python code-point slices. + """ + cleaned = re.sub(r"\s+", " ", str(title or "")).strip() + if not cleaned: + return "Hermes Chat" + if utf16_len(cleaned) > 80: + cleaned = _prefix_within_utf16_limit(cleaned, 77).rstrip() + "..." + return cleaned + + async def _rename_discord_auto_thread_for_session_title( + self, + source: SessionSource, + session_id: str, + title: str, + ) -> None: + """Best-effort semantic rename of a newly auto-created Discord thread.""" + if not await asyncio.to_thread(self._is_discord_auto_thread_lane, source): + return + adapter = self.adapters.get(source.platform) if getattr(self, "adapters", None) else None + if adapter is None: + return + rename_thread = getattr(adapter, "rename_thread", None) + if rename_thread is None: + return + thread_name = self._sanitize_discord_thread_title(title) + try: + await rename_thread( + str(source.thread_id), + thread_name, + only_if_current_name=getattr(source, "auto_thread_initial_name", None), + ) + except Exception: + logger.debug("Failed to rename Discord auto-thread for generated session title", exc_info=True) + + def _schedule_discord_semantic_thread_rename( + self, + source: SessionSource, + session_id: str, + title: str, + ) -> None: + """Schedule Discord auto-thread rename from the auto-title background thread.""" + if not title or not self._is_discord_auto_thread_lane(source): + return + try: + loop = asyncio.get_running_loop() + except RuntimeError: + loop = getattr(self, "_gateway_loop", None) + if loop is None or loop.is_closed(): + return + try: + copied_source = dataclasses.replace(source) + except Exception: + copied_source = source + future = safe_schedule_threadsafe( + self._rename_discord_auto_thread_for_session_title(copied_source, session_id, title), + loop, + logger=logger, + log_message="Discord semantic thread rename failed to schedule", + ) + if future is None: + return + + def _log_rename_failure(fut) -> None: + try: + fut.result() + except Exception: + logger.debug("Discord semantic thread rename failed", exc_info=True) + + future.add_done_callback(_log_rename_failure) + async def _rename_telegram_topic_for_session_title( self, source: SessionSource, @@ -13066,7 +13849,7 @@ async def _rename_telegram_topic_for_session_title( # Check the class, not the instance — getattr() on MagicMock # auto-creates attributes, so `hasattr(adapter, "_get_dm_topic_info")` # would return True for every test double. - adapter = self.adapters.get(source.platform) if getattr(self, "adapters", None) else None + adapter = self._adapter_for_source(source) if adapter is not None: get_info = getattr(type(adapter), "_get_dm_topic_info", None) if callable(get_info): @@ -13466,8 +14249,8 @@ async def _execute_mcp_reload(self, event: MessageEvent) -> str: "content": f"[IMPORTANT: MCP servers have been reloaded. {change_detail}{tool_summary}. The tool list for this conversation has been updated accordingly.]", } try: - session_entry = self.session_store.get_or_create_session(event.source) - self.session_store.append_to_transcript( + session_entry = await self.async_session_store.get_or_create_session(event.source) + await self.async_session_store.append_to_transcript( session_entry.session_id, reload_msg ) except Exception: @@ -13625,7 +14408,7 @@ async def _request_slash_confirm( # cannot race the send_slash_confirm return. _slash_confirm_mod.register(session_key, confirm_id, command, handler) - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) metadata = self._thread_metadata_for_source(source, self._reply_anchor_for_event(event)) used_buttons = False @@ -14376,25 +15159,62 @@ def _shutdown_executor(self) -> None: except TypeError: executor.shutdown(wait=False) - def _decide_image_input_mode(self) -> str: - """Resolve the image-input routing for the currently active model. + def _decide_image_input_mode( + self, + *, + source: Optional[SessionSource] = None, + session_key: Optional[str] = None, + user_config: Optional[dict] = None, + provider: Optional[str] = None, + model: Optional[str] = None, + ) -> str: + """Resolve image-input routing for the effective model this turn. Returns ``"native"`` (attach pixels on the user turn) or ``"text"`` (pre-analyze with vision_analyze and prepend the description). See agent/image_routing.py for the full decision table. - The active provider/model are read from config.yaml so the decision - tracks ``/model`` switches automatically on the next message. + Gateway sessions can have /model overrides that live outside + config.yaml. Image preprocessing runs before AIAgent sets the + auxiliary_client runtime globals, so resolve the same per-session + runtime bundle the upcoming agent turn will use instead of consulting + only the persisted default model. """ try: from agent.image_routing import decide_image_input_mode from agent.auxiliary_client import _read_main_model, _read_main_provider from hermes_cli.config import load_config - cfg = load_config() - provider = _read_main_provider() - model = _read_main_model() - return decide_image_input_mode(provider, model, cfg) + cfg = user_config if isinstance(user_config, dict) else load_config() + resolved_provider = (provider or "").strip() + resolved_model = (model or "").strip() + + needs_session_runtime = not resolved_provider or not resolved_model + has_session_identity = source is not None or session_key + if needs_session_runtime and has_session_identity: + try: + turn_model, runtime_kwargs = self._resolve_session_agent_runtime( + source=source, + session_key=session_key, + user_config=cfg, + ) + if not resolved_model and isinstance(turn_model, str): + resolved_model = turn_model.strip() + runtime_provider = runtime_kwargs.get("provider") if isinstance(runtime_kwargs, dict) else None + if not resolved_provider and isinstance(runtime_provider, str): + resolved_provider = runtime_provider.strip() + except Exception as exc: + logger.debug( + "image_routing: session runtime resolution failed, falling back to config — %s", + exc, + ) + + if not resolved_provider: + resolved_provider = _read_main_provider() + if not resolved_model: + resolved_model = _read_main_model() + + return decide_image_input_mode(resolved_provider, resolved_model, cfg) except Exception as exc: logger.debug("image_routing: decision failed, falling back to text — %s", exc) return "text" @@ -14599,10 +15419,10 @@ async def _dequeue_pending_with_transcription( enriched_text, successful_transcripts = await self._enrich_message_with_transcription( text, audio_paths, ) - # Echo raw transcripts back to the user so voice interrupts - # feel identical to fresh voice messages. - if successful_transcripts: - echo_adapter = self.adapters.get(source.platform) + # Echo raw transcripts back to the user when configured so voice + # interrupts feel identical to fresh voice messages. + if successful_transcripts and self._should_echo_stt_transcripts(): + echo_adapter = self._adapter_for_source(source) echo_meta = {"thread_id": source.thread_id} if source.thread_id else None if echo_adapter: for tx in successful_transcripts: @@ -14664,6 +15484,13 @@ def _build_process_event_source(self, evt: dict): chat_type = str(evt.get("chat_type") or derived_chat_type or "").strip().lower() chat_id = str(evt.get("chat_id") or derived_chat_id or "").strip() if not platform_name or not chat_type or not chat_id: + logger.warning( + "Synthetic event source unresolvable: " + "session_key=%r platform=%r chat_type=%r chat_id=%r " + "evt_type=%s", + session_key, platform_name, chat_type, chat_id, + evt.get("type", "?"), + ) return None try: @@ -14694,11 +15521,17 @@ def _build_process_event_source(self, evt: dict): user_name=str(evt.get("user_name") or "").strip() or None, ) - async def _inject_watch_notification(self, synth_text: str, evt: dict) -> None: - """Inject a watch-pattern notification as a synthetic message event. + async def _inject_watch_notification( + self, synth_text: str, evt: dict, + ) -> Optional[bool]: + """Inject a watch/completion notification as a synthetic message event. - Routing must come from the queued watch event itself, not from whatever + Routing must come from the queued event itself, not from whatever foreground message happened to be active when the queue was drained. + Returns ``True`` after adapter acceptance, ``False`` after a retryable + adapter failure, and ``None`` when the event has no gateway route. This + is not a transactional boundary: a process crash after adapter + acceptance can still cause durable at-least-once replay. """ source = self._build_process_event_source(evt) if not source: @@ -14706,7 +15539,7 @@ async def _inject_watch_notification(self, synth_text: str, evt: dict) -> None: "Dropping watch notification with no routing metadata for process %s", evt.get("session_id", "unknown"), ) - return + return None platform_name = source.platform.value if hasattr(source.platform, "value") else str(source.platform) adapter = None for p, a in self.adapters.items(): @@ -14714,14 +15547,19 @@ async def _inject_watch_notification(self, synth_text: str, evt: dict) -> None: adapter = a break if not adapter: - return + return None try: + metadata = {} + parent_session_id = str(evt.get("parent_session_id") or "").strip() + if parent_session_id: + metadata["gateway_session_id"] = parent_session_id synth_event = MessageEvent( text=synth_text, message_type=MessageType.TEXT, source=source, internal=True, message_id=str(evt.get("message_id") or "").strip() or None, + metadata=metadata, ) logger.info( "Watch pattern notification — injecting for %s chat=%s thread=%s", @@ -14730,8 +15568,118 @@ async def _inject_watch_notification(self, synth_text: str, evt: dict) -> None: source.thread_id, ) await adapter.handle_message(synth_event) + return True except Exception as e: logger.error("Watch notification injection error: %s", e) + return False + + @staticmethod + def _completion_delivery_identity(evt: dict) -> Optional[tuple[str, str, object]]: + """Return a producer-stable identity when one is available. + + Delegation UUIDs identify one producer completion. Process session IDs + are normally unique too, but include the persisted spawn epoch so an + explicitly reused ID represents a distinct process incarnation. Legacy + process events without ``started_at`` are delivered without deduplication + rather than risking suppression of a real completion. + """ + evt_type = str(evt.get("type") or "") + if evt_type == "async_delegation": + producer_id = str(evt.get("delegation_id") or "") + return (evt_type, producer_id, "") if producer_id else None + if evt_type == "completion": + producer_id = str(evt.get("session_id") or "") + started_at = evt.get("started_at") + if producer_id and started_at is not None: + return (evt_type, producer_id, started_at) + return None + + async def _deliver_completion_notification( + self, synth_text: str, evt: dict, + ) -> Optional[bool]: + """Deliver once per live gateway, or return False for a retry. + + ``True`` means this caller reached adapter acceptance, ``False`` means + injection failed and the claim was released for retry, and ``None`` + means either another same-lifecycle caller owns/delivered the producer + event or the event has no gateway route. No cross-process exactly-once + guarantee is claimed. + """ + identity = self._completion_delivery_identity(evt) + durable_claim_id = "" + durable_delegation_id = "" + if evt.get("type") == "async_delegation": + durable_delegation_id = str(evt.get("delegation_id") or "") + if durable_delegation_id: + try: + from tools.async_delegation import claim_completion_delivery + + durable_claim_id = f"gateway:{id(self)}:{__import__('uuid').uuid4().hex}" + if not claim_completion_delivery( + durable_delegation_id, durable_claim_id, + ): + return None + except Exception as exc: + logger.warning( + "Could not claim durable async completion %s: %s", + durable_delegation_id, exc, + ) + return False + if identity is not None: + with self._completion_delivery_lock: + if ( + identity in self._completion_deliveries_inflight + or identity in self._completion_deliveries_delivered + ): + return None + self._completion_deliveries_inflight.add(identity) + + accepted = False + try: + injection_result = await self._inject_watch_notification(synth_text, evt) + if injection_result is not True: + return injection_result + accepted = True + + if identity is not None: + with self._completion_delivery_lock: + self._completion_deliveries_inflight.discard(identity) + self._completion_deliveries_delivered[identity] = None + while ( + len(self._completion_deliveries_delivered) + > self._completion_delivery_retention + ): + self._completion_deliveries_delivered.popitem(last=False) + + # If the durable async-delegation producer branch is present, its + # SQLite row remains the authoritative replay state. Acknowledge it + # after adapter acceptance; this gateway keeps no parallel ledger. + if durable_claim_id: + try: + from tools.async_delegation import complete_completion_delivery + + complete_completion_delivery( + durable_delegation_id, durable_claim_id, + ) + except Exception as exc: + logger.warning( + "Could not acknowledge durable async completion %s: %s", + durable_delegation_id, exc, + ) + return True + finally: + if identity is not None and not accepted: + with self._completion_delivery_lock: + self._completion_deliveries_inflight.discard(identity) + if durable_claim_id and not accepted: + try: + from tools.async_delegation import release_completion_delivery + + release_completion_delivery( + durable_delegation_id, durable_claim_id, + ) + except Exception: + logger.debug("Could not release durable completion claim", exc_info=True) def _enrich_async_delegation_routing(self, evt: dict) -> None: """Fill platform/chat_id/thread_id/chat_type on an async-delegation event. @@ -14794,8 +15742,11 @@ async def _async_delegation_watcher(self, interval: float = 2.0) -> None: if not synth_text: continue try: - await self._inject_watch_notification(synth_text, evt) + delivered = await self._deliver_completion_notification(synth_text, evt) + if delivered is False: + _pr.completion_queue.put(evt) except Exception as e: + _pr.completion_queue.put(evt) logger.error("Async delegation injection error: %s", e) except Exception as e: logger.debug("Async delegation watcher error: %s", e) @@ -14861,8 +15812,12 @@ async def _run_process_watcher(self, watcher: dict) -> None: # (#10156) — a status check must not suppress this delivery turn. from tools.process_registry import format_process_notification, process_registry as _pr_check if agent_notify and not _pr_check.is_completion_consumed(session_id): + from agent.redact import redact_terminal_output from tools.ansi_strip import strip_ansi + _command = getattr(session, "command", "") or "" _raw = strip_ansi(session.output_buffer) if session.output_buffer else "" + _raw = redact_terminal_output(_raw, _command) + _command = _redact_gateway_user_facing_secrets(_command) # Truncate at line boundaries so notifications never start # mid-line (fixes #23284). Keep the last ~2000 chars but # snap to the nearest preceding newline, then prepend a @@ -14875,57 +15830,34 @@ async def _run_process_watcher(self, watcher: dict) -> None: _out = f"[… output truncated — showing last {len(_tail)} chars]\n{_tail}" else: _out = _raw - synth_text = format_process_notification({ + completion_evt = { "type": "completion", - "session_id": session_id, - "command": session.command, - "exit_code": session.exit_code, - "completion_reason": getattr(session, "completion_reason", "exited"), - "termination_source": getattr(session, "termination_source", ""), - "output": _out, - }) - if not synth_text: - break - source = self._build_process_event_source({ "session_id": session_id, "session_key": session_key, "platform": platform_name, + "chat_type": watcher.get("chat_type", ""), "chat_id": chat_id, "thread_id": thread_id, "user_id": user_id, "user_name": user_name, - }) - if not source: - logger.warning( - "Dropping completion notification with no routing metadata for process %s", - session_id, - ) + "message_id": message_id, + "started_at": getattr(session, "started_at", None), + "command": _command, + "exit_code": session.exit_code, + "completion_reason": getattr(session, "completion_reason", "exited"), + "termination_source": getattr(session, "termination_source", ""), + "output": _out, + } + synth_text = format_process_notification(completion_evt) + if not synth_text: break - - adapter = None - for p, a in self.adapters.items(): - if p == source.platform: - adapter = a - break - if adapter and source.chat_id: - try: - synth_event = MessageEvent( - text=synth_text, - message_type=MessageType.TEXT, - source=source, - internal=True, - message_id=message_id, - ) - logger.info( - "Process %s finished — injecting agent notification for session %s chat=%s thread=%s", - session_id, - session_key, - source.chat_id, - source.thread_id, - ) - await adapter.handle_message(synth_event) - except Exception as e: - logger.error("Agent notify injection error: %s", e) + delivered = await self._deliver_completion_notification( + synth_text, completion_evt, + ) + if delivered is False: + # The process remains terminal; retry after failed + # adapter injection instead of suppressing the result. + continue break # --- Normal text-only notification --- @@ -15008,6 +15940,8 @@ async def _run_process_watcher(self, watcher: dict) -> None: ("model", "max_tokens"), ("compression", "enabled"), ("compression", "threshold"), + ("compression", "codex_gpt55_autoraise"), + ("compression", "codex_app_server_auto"), ("compression", "target_ratio"), ("compression", "protect_last_n"), ("agent", "disabled_toolsets"), @@ -15207,6 +16141,7 @@ def _rehydrate_session_model_override(self, session_key: str) -> None: runtime = _resolve_runtime_agent_kwargs_for_provider(provider) override["api_key"] = runtime.get("api_key") override["api_mode"] = runtime.get("api_mode") + override["credential_pool"] = runtime.get("credential_pool") if not override.get("base_url"): override["base_url"] = runtime.get("base_url") except Exception: @@ -15236,10 +16171,18 @@ def _apply_session_model_override( if not override: return model, runtime_kwargs model = override.get("model", model) - for key in ("provider", "api_key", "base_url", "api_mode"): + for key in ("provider", "api_key", "base_url", "api_mode", "credential_pool"): val = override.get(key) if val is not None: runtime_kwargs[key] = val + if ( + runtime_kwargs.get("api_key") + and runtime_kwargs.get("credential_pool") is None + and override.get("provider") + ): + runtime_kwargs["credential_pool"] = _credential_pool_for_provider( + override.get("provider") + ) return model, runtime_kwargs def _is_intentional_model_switch(self, session_key: str, agent_model: str) -> bool: @@ -15415,7 +16358,7 @@ async def _interrupt_and_clear_session( if running_agent and running_agent is not _AGENT_PENDING_SENTINEL: running_agent.interrupt(interrupt_reason) self._invalidate_session_run_generation(session_key, reason=invalidation_reason) - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter and hasattr(adapter, "interrupt_session_activity"): await adapter.interrupt_session_activity(session_key, source.chat_id) if adapter and hasattr(adapter, "get_pending_message"): @@ -15423,6 +16366,16 @@ async def _interrupt_and_clear_session( self._pending_messages.pop(session_key, None) if release_running_state: self._release_running_agent_state(session_key) + # Evict the cached agent: ``_interrupt_requested`` is only + # cleared by the turn finalizer, so on a hung or still-draining + # run the flag survives the lock release and kills the session's + # NEXT message at the top of the tool loop (interrupted=True, + # api_calls=0, empty response — silently swallowed, #44212). + # Evicting mirrors the /new and /model paths: the next message + # rebuilds the agent from session history, while the old agent + # object keeps its interrupt flag so a hung drain still dies + # when it unblocks. + self._evict_cached_agent(session_key) async def _refresh_agent_cache_message_count( self, session_key: str, session_id: Optional[str] @@ -15586,6 +16539,72 @@ def _init_cached_agent_for_turn(agent: Any, interrupt_depth: int) -> None: agent._last_flushed_db_idx = 0 agent._api_call_count = 0 + def _commit_memory_before_soft_evict(self, agent: Any, key: str) -> None: + """Fire on_session_end extraction before soft-evicting a live agent. + + Soft eviction (``_release_evicted_agent_soft``) deliberately keeps the + session resumable and does NOT fire ``on_session_end`` — that hook is + reserved for the true session boundary, tear-down done by + ``_session_expiry_watcher`` when the session finally expires. + + But the watcher tears down whatever agent it finds in ``_agent_cache`` + at expiry time. If cache pressure (the LRU cap) soft-evicts a + finalizable session's agent BEFORE it expires, the watcher later finds + no cached agent and ``on_session_end`` is silently skipped — memory + providers never see the transcript (#11205, LRU-cap variant). + + We hold the live, fully-scoped agent right now, so commit its + end-of-session memory extraction here using the agent's own memory + manager (correct per-user/chat scoping, no reconstruction). This uses + ``commit_memory_session`` — extraction WITHOUT provider teardown — so + the eviction stays soft and a resumed turn keeps working. + + Only fires for sessions the expiry watcher will eventually finalize + (finite reset policy). For ``mode == "none"`` sessions the watcher + never runs, so there is no missed-boundary to compensate for and we + skip the commit (the agent is simply released). Best-effort: any + failure is swallowed so eviction still proceeds. + """ + if agent is None or not hasattr(agent, "commit_memory_session"): + return + if getattr(agent, "_memory_manager", None) is None: + return # no external memory provider — nothing to commit + try: + _store = getattr(self, "session_store", None) + if _store is None: + return + _store._ensure_loaded() + entry = _store._entries.get(key) + if entry is None: + return + # Only compensate when the watcher would otherwise expect to find + # this agent at expiry (finite policy, not yet expired). Expired + # sessions are torn down by the watcher directly; mode="none" + # sessions are never finalized. + if not _store.is_session_finalizable(entry): + return + if _store._is_session_expired(entry): + return + messages = getattr(agent, "_session_messages", None) + agent.commit_memory_session(messages if isinstance(messages, list) else None) + logger.debug( + "Committed on_session_end extraction before soft-evicting " + "finalizable session=%s (cache pressure, pre-expiry)", key, + ) + except Exception as _e: + logger.debug("Pre-evict memory commit failed for %s: %s", key, _e) + + def _commit_then_release_soft(self, agent: Any, key: str) -> None: + """Commit end-of-session memory (if warranted), then soft-release. + + Runs on the daemon eviction thread so the memory-provider call and the + client teardown never block the caller's held cache lock. Order matters: + commit uses the live agent's memory manager before ``release_clients`` + drops the message buffer. + """ + self._commit_memory_before_soft_evict(agent, key) + self._release_evicted_agent_soft(agent) + def _release_evicted_agent_soft(self, agent: Any) -> None: """Soft cleanup for cache-evicted agents — preserves session tool state. @@ -15684,9 +16703,15 @@ def _enforce_agent_cache_cap(self) -> None: key, len(_cache), ) if agent is not None: + # Commit end-of-session memory extraction, then soft-release, + # both on the daemon thread so the (possibly network-bound) + # provider call never blocks the held cache lock. The commit + # only fires for finalizable-not-yet-expired sessions whose + # agent would otherwise vanish before the expiry watcher can + # fire on_session_end (#11205, LRU-cap variant). threading.Thread( - target=self._release_evicted_agent_soft, - args=(agent,), + target=self._commit_then_release_soft, + args=(agent, key), daemon=True, name=f"agent-cache-evict-{key[:24]}", ).start() @@ -15724,6 +16749,45 @@ def _sweep_idle_cached_agents(self) -> int: if last_activity is None: continue if (now - last_activity) > _AGENT_CACHE_IDLE_TTL_SECS: + # Check whether the session has actually expired in the + # session store. If it hasn't (e.g. daily-reset mode + # where the reset fires hours after the user's last + # message), keep the agent in cache so the session-store + # expiry watcher can still find it and call + # on_session_end() with the live transcript. Skipping + # eviction here means the agent stays alive until the + # session genuinely expires, at which point the watcher + # (gateway/run.py _session_expiry_watcher) tears it down + # properly. (#11205 follow-up) + # + # BUT only defer when the watcher will EVER finalize this + # session. For a mode == "none" session the watcher never + # fires (is_session_finalizable() is False), so deferring + # would pin the agent in cache for the gateway's entire + # lifetime — the exact leak this idle sweep exists to + # relieve. Those sessions fall through to soft eviction + # WITHOUT on_session_end, and that is correct: a mode=="none" + # session never reaches a session-end boundary, so there is + # no missed on_session_end to compensate for. (The finite + # case — a session evicted under LRU-cap pressure before it + # expires — is instead covered by _commit_memory_before_soft_ + # evict on the cap path, which fires on_session_end via the + # live agent's memory manager before releasing it.) + session_entry = None + _store = getattr(self, "session_store", None) + try: + if _store is not None: + _store._ensure_loaded() + session_entry = _store._entries.get(key) + except Exception: + session_entry = None + if ( + session_entry is not None + and _store is not None + and _store.is_session_finalizable(session_entry) + and not _store._is_session_expired(session_entry) + ): + continue # keep agent — finite session hasn't expired to_evict.append((key, agent)) for key, _ in to_evict: _cache.pop(key, None) @@ -15754,7 +16818,8 @@ def _get_proxy_url(self) -> Optional[str]: if url: return url.rstrip("/") cfg = _load_gateway_config() - url = (cfg.get("gateway") or {}).get("proxy_url", "").strip() + url = (cfg.get("gateway") or {}).get("proxy_url") + url = (url or "").strip() if url: return url.rstrip("/") return None @@ -15869,7 +16934,7 @@ def _run_still_current() -> bool: if _streaming_enabled: try: from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfig - _adapter = self.adapters.get(source.platform) + _adapter = self._adapter_for_source(source) if _adapter: _pause_typing_before_finalize = None if source.platform == Platform.TELEGRAM and hasattr(_adapter, "pause_typing_for_chat"): @@ -15920,7 +16985,7 @@ def _pause_typing_before_finalize( stream_task = asyncio.create_task(_stream_consumer.run()) # Send typing indicator - _adapter = self.adapters.get(source.platform) + _adapter = self._adapter_for_source(source) if _adapter: try: await _adapter.send_typing(source.chat_id, metadata=_thread_metadata) @@ -15995,6 +17060,10 @@ def _pause_typing_before_finalize( _stream_consumer.on_delta(content) except json.JSONDecodeError: pass + if len(buffer) > _GATEWAY_PROXY_SSE_BUFFER_MAX_CHARS: + raise ValueError( + "Proxy SSE stream exceeded max buffer size without a line boundary" + ) except asyncio.CancelledError: raise @@ -16222,6 +17291,47 @@ def _run_still_current() -> bool: ) # Tool progress grouping: "accumulate" (edit one bubble) or "separate" (one msg per tool) progress_grouping = resolve_display_setting(user_config, platform_key, "tool_progress_grouping") or "accumulate" + from gateway.status_phrases import choose_status_phrase, resolve_status_phrase_catalog + _generic_status_recent: List[str] = [] + _generic_status_catalog = resolve_status_phrase_catalog(user_config, platform_key) + + def _display_surface_mode( + setting: str, + *, + default: bool = False, + require_platform_override_for: set[Any] | None = None, + allow_generic: bool = False, + ) -> str: + """Return off|raw|generic for a gateway visibility surface.""" + if require_platform_override_for: + current_platform = _gateway_platform_value(source.platform) + platform_only = { + _gateway_platform_value(item) + for item in require_platform_override_for + } + if ( + current_platform in platform_only + and not _has_platform_display_override(user_config, platform_key, setting) + ): + return "off" + value = resolve_display_setting(user_config, platform_key, setting, default) + if isinstance(value, str) and value.strip().lower() == "generic": + return "generic" if allow_generic else "off" + return "raw" if bool(value) else "off" + + def _generic_status_phrase(kind: str, *, tool_name: str | None = None, preview: str | None = None, args: Any = None) -> str: + try: + return choose_status_phrase( + kind, + tool_name=tool_name, + preview=preview, + args=args, + recent=_generic_status_recent, + catalog=_generic_status_catalog, + ) + except Exception as _phrase_err: + logger.debug("generic status phrase selection failed: %s", _phrase_err) + return "still on it" if kind in {"heartbeat", "waiting", "long_running", "status"} else "one sec" # Disable tool progress for webhooks - they don't support message editing, # so each progress line would be sent as a separate message. from gateway.config import Platform @@ -16233,29 +17343,25 @@ def _run_still_current() -> bool: # Natural assistant status messages are intentionally independent from # tool progress and token streaming. Users can keep tool_progress quiet # in chat platforms while opting into concise mid-turn updates. + interim_assistant_messages_mode = _display_surface_mode( + "interim_assistant_messages", + default=True, + require_platform_override_for={Platform.MATTERMOST}, + ) interim_assistant_messages_enabled = ( source.platform != Platform.WEBHOOK - and _resolve_gateway_display_bool( - user_config, - platform_key, - "interim_assistant_messages", - default=True, - platform=source.platform, - require_platform_override_for={Platform.MATTERMOST}, - ) + and interim_assistant_messages_mode != "off" ) # thinking_progress is independent — if enabled, we need the progress # queue even when tool_progress is off (thinking relay uses same infra). # Mattermost requires a per-platform opt-in: global scratch-text display # is too easy to leak into busy public threads. - _thinking_enabled = _resolve_gateway_display_bool( - user_config, - platform_key, + _thinking_mode = _display_surface_mode( "thinking_progress", default=False, - platform=source.platform, require_platform_override_for={Platform.MATTERMOST}, ) + _thinking_enabled = _thinking_mode != "off" needs_progress_queue = tool_progress_enabled or _thinking_enabled @@ -16319,7 +17425,7 @@ def voice_ack_callback(call_id, tool_name, args): _cleanup_progress = bool( resolve_display_setting(user_config, platform_key, "cleanup_progress") ) - _cleanup_adapter = self.adapters.get(source.platform) if _cleanup_progress else None + _cleanup_adapter = self._adapter_for_source(source) if _cleanup_progress else None if _cleanup_adapter is not None and ( type(_cleanup_adapter).delete_message is BasePlatformAdapter.delete_message ): @@ -16419,7 +17525,7 @@ def progress_callback(event_type: str, tool_name: str = None, preview: str = Non if progress_mode == "new" and tool_name == last_tool[0]: return last_tool[0] = tool_name - + # Build progress message with primary argument preview from agent.display import get_tool_emoji emoji = get_tool_emoji(tool_name, default="⚙️") @@ -16440,7 +17546,7 @@ def progress_callback(event_type: str, tool_name: str = None, preview: str = Non _code_block_full = None _code_block_short = None try: - _progress_adapter = self.adapters.get(source.platform) + _progress_adapter = self._adapter_for_source(source) except Exception: _progress_adapter = None if ( @@ -16630,7 +17736,7 @@ async def send_progress_messages(): if not progress_queue: return - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if not adapter: return @@ -17005,7 +18111,7 @@ def _event_callback_sync(event_type: str, context: dict) -> None: logger.debug("event_callback hook error: %s", _e) # Bridge sync status_callback → async adapter.send for context pressure - _status_adapter = self.adapters.get(source.platform) + _status_adapter = self._adapter_for_source(source) _status_chat_id = source.chat_id if source.platform == Platform.FEISHU and source.thread_id and event_message_id: # Feishu topics only keep messages inside the topic when they are @@ -17151,7 +18257,7 @@ def run_sync(): if _want_stream_deltas or _want_interim_consumer: try: from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfig - _adapter = self.adapters.get(source.platform) + _adapter = self._adapter_for_source(source) if _adapter: _pause_typing_before_finalize = None if source.platform == Platform.TELEGRAM and hasattr(_adapter, "pause_typing_for_chat"): @@ -17219,18 +18325,19 @@ def _stream_delta_cb(text: str) -> None: def _interim_assistant_cb(text: str, *, already_streamed: bool = False) -> None: if not _run_still_current(): return + display_text = text if _stream_consumer is not None: if already_streamed: _stream_consumer.on_segment_break() else: - _stream_consumer.on_commentary(text) + _stream_consumer.on_commentary(display_text) return - if already_streamed or not _status_adapter or not str(text or "").strip(): + if already_streamed or not _status_adapter or not str(display_text or "").strip(): return safe_schedule_threadsafe( _status_adapter.send( _status_chat_id, - text, + display_text, metadata=_status_thread_metadata, ), _loop_for_step, @@ -17343,6 +18450,18 @@ def _interim_assistant_cb(text: str, *, already_streamed: bool = False) -> None: logger.debug("Reusing cached agent for session %s", session_key) reused_cached_agent = True + # Lock released — refresh the fallback chain from disk for the + # reused agent OUTSIDE the cache lock (config.yaml read is disk + # I/O; the idle-sweep watcher contends on this lock and stalls + # Discord heartbeats — same reasoning as #52197). A chain + # configured after this agent was cached (or after gateway start) + # must reach the next turn (#60955). Per-session turn + # serialization (_running_agents) keeps this safe post-lock. + if reused_cached_agent and agent is not None: + self._apply_fallback_chain_to_agent( + agent, self._refresh_fallback_model(), + ) + # Lock released — now schedule cleanup of any cross-process-evicted # agent on a daemon thread so memory-provider shutdown / socket # teardown never blocks the gateway event loop or the cache lock @@ -17395,7 +18514,8 @@ def _interim_assistant_cb(text: str, *, already_streamed: bool = False) -> None: thread_id=source.thread_id, gateway_session_key=session_key, session_db=getattr(self._session_db, "_db", self._session_db), - fallback_model=self._fallback_model, + # Reload from disk — do not reuse the startup snapshot (#60955). + fallback_model=self._refresh_fallback_model(), ) if _cache_lock and _cache is not None: with _cache_lock: @@ -17650,7 +18770,15 @@ def _clarify_callback_sync(question: str, choices) -> str: "conversation context (possible FTS write corruption)", session_key, len(agent_history), len(_selected), ) - agent_history = _selected + # The live in-memory history bypassed the + # _build_gateway_agent_history cleanup pipeline above — + # re-apply the stale-confirmation expiry (#59607) so a + # dangerous confirmation can't slip through this path + # either. Idempotent; messages without timestamps are + # untouched. + agent_history = _strip_stale_dangerous_confirmations( + _selected, now=time.time() + ) # Collect MEDIA paths already in history so we can exclude them # from the current turn's extraction. This is compression-safe: @@ -17708,6 +18836,8 @@ def _approval_notify_sync(approval_data: dict) -> None: session_key=_approval_session_key, description=desc, metadata=_status_thread_metadata, + allow_permanent=approval_data.get("allow_permanent", True), + smart_denied=approval_data.get("smart_denied", False), ), _loop_for_step, logger=logger, @@ -17732,13 +18862,12 @@ def _approval_notify_sync(approval_data: dict) -> None: # can actually type (`!approve`) — typed "/" is blocked in # Slack threads and reserved by Matrix clients. _p = getattr(_status_adapter, "typed_command_prefix", "/") - cmd_preview = cmd[:200] + "..." if len(cmd) > 200 else cmd - msg = ( - f"⚠️ **Dangerous command requires approval:**\n" - f"```\n{cmd_preview}\n```\n" - f"Reason: {desc}\n\n" - f"Reply `{_p}approve` to execute, `{_p}approve session` to approve this pattern " - f"for the session, `{_p}approve always` to approve permanently, or `{_p}deny` to cancel." + msg = _format_exec_approval_fallback( + cmd, + desc, + _p, + allow_permanent=approval_data.get("allow_permanent", True), + smart_denied=approval_data.get("smart_denied", False), ) try: _approval_send_fut = safe_schedule_threadsafe( @@ -18206,6 +19335,12 @@ def _title_failure_cb(task: str, exc: BaseException) -> None: effective_session_id, title, ) + elif self._is_discord_auto_thread_lane(source): + maybe_auto_title_kwargs["title_callback"] = lambda title: self._schedule_discord_semantic_thread_rename( + source, + effective_session_id, + title, + ) maybe_auto_title( getattr(self._session_db, "_db", self._session_db), effective_session_id, @@ -18318,7 +19453,7 @@ async def monitor_for_interrupt(): try: # Re-resolve adapter each iteration so reconnects don't # leave us holding a stale reference. - _adapter = self.adapters.get(source.platform) + _adapter = self._adapter_for_source(source) if not _adapter: continue # Check if adapter has a pending interrupt for this session. @@ -18345,7 +19480,7 @@ async def monitor_for_interrupt(): # real transcript instead of an empty string # (or file-path placeholder). Matches the UX # of fresh voice messages including the - # 🎙️ echo back to the user. + # optional 🎙️ echo back to the user. _media_urls = getattr(_peek_event, "media_urls", None) or [] _media_types = getattr(_peek_event, "media_types", None) or [] _audio_paths = [] @@ -18363,7 +19498,7 @@ async def monitor_for_interrupt(): pending_text, _audio_paths, ) pending_text = _enriched - if _transcripts: + if _transcripts and self._should_echo_stt_transcripts(): _echo_meta = {"thread_id": source.thread_id} if source.thread_id else None for _tx in _transcripts: try: @@ -18401,21 +19536,19 @@ async def monitor_for_interrupt(): # 0 = disable notifications. _NOTIFY_INTERVAL_RAW = _float_env("HERMES_AGENT_NOTIFY_INTERVAL", 180) _NOTIFY_INTERVAL = _NOTIFY_INTERVAL_RAW if _NOTIFY_INTERVAL_RAW > 0 else None - if not bool( - resolve_display_setting( - user_config, - platform_key, - "long_running_notifications", - True, - ) - ): + _long_running_mode = _display_surface_mode( + "long_running_notifications", + default=True, + allow_generic=True, + ) + if _long_running_mode == "off": _NOTIFY_INTERVAL = None _notify_start = time.time() async def _notify_long_running(): if _NOTIFY_INTERVAL is None: return # Notifications disabled (gateway_notify_interval: 0) - _notify_adapter = self.adapters.get(source.platform) + _notify_adapter = self._adapter_for_source(source) if not _notify_adapter: return # Track the heartbeat message id so we can edit-in-place on @@ -18470,7 +19603,11 @@ async def _notify_long_running(): _status_detail = " — " + ", ".join(_parts) except Exception: pass - _heartbeat_text = f"⏳ Working — {_elapsed_mins} min{_status_detail}" + _heartbeat_text = ( + _generic_status_phrase("status") + if _long_running_mode == "generic" + else f"⏳ Working — {_elapsed_mins} min{_status_detail}" + ) try: _notify_res = None if _heartbeat_msg_id: @@ -18556,7 +19693,7 @@ def _stream_confirmed_final_delivery( # Backup interrupt check: if the monitor task died or # missed the interrupt, catch it here. if not _interrupt_detected.is_set() and session_key: - _backup_adapter = self.adapters.get(source.platform) + _backup_adapter = self._adapter_for_source(source) _backup_agent = agent_holder[0] if (_backup_adapter and _backup_agent and hasattr(_backup_adapter, 'has_pending_interrupt') @@ -18596,7 +19733,7 @@ def _stream_confirmed_final_delivery( if (not _warning_fired and _agent_warning is not None and _idle_secs >= _agent_warning): _warning_fired = True - _warn_adapter = self.adapters.get(source.platform) + _warn_adapter = self._adapter_for_source(source) if _warn_adapter: _elapsed_warn = int(_agent_warning // 60) or 1 _remaining_mins = int((_agent_timeout - _agent_warning) // 60) or 1 @@ -18616,7 +19753,7 @@ def _stream_confirmed_final_delivery( break # Backup interrupt check (same as unlimited path). if not _interrupt_detected.is_set() and session_key: - _backup_adapter = self.adapters.get(source.platform) + _backup_adapter = self._adapter_for_source(source) _backup_agent = agent_holder[0] if (_backup_adapter and _backup_agent and hasattr(_backup_adapter, 'has_pending_interrupt') @@ -18733,7 +19870,7 @@ def _stream_confirmed_final_delivery( # Check if we were interrupted OR have a queued message (/queue). result = result_holder[0] - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) # Get pending message from adapter. # Use session_key (not source.chat_id) to match adapter's storage keys. @@ -18762,9 +19899,9 @@ def _stream_confirmed_final_delivery( # Transcribe audio media on the dequeued event BEFORE it is # handed back as the next user turn, so queued/interrupting # voice messages drain with the real transcript instead of - # a file-path placeholder. Echo each transcript back to the - # user (same 🎙️ format as fresh voice messages) so voice - # interrupts feel identical to text interrupts. + # a file-path placeholder. When configured, echo each + # transcript back to the user in the same 🎙️ format as + # fresh voice messages. _pending_text = pending_event.text or "" _media_urls = getattr(pending_event, "media_urls", None) or [] _media_types = getattr(pending_event, "media_types", None) or [] @@ -18783,7 +19920,7 @@ def _stream_confirmed_final_delivery( _pending_text, _audio_paths, ) pending = _enriched or None - if _transcripts: + if _transcripts and self._should_echo_stt_transcripts(): _echo_meta = {"thread_id": source.thread_id} if source.thread_id else None for _tx in _transcripts: try: @@ -18864,7 +20001,7 @@ def _stream_confirmed_final_delivery( "queueing message instead of recursing.", _interrupt_depth, session_key, ) - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter and pending_event: merge_pending_message_event(adapter._pending_messages, session_key, pending_event) elif adapter and hasattr(adapter, 'queue_message'): @@ -18947,6 +20084,7 @@ def _stream_confirmed_final_delivery( next_message = pending next_message_id = None next_channel_prompt = None + next_session_key = session_key if pending_event is not None: next_source = getattr(pending_event, "source", None) or source if self._is_goal_continuation_event(pending_event) and not self._goal_still_active_for_session(session_id): @@ -18955,10 +20093,24 @@ def _stream_confirmed_final_delivery( session_key or "?", ) return result - next_message = await self._prepare_inbound_message_text( + # Resolve the follow-up's session key BEFORE preparing the + # inbound text: _prepare_inbound_message_text buffers native + # image paths under the key it is given, and the recursive + # _run_agent below consumes them under next_session_key. + # The write and consume keys must match or the images drop. + try: + next_session_key = self._session_key_for_source(next_source) + except Exception: + logger.debug( + "Queued follow-up session-key resolution failed; reusing %s", + session_key or "?", + exc_info=True, + ) + next_message = await self._prepare_profile_scoped_inbound_message_text( event=pending_event, source=next_source, history=updated_history, + session_key=next_session_key, ) if next_message is None: return result @@ -18968,7 +20120,7 @@ def _stream_confirmed_final_delivery( # Restart typing indicator so the user sees activity while # the follow-up turn runs. The outer _process_message_background # typing task is still alive but may be stale. - _followup_adapter = self.adapters.get(source.platform) + _followup_adapter = self._adapter_for_source(source) if _followup_adapter: try: await _followup_adapter.send_typing( @@ -19000,7 +20152,7 @@ def _stream_confirmed_final_delivery( history=updated_history, source=next_source, session_id=session_id, - session_key=session_key, + session_key=next_session_key, run_generation=run_generation, _interrupt_depth=_interrupt_depth + 1, event_message_id=next_message_id, @@ -19380,6 +20532,48 @@ def _start_cron_ticker(stop_event: threading.Event, adapters=None, loop=None, in InProcessCronScheduler().start(stop_event, adapters=adapters, loop=loop, interval=interval) +# Upper bound for cooperatively draining the cron ticker on shutdown. The cron +# thread delivers via ``safe_schedule_threadsafe`` and blocks on +# ``future.result(timeout=60)`` (see cron/scheduler.py::_deliver_result), so a +# single in-flight delivery unblocks within ~60s. The extra margin covers the +# hop back through run_one_job's bookkeeping. +_CRON_SHUTDOWN_DRAIN_TIMEOUT = 65.0 + +# Upper bound for cooperatively draining the housekeeping ticker on shutdown. +# Housekeeping periodically refreshes the channel directory via +# ``safe_schedule_threadsafe(build_channel_directory(...), loop)`` and blocks on +# ``fut.result(timeout=30)`` (see ``_start_gateway_housekeeping``) — the same +# loop-scheduled-future pattern as cron. So the cooperative bound must cover +# that 30s future (plus margin) rather than the old 5s join, otherwise a +# channel-directory refresh in flight at shutdown gets abandoned mid-resolve. +# Unlike a dropped cron delivery this is not user-facing (it self-heals on the +# next tick), but bounding it correctly keeps the drain honest. +_HOUSEKEEPING_SHUTDOWN_DRAIN_TIMEOUT = 35.0 + + +async def _await_thread_exit( + thread: Optional[threading.Thread], timeout: float, poll: float = 0.1 +) -> bool: + """Wait for a daemon thread to exit WITHOUT blocking the event loop. + + A synchronous ``thread.join()`` here would freeze the event loop — fatal + for the cron ticker, whose in-flight delivery is a coroutine scheduled onto + *this* loop via ``safe_schedule_threadsafe``. Blocking the loop deadlocks + that delivery (the loop can never run it), so ``join(timeout=5)`` always + times out and the message is silently dropped on restart (#58818). + + Polling ``is_alive()`` with ``await asyncio.sleep`` keeps the loop running + so the pending delivery completes, then the ticker sees ``stop_event`` and + exits. Returns True if the thread exited within ``timeout``. + """ + if thread is None: + return True + deadline = asyncio.get_running_loop().time() + max(0.0, timeout) + while thread.is_alive() and asyncio.get_running_loop().time() < deadline: + await asyncio.sleep(poll) + return not thread.is_alive() + + async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool = False, verbosity: Optional[int] = 0) -> bool: """ Start the gateway and run until interrupted. @@ -19835,13 +21029,21 @@ def restart_signal_handler(): # historical in-process 60s ticker; an external provider (e.g. chronos) # may arm a schedule and return. Pass the event loop so cron delivery can # use live adapters (E2EE support). - from cron.scheduler_provider import resolve_cron_scheduler + from cron.scheduler_provider import InProcessCronScheduler, resolve_cron_scheduler cron_stop = threading.Event() cron_provider = resolve_cron_scheduler() + cron_start_kwargs = {"adapters": runner.adapters, "loop": asyncio.get_running_loop()} + # External cron providers own their remote scheduling contract. Only the + # in-process ticker polls local due jobs, so only it receives the local + # external-drain dispatch gate. + if isinstance(cron_provider, InProcessCronScheduler): + cron_start_kwargs["can_dispatch"] = lambda: not ( + runner._draining or runner._external_drain_active + ) cron_thread = threading.Thread( target=cron_provider.start, args=(cron_stop,), - kwargs={"adapters": runner.adapters, "loop": asyncio.get_running_loop()}, + kwargs=cron_start_kwargs, daemon=True, name="cron-scheduler", ) @@ -19874,14 +21076,28 @@ def restart_signal_handler(): logger.error("Gateway exiting with failure: %s", runner.exit_reason) return False - # Stop cron scheduler + housekeeping cleanly + # Stop cron scheduler + housekeeping cleanly. + # + # These MUST be awaited cooperatively, not join()ed. A cron delivery in + # flight when the gateway restarts is a coroutine scheduled onto THIS event + # loop (safe_schedule_threadsafe); the ticker thread is blocked on its + # future.result(). A synchronous cron_thread.join() would block the loop, + # so that delivery could never run — it timed out and the message was + # silently dropped (#58818). Awaiting keeps the loop alive so the in-flight + # delivery finishes before we tear down. cron_stop.set() try: cron_provider.stop() except Exception as e: logger.debug("Cron provider stop() error: %s", e) - cron_thread.join(timeout=5) - housekeeping_thread.join(timeout=5) + if not await _await_thread_exit(cron_thread, timeout=_CRON_SHUTDOWN_DRAIN_TIMEOUT): + logger.warning( + "Cron ticker did not exit within %.0fs of shutdown — an in-flight " + "delivery may have been dropped.", _CRON_SHUTDOWN_DRAIN_TIMEOUT, + ) + await _await_thread_exit( + housekeeping_thread, timeout=_HOUSEKEEPING_SHUTDOWN_DRAIN_TIMEOUT + ) # Stop the planned-stop watcher (daemon=True so this is belt-and-suspenders). _planned_stop_watcher_stop.set() @@ -20000,24 +21216,41 @@ def _exit_after_graceful_shutdown(exit_code: int) -> None: released — so this is a no-op on the normal shutdown path and the actual cleanup on the early-exit paths. - Logging is not flushed here: the gateway's handlers are synchronous - ``RotatingFileHandler``s that write each record immediately (no - ``MemoryHandler``/``QueueHandler`` buffering), so there is nothing pending. - Only stdio is buffered, so only stdio is flushed. + Logging IS drained here: the rotating file handlers are driven by an + async ``QueueListener`` on a dedicated thread (see + ``hermes_logging._register_queued_handler``), so records emitted right + before shutdown may still be sitting in the in-memory queue. ``os._exit`` + below bypasses ``atexit``, so the ``atexit``-registered listener drain + never runs on this path — we drain explicitly (bounded, via + ``drain_log_queue``) or lose the last log lines (including the shutdown + reason on the early-exit paths). Stdio is flushed too. """ for stream in (sys.stdout, sys.stderr): try: stream.flush() except Exception: pass - # Guaranteed cleanup chokepoint: os._exit skips atexit, and the early - # SystemExit exit paths never run _stop_impl, so release here (idempotent). + # Release PID + runtime lock BEFORE the log drain: the drain is bounded but + # could still take up to its timeout on a wedged disk, and these locks must + # never be stranded. os._exit skips atexit, and the early SystemExit exit + # paths never run _stop_impl, so release here (idempotent). try: from gateway.status import remove_pid_file, release_gateway_runtime_lock remove_pid_file() release_gateway_runtime_lock() except Exception: pass + # Drain the async log queue: os._exit bypasses atexit, so the listener's + # atexit drain won't fire. Use drain_log_queue() (bounded, no restart), NOT + # flush_log_queue(): if the listener is wedged on the rotation lock — the + # exact failure this async-logging change survives — an unbounded stop() + # join would re-freeze the shutdown. drain_log_queue() no-ops when logging + # never initialized a queue (very early aborts), so this is always safe. + try: + from hermes_logging import drain_log_queue + drain_log_queue(timeout=1.0) + except Exception: + pass os._exit(exit_code) diff --git a/hermes_cli/config.py b/hermes_cli/config.py index 8748db2cb136e..b747196bffb1d 100644 --- a/hermes_cli/config.py +++ b/hermes_cli/config.py @@ -93,7 +93,9 @@ def _backup_corrupt_config(config_path: Path) -> Optional[Path]: return None -def _warn_config_parse_failure(config_path: Path, exc: Exception) -> None: +def _warn_config_parse_failure( + config_path: Path, exc: Exception, *, fallback: str = "defaults" +) -> None: """Surface a config.yaml parse failure to user, log, and stderr. A YAML parse error in ``~/.hermes/config.yaml`` causes ``load_config()`` @@ -110,6 +112,11 @@ def _warn_config_parse_failure(config_path: Path, exc: Exception) -> None: timestamped ``.bak`` (best-effort) so the user's recoverable content survives any later rewrite of ``config.yaml`` by the setup wizard or ``hermes config set``. + + ``fallback`` selects the message wording: ``"defaults"`` (fresh process, + nothing else to serve) or ``"last-known-good"`` (in-process retention of + the previously loaded config — see the codex#31188 port in + ``_load_config_impl``). """ try: st = config_path.stat() @@ -122,12 +129,19 @@ def _warn_config_parse_failure(config_path: Path, exc: Exception) -> None: backup_path = _backup_corrupt_config(config_path) - msg = ( - f"Failed to parse {config_path}: {exc}. " - f"Falling back to default config — every user override " - f"(auxiliary providers, fallback chain, model settings) is being IGNORED. " - f"Fix the YAML and restart." - ) + if fallback == "last-known-good": + msg = ( + f"Failed to parse {config_path}: {exc}. " + f"Keeping the previously loaded config for this process — " + f"edits to config.yaml are being IGNORED until the YAML is fixed." + ) + else: + msg = ( + f"Failed to parse {config_path}: {exc}. " + f"Falling back to default config — every user override " + f"(auxiliary providers, fallback chain, model settings) is being IGNORED. " + f"Fix the YAML and restart." + ) if backup_path is not None: msg += f" A copy of the corrupted file was saved to {backup_path}." logger.warning(msg) @@ -224,9 +238,11 @@ def _reject_denylisted_env_var(key: str) -> None: # produces a fresh inode, so stat() sees a new mtime_ns and the next # load repopulates automatically — no explicit invalidation hook. # Cached tuple is (user_mtime_ns, user_size, managed_mtime_ns, managed_size, -# merged_value) — the managed-file signature is folded in so editing the -# managed-scope config.yaml invalidates the cache (see managed_scope). -_LOAD_CONFIG_CACHE: Dict[str, Tuple[int, int, int, int, Dict[str, Any]]] = {} +# merged_value, env_ref_snapshot) — the managed-file signature is folded in so +# editing the managed-scope config.yaml invalidates the cache (see +# managed_scope), and the env snapshot invalidates it when a referenced ${VAR} +# changes value (late .env load, in-process rotation — #58514). +_LOAD_CONFIG_CACHE: Dict[str, Tuple[int, int, int, int, Dict[str, Any], Dict[str, Optional[str]]]] = {} # (path, mtime_ns, size) -> cached raw yaml dict. Same pattern as # _LOAD_CONFIG_CACHE but for read_raw_config() — used when callers want # the user's on-disk values without defaults merged in. @@ -439,8 +455,20 @@ def detect_install_method(project_root: Optional[Path] = None) -> str: managed = get_managed_system() if managed: return managed.lower().replace(" ", "-") - if (root / ".git").is_dir(): + + # detect git repo installs (normal installer, development env) + git_path = root / ".git" + if git_path.is_dir(): return "git" + + # detect git repo installs from worktrees + if git_path.is_file(): + try: + content = git_path.read_text(encoding="utf-8").strip() + if content.startswith("gitdir:"): + return "git" + except OSError: + pass return "pip" @@ -526,10 +554,54 @@ def recommended_update_command() -> str: managed_cmd = get_managed_update_command() if managed_cmd: return managed_cmd - method = detect_install_method() + method = detect_install_method(get_project_root()) return recommended_update_command_for_method(method) +# ============================================================================= +# Unsupported install methods (pip, Homebrew) — deprecation notice +# ============================================================================= +# +# pip/PyPI and Homebrew are NOT an officially supported distribution method +# (see website/docs/getting-started/platform-support.md, "Unsupported" +# section). pip exists on PyPI for internal/CI reasons, not end-user installs; +# Homebrew is a legacy packaging path. Unlike NixOS/Homebrew "managed mode" +# (which hard-blocks config writes), this is a warn-don't-block deprecation +# notice surfaced everywhere the user might see install-method state: the CLI +# banner, the TUI/desktop session info panel, and ``hermes update``. NixOS +# stays fully supported (Tier 2) and must never hit this path. + +PLATFORM_SUPPORT_DOCS_URL = "https://hermes-agent.nousresearch.com/docs/getting-started/platform-support" + +_UNSUPPORTED_INSTALL_METHODS = frozenset({"pip", "homebrew"}) + + +def is_unsupported_install_method(method: str) -> bool: + """Whether ``method`` (from ``detect_install_method()``) is deprecated.""" + return method in _UNSUPPORTED_INSTALL_METHODS + + +def unsupported_install_method_label(method: str) -> str: + """Human-readable name for an unsupported install method.""" + return "pip" if method == "pip" else "Homebrew" + + +def format_unsupported_install_warning(method: str) -> str: + """Plain-text (no markup) deprecation notice for pip/Homebrew installs. + + Shared verbatim across the CLI banner, TUI/desktop ``session.info``, and + ``hermes update`` / ``hermes update --check`` so the wording — and the + docs link — stays consistent across every surface instead of drifting + into three slightly different warnings. + """ + label = unsupported_install_method_label(method) + return ( + f"{label} installs are no longer an officially supported platform and " + f"will not receive further updates. See {PLATFORM_SUPPORT_DOCS_URL} " + "for supported install methods." + ) + + # Long-form text for ``hermes update`` / ``--check`` when running inside the # Docker image. Surfaced by ``cmd_update`` and ``_cmd_update_check`` in # hermes_cli/main.py; lives here so the wording stays consistent and we @@ -847,6 +919,15 @@ def ensure_hermes_home(): any files created (e.g. SOUL.md) are group-writable (0660). """ home = get_hermes_home() + # Named profiles must be created explicitly (e.g. ``hermes profile create``). + # If a stale process keeps running after the profile was renamed/deleted, + # silently mkdir-ing the old HERMES_HOME would resurrect an empty skeleton + # and make the deleted profile reappear in Desktop/profile lists. + if home.parent.name == "profiles" and not home.exists(): + raise FileNotFoundError( + f"Named profile home does not exist: {home}. " + "Create the profile explicitly before using it." + ) if is_managed(): old_umask = os.umask(0o007) try: @@ -1138,7 +1219,23 @@ def _ensure_hermes_home_managed(home: Path): "singularity_image": "docker://nikolaik/python-nodejs:python3.11-nodejs20", "modal_image": "nikolaik/python-nodejs:python3.11-nodejs20", "daytona_image": "nikolaik/python-nodejs:python3.11-nodejs20", - # Container resource limits (docker, singularity, modal, daytona — ignored for local/ssh) + "tenki_image": "", + # Blank so the documented TENKI_API_ENDPOINT / TENKI_API_URL and Tenki + # CLI-config fallbacks in resolve_tenki_api_endpoint() are reachable. A + # non-blank default here is bridged as an explicit value and would mask + # them. Blank resolves to https://api.tenki.cloud downstream. + "tenki_api_endpoint": "", + "tenki_workspace_id": "", + "tenki_project_id": "", + "tenki_name_prefix": "hermes", + "tenki_allow_inbound": False, + "tenki_allow_outbound": True, + "tenki_max_duration": 3600, + "tenki_idle_timeout": 0, + "tenki_pause_retention": 0, + "tenki_sync_hermes_home": False, + "tenki_forward_env": [], + # Container resource limits (docker, singularity, modal, daytona, tenki — ignored for local/ssh) "container_cpu": 1, "container_memory": 5120, # MB (default 5GB) "container_disk": 51200, # MB (default 50GB) @@ -1154,6 +1251,9 @@ def _ensure_hermes_home_managed(home: Path): # Explicit opt-in: mount the host cwd into /workspace for Docker sessions. # Default off because passing host directories into a sandbox weakens isolation. "docker_mount_cwd_to_workspace": False, + # Opt-in egress lockdown for Docker terminal sessions. When false, + # Docker runs with --network=none so commands cannot reach the network. + "docker_network": True, "docker_extra_args": [], # Extra flags passed verbatim to docker run # Explicit opt-in: run the Docker container as the host user's uid:gid # (via `--user`). When enabled, files written into bind-mounted dirs @@ -1327,7 +1427,11 @@ def _ensure_hermes_home_managed(home: Path): "compression": { "enabled": True, - "threshold": 0.50, # compress when context usage exceeds this ratio + "threshold": 0.50, # compress when context usage exceeds this ratio. + # Models with context windows below 512K are + # floored at 0.75 (raise-only) so compaction + # doesn't fire with half the window still free; + # set this above 0.75 to override the floor. "target_ratio": 0.20, # fraction of threshold to preserve as recent tail "protect_last_n": 20, # minimum recent messages to keep uncompressed "hygiene_hard_message_limit": 5000, # gateway session-hygiene force-compress threshold by message count @@ -1348,16 +1452,30 @@ def _ensure_hermes_home_managed(home: Path): # Default False matches historical behavior; set to # True if you'd rather pause than silently lose # context turns when your aux model is flaky. - "codex_gpt55_autoraise": True, # When True, gpt-5.5 on the ChatGPT Codex OAuth - # route raises its compaction trigger to 85% (vs the - # global `threshold` above). Codex hard-caps gpt-5.5 - # at a 272K window, so the default 50% would compact - # at ~136K and waste half the usable context. Set to - # False to opt back down to the global threshold - # (e.g. 0.50) for Codex gpt-5.5 sessions. Only this - # exact route is affected — gpt-5.5 on OpenAI's - # direct API, OpenRouter, and Copilot keep the - # global threshold regardless. + "codex_gpt55_autoraise": True, # Historical key name kept for compatibility. + # When True, gpt-5.4 / gpt-5.5 / gpt-5.6 on the + # ChatGPT Codex OAuth route raise their compaction + # trigger to 85% (vs the global `threshold` above). + # Codex hard-caps these families at a 272K window, so + # the default 50% would compact at ~136K and waste half + # the usable context. Set to False to opt back down to + # the global threshold (e.g. 0.50) for those Codex + # sessions. Only this exact route is affected — + # gpt-5.4 / 5.5 / 5.6 on OpenAI's direct API, + # OpenRouter, and Copilot keep the global threshold + # regardless. + "codex_gpt55_autoraise_notice": True, # Display the one-time Codex gpt-5.4/5.5/5.6 + # autoraise banner. Set False to keep the + # 85% threshold autoraise but suppress the + # user-facing notice in CLI/gateway output. + "codex_app_server_auto": "native", # Codex app-server (codex CLI runtime) thread + # compaction mode. The codex agent owns the real + # thread context, so Hermes' summarizer cannot + # shrink it (#36801). native = codex decides when + # to compact its own thread (default); hermes = + # Hermes' compression threshold triggers + # thread/compact/start; off = never auto-trigger + # (codex may still compact natively). "in_place": True, # When True, compaction rewrites the message # list and rebuilds the system prompt WITHOUT # rotating the session id — the conversation @@ -1662,6 +1780,10 @@ def _ensure_hermes_home_managed(home: Path): # behavior of showing tool-call summaries inline. "resume_skip_tool_only": True, "busy_input_mode": "interrupt", # interrupt | queue | steer + # When busy_input_mode="steer", suppress only the visible + # "Steered into current run" confirmation bubble by setting this false. + # The mid-turn steering itself still happens. + "busy_steer_ack_enabled": True, # Which interface bare `hermes` (and `hermes chat`) launches by default: # "cli" — the classic prompt_toolkit REPL (default, preserves prior behavior) # "tui" — the modern Ink TUI (same as passing `--tui`) @@ -1679,7 +1801,11 @@ def _ensure_hermes_home_managed(home: Path): # dashboard. Set false to suppress the hint. "tui_agents_nudge": True, "bell_on_complete": False, - "show_reasoning": False, + # Stream the model's reasoning/thinking live before the response. + # Default ON: on thinking models the reasoning phase can run tens of + # seconds, and with this off the user stares at a spinner the whole + # time even though tokens are streaming. Set false for quiet output. + "show_reasoning": True, # When reasoning display is on, the post-response "Reasoning" recap box # collapses long thinking to the first 10 lines. Set true to print the # complete thinking text uncollapsed (live streaming is always full). @@ -1691,7 +1817,8 @@ def _ensure_hermes_home_managed(home: Path): # Per-platform overrides via display.platforms..memory_notifications. "memory_notifications": "on", "streaming": False, - "timestamps": False, # Show [HH:MM] on user and assistant labels + "timestamps": False, # Show timestamp on user and assistant labels + "timestamp_format": "%H:%M", # strftime format for timestamps (e.g. "%b-%d %H:%M") "final_response_markdown": "strip", # render | strip | raw # Preserve recent classic CLI output across Ctrl+L, /redraw, and # terminal resize full-screen clears. Disable if a terminal emulator @@ -1760,6 +1887,15 @@ def _ensure_hermes_home_managed(home: Path): # applies where tool_progress is already enabled. Per-platform override # via display.platforms..tool_progress_grouping. "tool_progress_grouping": "accumulate", + # Optional custom phrases for generic long-running status messages. + # Built-in defaults live in gateway/assets/status_phrases.yaml. Users + # can set `path`/`paths` to HERMES_HOME-relative YAML files/directories + # (or rely on conventional status_phrases.yaml / status_phrases/*.yaml). + # Keys: status, generic. Use + # mode: "append" (default) to add phrases, or "replace" to fully + # replace configured surfaces. Per-platform overrides live under + # display.platforms..status_phrases. + "status_phrases": {}, # How a reasoning/thinking summary renders when show_reasoning is on. # "code" (default) = 💭 fenced code block; "blockquote" = "> " lines; # "subtext" = "-# " lines (Discord small grey metadata text). Discord @@ -2004,6 +2140,10 @@ def _ensure_hermes_home_managed(home: Path): "stt": { "enabled": True, + # When true, gateway voice messages are transcribed for the agent and + # the raw transcript is also echoed back to the user as a 🎙️ message. + # Set false to keep STT for the agent while suppressing that user-facing echo. + "echo_transcripts": True, "provider": "local", # "local" (free, faster-whisper) | "groq" | "openai" (Whisper API) | "mistral" (Voxtral Transcribe) | "elevenlabs" (Scribe) "local": { "model": "base", # tiny, base, small, medium, large-v3 @@ -2116,8 +2256,8 @@ def _ensure_hermes_home_managed(home: Path): # (API, tools, iteration budget), never a delegation # stopwatch. Set a positive number of seconds # (floor 30s) to enforce a hard cap. - "reasoning_effort": "", # reasoning effort for subagents: "xhigh", "high", "medium", - # "low", "minimal", "none" (empty = inherit parent's level) + "reasoning_effort": "", # subagent effort: "ultra", "max", "xhigh", "high", + # "medium", "low", "minimal", "none" (empty = inherit) "max_concurrent_children": 3, # unified concurrency cap: max parallel children per batch # AND max concurrent background (background=true) # delegation units. New async dispatches beyond the cap @@ -2181,8 +2321,6 @@ def _ensure_hermes_home_managed(home: Path): {"provider": "openrouter", "model": "deepseek/deepseek-v4-pro"}, ], "aggregator": {"provider": "openrouter", "model": "anthropic/claude-opus-4.8"}, - "reference_temperature": 0.6, - "aggregator_temperature": 0.4, "max_tokens": 4096, "enabled": True, } @@ -2337,6 +2475,11 @@ def _ensure_hermes_home_managed(home: Path): # real memory cost. Default 32 MiB matches the historical hardcoded # cap. Set to 0 for no cap. Env override: DISCORD_MAX_ATTACHMENT_BYTES. "max_attachment_bytes": 33554432, + # When True, Discord approval prompts mention numeric allowed users so + # owners notice approval requests in shared channels/threads. Env + # override: DISCORD_APPROVAL_MENTIONS. Default false avoids surprise + # pings. + "approval_mentions": False, # Voice-channel audio effects (the continuous mixer). OFF by default. # When enabled, the bot installs a software mixer on the outgoing voice # stream so a low ambient "thinking" bed, verbal acknowledgements, and @@ -2396,17 +2539,27 @@ def _ensure_hermes_home_managed(home: Path): }, # Approval mode for dangerous commands: - # manual — always prompt the user (default) - # smart — use auxiliary LLM to auto-approve low-risk commands, prompt for high-risk + # manual — always prompt the user + # smart — use auxiliary LLM to auto-approve low-risk commands (default) # off — skip all approval prompts (equivalent to --yolo) # # cron_mode — what to do when a cron job hits a dangerous command: # deny — block the command and let the agent find another way (default, safe) # approve — auto-approve all dangerous commands in cron jobs "approvals": { - "mode": "manual", + "mode": "smart", "timeout": 60, "cron_mode": "deny", + # User-defined deny rules: fnmatch globs matched against terminal + # commands. A match blocks the command unconditionally — BEFORE the + # --yolo / /yolo / mode=off bypass — making this the user-editable + # counterpart to the code-shipped hardline blocklist. Patterns are + # case-insensitive and must be quoted in YAML when they start with + # * or contain {}/!/: sequences. Example: + # deny: + # - "git push --force*" + # - "*curl*|*sh*" + "deny": [], # When true, /reload-mcp asks the user to confirm before rebuilding # the MCP tool set for the active session. Reloading invalidates # the provider prompt cache (tool schemas are baked into the system @@ -2717,6 +2870,13 @@ def _ensure_hermes_home_managed(home: Path): # works as a manual override and wins if set explicitly. "platform_connect_timeout": 30, + # Whether the gateway keeps writing the legacy sessions.json mirror of + # its routing index. The primary copy lives in state.db (the + # gateway_routing table). Default True for backward compatibility with + # external tooling and downgrade safety; set to false to stop + # producing ~/.hermes/sessions/sessions.json entirely. + "write_sessions_json": True, + # Scale-to-zero idle detection (Phase 0). The gateway watches for idle # and, when an instance is opted in via the NAS "Labs" toggle (carried as # the HERMES_SCALE_TO_ZERO env stamp) AND messaging is relay-only/absent @@ -2941,6 +3101,11 @@ def _ensure_hermes_home_managed(home: Path): # ignored paths — node_modules, venv, build outputs — # are never touched. "non_interactive_local_changes": "stash", + # Refresh an already-installed cua-driver during `hermes update`. + # The refresh is best-effort and macOS-only. Turn this off if the + # upstream installer is not appropriate for the machine, for example + # on non-admin accounts where `/Applications` is not writable. + "refresh_cua_driver": True, }, # Language Server Protocol — semantic diagnostics from real @@ -3014,6 +3179,15 @@ def _ensure_hermes_home_managed(home: Path): # Pull credentials from external secret managers at process startup # rather than storing them in ~/.hermes/.env. "secrets": { + # Optional explicit ordering of enabled secret sources. When + # omitted, sources run in registration order (bundled first, + # then plugin-registered). Regardless of this list, "mapped" + # sources (explicit VAR→ref bindings, e.g. a future 1Password + # env: map) always take precedence over "bulk" sources + # (project dumps like Bitwarden BSM), and the first source to + # claim a var wins — later claims are skipped with a warning. + # Example: sources: [onepassword, bitwarden] + # "sources": [], "bitwarden": { # Master switch. When false, BSM is never contacted and the # bws binary is never auto-installed — same as not having @@ -3045,6 +3219,34 @@ def _ensure_hermes_home_managed(home: Path): # `hermes secrets bitwarden setup`. "server_url": "", }, + "onepassword": { + # Master switch. When false, the op CLI is never invoked — + # same as not having this section at all. + "enabled": False, + # Mapping of env-var name → 1Password secret reference + # (op://vault/item/field). Each entry is resolved with a + # single `op read` at startup. + "env": {}, + # Optional account shorthand / sign-in address passed as + # `op read --account `. Empty = op's default account. + "account": "", + # Name of the env var holding a 1Password service-account token + # for headless auth. Sourced from ~/.hermes/.env (or the shell) + # and exported to the op child as OP_SERVICE_ACCOUNT_TOKEN. + # Leave the var unset to use an interactive/desktop op session. + "service_account_token_env": "OP_SERVICE_ACCOUNT_TOKEN", + # Optional absolute path to the op binary. When set it is used + # verbatim (PATH is not consulted) — pin this to avoid trusting + # whatever `op` appears first on PATH. Empty = resolve via PATH. + "binary_path": "", + # Seconds to cache resolved values in-process and on disk. 0 + # disables BOTH cache layers (no values are written to disk). + "cache_ttl_seconds": 300, + # When True (default), resolved values overwrite existing env + # vars so rotating a secret in 1Password takes effect on next + # start. Flip to false to let .env / shell exports win locally. + "override_existing": True, + }, }, # Paste collapse thresholds (TUI + CLI). @@ -3349,6 +3551,14 @@ def _ensure_hermes_home_managed(home: Path): "category": "provider", "advanced": True, }, + "FIREWORKS_API_KEY": { + "description": "Fireworks AI API key", + "prompt": "Fireworks AI API key", + "url": "https://app.fireworks.ai/settings/users/api-keys", + "password": True, + "category": "provider", + "advanced": True, + }, "MINIMAX_API_KEY": { "description": "MiniMax API key (international)", "prompt": "MiniMax API key", @@ -4459,6 +4669,26 @@ def get_missing_skill_config_vars() -> List[Dict[str, Any]]: return missing +# ``_normalize_custom_provider_entry`` runs on every ``load_picker_context()`` +# call (i.e. per interactive picker/inventory request), so any warning it emits +# fires repeatedly for the same static config. Deduplicate per (provider, +# signature): on Windows a repeated-warning storm contends on +# ``concurrent-log-handler``'s cross-process rotation lock and can peg a core / +# stall the gateway/serve event loop. The cache lives for the process lifetime. +_PROVIDER_NORMALIZE_WARNED: set = set() + + +def _warn_once_per_provider( + provider_key: str, signature: str, msg: str, *args: Any +) -> None: + """Emit ``logger.warning(msg, *args)`` at most once per (provider, signature).""" + dedup_key = (provider_key or "?", signature) + if dedup_key in _PROVIDER_NORMALIZE_WARNED: + return + _PROVIDER_NORMALIZE_WARNED.add(dedup_key) + logger.warning(msg, *args) + + def _normalize_custom_provider_entry( entry: Any, *, @@ -4485,6 +4715,11 @@ def _normalize_custom_provider_entry( if "api_key_env" in entry and "key_env" not in entry: entry["key_env"] = entry["api_key_env"] _KNOWN_KEYS = { + # ``provider`` duplicates the ``providers.`` mapping key and is + # unused here, but Hermes' own config writer has historically emitted it + # into provider entries. Accept it silently so those (self-written) + # configs don't warn on every load. + "provider", "name", "api", "url", "base_url", "api_key", "key_env", "api_key_env", "api_mode", "transport", "model", "default_model", "models", "context_length", "rate_limit_delay", @@ -4494,7 +4729,8 @@ def _normalize_custom_provider_entry( } for camel, snake in _CAMEL_ALIASES.items(): if camel in entry and snake not in entry: - logger.warning( + _warn_once_per_provider( + provider_key, f"camel:{camel}", "providers.%s: camelCase key '%s' auto-mapped to '%s' " "(use snake_case to avoid this warning)", provider_key or "?", camel, snake, @@ -4502,7 +4738,8 @@ def _normalize_custom_provider_entry( entry[snake] = entry[camel] unknown = set(entry.keys()) - _KNOWN_KEYS - set(_CAMEL_ALIASES.keys()) if unknown: - logger.warning( + _warn_once_per_provider( + provider_key, "unknown:" + ",".join(sorted(unknown)), "providers.%s: unknown config keys ignored: %s", provider_key or "?", ", ".join(sorted(unknown)), ) @@ -4573,13 +4810,29 @@ def _normalize_custom_provider_entry( if isinstance(models, dict) and models: normalized["models"] = models elif isinstance(models, list) and models: - # Hand-edited configs (and older Hermes versions) write ``models`` as - # a plain list of model ids. Preserve them by converting to the dict - # shape downstream code expects; otherwise normalize silently drops - # the list and /model shows the provider with (0) models. - normalized["models"] = { - str(m): {} for m in models if isinstance(m, str) and m.strip() - } + # Hand-edited configs (and older Hermes versions) may write + # ``models`` as a plain list of ids or as ``[{id: ...}]`` rows. + # Preserve both by converting to the dict shape downstream code + # expects; otherwise normalize silently drops the list and /model + # shows the provider with (0) models. + normalized_models: Dict[str, Any] = {} + for item in models: + if isinstance(item, str) and item.strip(): + normalized_models[item.strip()] = {} + continue + if not isinstance(item, dict): + continue + model_id = item.get("id") + if not isinstance(model_id, str) or not model_id.strip(): + model_id = item.get("name") + if not isinstance(model_id, str) or not model_id.strip(): + continue + model_meta = { + k: v for k, v in item.items() if k not in {"id", "name"} + } + normalized_models[model_id.strip()] = model_meta + if normalized_models: + normalized["models"] = normalized_models context_length = entry.get("context_length") if isinstance(context_length, int) and context_length > 0: @@ -4600,11 +4853,9 @@ def _normalize_custom_provider_entry( # Per-provider extra HTTP headers (proxies, gateways, custom auth). # Values may carry credentials (e.g. CF-Access-Client-Secret) — never # log them anywhere downstream. - extra_headers = entry.get("extra_headers") - if isinstance(extra_headers, dict) and extra_headers: - normalized["extra_headers"] = { - str(k): str(v) for k, v in extra_headers.items() if v is not None - } + normalized_headers = normalize_extra_headers(entry.get("extra_headers")) + if normalized_headers: + normalized["extra_headers"] = normalized_headers ssl_ca_cert = entry.get("ssl_ca_cert") if isinstance(ssl_ca_cert, str) and ssl_ca_cert.strip(): @@ -4787,6 +5038,23 @@ def apply_custom_provider_tls_to_client_kwargs( client_kwargs["ssl_verify"] = tls["ssl_verify"] +def normalize_extra_headers(extra_headers: Any) -> Dict[str, str]: + """Normalize a raw ``extra_headers`` value into a ``dict[str, str]``. + + Stringifies keys and values and drops entries whose value is ``None``. + Returns ``{}`` for non-dict or empty inputs. This is the single shared + normalizer for per-provider ``extra_headers`` across config normalization, + runtime resolution, client construction, and live ``/models`` discovery. + + SECURITY: header values routinely carry credentials (Cloudflare Access + service tokens, proxy auth, custom bearer schemes). Callers must never + log the returned values. + """ + if not isinstance(extra_headers, dict) or not extra_headers: + return {} + return {str(k): str(v) for k, v in extra_headers.items() if v is not None} + + def get_custom_provider_extra_headers( base_url: str, custom_providers: Optional[List[Dict[str, Any]]] = None, @@ -4818,12 +5086,7 @@ def get_custom_provider_extra_headers( entry_url = (entry.get("base_url") or "").rstrip("/").lower() if not entry_url or entry_url != target_url: continue - extra_headers = entry.get("extra_headers") - if isinstance(extra_headers, dict) and extra_headers: - return { - str(k): str(v) for k, v in extra_headers.items() if v is not None - } - return {} + return normalize_extra_headers(entry.get("extra_headers")) return {} @@ -5196,8 +5459,8 @@ def warn_deprecated_cwd_env_vars(config: Optional[Dict[str, Any]] = None) -> Non hint_path = os.environ.get("HERMES_HOME", "~/.hermes") lines.insert(0, "\033[33m⚠ Deprecated .env settings detected:\033[0m") lines.append( - f" \033[2mMove to config.yaml instead: " - f"terminal:\\n cwd: /your/project/path\033[0m" + " \033[2mMove to config.yaml instead: " + "terminal:\\n cwd: /your/project/path\033[0m" ) lines.append( f" \033[2mThen remove the old entries from {hint_path}/.env\033[0m" @@ -5264,7 +5527,7 @@ def migrate_config(interactive: bool = True, quiet: bool = False) -> Dict[str, A if old_enabled and old_enabled.lower() in {"false", "0", "no"}: display["tool_progress"] = "off" results["config_added"].append("display.tool_progress=off (from HERMES_TOOL_PROGRESS=false)") - elif old_mode and old_mode.lower() in {"new", "all"}: + elif old_mode and old_mode.lower() in {"new", "all", "verbose"}: display["tool_progress"] = old_mode.lower() results["config_added"].append(f"display.tool_progress={old_mode.lower()} (from HERMES_TOOL_PROGRESS_MODE)") else: @@ -5430,7 +5693,7 @@ def migrate_config(interactive: bool = True, quiet: bool = False) -> Dict[str, A config["stt"] = stt _persist_migration(config) if not quiet: - print(f" ✓ Migrated legacy stt.model to provider-specific config") + print(" ✓ Migrated legacy stt.model to provider-specific config") # ── Version 14 → 15: add explicit gateway interim-message gate ── if current_ver < 15: @@ -6004,6 +6267,12 @@ def _deep_merge(base: dict, override: dict) -> dict: Keys in *override* take precedence. If both values are dicts the merge recurses, so a user who overrides only ``tts.elevenlabs.voice_id`` will keep the default ``tts.elevenlabs.model_id`` intact. + + An empty section key in config.yaml (``terminal:`` with no value) parses + as YAML ``None``; treating that as an override would replace the entire + default dict with ``None`` and crash every downstream consumer that + expects a mapping (#58277). A ``None`` override of a dict default is + ignored — same as the key being absent. """ result = base.copy() for key, value in override.items(): @@ -6013,6 +6282,8 @@ def _deep_merge(base: dict, override: dict) -> dict: and isinstance(value, dict) ): result[key] = _deep_merge(result[key], value) + elif key in result and isinstance(result[key], dict) and value is None: + continue else: result[key] = value return result @@ -6061,6 +6332,31 @@ def _expand_env_vars(obj): return obj +def _env_ref_snapshot(obj, snapshot=None): + """Map every ``${VAR}`` name referenced in config values to its current + ``os.environ`` value (``None`` when unset). + + Stored alongside cached ``load_config()`` results so a cache hit can + detect that the cached expansion was made against a *different* + environment — e.g. a ``load_config()`` that ran before + ``load_hermes_dotenv()`` populated the process env, or an env var + rotated in-process after the first load. File mtime/size alone cannot + see either case (#58514). + """ + if snapshot is None: + snapshot = {} + if isinstance(obj, str): + for name in re.findall(r"\${([^}]+)}", obj): + snapshot[name] = os.environ.get(name) + elif isinstance(obj, dict): + for value in obj.values(): + _env_ref_snapshot(value, snapshot) + elif isinstance(obj, list): + for item in obj: + _env_ref_snapshot(item, snapshot) + return snapshot + + def _items_by_unique_name(items): """Return a name-indexed dict only when all items have unique string names.""" if not isinstance(items, list): @@ -6328,6 +6624,31 @@ def _normalize_max_turns_config(config: Dict[str, Any]) -> Dict[str, Any]: return config +def _normalize_terminal_backend_defaults( + config: Dict[str, Any], + raw_config: Optional[Dict[str, Any]] = None, +) -> Dict[str, Any]: + """Apply backend-specific terminal defaults without writing them to config.yaml.""" + terminal = config.get("terminal") + if not isinstance(terminal, dict): + return config + + backend = str(terminal.get("backend") or terminal.get("env_type") or "").lower() + if backend != "tenki": + return config + + raw_terminal = raw_config.get("terminal") if isinstance(raw_config, dict) else {} + explicit_persistence = isinstance(raw_terminal, dict) and "container_persistent" in raw_terminal + if explicit_persistence: + return config + + config = dict(config) + terminal = dict(terminal) + terminal["container_persistent"] = False + config["terminal"] = terminal + return config + + def cfg_get(cfg: Optional[Dict[str, Any]], *keys: str, default: Any = None) -> Any: """Traverse nested dict keys safely, returning ``default`` on any miss. @@ -6413,6 +6734,56 @@ def read_raw_config() -> Dict[str, Any]: return data +def require_readable_config_before_write(config_path: Optional[Path] = None) -> None: + """Refuse to replace an existing config.yaml that cannot be read.""" + if config_path is None: + config_path = get_config_path() + try: + config_path.stat() + except FileNotFoundError: + return + except OSError as exc: + raise RuntimeError( + f"Refusing to overwrite {config_path}: existing config.yaml cannot be accessed " + f"({exc}). Fix the file permissions or move it aside first." + ) from exc + + try: + with open(config_path, "rb") as f: + f.read(1) + except OSError as exc: + raise RuntimeError( + f"Refusing to overwrite {config_path}: existing config.yaml cannot be read " + f"({exc}). Fix the file permissions or move it aside first." + ) from exc + + +def atomic_config_write(config_path: Path, data: Any, **kwargs: Any) -> None: + """Fail-closed atomic write for ``config.yaml``. + + The single chokepoint every config-update path should use instead of + calling :func:`utils.atomic_yaml_write` directly. It runs + :func:`require_readable_config_before_write` first, so a full-file + replacement can never silently clobber an existing ``config.yaml`` that + degraded to an empty dict on read (permission error, broken mount, + transient I/O). New-file creation still works when the path is absent. + + Root cause this guards: ``read_raw_config()`` returns ``{}`` for BOTH an + absent file and an unreadable-but-present file. Callers that read then + overwrite can't tell the two apart, so an unreadable config would be + replaced with only defaults or the single edited section. Routing every + write through this helper enforces the invariant in one place rather than + relying on each of ~15 independent write sites to remember the guard. + + ``kwargs`` are forwarded verbatim to ``atomic_yaml_write`` + (``sort_keys``, ``default_flow_style``, ``extra_content``, ...). + """ + from utils import atomic_yaml_write + + require_readable_config_before_write(config_path) + atomic_yaml_write(config_path, data, **kwargs) + + def load_config() -> Dict[str, Any]: """Load configuration from ~/.hermes/config.yaml. @@ -6492,6 +6863,18 @@ def write_platform_config_field( "singularity_image": "TERMINAL_SINGULARITY_IMAGE", "modal_image": "TERMINAL_MODAL_IMAGE", "daytona_image": "TERMINAL_DAYTONA_IMAGE", + "tenki_image": "TERMINAL_TENKI_IMAGE", + "tenki_api_endpoint": "TERMINAL_TENKI_API_ENDPOINT", + "tenki_workspace_id": "TERMINAL_TENKI_WORKSPACE_ID", + "tenki_project_id": "TERMINAL_TENKI_PROJECT_ID", + "tenki_name_prefix": "TERMINAL_TENKI_NAME_PREFIX", + "tenki_allow_inbound": "TERMINAL_TENKI_ALLOW_INBOUND", + "tenki_allow_outbound": "TERMINAL_TENKI_ALLOW_OUTBOUND", + "tenki_max_duration": "TERMINAL_TENKI_MAX_DURATION", + "tenki_idle_timeout": "TERMINAL_TENKI_IDLE_TIMEOUT", + "tenki_pause_retention": "TERMINAL_TENKI_PAUSE_RETENTION", + "tenki_sync_hermes_home": "TERMINAL_TENKI_SYNC_HERMES_HOME", + "tenki_forward_env": "TERMINAL_TENKI_FORWARD_ENV", "ssh_host": "TERMINAL_SSH_HOST", "ssh_user": "TERMINAL_SSH_USER", "ssh_port": "TERMINAL_SSH_PORT", @@ -6503,6 +6886,7 @@ def write_platform_config_field( "docker_volumes": "TERMINAL_DOCKER_VOLUMES", "docker_env": "TERMINAL_DOCKER_ENV", "docker_mount_cwd_to_workspace": "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", + "docker_network": "TERMINAL_DOCKER_NETWORK", "docker_extra_args": "TERMINAL_DOCKER_EXTRA_ARGS", "docker_run_as_host_user": "TERMINAL_DOCKER_RUN_AS_HOST_USER", "docker_persist_across_processes": "TERMINAL_DOCKER_PERSIST_ACROSS_PROCESSES", @@ -6546,10 +6930,20 @@ def apply_terminal_config_to_env( target = os.environ if env is None else env raw_config = read_raw_config() + raw_terminal_defaults_source: Dict[str, Any] = raw_config + try: + from hermes_cli import managed_scope + + managed_config = managed_scope.load_managed_config() + if managed_config: + raw_terminal_defaults_source = _deep_merge(raw_terminal_defaults_source, managed_config) + except Exception: + pass file_has_terminal_config = isinstance(raw_config.get("terminal"), dict) should_override = file_has_terminal_config if override is None else override cfg = config if config is not None else load_config_readonly() + cfg = _normalize_terminal_backend_defaults(cfg, raw_terminal_defaults_source) terminal_cfg = cfg.get("terminal", {}) if isinstance(cfg, dict) else {} if not isinstance(terminal_cfg, dict): return target @@ -6610,9 +7004,17 @@ def _load_config_impl(*, want_deepcopy: bool) -> Dict[str, Any]: cached = _LOAD_CONFIG_CACHE.get(path_key) if cached is not None and cache_sig is not None and cached[:4] == cache_sig: - return copy.deepcopy(cached[4]) if want_deepcopy else cached[4] + # File signatures match, but the cached expansion is only valid if + # every ${VAR} it was expanded against still has the same value. + # Without this, a load_config() that ran before load_hermes_dotenv() + # pins unexpanded literals (e.g. auxiliary..api_key) for the + # life of the process (#58514). + env_snapshot = cached[5] if len(cached) > 5 else {} + if all(os.environ.get(k) == v for k, v in env_snapshot.items()): + return copy.deepcopy(cached[4]) if want_deepcopy else cached[4] config = copy.deepcopy(DEFAULT_CONFIG) + user_config: Dict[str, Any] = {} if user_sig is not None: try: @@ -6628,7 +7030,45 @@ def _load_config_impl(*, want_deepcopy: bool) -> Dict[str, Any]: config = _deep_merge(config, user_config) except Exception as e: - _warn_config_parse_failure(config_path, e) + # Last-known-good fallback (port of openai/codex#31188's + # invariant: a parse failure in a policy/config file must not + # silently replace the effective policy with an empty/default + # one). Falling through to DEFAULT_CONFIG here drops EVERY user + # override — including security-critical ``approvals.deny`` + # rules, which are supposed to block commands even under yolo. + # A long-running gateway whose user mid-edits config.yaml into + # broken YAML would silently lose those rules on the next load. + # Within a running process we still have the last successfully + # loaded config — keep serving it until the file is fixed. + # Fresh processes with no last-known-good keep the existing + # DEFAULT_CONFIG fallback. + lkg = _LAST_EXPANDED_CONFIG_BY_PATH.get(path_key) + _warn_config_parse_failure( + config_path, + e, + fallback="last-known-good" if lkg is not None else "defaults", + ) + if lkg is not None: + # save_config() stores the pre-expansion normalized dict + # (env-ref templates preserved); the load path stores the + # expanded one. Expand defensively — idempotent when the + # stored value is already expanded. + from typing import cast as _cast + lkg_copy: Dict[str, Any] = _cast( + Dict[str, Any], _expand_env_vars(copy.deepcopy(lkg)) + ) + if cache_sig is not None: + # Cache under the corrupt file's signature (empty env + # snapshot: always valid) so repeated loads don't + # re-parse the broken file; fixing the file changes the + # signature and triggers a normal reload. + _empty_env: Dict[str, Optional[str]] = {} + _LOAD_CONFIG_CACHE[path_key] = ( + cache_sig[0], cache_sig[1], + cache_sig[2], cache_sig[3], + lkg_copy, _empty_env, + ) + return copy.deepcopy(lkg_copy) if want_deepcopy else lkg_copy normalized = _normalize_root_model_keys(_normalize_max_turns_config(config)) expanded = _expand_env_vars(normalized) @@ -6638,18 +7078,27 @@ def _load_config_impl(*, want_deepcopy: bool) -> Dict[str, Any]: # This deliberately inverts the usual env-over-config precedence for the # keys the managed layer pins — see docs/design/managed-scope.md §4.1. managed_config = managed_scope.load_managed_config() + raw_terminal_defaults_source: Dict[str, Any] = user_config if managed_config: managed_expanded = _expand_env_vars(managed_config) expanded = _deep_merge(expanded, managed_expanded) + raw_terminal_defaults_source = _deep_merge(raw_terminal_defaults_source, managed_config) + expanded = _normalize_terminal_backend_defaults(expanded, raw_terminal_defaults_source) _LAST_EXPANDED_CONFIG_BY_PATH[path_key] = copy.deepcopy(expanded) if cache_sig is not None: # Cache stores a separate deepcopy so subsequent ``load_config()`` # (deepcopy=True) callers can mutate freely without affecting the # cached value, and ``load_config_readonly()`` (deepcopy=False) # callers all see the same stable cached object. The cached tuple is - # (user_mtime, user_size, managed_mtime, managed_size, value). + # (user_mtime, user_size, managed_mtime, managed_size, value, + # env_ref_snapshot). The snapshot records the environment values + # this expansion was made against so later loads can detect env + # drift (late .env load, in-process rotation) — see cache hit above. cached_copy = copy.deepcopy(expanded) - _LOAD_CONFIG_CACHE[path_key] = (*cache_sig, cached_copy) + env_snapshot = _env_ref_snapshot(normalized) + if managed_config: + _env_ref_snapshot(managed_config, env_snapshot) + _LOAD_CONFIG_CACHE[path_key] = (*cache_sig, cached_copy, env_snapshot) # On the readonly path return the same cached object subsequent # calls will see — keeps "two readonly calls return the same # object" invariant that callers may rely on for identity checks. @@ -6778,6 +7227,7 @@ def save_config( ensure_hermes_home() config_path = get_config_path() + require_readable_config_before_write(config_path) # Compute explicit user paths BEFORE any normalisation -------- # _normalize_max_turns_config may inject agent.max_turns from # DEFAULT_CONFIG; using the raw dict preserves which paths the @@ -7124,8 +7574,8 @@ def _check_non_ascii_credential(key: str, value: str) -> str: f"\n" + "\n".join(f" {line}" for line in bad_chars[:5]) + ("\n ... and more" if len(bad_chars) > 5 else "") - + f"\n\n The non-ASCII characters have been stripped automatically.\n" - f" If authentication fails, re-copy the key from the provider's dashboard.\n", + + "\n\n The non-ASCII characters have been stripped automatically.\n" + " If authentication fails, re-copy the key from the provider's dashboard.\n", file=sys.stderr, ) return sanitized @@ -7557,7 +8007,7 @@ def show_config(): print(color("◆ Display", Colors.CYAN, Colors.BOLD)) display = config.get('display', {}) print(f" Personality: {display.get('personality') or 'none'}") - print(f" Reasoning: {'on' if display.get('show_reasoning', False) else 'off'}") + print(f" Reasoning: {'on' if display.get('show_reasoning', True) else 'off'}") print(f" Bell: {'on' if display.get('bell_on_complete', False) else 'off'}") ump = display.get('user_message_preview', {}) if isinstance(display.get('user_message_preview', {}), dict) else {} ump_first = ump.get('first_lines', 2) @@ -7584,6 +8034,12 @@ def show_config(): print(f" Daytona image: {terminal.get('daytona_image', 'nikolaik/python-nodejs:python3.11-nodejs20')}") daytona_key = get_env_value('DAYTONA_API_KEY') print(f" API key: {'configured' if daytona_key else '(not set)'}") + elif terminal.get('backend') == 'tenki': + print(f" Tenki image: {terminal.get('tenki_image') or '(Tenki default)'}") + print(f" Endpoint: {terminal.get('tenki_api_endpoint') or 'https://api.tenki.cloud'}") + print(f" Workspace: {terminal.get('tenki_workspace_id') or '(from Tenki CLI)'}") + print(f" Project: {terminal.get('tenki_project_id') or '(from Tenki CLI)'}") + print(f" Sync .hermes: {'enabled' if terminal.get('tenki_sync_hermes_home') else 'disabled'}") elif terminal.get('backend') == 'ssh': ssh_host = get_env_value('TERMINAL_SSH_HOST') ssh_user = get_env_value('TERMINAL_SSH_USER') @@ -7714,6 +8170,20 @@ def edit_config(): subprocess.run([editor, str(config_path)]) +def _default_value_for_key(dotted_key: str): + """Return the leaf value declared for *dotted_key* in ``DEFAULT_CONFIG``. + + Unknown keys and non-leaf paths return ``None`` so they retain the legacy + best-effort coercion used by ``config set``. + """ + node = DEFAULT_CONFIG + for part in dotted_key.split("."): + if not isinstance(node, dict) or part not in node: + return None + node = node[part] + return node if not isinstance(node, dict) else None + + def set_config_value(key: str, value: str): """Set a configuration value.""" if is_managed(): @@ -7757,6 +8227,7 @@ def set_config_value(key: str, value: str): # Read the raw user config (not merged with defaults) to avoid # dumping all default values back to the file config_path = get_config_path() + require_readable_config_before_write(config_path) user_config = {} if config_path.exists(): try: @@ -7770,16 +8241,21 @@ def set_config_value(key: str, value: str): # _set_nested which preserves list-typed nodes; before #17876 the # inline navigation here silently overwrote lists with dicts. - # Convert value to appropriate type - if value.lower() in {'true', 'yes', 'on'}: - value = True - elif value.lower() in {'false', 'no', 'off'}: - value = False - elif value.isdigit(): - value = int(value) - elif value.replace('.', '', 1).isdigit(): - value = float(value) - + # Preserve values for string-typed settings. In particular, enum members + # such as approvals.mode="off" must not become YAML booleans. Unknown keys + # retain the historical best-effort coercion behavior. + coerced_value: Any = value + if not isinstance(_default_value_for_key(key), str): + if value.lower() in {'true', 'yes', 'on'}: + coerced_value = True + elif value.lower() in {'false', 'no', 'off'}: + coerced_value = False + elif value.isdigit(): + coerced_value = int(value) + elif value.replace('.', '', 1).isdigit(): + coerced_value = float(value) + + value = coerced_value _set_nested(user_config, key, value) # Normalize the api_base → base_url alias at set-time too (issue #8919), # so a fresh `hermes config set model.api_base ...` lands on the canonical diff --git a/hermes_cli/doctor.py b/hermes_cli/doctor.py index de921e18df14f..2f7cacc2cb709 100644 --- a/hermes_cli/doctor.py +++ b/hermes_cli/doctor.py @@ -43,6 +43,7 @@ "KIMI_API_KEY", "KIMI_CN_API_KEY", "GMI_API_KEY", + "FIREWORKS_API_KEY", "MINIMAX_API_KEY", "MINIMAX_CN_API_KEY", "KILOCODE_API_KEY", @@ -200,6 +201,32 @@ def _fail_and_issue(text: str, detail: str, fix: str, issues: list[str]) -> None issues.append(fix) +def _enabled_cli_toolsets_for_doctor() -> set[str] | None: + """Return toolsets enabled for the CLI, or None if config resolution fails.""" + try: + from hermes_cli.config import load_config + from hermes_cli.tools_config import _get_platform_tools + + return {str(toolset) for toolset in _get_platform_tools(load_config() or {}, "cli")} + except Exception: + return None + + +def _missing_api_key_toolsets_for_summary(unavailable: list[dict]) -> list[dict]: + """Filter unavailable API-key toolsets to those enabled for the CLI.""" + api_key_unavailable = [ + item for item in unavailable + if item.get("missing_vars") or item.get("env_vars") + ] + enabled_toolsets = _enabled_cli_toolsets_for_doctor() + if enabled_toolsets is None: + return api_key_unavailable + return [ + item for item in api_key_unavailable + if str(item.get("name") or "") in enabled_toolsets + ] + + def _read_pyproject_version() -> str | None: """Read the ``version = "..."`` from ``pyproject.toml`` at the project root. @@ -820,6 +847,10 @@ def run_doctor(args): "lmstudio", "nous", "nvidia", + # Fireworks' native model IDs are slash-form + # (accounts/fireworks/models/... and .../routers/...), so a "/" + # is expected, not an aggregator vendor prefix. + "fireworks", } provider_accepts_vendor_slug = ( provider_policy_id in providers_accepting_vendor_slugs @@ -958,8 +989,8 @@ def run_doctor(args): model_section[k] = raw_config.pop(k) else: raw_config.pop(k) - from utils import atomic_yaml_write - atomic_yaml_write(config_path, raw_config) + from hermes_cli.config import atomic_config_write + atomic_config_write(config_path, raw_config) check_ok("Migrated stale root-level keys into model section") fixed_count += 1 else: @@ -1522,15 +1553,20 @@ def run_doctor(args): # Tenki (if using tenki backend) if terminal_env == "tenki": try: + from hermes_cli.config import load_config_readonly from tools.tenki_config import ( has_tenki_auth, resolve_tenki_project_id, resolve_tenki_workspace_id, ) except Exception: + load_config_readonly = lambda: {} # noqa: E731 has_tenki_auth = lambda: False # noqa: E731 resolve_tenki_project_id = lambda _explicit="": "" # noqa: E731 resolve_tenki_workspace_id = lambda _explicit="": "" # noqa: E731 + terminal_cfg = load_config_readonly().get("terminal", {}) + if not isinstance(terminal_cfg, dict): + terminal_cfg = {} if has_tenki_auth(): check_ok("Tenki auth", "(configured)") @@ -1542,16 +1578,18 @@ def run_doctor(args): issues, ) - workspace_id = resolve_tenki_workspace_id(os.getenv("TERMINAL_TENKI_WORKSPACE_ID", "")) - project_id = resolve_tenki_project_id(os.getenv("TERMINAL_TENKI_PROJECT_ID", "")) + workspace_id = resolve_tenki_workspace_id( + os.getenv("TERMINAL_TENKI_WORKSPACE_ID") or terminal_cfg.get("tenki_workspace_id", "") + ) + project_id = resolve_tenki_project_id( + os.getenv("TERMINAL_TENKI_PROJECT_ID") or terminal_cfg.get("tenki_project_id", "") + ) if workspace_id and project_id: check_ok("Tenki workspace/project", "(configured)") else: - _fail_and_issue( + check_warn( "Tenki workspace/project not configured", - "(required for TERMINAL_ENV=tenki)", - "Run tenki login or set terminal.tenki_workspace_id and terminal.tenki_project_id", - issues, + "(optional for sessions; required for volume-backed workflows)", ) if importlib.util.find_spec("tenki_sandbox") is not None: @@ -2207,8 +2245,10 @@ def _probe_azure_entra() -> _ConnectivityResult: else: check_warn(item["name"], "(system dependency not met)") - # Count disabled tools with API key requirements - api_disabled = [u for u in unavailable if (u.get("missing_vars") or u.get("env_vars"))] + # Count missing API-key requirements only for toolsets enabled in the + # current CLI platform. Default-off or explicitly disabled toolsets may + # still show warnings above, but should not pollute the final summary. + api_disabled = _missing_api_key_toolsets_for_summary(unavailable) if api_disabled: issues.append("Run 'hermes setup' to configure missing API keys for full tool access") except Exception as e: diff --git a/hermes_cli/setup.py b/hermes_cli/setup.py index e09a410fb3b62..fd2177af9b8d6 100644 --- a/hermes_cli/setup.py +++ b/hermes_cli/setup.py @@ -673,7 +673,7 @@ def _print_setup_summary(config: dict, hermes_home): def _prompt_container_resources(config: dict): - """Prompt for container resource settings (Docker, Singularity, Modal, Daytona).""" + """Prompt for container resource settings (Docker, Singularity, Modal, Daytona, Tenki).""" terminal = config.setdefault("terminal", {}) print() @@ -828,17 +828,24 @@ def _install_neutts_deps() -> bool: print_info("Installing neutts Python package...") print_info("This will also download the TTS model (~300MB) on first use.") print() + + # Route through the canonical uv → pip → ensurepip ladder so pip-less + # venvs (Ubuntu 25.10 `python -m venv`, `uv venv`) work out of the box. + from hermes_cli.tools_config import _pip_install + try: - subprocess.run( - [sys.executable, "-m", "pip", "install", "-U", "neutts[all]", "--quiet"], - check=True, timeout=300, - ) - print_success("neutts installed successfully") - return True - except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e: + result = _pip_install(["-U", "neutts[all]", "--quiet"], timeout=300) + except Exception as e: print_error(f"Failed to install neutts: {e}") - print_info("Try manually: python -m pip install -U neutts[all]") + print_info("Try manually: uv pip install -U 'neutts[all]'") return False + if result.returncode == 0: + print_success("neutts installed successfully") + return True + err = (result.stderr or "").strip() + print_error(f"Failed to install neutts: {err[:300] if err else 'install failed'}") + print_info("Try manually: uv pip install -U 'neutts[all]'") + return False def _install_kittentts_deps() -> bool: @@ -853,17 +860,22 @@ def _install_kittentts_deps() -> bool: print() print_info("Installing kittentts Python package (~25-80MB model downloaded on first use)...") print() + + from hermes_cli.tools_config import _pip_install + try: - subprocess.run( - [sys.executable, "-m", "pip", "install", "-U", wheel_url, "soundfile", "--quiet"], - check=True, timeout=300, - ) - print_success("kittentts installed successfully") - return True - except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e: + result = _pip_install(["-U", wheel_url, "soundfile", "--quiet"], timeout=300) + except Exception as e: print_error(f"Failed to install kittentts: {e}") - print_info(f"Try manually: python -m pip install -U '{wheel_url}' soundfile") + print_info(f"Try manually: uv pip install -U '{wheel_url}' soundfile") return False + if result.returncode == 0: + print_success("kittentts installed successfully") + return True + err = (result.stderr or "").strip() + print_error(f"Failed to install kittentts: {err[:300] if err else 'install failed'}") + print_info(f"Try manually: uv pip install -U '{wheel_url}' soundfile") + return False def _xai_oauth_logged_in_for_setup() -> bool: @@ -881,7 +893,7 @@ def _xai_oauth_logged_in_for_setup() -> bool: def _run_xai_oauth_login_from_setup() -> bool: - """Run the xAI Grok OAuth loopback login from inside the setup wizard. + """Run the xAI Grok OAuth device-code login from inside the setup wizard. Returns True on success, False on any failure (the caller falls back to whatever the user picked next, e.g. Edge TTS). @@ -892,7 +904,7 @@ def _run_xai_oauth_login_from_setup() -> bool: _is_remote_session, _save_xai_oauth_tokens, _update_config_for_provider, - _xai_oauth_loopback_login, + _xai_oauth_device_code_login, ) except Exception as exc: print_warning(f"xAI Grok OAuth helpers unavailable: {exc}") @@ -902,12 +914,13 @@ def _run_xai_oauth_login_from_setup() -> bool: print() print_info("Signing in to xAI Grok OAuth (SuperGrok / Premium+)...") try: - creds = _xai_oauth_loopback_login(open_browser=open_browser) + creds = _xai_oauth_device_code_login(open_browser=open_browser) _save_xai_oauth_tokens( creds["tokens"], discovery=creds.get("discovery"), redirect_uri=creds.get("redirect_uri", ""), last_refresh=creds.get("last_refresh"), + auth_mode="oauth_device_code", ) _update_config_for_provider( "xai-oauth", creds.get("base_url", DEFAULT_XAI_OAUTH_BASE_URL) @@ -1183,11 +1196,12 @@ def setup_terminal_backend(config: dict): "Modal - serverless cloud sandbox", "SSH - run on a remote machine", "Daytona - persistent cloud development environment", + "Tenki Agent - Tenki cloud sandbox", ] - idx_to_backend = {0: "local", 1: "docker", 2: "modal", 3: "ssh", 4: "daytona"} - backend_to_idx = {"local": 0, "docker": 1, "modal": 2, "ssh": 3, "daytona": 4} + idx_to_backend = {0: "local", 1: "docker", 2: "modal", 3: "ssh", 4: "daytona", 5: "tenki"} + backend_to_idx = {"local": 0, "docker": 1, "modal": 2, "ssh": 3, "daytona": 4, "tenki": 5} - next_idx = 5 + next_idx = 6 if is_linux: terminal_choices.append("Singularity/Apptainer - HPC-friendly container") idx_to_backend[next_idx] = "singularity" @@ -1301,32 +1315,13 @@ def setup_terminal_backend(config: dict): __import__("modal") except ImportError: print_info("Installing modal SDK...") - import subprocess - - uv_bin = shutil.which("uv") - if uv_bin: - result = subprocess.run( - [ - uv_bin, - "pip", - "install", - "--python", - sys.executable, - "modal", - ], - capture_output=True, - text=True, - ) - else: - result = subprocess.run( - [sys.executable, "-m", "pip", "install", "modal"], - capture_output=True, - text=True, - ) + from hermes_cli.tools_config import _pip_install + + result = _pip_install(["modal"]) if result.returncode == 0: print_success("modal SDK installed") else: - print_warning("Install failed — run manually: pip install modal") + print_warning("Install failed — run manually: uv pip install modal") # Modal token print() @@ -1361,25 +1356,13 @@ def setup_terminal_backend(config: dict): __import__("daytona") except ImportError: print_info("Installing daytona SDK...") - import subprocess + from hermes_cli.tools_config import _pip_install - uv_bin = shutil.which("uv") - if uv_bin: - result = subprocess.run( - [uv_bin, "pip", "install", "--python", sys.executable, "daytona"], - capture_output=True, - text=True, - ) - else: - result = subprocess.run( - [sys.executable, "-m", "pip", "install", "daytona"], - capture_output=True, - text=True, - ) + result = _pip_install(["daytona"]) if result.returncode == 0: print_success("daytona SDK installed") else: - print_warning("Install failed — run manually: pip install daytona") + print_warning("Install failed — run manually: uv pip install daytona") if result.stderr: print_info(f" Error: {result.stderr.strip().splitlines()[-1]}") @@ -1404,6 +1387,82 @@ def setup_terminal_backend(config: dict): "daytona_image", "nikolaik/python-nodejs:python3.11-nodejs20" ) + elif selected_backend == "tenki": + print_success("Terminal backend: Tenki Agent") + print_info("Cloud sandboxes are created on demand and terminated by default.") + print_info("Requires Tenki CLI login or TENKI_AUTH_TOKEN/TENKI_API_KEY.") + + try: + __import__("tenki_sandbox") + except ImportError: + print_info("Installing Tenki SDK...") + import subprocess + + uv_bin = shutil.which("uv") + package = "tenki-sandbox==0.1.1" + if uv_bin: + result = subprocess.run( + [uv_bin, "pip", "install", "--python", sys.executable, package], + capture_output=True, + text=True, + ) + else: + result = subprocess.run( + [sys.executable, "-m", "pip", "install", package], + capture_output=True, + text=True, + ) + if result.returncode == 0: + print_success("Tenki SDK installed") + else: + print_warning("Install failed — run manually: pip install tenki-sandbox==0.1.1") + if result.stderr: + print_info(f" Error: {result.stderr.strip().splitlines()[-1]}") + + from tools.tenki_config import ( + has_tenki_auth, + resolve_tenki_api_endpoint, + resolve_tenki_project_id, + resolve_tenki_workspace_id, + ) + + terminal = config.setdefault("terminal", {}) + endpoint = resolve_tenki_api_endpoint(terminal.get("tenki_api_endpoint", "")) + workspace_id = resolve_tenki_workspace_id(terminal.get("tenki_workspace_id", "")) + project_id = resolve_tenki_project_id(terminal.get("tenki_project_id", "")) + + terminal["tenki_api_endpoint"] = endpoint + if workspace_id: + terminal["tenki_workspace_id"] = workspace_id + if project_id: + terminal["tenki_project_id"] = project_id + terminal.setdefault("tenki_image", "") + terminal.setdefault("tenki_name_prefix", "hermes") + terminal.setdefault("tenki_allow_inbound", False) + terminal.setdefault("tenki_allow_outbound", True) + terminal.setdefault("tenki_max_duration", 3600) + terminal.setdefault("tenki_idle_timeout", 0) + terminal.setdefault("tenki_pause_retention", 0) + terminal.setdefault("tenki_sync_hermes_home", False) + if current_backend == "tenki": + terminal.setdefault("container_persistent", False) + terminal.setdefault("cwd", "/home/tenki") + else: + terminal["container_persistent"] = False + terminal["cwd"] = "/home/tenki" + + print_info(f" Endpoint: {endpoint}") + print_info(f" Workspace: {workspace_id or '(not found; run tenki login)'}") + print_info(f" Project: {project_id or '(not found; run tenki login)'}") + if has_tenki_auth(): + print_info(" Tenki auth: already configured") + else: + print_warning(" Tenki auth not found") + token = prompt(" Tenki token/API key (optional; leave blank to run tenki login)", password=True) + if token: + save_env_value("TENKI_API_KEY", token) + print_success(" Configured") + elif selected_backend == "ssh": print_success("Terminal backend: SSH") print_info("Run commands on a remote machine via SSH.") @@ -1481,9 +1540,9 @@ def _apply_default_agent_settings(config: dict): config.setdefault("compression", {})["enabled"] = True config["compression"]["threshold"] = 0.50 - # Default to never auto-resetting sessions. The gateway treats absent - # session_reset as "both", so we must write "none" explicitly to make - # the no-auto-reset default actually take effect. + # Default: never auto-reset sessions. This matches the gateway's own + # default (SessionResetPolicy.mode = "none"); we still write it + # explicitly so the choice is visible/editable in config.yaml. config.setdefault("session_reset", {})["mode"] = "none" save_config(config) @@ -1594,19 +1653,19 @@ def setup_agent_settings(config: dict): print_info("") reset_choices = [ - "Inactivity + daily reset (recommended - reset whichever comes first)", + "Inactivity + daily reset (reset whichever comes first)", "Inactivity only (reset after N minutes of no messages)", "Daily only (reset at a fixed hour each day)", - "Never auto-reset (context lives until /reset or context compression)", + "Never auto-reset (recommended - context lives until /reset or context compression)", "Keep current settings", ] current_policy = config.get("session_reset", {}) - current_mode = current_policy.get("mode", "both") + current_mode = current_policy.get("mode", "none") current_idle = current_policy.get("idle_minutes", 1440) current_hour = current_policy.get("at_hour", 4) - default_reset = {"both": 0, "idle": 1, "daily": 2, "none": 3}.get(current_mode, 0) + default_reset = {"both": 0, "idle": 1, "daily": 2, "none": 3}.get(current_mode, 3) reset_idx = prompt_choice("Session reset mode:", reset_choices, default_reset) @@ -3053,6 +3112,12 @@ def _blank_slate_minimal_toolsets(config: dict): continue # platform composites — not user-facing toolsets if isinstance(tdef, dict) and tdef.get("includes"): continue # composite groupings, not leaf toolsets + if isinstance(tdef, dict) and tdef.get("posture"): + continue # posture toolsets (e.g. coding) are session-level + # selections made by agent/coding_context.py — not permanent + # user-facing disables. Adding them here causes model_tools + # to subtract their tools (terminal, read_file, …) from the + # minimal Blank Slate surface (#57315). all_keys.add(k) disabled = sorted(all_keys - keep) diff --git a/hermes_cli/status.py b/hermes_cli/status.py index becc94034004d..43c7a18fcaf7a 100644 --- a/hermes_cli/status.py +++ b/hermes_cli/status.py @@ -425,6 +425,33 @@ def _resolve_env(env_ref) -> str: elif terminal_env == "daytona": daytona_image = os.getenv("TERMINAL_DAYTONA_IMAGE", "nikolaik/python-nodejs:python3.11-nodejs20") print(f" Daytona Image: {daytona_image}") + elif terminal_env == "tenki": + from tools.tenki_config import ( + resolve_tenki_api_endpoint, + resolve_tenki_project_id, + resolve_tenki_workspace_id, + ) + + tenki_image = os.getenv("TERMINAL_TENKI_IMAGE") or terminal_cfg.get("tenki_image", "") + tenki_endpoint = resolve_tenki_api_endpoint( + os.getenv("TERMINAL_TENKI_API_ENDPOINT") or terminal_cfg.get("tenki_api_endpoint", "") + ) + tenki_workspace = resolve_tenki_workspace_id( + os.getenv("TERMINAL_TENKI_WORKSPACE_ID") or terminal_cfg.get("tenki_workspace_id", "") + ) + tenki_project = resolve_tenki_project_id( + os.getenv("TERMINAL_TENKI_PROJECT_ID") or terminal_cfg.get("tenki_project_id", "") + ) + tenki_sync_value = os.getenv("TERMINAL_TENKI_SYNC_HERMES_HOME") + if tenki_sync_value is None: + tenki_sync = bool(terminal_cfg.get("tenki_sync_hermes_home", False)) + else: + tenki_sync = tenki_sync_value.lower() in {"true", "1", "yes"} + print(f" Tenki Image: {tenki_image or '(Tenki default)'}") + print(f" Endpoint: {tenki_endpoint}") + print(f" Workspace: {tenki_workspace or '(not found)'}") + print(f" Project: {tenki_project or '(not found)'}") + print(f" Sync .hermes: {check_mark(tenki_sync)} {'enabled' if tenki_sync else 'disabled'}") sudo_password = os.getenv("SUDO_PASSWORD", "") print(f" Sudo: {check_mark(bool(sudo_password))} {'enabled' if sudo_password else 'disabled'}") @@ -543,17 +570,39 @@ def _resolve_env(env_ref) -> str: print() print(color("◆ Sessions", Colors.CYAN, Colors.BOLD)) - sessions_file = get_hermes_home() / "sessions" / "sessions.json" - if sessions_file.exists(): - import json + # Gateway session count: state.db is the source of truth (#9006); + # fall back to sessions.json for pre-migration installs. + _session_count = None + try: + from hermes_state import SessionDB + _db = SessionDB() try: - with open(sessions_file, encoding="utf-8") as f: - data = json.load(f) - print(f" Active: {len(data)} session(s)") - except Exception: - print(" Active: (error reading sessions file)") + _lister = getattr(_db, "list_gateway_sessions", None) + if callable(_lister): + _session_count = len(_lister(active_only=True)) + finally: + _db.close() + except Exception: + _session_count = None + + if _session_count is not None and _session_count > 0: + print(f" Active: {_session_count} session(s)") else: - print(" Active: 0") + sessions_file = get_hermes_home() / "sessions" / "sessions.json" + if sessions_file.exists(): + import json + try: + with open(sessions_file, encoding="utf-8") as f: + data = json.load(f) + _entries = { + k: v for k, v in data.items() + if not str(k).startswith("_") + } if isinstance(data, dict) else {} + print(f" Active: {len(_entries)} session(s)") + except Exception: + print(" Active: (error reading sessions file)") + else: + print(f" Active: {_session_count if _session_count is not None else 0}") # ========================================================================= # Deep checks diff --git a/hermes_cli/tips.py b/hermes_cli/tips.py index 107d9d19161ae..9b8a8466dd4a6 100644 --- a/hermes_cli/tips.py +++ b/hermes_cli/tips.py @@ -433,7 +433,7 @@ "hermes chat --source tool tags programmatic chats so they don't clutter hermes sessions list.", 'hermes dump --show-keys includes redacted API key fingerprints for deeper support debugging.', 'hermes sessions rename "new title" renames any past session; hermes sessions delete removes one.', - 'hermes import restores a session export or profile archive produced by sessions export or profile export.', + 'hermes import restores a full Hermes backup zip; session JSON/JSONL exports import from the dashboard Sessions page.', 'hermes fallback manages the fallback_model chain interactively — no hand-editing config.yaml.', 'hermes pairing rotates the DM pairing token — the first messager after rotation claims access to the bot.', 'hermes setup walks first-time users through provider, keys, and platform wiring in one interactive flow.', diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py index e3d431bed3348..55692d36b2c9f 100644 --- a/hermes_cli/web_server.py +++ b/hermes_cli/web_server.py @@ -12,11 +12,16 @@ from contextlib import asynccontextmanager, contextmanager import asyncio +import atexit import base64 import binascii +import concurrent.futures +import functools from dataclasses import dataclass from datetime import datetime, timezone +import hashlib import hmac +import inspect import importlib.util import json import logging @@ -24,6 +29,7 @@ import os import re import secrets +import shlex import shutil import stat import subprocess @@ -69,14 +75,10 @@ write_platform_config_field, _deep_merge, ) -from hermes_cli.memory_providers import ( - MemoryProvider, - ProviderField, - get_memory_provider, -) from gateway.status import ( derive_gateway_busy, derive_gateway_drainable, + get_running_pid_cached, get_running_pid, get_runtime_status_running_pid, parse_active_agents, @@ -93,6 +95,7 @@ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response from fastapi.staticfiles import StaticFiles from pydantic import BaseModel + from starlette.concurrency import run_in_threadpool except ImportError: # First try lazy-installing the dashboard extras. Only the user actually # running `hermes dashboard` needs fastapi+uvicorn; lazy install keeps @@ -108,6 +111,7 @@ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response from fastapi.staticfiles import StaticFiles from pydantic import BaseModel + from starlette.concurrency import run_in_threadpool except Exception: raise SystemExit( "Web UI requires fastapi and uvicorn.\n" @@ -200,9 +204,14 @@ async def _lifespan(app: "FastAPI"): ) cron_thread.start() + # Reap idle/dead keep-alive PTY sessions in the background (30-min TTL). + pty_reaper_task = asyncio.create_task(run_reaper(PTY_REGISTRY)) + try: yield finally: + pty_reaper_task.cancel() + await PTY_REGISTRY.close_all() if cron_stop is not None: cron_stop.set() @@ -477,6 +486,73 @@ async def host_header_middleware(request: Request, call_next): return await call_next(request) +@app.middleware("http") +async def _plugin_api_runtime_gate(request: Request, call_next): + """Block requests to disabled plugin API routes at request time. + + :func:`_mount_plugin_api_routes` gates at import time, but if a plugin + is disabled *after* the dashboard is already running, its FastAPI router + remains mounted until restart. This middleware enforces the enabled/ + disabled policy on every request to ``/api/plugins/{name}/...`` so that + runtime config changes take effect immediately. + + Registered BEFORE the auth middlewares (so it executes AFTER them): a + request that hasn't cleared auth must get auth's 401 first, never this + gate's 404 — otherwise an unauthenticated caller could fingerprint which + plugins are installed/enabled by reading the status code. We only reach + the enabled/disabled check for a request that auth already let through. + """ + path = request.url.path + if path.startswith("/api/plugins/"): + # Only gate authenticated requests. Unauthenticated ones fall + # through so auth_middleware / the OAuth gate return 401 first and + # this route can't be used as a plugin-name oracle. + _authed = ( + getattr(request.state, "token_authenticated", False) + or getattr(request.app.state, "auth_required", False) + or _has_valid_session_token(request) + or _has_valid_query_token(request, path) + ) + if _authed: + # Extract plugin name from /api/plugins//... + parts = path.split("/") + # parts: ['', 'api', 'plugins', '', ...] + if len(parts) >= 4: + plugin_name = parts[3] + if plugin_name: + try: + from hermes_cli.plugins_cmd import ( + _get_enabled_set, + _get_disabled_set, + ) + enabled_set = _get_enabled_set() + disabled_set = _get_disabled_set() + except Exception: + enabled_set = set() + disabled_set = set() + # Determine plugin source. Check the cached plugin list; + # if not found, assume user plugin (safe default — blocks). + plugins = _get_dashboard_plugins() + plugin = next( + (p for p in plugins if p.get("name") == plugin_name), + None, + ) + source = plugin.get("source") if plugin else "user" + if source == "user": + if plugin_name in disabled_set or plugin_name not in enabled_set: + return JSONResponse( + status_code=404, + content={"detail": "Plugin not found"}, + ) + elif source == "bundled": + if plugin_name in disabled_set: + return JSONResponse( + status_code=404, + content={"detail": "Plugin not found"}, + ) + return await call_next(request) + + # --------------------------------------------------------------------------- # Dashboard OAuth auth gate — engaged only when start_server flags the # bind as non-loopback-without-insecure. No-op pass-through in loopback @@ -592,15 +668,10 @@ async def _token_auth_seam(request: Request, call_next): "description": "Input behavior while agent is running", "options": ["interrupt", "queue", "steer"], }, - "memory.provider": { - "type": "select", - "description": "Memory provider plugin", - "options": ["builtin", "honcho"], - }, "approvals.mode": { "type": "select", "description": "Dangerous command approval mode", - "options": ["ask", "yolo", "deny"], + "options": ["manual", "smart", "off"], }, "context.engine": { "type": "select", @@ -625,7 +696,7 @@ async def _token_auth_seam(request: Request, call_next): "delegation.reasoning_effort": { "type": "select", "description": "Reasoning effort for delegated subagents", - "options": ["", "low", "medium", "high"], + "options": ["", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"], }, "updates.non_interactive_local_changes": { "type": "select", @@ -637,6 +708,14 @@ async def _token_auth_seam(request: Request, call_next): ), "options": ["stash", "discard"], }, + "updates.refresh_cua_driver": { + "type": "bool", + "description": ( + "Refresh an already-installed cua-driver during hermes update. " + "Disable this on non-admin macOS accounts where /Applications is " + "not writable." + ), + }, } # Categories with fewer fields get merged into "general" to avoid tab sprawl. @@ -701,7 +780,7 @@ def _build_schema_from_config( full_key = f"{prefix}.{key}" if prefix else key # Skip internal / version keys - if full_key in {"_config_version",}: + if full_key in {"_config_version", "memory.provider"}: continue # Category is the first path component for nested keys, or "general" @@ -773,7 +852,11 @@ class EnvVarReveal(BaseModel): class MemoryProviderConfigUpdate(BaseModel): - values: Dict[str, str] = {} + values: Dict[str, Any] = {} + + +class MemoryProviderSetupRequest(BaseModel): + values: Dict[str, Any] = {} class MessagingPlatformUpdate(BaseModel): @@ -794,6 +877,18 @@ class TelegramOnboardingApply(BaseModel): profile: Optional[str] = None +class WhatsAppOnboardingStart(BaseModel): + mode: Optional[str] = "bot" + allowed_users: Optional[str] = "" + profile: Optional[str] = None + + +class WhatsAppOnboardingApply(BaseModel): + mode: Optional[str] = None + allowed_users: Optional[str] = None + profile: Optional[str] = None + + class AudioTranscriptionRequest(BaseModel): data_url: str mime_type: Optional[str] = None @@ -805,6 +900,11 @@ class ManagedFileUpload(BaseModel): overwrite: bool = True +class ChatImageUpload(BaseModel): + data_url: str + filename: Optional[str] = None + + class ManagedDirectoryCreate(BaseModel): path: str @@ -873,8 +973,10 @@ class MoaModelSlot(BaseModel): class MoaPresetPayload(BaseModel): reference_models: list[MoaModelSlot] = [] aggregator: MoaModelSlot = MoaModelSlot() - reference_temperature: float = 0.6 - aggregator_temperature: float = 0.4 + # None = temperature omitted from API calls (provider default), matching + # single-model agent behavior. + reference_temperature: Optional[float] = None + aggregator_temperature: Optional[float] = None max_tokens: int = 4096 enabled: bool = True @@ -887,8 +989,8 @@ class MoaConfigPayload(BaseModel): # clients during this PR's transition window. reference_models: list[MoaModelSlot] = [] aggregator: MoaModelSlot = MoaModelSlot() - reference_temperature: float = 0.6 - aggregator_temperature: float = 0.4 + reference_temperature: Optional[float] = None + aggregator_temperature: Optional[float] = None max_tokens: int = 4096 enabled: bool = True profile: Optional[str] = None @@ -921,19 +1023,42 @@ def _normalize_main_model_assignment(provider: str, model: str) -> tuple[str, st ``normalize_model_for_provider`` (e.g. ``anthropic/claude-opus-4.6`` on native anthropic → ``claude-opus-4-6``). """ + from hermes_cli.config import get_compatible_custom_providers from hermes_cli.models import _KNOWN_PROVIDER_NAMES, normalize_provider from hermes_cli.model_normalize import normalize_model_for_provider + from hermes_cli.providers import resolve_custom_provider, resolve_user_provider prov_in = (provider or "").strip() model_in = (model or "").strip() canonical = normalize_provider(prov_in) + # User-declared providers are real routing targets, not analytics vendor + # labels. Resolve them before the unknown-vendor fallback. ``providers:`` + # keeps its declared bare slug; ``custom_providers:`` canonicalizes both a + # bare display name and ``custom:`` to the durable custom slug. + try: + cfg = load_config() + except Exception: + cfg = {} + user_providers = cfg.get("providers") if isinstance(cfg, dict) else None + user_provider = resolve_user_provider( + prov_in, user_providers if isinstance(user_providers, dict) else {} + ) + custom_provider = resolve_custom_provider( + prov_in, + get_compatible_custom_providers(cfg) if isinstance(cfg, dict) else [], + ) + if user_provider is not None: + return user_provider.id, model_in + if custom_provider is not None: + return custom_provider.id, model_in + if canonical not in _KNOWN_PROVIDER_NAMES and "/" in model_in: # Vendor prefix posing as a provider (analytics fallback). Resolve # against the user's current provider when it's an aggregator that # serves vendor-prefixed slugs; otherwise default to openrouter. try: - cur_cfg = load_config().get("model", {}) + cur_cfg = cfg.get("model", {}) cur_provider = ( str(cur_cfg.get("provider", "") or "").strip().lower() if isinstance(cur_cfg, dict) else "" @@ -1027,6 +1152,8 @@ def _apply_main_model_assignment( ) _GATEWAY_HEALTH_TIMEOUT = 3.0 +_STATUS_ACTIVE_SESSIONS_TIMEOUT = 0.75 + # DEPRECATED (scheduled for removal): GATEWAY_HEALTH_URL / GATEWAY_HEALTH_TIMEOUT. # Cross-container / cross-host gateway liveness detection will be folded into a # first-class dashboard config key so it's no longer Docker-adjacent lore buried @@ -1077,6 +1204,51 @@ def _probe_gateway_health() -> tuple[bool, dict | None]: return False, None +def _count_status_active_sessions() -> int: + """Return the dashboard status active-session count. + + This is best-effort status garnish, not a critical path. Use a read-only + connection so /api/status never tries to initialise or migrate state.db + while another Hermes process is writing to it. + """ + from hermes_state import DEFAULT_DB_PATH, SessionDB + + # read_only opens require the DB to already exist (see SessionDB.__init__ + # read_only contract) — on a fresh install every /api/status poll would + # otherwise pay an OperationalError until the first session is written. + if not DEFAULT_DB_PATH.exists(): + return 0 + + db = SessionDB(read_only=True) + try: + sessions = db.list_sessions_rich(limit=50, compact_rows=True) + now = time.time() + return sum( + 1 for s in sessions + if s.get("ended_at") is None + and (now - s.get("last_active", s.get("started_at", 0))) < 300 + ) + finally: + db.close() + + +async def _status_active_sessions() -> int: + loop = asyncio.get_running_loop() + try: + return await asyncio.wait_for( + loop.run_in_executor(None, _count_status_active_sessions), + timeout=_STATUS_ACTIVE_SESSIONS_TIMEOUT, + ) + except asyncio.TimeoutError: + _log.debug( + "/api/status active session count exceeded %.2fs; returning 0", + _STATUS_ACTIVE_SESSIONS_TIMEOUT, + ) + except Exception as exc: + _log.debug("/api/status active session count unavailable: %s", exc) + return 0 + + # Image MIME types this endpoint will serve. Extension-allowlisted so an # authenticated caller can't pull non-image files through it. _MEDIA_CONTENT_TYPES = { @@ -1117,6 +1289,90 @@ class ManagedFilesPolicy: "target", "venv", } + +# Filenames that must never be listed, read, or downloaded through the +# managed-files API. These typically contain credentials (API keys, tokens) +# and exposing them through the dashboard file browser is a security leak — +# see issue #57505. The set mirrors the credential-file basenames of the two +# canonical credential guards elsewhere in the codebase +# (agent.file_safety.get_read_block_error and +# gateway.platforms.base._ROOT_CREDENTIAL_FILES) so the dashboard Files tab +# doesn't lag behind them — an operator can point the managed root at +# HERMES_HOME itself, at which point every one of these basenames is a live +# secret store sitting in the browsable tree. +_SENSITIVE_MANAGED_FILE_BASENAMES = frozenset({ + "auth.json", + "auth.lock", + "credentials", + "config.yaml", + ".anthropic_oauth.json", + "google_token.json", + "google_oauth_pending.json", + "google_oauth.json", + "webhook_subscriptions.json", + "bws_cache.json", + # git's credential-store helper cache (agent.file_safety blocks this too). + ".git-credentials", +}) + +# Directory names whose entire subtree is credential material. Both canonical +# guards deny these as directory trees, not basenames: +# * gateway.platforms.base._ROOT_CREDENTIAL_DIRS = {"pairing", "mcp-tokens"} +# * agent.file_safety.get_read_block_error (mcp-tokens/ prefix match) +# The managed-files API lets the browser descend into subdirs, so a +# basename-only guard would still expose e.g. ``mcp-tokens/.json`` +# (live MCP OAuth tokens) and ``pairing/``. We match on ANY path component +# so these trees are blocked wherever they appear under the browsable root, +# without needing to resolve them relative to HERMES_HOME. +_SENSITIVE_MANAGED_DIR_NAMES = frozenset({ + "mcp-tokens", + "pairing", +}) + + +def _is_sensitive_filename(name: str) -> bool: + """Return True for a basename the managed-files API must never expose. + + Covers ``.env`` / ``.env.`` / ``.envrc`` variants plus the + canonical Hermes credential-store basenames (see + ``_SENSITIVE_MANAGED_FILE_BASENAMES`` above). + + Case-insensitive so ``.ENV`` / ``.Env.local`` / ``Auth.JSON`` on + case-insensitive filesystems (macOS/Windows mounts) can't slip past + the guard. + + Basename-only: for the directory-tree credential stores + (``mcp-tokens/``, ``pairing/``) that the canonical guards also deny, + use :func:`_is_sensitive_path`, which the API call sites route through. + """ + lowered = name.lower() + if lowered == ".env" or lowered.startswith(".env.") or lowered == ".envrc": + return True + return lowered in _SENSITIVE_MANAGED_FILE_BASENAMES + + +def _is_sensitive_path(path: Path) -> bool: + """Return True for any path the managed-files API must never expose. + + Combines the basename denylist (:func:`_is_sensitive_filename`) with a + credential-directory-tree check: a path is sensitive if its own basename + is sensitive OR any of its path components is a credential directory + (``mcp-tokens`` / ``pairing``). The component match is case-insensitive + and needs no HERMES_HOME resolution, so it blocks these trees wherever + they sit under the operator-configured managed root — closing the gap + the canonical guards cover as directory trees but a basename-only check + would miss. + + Read-side only: this guards list/read/download (the #57505 exfil surface). + The write endpoints (upload/mkdir/delete) are a separate threat class + handled by the write-path checks; extending this guard to them is out of + scope for this fix. + """ + if _is_sensitive_filename(path.name): + return True + return any(part.lower() in _SENSITIVE_MANAGED_DIR_NAMES for part in path.parts) + + _FS_DATA_URL_MAX_BYTES = 16 * 1024 * 1024 _FS_TEXT_SOURCE_MAX_BYTES = 64 * 1024 * 1024 _FS_TEXT_PREVIEW_MAX_BYTES = 512 * 1024 @@ -1538,6 +1794,91 @@ def _decode_data_url(data_url: str) -> tuple[bytes, str]: return data, mime_type +_CHAT_IMAGE_UPLOAD_MAX_BYTES = 25 * 1024 * 1024 +_CHAT_IMAGE_ALLOWED_EXTENSIONS = frozenset({".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"}) +_CHAT_IMAGE_MAGIC: tuple[tuple[bytes, str], ...] = ( + (b"\x89PNG\r\n\x1a\n", ".png"), + (b"\xff\xd8\xff", ".jpg"), + (b"GIF87a", ".gif"), + (b"GIF89a", ".gif"), + (b"BM", ".bmp"), +) + + +def _sanitize_chat_image_filename(filename: str | None) -> str: + candidate = Path(str(filename or "").strip()).name + candidate = re.sub(r"[\x00-\x1f]+", "_", candidate) + candidate = candidate.strip().strip(".") + return candidate or "pasted-image" + + +def _chat_image_extension(data: bytes) -> str | None: + head = data[:16] + if head.startswith(b"RIFF") and head[8:12] == b"WEBP": + return ".webp" + for sig, ext in _CHAT_IMAGE_MAGIC: + if head.startswith(sig): + return ext + return None + + +def _decode_chat_image_upload(payload: ChatImageUpload) -> tuple[bytes, str, str]: + data, mime_type = _decode_data_url(payload.data_url) + if not mime_type.lower().startswith("image/"): + raise HTTPException(status_code=400, detail="Upload payload must be an image") + if len(data) > _CHAT_IMAGE_UPLOAD_MAX_BYTES: + mb = _CHAT_IMAGE_UPLOAD_MAX_BYTES // (1024 * 1024) + raise HTTPException(status_code=413, detail=f"Image is too large; cap is {mb} MB") + + ext = _chat_image_extension(data) + if ext not in _CHAT_IMAGE_ALLOWED_EXTENSIONS: + raise HTTPException(status_code=400, detail="Unsupported image type") + return data, mime_type, ext + + +@app.post("/api/chat/image-upload") +async def upload_chat_image(payload: ChatImageUpload, profile: Optional[str] = None): + """Persist a browser-provided chat image where the embedded TUI can read it. + + The dashboard /chat page runs Hermes inside an xterm.js PTY. Browser + clipboard image bytes are not visible to the server-side clipboard, so the + page uploads them here, then drives the TUI's ``/image `` command + with the returned gateway-visible path. Files land under + ``HERMES_HOME/images/`` — the same directory ``clipboard.paste`` / + ``image.attach`` already use. + """ + data, mime_type, ext = _decode_chat_image_upload(payload) + with _profile_scope(profile) as scoped_home: + home = scoped_home or get_hermes_home() + img_dir = Path(home) / "images" + try: + img_dir.mkdir(parents=True, exist_ok=True) + except PermissionError: + raise HTTPException(status_code=403, detail="Image directory is not writable") + except OSError as exc: + raise HTTPException(status_code=500, detail=f"Could not create image directory: {exc}") + + stem = Path(_sanitize_chat_image_filename(payload.filename)).stem or "pasted-image" + stem = re.sub(r"[^A-Za-z0-9_.-]+", "_", stem).strip("._-") or "pasted-image" + ts = datetime.now().strftime("%Y%m%d_%H%M%S") + target = img_dir / f"dashboard_{ts}_{secrets.token_hex(4)}_{stem}{ext}" + + try: + target.write_bytes(data) + except PermissionError: + raise HTTPException(status_code=403, detail="Image directory is not writable") + except OSError as exc: + raise HTTPException(status_code=500, detail=f"Could not write image: {exc}") + + return { + "ok": True, + "path": str(target), + "name": target.name, + "bytes": len(data), + "mime_type": mime_type, + } + + @app.get("/api/files") async def list_managed_files(request: Request, path: Optional[str] = None): policy, target, display_path = _resolve_managed_path(path, request) @@ -1547,7 +1888,11 @@ async def list_managed_files(request: Request, path: Optional[str] = None): raise HTTPException(status_code=400, detail="Path is not a directory") try: - entries = [_managed_file_entry(policy, child) for child in target.iterdir()] + entries = [ + _managed_file_entry(policy, child) + for child in target.iterdir() + if not _is_sensitive_path(child) + ] except PermissionError: raise HTTPException(status_code=403, detail="Directory is not readable") except OSError as exc: @@ -1573,6 +1918,8 @@ async def read_managed_file(request: Request, path: str): raise HTTPException(status_code=404, detail="File not found") if not target.is_file(): raise HTTPException(status_code=400, detail="Path is not a file") + if _is_sensitive_path(target): + raise HTTPException(status_code=403, detail="Access to sensitive files is not allowed") try: size = target.stat().st_size @@ -1615,6 +1962,8 @@ async def download_managed_file(request: Request, path: str): raise HTTPException(status_code=404, detail="File not found") if not target.is_file(): raise HTTPException(status_code=400, detail="Path is not a file") + if _is_sensitive_path(target): + raise HTTPException(status_code=403, detail="Access to sensitive files is not allowed") try: size = target.stat().st_size @@ -1939,7 +2288,6 @@ def _git_path(path: str) -> str: class GitPathBody(BaseModel): path: str - class GitFileBody(BaseModel): path: str file: Optional[str] = None @@ -1985,6 +2333,11 @@ async def git_branches_route(path: str): return {"branches": await _git_op(_web_git.branch_list, _git_path(path))} +@app.get("/api/git/base-branches") +async def git_base_branches_route(path: str): + return {"branches": await _git_op(_web_git.base_branch_list, _git_path(path))} + + @app.get("/api/git/review/list") async def git_review_list_route(path: str, scope: str = "uncommitted", base: Optional[str] = None): return await _git_op(_web_git.review_list, _git_path(path), scope, base) @@ -2074,6 +2427,136 @@ async def git_branch_switch_route(body: GitBranchSwitchBody): return await _git_op(_web_git.branch_switch, _git_path(body.path), body.branch) +# Host TCP ports each port-binding gateway platform listens on, as +# ``platform-name -> (config port key, adapter default)``. Mirrors +# ``_PORT_BINDING_PLATFORM_VALUES`` in gateway/run.py and each adapter's +# DEFAULT_PORT / DEFAULT_WEBHOOK_PORT constant. Used only for the dashboard's +# gateway-topology readout — best-effort display data, not a bind source. +_PORT_BINDING_PLATFORM_PORTS: Dict[str, Tuple[str, int]] = { + "webhook": ("port", 8644), + "api_server": ("port", 8642), + "msgraph_webhook": ("port", 8646), + "feishu": ("webhook_port", 8765), + "wecom_callback": ("port", 8645), + "bluebubbles": ("webhook_port", 8645), + "sms": ("webhook_port", 8080), + "whatsapp_cloud": ("webhook_port", 8090), + "line": ("port", 8646), +} + +# Platform states that mean the adapter is NOT serving its port right now. +_PLATFORM_DEAD_STATES = frozenset({"fatal", "disconnected", "stopped"}) + + +def _profile_platform_ports(profile_home: Path, runtime: Optional[dict]) -> Dict[str, int]: + """Best-effort map of ``platform -> host TCP port`` for one profile's gateway. + + Reads the platforms the running gateway reported in its + ``gateway_state.json`` and resolves each port-binding platform's port from + the profile's ``config.yaml`` (top-level ``platforms:`` wins over + ``gateway.platforms:``, matching ``load_gateway_config`` precedence), + falling back to the adapter default. Display-only: env-var port overrides + (e.g. ``WEBHOOK_PORT`` in that profile's .env) are not resolved here. + """ + platforms = (runtime or {}).get("platforms") or {} + active = [ + name for name, state in platforms.items() + if name in _PORT_BINDING_PLATFORM_PORTS + and isinstance(state, dict) + and state.get("state") not in _PLATFORM_DEAD_STATES + ] + if not active: + return {} + + blocks: Dict[str, dict] = {} + try: + with open(profile_home / "config.yaml", encoding="utf-8") as f: + cfg = yaml.safe_load(f) or {} + gateway_cfg = cfg.get("gateway") if isinstance(cfg.get("gateway"), dict) else {} + # gateway.platforms first, top-level platforms second — later wins, + # matching the precedence in gateway.config.load_gateway_config(). + for src in ((gateway_cfg or {}).get("platforms"), cfg.get("platforms")): + if not isinstance(src, dict): + continue + for plat_name, plat_block in src.items(): + if isinstance(plat_block, dict): + blocks.setdefault(plat_name, {}).update(plat_block) + except Exception: + blocks = {} + + ports: Dict[str, int] = {} + for name in active: + port_key, default_port = _PORT_BINDING_PLATFORM_PORTS[name] + block = blocks.get(name) or {} + extra = block.get("extra") if isinstance(block.get("extra"), dict) else {} + raw = block.get(port_key, (extra or {}).get(port_key, default_port)) + try: + ports[name] = int(raw) + except (TypeError, ValueError): + ports[name] = default_port + return ports + + +def _collect_profile_gateway_topology() -> Dict[str, Any]: + """Enumerate profiles and the gateways serving them for ``/api/status``. + + Returns ``{"profiles": [...], "gateway_mode": ..., "gateways": [...]}``: + + * ``profiles`` — every profile on the host (default + named), from + ``profiles_to_serve(True)`` (the cheap enumeration chokepoint — no + per-profile config reads or skill counts). + * ``gateways`` — one entry per profile with a LIVE gateway process: + ``{"profile", "ports", "served_profiles"?}``. Liveness reuses + ``_check_gateway_running`` so this agrees with the profiles sidebar. + * ``gateway_mode`` — ``"multiplex"`` when the default gateway serves + multiple profiles (gateway.multiplex_profiles), ``"single"`` for one + live gateway, ``"multiple"`` for independent per-profile gateways, + ``"none"`` when nothing is running. + """ + try: + from hermes_cli.profiles import _check_gateway_running, profiles_to_serve + from gateway.status import read_runtime_status + homes = profiles_to_serve(True) + except Exception: + _log.debug("profile/gateway topology enumeration failed", exc_info=True) + return {"profiles": [], "gateway_mode": "unknown", "gateways": []} + + profile_names = [name for name, _home in homes] + gateways: List[Dict[str, Any]] = [] + multiplex = False + for name, home in homes: + try: + if not _check_gateway_running(home): + continue + except Exception: + continue + try: + runtime = read_runtime_status(home / "gateway_state.json") + except Exception: + runtime = None + served = [str(p) for p in ((runtime or {}).get("served_profiles") or [])] + if name == "default" and len(served) > 1: + multiplex = True + entry: Dict[str, Any] = { + "profile": name, + "ports": _profile_platform_ports(home, runtime), + } + if served: + entry["served_profiles"] = served + gateways.append(entry) + + if multiplex: + mode = "multiplex" + elif len(gateways) > 1: + mode = "multiple" + elif len(gateways) == 1: + mode = "single" + else: + mode = "none" + + return {"profiles": profile_names, "gateway_mode": mode, "gateways": gateways} + + @app.get("/api/status") async def get_status(profile: Optional[str] = None): status_scope = None @@ -2097,7 +2580,7 @@ async def get_status(profile: Optional[str] = None): # Try local PID check first (same-host). If that fails and a remote # GATEWAY_HEALTH_URL is configured, probe the gateway over HTTP so the # dashboard works when the gateway runs in a separate container. - gateway_pid = get_running_pid() + gateway_pid = get_running_pid_cached() gateway_running = gateway_pid is not None remote_health_body: dict | None = None @@ -2170,22 +2653,7 @@ async def get_status(profile: Optional[str] = None): if gateway_running and gateway_state is None and remote_health_body is not None: gateway_state = "running" - active_sessions = 0 - try: - from hermes_state import SessionDB - db = SessionDB() - try: - sessions = db.list_sessions_rich(limit=50) - now = time.time() - active_sessions = sum( - 1 for s in sessions - if s.get("ended_at") is None - and (now - s.get("last_active", s.get("started_at", 0))) < 300 - ) - finally: - db.close() - except Exception: - pass + active_sessions = await _status_active_sessions() # Busy/drainable readout (NAS lifecycle-safety gate). active_agents is # the in-flight gateway-turn count the gateway now persists at every @@ -2227,6 +2695,21 @@ async def get_status(profile: Optional[str] = None): # Module not importable yet (early startup) — leave as []. pass + # Nous bootstrap-session validity for the NAS health sweep. A hosted + # agent whose Nous auth dies terminally (invalid_grant / quarantine) + # looks HEALTHY to every liveness/connectivity probe — the machine, + # relay, and this dashboard all stay up — yet every inference turn + # fails. This is the ONLY signal that surfaces that condition, and it + # is determinable with no working token (local auth-store state). NAS + # re-mints the bootstrap session when it reads "terminal". Best-effort: + # never let auth classification break the public liveness probe. + nous_session_valid = "unknown" + try: + from hermes_cli.auth import get_nous_session_validity + nous_session_valid = get_nous_session_validity() + except Exception: + nous_session_valid = "unknown" + # Always-public liveness + auth-gate shape. Safe for external uptime # probes (NAS's wildcard-subdomain liveness probe), the SPA's pre-login # bootstrap, and anyone who can curl the host — i.e. exactly the audience @@ -2249,18 +2732,38 @@ async def get_status(profile: Optional[str] = None): "active_sessions": active_sessions, "auth_required": auth_required, "auth_providers": auth_providers, + "nous_session_valid": nous_session_valid, } - # Absolute host paths, the gateway PID, and the internal gateway health - # URL are deployment recon a liveness probe never needs. ``/api/status`` - # is in ``PUBLIC_API_PATHS`` so it bypasses dashboard auth; on a - # network-exposed (gated) bind that means *any* unauthenticated caller - # reaches it, and leaking host metadata there contradicts the allowlist's - # own contract ("version, gateway state, active session count, and the - # dashboard auth-gate shape. No bodies, no session content, no secrets"). - # Surface this detail only on a loopback / ``--insecure`` bind, where the - # dashboard is local-only and the caller is already inside the trust - # envelope — the same loopback/gated split ``should_require_auth`` draws. + # Profile + gateway topology: which profiles exist, whether one + # multiplexed gateway or several per-profile gateways serve them, and + # (gated) which host ports the live gateways' port-binding platforms + # listen on. Enumerating profiles walks the filesystem and probes the + # process table, so keep it off the event loop. + # + # Split by sensitivity: profile NAMES (``profiles``) and the gateway + # ``gateway_mode`` are low-sensitivity PRODUCT surface — Hermes Cloud + # renders the profile list in the Portal, which reads this endpoint over + # the network (a gated bind), so they must survive the auth gate. The + # per-gateway ``gateways[]`` detail carries host ports (deployment + # recon), so it stays gated with the host paths / PID below. + topology = await asyncio.get_running_loop().run_in_executor( + None, _collect_profile_gateway_topology + ) + status["profiles"] = topology["profiles"] + status["gateway_mode"] = topology["gateway_mode"] + + # Absolute host paths, the gateway PID, the internal gateway health + # URL, and per-gateway ports are deployment recon a liveness probe never + # needs. ``/api/status`` is in ``PUBLIC_API_PATHS`` so it bypasses + # dashboard auth; on a network-exposed (gated) bind that means *any* + # unauthenticated caller reaches it, and leaking host metadata there + # contradicts the allowlist's own contract ("version, gateway state, + # active session count, and the dashboard auth-gate shape. No bodies, no + # session content, no secrets"). Surface this detail only on a loopback + # / ``--insecure`` bind, where the dashboard is local-only and the + # caller is already inside the trust envelope — the same loopback/gated + # split ``should_require_auth`` draws. if not auth_required: status.update({ "hermes_home": str(get_hermes_home()), @@ -2268,6 +2771,7 @@ async def get_status(profile: Optional[str] = None): "env_path": str(get_env_path()), "gateway_pid": gateway_pid, "gateway_health_url": _GATEWAY_HEALTH_URL, + "gateways": topology["gateways"], }) return status @@ -2660,6 +3164,9 @@ async def run_debug_share_endpoint(body: DebugShareRequest | None = None): # --------------------------------------------------------------------------- _ACTION_LOG_DIR: Path = get_hermes_home() / "logs" +_ACTION_LOG_TAIL_MAX_BYTES = 256 * 1024 +_ACTION_LOG_TAIL_INITIAL_CHUNK_BYTES = 8 * 1024 +_ACTION_LOG_TAIL_MAX_CHUNK_BYTES = 64 * 1024 # Short ``name`` (from the URL) → absolute log file path. _ACTION_LOG_FILES: Dict[str, str] = { @@ -2761,17 +3268,50 @@ def _spawn_hermes_action(subcommand: List[str], name: str) -> subprocess.Popen: def _tail_lines(path: Path, n: int) -> List[str]: - """Return the last ``n`` lines of ``path``. Reads the whole file — fine - for our small per-action logs. Binary-decoded with ``errors='replace'`` - so log corruption doesn't 500 the endpoint.""" - if not path.exists(): + """Return the last ``n`` lines of ``path`` without loading huge logs.""" + if n <= 0 or not path.exists(): + return [] + try: + size = path.stat().st_size + except OSError: return [] + if size <= 0: + return [] + + min_offset = max(0, size - _ACTION_LOG_TAIL_MAX_BYTES) + offset = size + chunk_size = _ACTION_LOG_TAIL_INITIAL_CHUNK_BYTES + newline_count = 0 + chunks: List[bytes] = [] + drop_partial_first_line = False + try: - text = path.read_text(encoding="utf-8", errors="replace") + with path.open("rb") as handle: + while offset > min_offset and newline_count <= n: + read_size = min(chunk_size, offset - min_offset) + offset -= read_size + handle.seek(offset) + chunk = handle.read(read_size) + chunks.append(chunk) + newline_count += chunk.count(b"\n") + chunk_size = min( + chunk_size * 2, + _ACTION_LOG_TAIL_MAX_CHUNK_BYTES, + ) + if offset > 0: + handle.seek(offset - 1) + drop_partial_first_line = handle.read(1) != b"\n" except OSError: return [] - lines = text.splitlines() - return lines[-n:] if n > 0 else lines + + lines = ( + b"".join(reversed(chunks)) + .decode("utf-8", errors="replace") + .splitlines() + ) + if drop_partial_first_line and lines: + lines = lines[1:] + return lines[-n:] def _gateway_subcommand(profile: Optional[str], verb: str) -> List[str]: @@ -3412,8 +3952,25 @@ async def get_action_status(name: str, lines: int = 200): } +# Per-row fields that no session LIST consumer reads but that dominate the +# payload. ``system_prompt`` is the fully rendered prompt — tens of KB per +# row — and made a 21-row /api/sessions response 528KB (96% dead weight), +# re-fetched by the desktop sidebar on every refresh. The desktop's +# SessionInfo type doesn't declare either field and the web UI never touches +# them; ``GET /api/sessions/{id}`` detail reads stay complete. List callers +# that genuinely need the full rows can pass ``?full=1``. +_SESSION_LIST_HEAVY_FIELDS = ("system_prompt", "model_config") + + +def _strip_session_list_rows(sessions: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + for s in sessions: + for key in _SESSION_LIST_HEAVY_FIELDS: + s.pop(key, None) + return sessions + + @app.get("/api/sessions") -async def get_sessions( +def get_sessions( limit: int = 20, offset: int = 0, min_messages: int = 0, @@ -3422,6 +3979,7 @@ async def get_sessions( source: str = None, exclude_sources: str = None, cwd_prefix: str = None, + full: bool = False, profile: Optional[str] = None, ): """List sessions. @@ -3435,6 +3993,9 @@ async def get_sessions( start time) or ``recent`` (by latest activity across the compression chain). ``recent`` keeps a long-running conversation on the first page after it auto-compresses into a fresh continuation id. + + Rows omit ``system_prompt``/``model_config`` (the payload-dominating + fields no list UI reads) unless ``full=1`` is passed. """ if archived not in ("exclude", "only", "include"): raise HTTPException( @@ -3470,6 +4031,10 @@ async def get_sessions( include_archived=include_archived, archived_only=archived_only, order_by_last_active=order == "recent", + # SQL-level projection: when the caller didn't ask for full + # rows, skip the system_prompt blob inside SQLite too (pairs + # with the API-level _strip_session_list_rows below). + compact_rows=not full, ) total = db.session_count( source=source or None, @@ -3491,6 +4056,8 @@ async def get_sessions( s["is_default_profile"] = profile_name == "default" # SQLite stores the flag as 0/1; expose a real JSON boolean. s["archived"] = bool(s.get("archived")) + if not full: + _strip_session_list_rows(sessions) return {"sessions": sessions, "total": total, "limit": limit, "offset": offset} finally: db.close() @@ -3511,6 +4078,7 @@ def get_profiles_sessions( profile: str = "all", source: str = None, exclude_sources: str = None, + full: bool = False, ): """Unified, read-only session list aggregated across ALL profiles. @@ -3520,6 +4088,9 @@ def get_profiles_sessions( browsable list and only spins up a profile's backend when the user actually interacts (sends a message). A user with a single (default) profile gets the same rows as ``/api/sessions``, just tagged ``profile="default"``. + + Rows omit ``system_prompt``/``model_config`` unless ``full=1`` — same + list projection as ``/api/sessions``. """ if archived not in ("exclude", "only", "include"): raise HTTPException(status_code=400, detail="archived must be one of: exclude, only, include") @@ -3582,6 +4153,8 @@ def get_profiles_sessions( include_archived=include_archived, archived_only=archived_only, order_by_last_active=order == "recent", + # Same SQL-level blob skip as /api/sessions (see above). + compact_rows=not full, ) profile_total = db.session_count( source=source_filter, @@ -3610,6 +4183,8 @@ def get_profiles_sessions( sort_key = "last_active" if order == "recent" else "started_at" merged.sort(key=lambda s: s.get(sort_key) or s.get("started_at") or 0, reverse=True) window = merged[offset:offset + limit] + if not full: + _strip_session_list_rows(window) return { "sessions": window, "total": total, @@ -3807,176 +4382,849 @@ def _normalize_config_for_web(config: Dict[str, Any]) -> Dict[str, Any]: return config -def _memory_provider_config_path(provider: MemoryProvider) -> Path: - return get_hermes_home() / provider.name / "config.json" - - -def _read_memory_provider_file(provider: MemoryProvider) -> Dict[str, Any]: - path = _memory_provider_config_path(provider) - if not path.exists(): - return {} - try: - data = json.loads(path.read_text(encoding="utf-8")) - except Exception: - _log.warning("Failed to read memory provider config from %s", path, exc_info=True) - return {} - return data if isinstance(data, dict) else {} +def _memory_provider_label(name: str) -> str: + return name.replace("_", " ").replace("-", " ").title() -def _read_field_value(field: ProviderField, data: Dict[str, Any]) -> str: - """Resolve the stored value for a non-secret field, honoring legacy reads.""" +def _normalize_memory_provider_name(name: Any) -> str: + provider = str(name or "").strip() + if provider.lower() in {"built-in", "builtin", "none"}: + return "" + return provider - for source_key in (field.key, *field.aliases): - value = data.get(source_key) - if value: - return str(value) - env_on_disk = load_env() - for env_key in field.env_fallbacks: - value = env_on_disk.get(env_key) - if value: - return str(value) +def _load_memory_provider(name: str): + try: + from plugins.memory import load_memory_provider - return field.default + return load_memory_provider(name) + except Exception: + _log.debug("Failed to load memory provider %s", name, exc_info=True) + return None -def _field_is_set(field: ProviderField, data: Dict[str, Any]) -> bool: - """Whether a secret field has a value anywhere it may have been written.""" +def _memory_provider_manifest(name: str) -> Dict[str, Any]: + try: + from plugins.memory import find_provider_dir + + provider_dir = find_provider_dir(name) + if provider_dir is None: + return {} + manifest_path = provider_dir / "plugin.yaml" + if not manifest_path.exists(): + return {} + with manifest_path.open(encoding="utf-8-sig") as handle: + manifest = yaml.safe_load(handle) or {} + return manifest if isinstance(manifest, dict) else {} + except Exception: + _log.debug("Failed to read memory provider manifest for %s", name, exc_info=True) + return {} - env_on_disk = load_env() - for env_key in (field.env_key, *field.env_fallbacks): - if env_key and env_on_disk.get(env_key): - return True - return any(data.get(source_key) for source_key in (field.key, *field.aliases)) +def _string_list(value: Any) -> List[str]: + if not isinstance(value, list): + return [] + return [str(item).strip() for item in value if str(item).strip()] -def _memory_provider_payload(provider: MemoryProvider) -> Dict[str, Any]: - data = _read_memory_provider_file(provider) - fields: List[Dict[str, Any]] = [] - for field in provider.fields: - entry: Dict[str, Any] = { - "key": field.key, - "label": field.label, - "kind": field.kind, - "description": field.description, - "placeholder": field.placeholder, - "options": [ - {"value": opt.value, "label": opt.label, "description": opt.description} - for opt in field.options - ], +def _memory_provider_setup_manifest(name: str) -> Dict[str, Any]: + manifest = _memory_provider_manifest(name) + external_dependencies: List[Dict[str, str]] = [] + for raw in manifest.get("external_dependencies") or []: + if not isinstance(raw, dict): + continue + dep = { + "name": str(raw.get("name") or "").strip(), + "install": str(raw.get("install") or "").strip(), + "check": str(raw.get("check") or "").strip(), } + if dep["name"] or dep["install"] or dep["check"]: + external_dependencies.append(dep) - if field.is_secret: - # Secrets are write-only over the API; only expose whether one is set. - entry["value"] = "" - entry["is_set"] = _field_is_set(field, data) - else: - value = _read_field_value(field, data) - if field.kind == "select" and value not in field.allowed_values(): - value = field.default - entry["value"] = value - entry["is_set"] = bool(value) - - fields.append(entry) + return { + "pip_dependencies": _string_list(manifest.get("pip_dependencies")), + "external_dependencies": external_dependencies, + "required_env": _string_list(manifest.get("requires_env")), + } - return {"name": provider.name, "label": provider.label, "fields": fields} +def _memory_provider_setup_info(name: str) -> Dict[str, Any]: + setup = _memory_provider_setup_manifest(name) + setup["dependencies_installed"] = _memory_provider_dependencies_installed(setup) + return setup -def _coerce_field_value(field: ProviderField, raw: str) -> str: - """Validate and normalize a submitted non-secret value, or raise ValueError.""" - value = (raw or "").strip() - if field.kind == "select": - if not value: - value = field.default - if value not in field.allowed_values(): - raise ValueError(f"Invalid value for '{field.key}'") - return value - return value or field.default +_MEMORY_PROVIDER_IMPORT_NAMES = { + "honcho-ai": "honcho", + "mem0ai": "mem0", + "hindsight-client": "hindsight_client", + "hindsight-all": "hindsight", +} -@app.get("/api/memory/providers/{name}/config") -async def get_memory_provider_config(name: str): - provider = get_memory_provider(name) - if provider is None: - # Undeclared providers (e.g. builtin) have no config surface. Return an - # empty schema so the generic panel simply renders nothing. - return {"name": name, "label": name, "fields": []} - return _memory_provider_payload(provider) +def _memory_provider_dependency_package(dep: str) -> str: + return re.split(r"[\[<>=!~;]", dep, maxsplit=1)[0].strip() -@app.put("/api/memory/providers/{name}/config") -async def update_memory_provider_config(name: str, body: MemoryProviderConfigUpdate): - provider = get_memory_provider(name) - if provider is None: - raise HTTPException(status_code=404, detail=f"Unknown memory provider: {name}") +def _memory_provider_import_name(dep: str) -> str: + package = _memory_provider_dependency_package(dep) + return _MEMORY_PROVIDER_IMPORT_NAMES.get(package, package.replace("-", "_")) - values = body.values or {} +def _dependency_importable(dep: str) -> bool: + import_name = _memory_provider_import_name(dep) + if not import_name: + return False try: - existing = _read_memory_provider_file(provider) - json_values: Dict[str, Any] = {} - secrets: Dict[str, str] = {} + __import__(import_name) + return True + except ImportError: + return False - for field in provider.fields: - if field.is_secret: - submitted = (values.get(field.key) or "").strip() - if submitted and field.env_key: - secrets[field.env_key] = submitted - continue - raw = ( - values[field.key] - if field.key in values - else str(existing.get(field.key, field.default)) - ) - json_values[field.key] = _coerce_field_value(field, raw) +def _trim_setup_output(value: Optional[str], limit: int = 4000) -> str: + text = str(value or "") + if len(text) <= limit: + return text + return f"{text[:limit]}\n... truncated ..." - config = load_config() - memory_config = config.get("memory") - if not isinstance(memory_config, dict): - memory_config = {} - config["memory"] = memory_config - memory_config["provider"] = provider.name - save_config(config) - path = _memory_provider_config_path(provider) - path.parent.mkdir(parents=True, exist_ok=True) - existing.update(json_values) - from utils import atomic_json_write +def _memory_provider_setup_env() -> Dict[str, str]: + env = os.environ.copy() + home = Path.home() + extra_bins = [ + home / ".brv-cli" / "bin", + home / ".local" / "bin", + home / ".npm-global" / "bin", + Path("/usr/local/bin"), + ] + existing_path = env.get("PATH", "") + prefix = os.pathsep.join(str(path) for path in extra_bins if path.exists()) + if prefix: + env["PATH"] = prefix + os.pathsep + existing_path + return env - atomic_json_write(path, existing, mode=0o600) - for env_key, secret in secrets.items(): - save_env_value(env_key, secret) +def _command_result( + *, + kind: str, + name: str, + status: str, + command: str = "", + completed: Optional[subprocess.CompletedProcess] = None, + error: Optional[str] = None, +) -> Dict[str, Any]: + return { + "kind": kind, + "name": name, + "status": status, + "command": command, + "returncode": None if completed is None else completed.returncode, + "stdout": "" if completed is None else _trim_setup_output(completed.stdout), + "stderr": _trim_setup_output(error or ("" if completed is None else completed.stderr)), + } - return {"ok": True} - except HTTPException: - raise - except ValueError as exc: - raise HTTPException(status_code=400, detail=str(exc)) from exc - except Exception: - _log.exception("PUT /api/memory/providers/%s/config failed", name) - raise HTTPException(status_code=500, detail="Internal server error") +def _run_setup_command( + command: Any, + *, + display: str, + shell: bool = False, + timeout: int = 180, +) -> subprocess.CompletedProcess: + return subprocess.run( + command, + shell=shell, + executable="/bin/bash" if shell else None, + env=_memory_provider_setup_env(), + capture_output=True, + text=True, + timeout=timeout, + check=False, + ) -@app.get("/api/config") -async def get_config(profile: Optional[str] = None): - with _profile_scope(profile): - config = _normalize_config_for_web(load_config()) - # Strip internal keys that the frontend shouldn't see or send back - return {k: v for k, v in config.items() if not k.startswith("_")} +def _memory_provider_dependencies_installed(setup: Dict[str, Any]) -> bool: + pip_dependencies = _string_list(setup.get("pip_dependencies")) + external_dependencies = setup.get("external_dependencies") or [] -@app.get("/api/config/defaults") -async def get_defaults(): - return DEFAULT_CONFIG + pip_ok = all(_dependency_importable(dep) for dep in pip_dependencies) + external_ok = True + for dep in external_dependencies: + if not isinstance(dep, dict): + continue + check_cmd = str(dep.get("check") or "").strip() + install_cmd = str(dep.get("install") or "").strip() + if not check_cmd: + if install_cmd: + external_ok = False + continue + try: + completed = _run_setup_command( + shlex.split(check_cmd), + display=check_cmd, + timeout=20, + ) + except Exception: + external_ok = False + continue + if completed.returncode != 0: + external_ok = False + return pip_ok and external_ok -@app.get("/api/config/schema") -async def get_schema(): - return {"fields": CONFIG_SCHEMA, "category_order": _CATEGORY_ORDER} + +def _install_memory_provider_pip_dependencies(dependencies: List[str]) -> List[Dict[str, Any]]: + missing = [dep for dep in dependencies if not _dependency_importable(dep)] + if not dependencies: + return [] + if not missing: + return [ + _command_result(kind="pip", name=", ".join(dependencies), status="already_installed") + ] + + uv_path = shutil.which("uv") + if uv_path: + command: Any = [uv_path, "pip", "install", "--python", sys.executable, "--quiet", *missing] + display = f"uv pip install --python {sys.executable} {' '.join(missing)}" + else: + command = [sys.executable, "-m", "pip", "install", "--quiet", *missing] + display = f"{sys.executable} -m pip install {' '.join(missing)}" + + try: + completed = _run_setup_command(command, display=display, timeout=240) + except Exception as exc: + return [ + _command_result( + kind="pip", + name=", ".join(missing), + status="failed", + command=display, + error=str(exc), + ) + ] + + return [ + _command_result( + kind="pip", + name=", ".join(missing), + status="installed" if completed.returncode == 0 else "failed", + command=display, + completed=completed, + ) + ] + + +def _install_memory_provider_external_dependencies( + dependencies: List[Dict[str, str]], +) -> List[Dict[str, Any]]: + results: List[Dict[str, Any]] = [] + for dep in dependencies: + name = dep.get("name") or "dependency" + check_cmd = dep.get("check") or "" + install_cmd = dep.get("install") or "" + + if check_cmd: + try: + check = _run_setup_command( + shlex.split(check_cmd), + display=check_cmd, + timeout=20, + ) + except Exception as exc: + results.append( + _command_result( + kind="external_check", + name=name, + status="missing" if install_cmd else "failed", + command=check_cmd, + error=str(exc), + ) + ) + else: + if check.returncode == 0: + results.append( + _command_result( + kind="external_check", + name=name, + status="already_installed", + command=check_cmd, + completed=check, + ) + ) + continue + results.append( + _command_result( + kind="external_check", + name=name, + status="missing" if install_cmd else "failed", + command=check_cmd, + completed=check, + ) + ) + + if not install_cmd: + continue + + if install_cmd: + try: + install = _run_setup_command( + install_cmd, + display=install_cmd, + shell=True, + timeout=300, + ) + except Exception as exc: + results.append( + _command_result( + kind="external_install", + name=name, + status="failed", + command=install_cmd, + error=str(exc), + ) + ) + continue + + results.append( + _command_result( + kind="external_install", + name=name, + status="installed" if install.returncode == 0 else "failed", + command=install_cmd, + completed=install, + ) + ) + + if check_cmd and install.returncode == 0: + try: + post_check = _run_setup_command( + shlex.split(check_cmd), + display=check_cmd, + timeout=20, + ) + results.append( + _command_result( + kind="external_check", + name=name, + status="verified" if post_check.returncode == 0 else "failed", + command=check_cmd, + completed=post_check, + ) + ) + except Exception as exc: + results.append( + _command_result( + kind="external_check", + name=name, + status="failed", + command=check_cmd, + error=str(exc), + ) + ) + + return results + + +def _install_memory_provider_setup(name: str) -> Dict[str, Any]: + provider = _load_memory_provider(name) + manifest = _memory_provider_manifest(name) + if provider is None and not manifest: + raise HTTPException(status_code=404, detail=f"Unknown memory provider: {name}") + + setup = _memory_provider_setup_manifest(name) + results = [] + results.extend(_install_memory_provider_pip_dependencies(setup["pip_dependencies"])) + results.extend( + _install_memory_provider_external_dependencies(setup["external_dependencies"]) + ) + + if not results: + results.append( + _command_result( + kind="setup", + name=name, + status="no_declared_steps", + ) + ) + + ok = all(result["status"] not in {"failed"} for result in results) + statuses = {row["name"]: row for row in _discover_memory_provider_statuses()} + return { + "ok": ok, + "provider": name, + "results": results, + "status": statuses.get(name), + } + + +def _normalize_memory_provider_schema(name: str, provider: Any) -> List[Dict[str, Any]]: + raw_schema: List[Dict[str, Any]] = [] + if provider is not None and hasattr(provider, "get_config_schema"): + try: + raw = provider.get_config_schema() + if isinstance(raw, list): + raw_schema = [field for field in raw if isinstance(field, dict)] + except Exception: + _log.warning("Failed to read memory provider schema for %s", name, exc_info=True) + + fields: List[Dict[str, Any]] = [] + for raw in raw_schema: + key = str(raw.get("key") or "").strip() + if not key: + continue + + choices = raw.get("choices") or raw.get("options") or [] + if not isinstance(choices, list): + choices = [] + + explicit_kind = str(raw.get("kind") or raw.get("type") or "").strip().lower() + if raw.get("secret"): + kind = "secret" + elif choices: + kind = "select" + elif explicit_kind in {"bool", "boolean"} or isinstance(raw.get("default"), bool): + kind = "boolean" + else: + kind = "text" + + options = [] + for choice in choices: + value = str(choice) + options.append({"value": value, "label": value, "description": ""}) + + description = str(raw.get("description") or "") + fields.append({ + "key": key, + "label": str(raw.get("label") or key.replace("_", " ").title()), + "kind": kind, + "description": description, + "placeholder": str(raw.get("placeholder") or ""), + "required": bool(raw.get("required", False)), + "default": raw.get("default", ""), + "options": options, + "url": str(raw.get("url") or ""), + "when": raw.get("when") if isinstance(raw.get("when"), dict) else None, + "_env_key": str(raw.get("env_var") or "") or None, + }) + + return fields + + +def _read_json_file(path: Path) -> Dict[str, Any]: + if not path.exists(): + return {} + try: + data = json.loads(path.read_text(encoding="utf-8")) + except Exception: + _log.debug("Failed to read JSON config from %s", path, exc_info=True) + return {} + return data if isinstance(data, dict) else {} + + +def _read_memory_provider_existing_values(name: str) -> Dict[str, Any]: + """Best-effort read of existing provider config across legacy/native stores.""" + + hermes_home = get_hermes_home() + values: Dict[str, Any] = {} + + # Common native provider stores. + for path in ( + hermes_home / f"{name}.json", + hermes_home / name / "config.json", + ): + values.update(_read_json_file(path)) + + try: + cfg = load_config() + except Exception: + cfg = {} + + memory_cfg = cfg.get("memory") if isinstance(cfg, dict) else {} + if isinstance(memory_cfg, dict): + provider_cfg = memory_cfg.get(name) + if isinstance(provider_cfg, dict): + values.update(provider_cfg) + legacy_cfg = memory_cfg.get("provider_config") + if isinstance(legacy_cfg, dict): + values = {**legacy_cfg, **values} + + # Holographic stores under plugins.hermes-memory-store. + plugins_cfg = cfg.get("plugins") if isinstance(cfg, dict) else {} + if name == "holographic" and isinstance(plugins_cfg, dict): + holographic_cfg = plugins_cfg.get("hermes-memory-store") + if isinstance(holographic_cfg, dict): + values.update(holographic_cfg) + + return values + + +def _env_lookup(env_key: Optional[str]) -> str: + if not env_key: + return "" + env_on_disk = load_env() + return str(env_on_disk.get(env_key) or os.environ.get(env_key) or "") + + +def _coerce_bool(value: Any, *, default: bool = False) -> bool: + if isinstance(value, bool): + return value + if value is None or value == "": + return default + if isinstance(value, (int, float)): + return bool(value) + text = str(value).strip().lower() + if text in {"1", "true", "yes", "on"}: + return True + if text in {"0", "false", "no", "off"}: + return False + raise ValueError(f"Invalid boolean value: {value}") + + +def _field_default(field: Dict[str, Any]) -> Any: + default = field.get("default", "") + if field["kind"] == "boolean": + return _coerce_bool(default, default=False) + return default + + +def _field_value(field: Dict[str, Any], data: Dict[str, Any]) -> Any: + if field["kind"] == "secret": + return "" + + value = data.get(field["key"]) + if value in (None, ""): + value = _env_lookup(field.get("_env_key")) + if value in (None, ""): + value = _field_default(field) + + if field["kind"] == "select": + allowed = {opt["value"] for opt in field.get("options", [])} + value = str(value) + return value if value in allowed else str(_field_default(field)) + if field["kind"] == "boolean": + return _coerce_bool(value, default=_coerce_bool(_field_default(field), default=False)) + return str(value) + + +def _field_is_set(field: Dict[str, Any], data: Dict[str, Any]) -> bool: + if field["kind"] == "secret": + return bool(_env_lookup(field.get("_env_key")) or data.get(field["key"])) + value = _field_value(field, data) + return value not in (None, "") + + +def _field_visible( + field: Dict[str, Any], + data: Dict[str, Any], + fields_by_key: Optional[Dict[str, Dict[str, Any]]] = None, +) -> bool: + when = field.get("when") + if not isinstance(when, dict) or not when: + return True + for dep_key, expected in when.items(): + dep_field = (fields_by_key or {}).get(str(dep_key)) or { + "key": str(dep_key), + "kind": "text", + "default": "", + "_env_key": None, + } + actual = _field_value(dep_field, data) + if str(actual) != str(expected): + return False + return True + + +def _public_memory_provider_field(field: Dict[str, Any], data: Dict[str, Any]) -> Dict[str, Any]: + entry = { + "key": field["key"], + "label": field["label"], + "kind": field["kind"], + "description": field["description"], + "placeholder": field["placeholder"], + "required": field["required"], + "value": "" if field["kind"] == "secret" else _field_value(field, data), + "is_set": _field_is_set(field, data), + "options": field.get("options", []), + "url": field.get("url", ""), + "when": field.get("when"), + } + return entry + + +def _memory_provider_payload(name: str, provider: Any) -> Dict[str, Any]: + data = _read_memory_provider_existing_values(name) + fields = [ + _public_memory_provider_field(field, data) + for field in _normalize_memory_provider_schema(name, provider) + ] + return { + "name": name, + "label": _memory_provider_label(name), + "fields": fields, + "setup": _memory_provider_setup_info(name), + } + + +def _coerce_schema_field(field: Dict[str, Any], raw: Any) -> Any: + if field["kind"] == "boolean": + return _coerce_bool(raw, default=_coerce_bool(_field_default(field), default=False)) + + value = str(raw if raw is not None else "").strip() + if field["kind"] == "select": + if not value: + value = str(_field_default(field)) + allowed = {opt["value"] for opt in field.get("options", [])} + if value not in allowed: + raise ValueError(f"Invalid value for '{field['key']}'") + return value + + return value or _field_default(field) + + +def _save_memory_provider_native_config(name: str, provider: Any, values: Dict[str, Any]) -> None: + if provider is not None and hasattr(provider, "save_config"): + try: + from agent.memory_provider import MemoryProvider as _BaseMemoryProvider + except Exception: + provider.save_config(values, str(get_hermes_home())) + return + if type(provider).save_config is not _BaseMemoryProvider.save_config: + provider.save_config(values, str(get_hermes_home())) + return + + cfg = load_config() + memory_cfg = cfg.get("memory") + if not isinstance(memory_cfg, dict): + memory_cfg = {} + cfg["memory"] = memory_cfg + current = memory_cfg.get(name) + if not isinstance(current, dict): + current = {} + current.update(values) + memory_cfg[name] = current + save_config(cfg) + + +def _memory_provider_is_configured(name: str, provider: Any) -> bool: + data = _read_memory_provider_existing_values(name) + fields = _normalize_memory_provider_schema(name, provider) + fields_by_key = {field["key"]: field for field in fields} + visible_fields = [ + field for field in fields if _field_visible(field, data, fields_by_key) + ] + required_fields = [field for field in visible_fields if field.get("required")] + if not required_fields: + return True + return all(_field_is_set(field, data) for field in required_fields) + + +def _discover_memory_provider_statuses() -> List[Dict[str, Any]]: + discovered: Dict[str, Dict[str, Any]] = {} + try: + from plugins.memory import discover_memory_providers + + for name, description, available in discover_memory_providers(): + discovered[str(name)] = { + "name": str(name), + "description": str(description or ""), + "available": bool(available), + "missing": False, + } + except Exception: + _log.exception("discover_memory_providers failed") + + cfg = load_config() + active = "" + mem = cfg.get("memory") + if isinstance(mem, dict): + active = _normalize_memory_provider_name(mem.get("provider")) + if active and active not in discovered: + discovered[active] = { + "name": active, + "description": "Configured provider was not found.", + "available": False, + "missing": True, + } + + providers: List[Dict[str, Any]] = [] + for name in sorted(discovered): + row = discovered[name] + provider = None if row["missing"] else _load_memory_provider(name) + setup = _memory_provider_setup_info(name) + configured = False if row["missing"] else _memory_provider_is_configured(name, provider) + schema_fields = [] if row["missing"] else _normalize_memory_provider_schema(name, provider) + if row["missing"]: + status = "missing" + elif not row["available"] and not setup.get("dependencies_installed", True): + status = "unavailable" + elif not configured: + status = "needs_config" + elif not row["available"] and schema_fields: + status = "needs_config" + elif not row["available"]: + status = "unavailable" + else: + status = "ready" + providers.append({ + "name": name, + "description": row["description"], + "available": row["available"], + "configured": configured, + "status": status, + "setup": setup, + }) + return providers + + +def _require_memory_provider_ready(name: str) -> None: + if not name: + return + statuses = {row["name"]: row for row in _discover_memory_provider_statuses()} + row = statuses.get(name) + if row is None: + raise HTTPException( + status_code=400, + detail=f"Unknown memory provider '{name}'.", + ) + if row["status"] != "ready": + raise HTTPException( + status_code=400, + detail=( + f"Memory provider '{name}' is not ready " + f"({row['status'].replace('_', ' ')}). Configure it in the dashboard first." + ), + ) + + +def _write_memory_provider_config_values( + name: str, + provider: Any, + values: Dict[str, Any], +) -> None: + existing = _read_memory_provider_existing_values(name) + fields = _normalize_memory_provider_schema(name, provider) + fields_by_key = {field["key"]: field for field in fields} + config_values: Dict[str, Any] = {} + secrets: Dict[str, str] = {} + + for field in fields: + if not _field_visible(field, {**existing, **config_values}, fields_by_key): + continue + + if field["kind"] == "secret": + submitted = str(values.get(field["key"]) or "").strip() + if submitted and field.get("_env_key"): + secrets[str(field["_env_key"])] = submitted + continue + + raw = ( + values[field["key"]] + if field["key"] in values + else existing.get(field["key"], _field_default(field)) + ) + config_values[field["key"]] = _coerce_schema_field(field, raw) + + _save_memory_provider_native_config(name, provider, config_values) + + for env_key, secret in secrets.items(): + save_env_value(env_key, secret) + + +_MEMORY_PROVIDER_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$") + + +def _require_valid_memory_provider_name(name: str) -> None: + """Reject provider names that could traverse outside the plugin dirs. + + ``name`` is interpolated into filesystem paths by ``find_provider_dir()`` + and gates which plugin manifest's setup commands run. A strict charset + allowlist (no path separators, no dots) makes traversal impossible + regardless of how the downstream lookup evolves. + """ + if not _MEMORY_PROVIDER_NAME_RE.fullmatch(name or ""): + raise HTTPException(status_code=404, detail=f"Unknown memory provider: {name}") + + +@app.get("/api/memory/providers/{name}/config") +async def get_memory_provider_config(name: str): + _require_valid_memory_provider_name(name) + provider = _load_memory_provider(name) + if provider is None: + # Undeclared providers (e.g. builtin) have no config surface. Return an + # empty schema so the generic panel simply renders nothing. + return {"name": name, "label": name, "fields": [], "setup": _memory_provider_setup_info(name)} + return _memory_provider_payload(name, provider) + + +@app.post("/api/memory/providers/{name}/setup") +async def setup_memory_provider(name: str, body: MemoryProviderSetupRequest): + _require_valid_memory_provider_name(name) + provider = _load_memory_provider(name) + if provider is None and not _memory_provider_manifest(name): + # No discoverable plugin directory → nothing whose manifest could + # legitimately declare setup commands. Refuse before the + # command-running path. (provider may be None with a manifest present + # when its pip deps aren't installed yet — that's the setup use case.) + raise HTTPException(status_code=404, detail=f"Unknown memory provider: {name}") + if provider is not None and body.values: + try: + _write_memory_provider_config_values(name, provider, body.values) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + except Exception: + _log.exception("Failed to persist memory provider setup values for %s", name) + raise HTTPException(status_code=500, detail="Internal server error") + return _install_memory_provider_setup(name) + + +@app.put("/api/memory/providers/{name}/config") +async def update_memory_provider_config(name: str, body: MemoryProviderConfigUpdate): + _require_valid_memory_provider_name(name) + provider = _load_memory_provider(name) + if provider is None: + raise HTTPException(status_code=404, detail=f"Unknown memory provider: {name}") + + values = body.values or {} + + try: + _write_memory_provider_config_values(name, provider, values) + _require_memory_provider_ready(name) + + config = load_config() + memory_config = config.get("memory") + if not isinstance(memory_config, dict): + memory_config = {} + config["memory"] = memory_config + memory_config["provider"] = name + save_config(config) + + return {"ok": True, "active": name} + except HTTPException: + raise + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + except Exception: + _log.exception("PUT /api/memory/providers/%s/config failed", name) + raise HTTPException(status_code=500, detail="Internal server error") + + +@app.get("/api/config") +async def get_config(profile: Optional[str] = None): + with _profile_scope(profile): + config = _normalize_config_for_web(load_config()) + # Strip internal keys that the frontend shouldn't see or send back + return {k: v for k, v in config.items() if not k.startswith("_")} + + +@app.get("/api/config/defaults") +async def get_defaults(): + return DEFAULT_CONFIG + + +@app.get("/api/config/schema") +async def get_schema(): + return {"fields": CONFIG_SCHEMA, "category_order": _CATEGORY_ORDER} _EMPTY_MODEL_INFO: dict = { @@ -4095,7 +5343,12 @@ def get_model_info(profile: Optional[str] = None): @app.get("/api/model/options") -def get_model_options(profile: Optional[str] = None, refresh: bool = False): +def get_model_options( + profile: Optional[str] = None, + refresh: bool = False, + include_unconfigured: bool = False, + explicit_only: bool = False, +): """Return authenticated providers + their curated model lists. REST equivalent of the ``model.options`` JSON-RPC on tui_gateway, so the @@ -4114,23 +5367,22 @@ def get_model_options(profile: Optional[str] = None, refresh: bool = False): try: from hermes_cli.inventory import build_models_payload, load_picker_context - # include_unconfigured + picker_hints + canonical_order mirror the - # tui_gateway `model.options` JSON-RPC handler exactly, so every GUI - # surface fed by this endpoint (Settings → Model, the first-run - # onboarding picker) sees the SAME full provider universe `hermes model` - # exposes — not just the authenticated subset. Unconfigured providers - # come back as skeleton rows carrying `authenticated=False` + - # `auth_type`/`key_env`/`warning` so the GUI can render a setup - # affordance instead of hiding the provider entirely. + # Most desktop surfaces should only list providers the user has already + # configured. Onboarding opts into the full provider universe via + # include_unconfigured=1 so it can still render setup affordances for + # providers that are not yet authenticated. with _profile_scope(profile): return build_models_payload( load_picker_context(), - include_unconfigured=True, + explicit_only=bool(explicit_only), + include_unconfigured=bool(include_unconfigured), picker_hints=True, canonical_order=True, pricing=True, capabilities=True, refresh=bool(refresh), + probe_custom_providers=bool(refresh), + probe_current_custom_provider=not bool(refresh), ) except HTTPException: raise @@ -4779,6 +6031,25 @@ def _catalog_provider_env_metadata() -> dict: "advanced": existing.get("advanced", True), "category": "provider", } + + # Vertex AI authenticates via OAuth2 (service-account JSON or ADC), not a + # pasted API key, so it also has no api_key_env_vars. Tag its credential + # env var to the provider card so it appears on the Keys tab (otherwise + # Vertex — a `hermes model` provider — would be invisible in the desktop + # app). The value is a filesystem path, not a secret string, so it is + # not a password field. + if d.auth_type == "vertex": + existing = meta.get("VERTEX_CREDENTIALS_PATH", {}) + meta["VERTEX_CREDENTIALS_PATH"] = { + "provider": d.slug, + "provider_label": d.label, + "description": existing.get("description") + or f"{d.label} — service account JSON path (or use ADC)", + "url": existing.get("url"), + "is_password": False, + "advanced": existing.get("advanced", True), + "category": "provider", + } return meta @@ -5076,7 +6347,12 @@ async def reveal_env_var( "name": "WhatsApp", "description": "Use Hermes through the bundled WhatsApp bridge with QR-based auth.", "docs_url": "https://github.com/tulir/whatsmeow", - "env_vars": ("WHATSAPP_ENABLED", "WHATSAPP_MODE", "WHATSAPP_ALLOWED_USERS"), + "env_vars": ( + "WHATSAPP_ENABLED", + "WHATSAPP_MODE", + "WHATSAPP_DM_POLICY", + "WHATSAPP_ALLOWED_USERS", + ), "required_env": (), }, "homeassistant": { @@ -5270,6 +6546,11 @@ async def reveal_env_var( "prompt": "WhatsApp mode", "advanced": True, }, + "WHATSAPP_DM_POLICY": { + "description": "How WhatsApp direct messages are authorized", + "prompt": "WhatsApp DM policy", + "advanced": True, + }, "WHATSAPP_ALLOWED_USERS": { "description": "Comma-separated WhatsApp users allowed to use the bot", "prompt": "Allowed WhatsApp users", @@ -5666,7 +6947,23 @@ def _messaging_platform_payload( error_code = error_code or "startup_failed" error_message = error_message or runtime_gateway_error - return { + whatsapp_setup = None + if platform_id == "whatsapp": + whatsapp_mode = ( + env_on_disk.get("WHATSAPP_MODE") + or ("" if scoped else os.getenv("WHATSAPP_MODE", "")) + ).strip() + allowed_users_value = ( + env_on_disk.get("WHATSAPP_ALLOWED_USERS") + or ("" if scoped else os.getenv("WHATSAPP_ALLOWED_USERS", "")) + ).strip() + whatsapp_setup = { + "mode": whatsapp_mode if whatsapp_mode in {"bot", "self-chat"} else "", + "allowed_users_set": bool(allowed_users_value), + "home_channel_set": bool(home_channel), + } + + payload = { "id": platform_id, "name": entry["name"], "description": entry["description"], @@ -5685,15 +6982,508 @@ def _messaging_platform_payload( "home_channel": home_channel, "env_vars": env_vars, } + if whatsapp_setup is not None: + payload["whatsapp_setup"] = whatsapp_setup + return payload def _write_platform_enabled(platform_id: str, enabled: bool) -> None: write_platform_config_field(platform_id, "enabled", enabled) -_TELEGRAM_ONBOARDING_DEFAULT_URL = "https://setup.hermes-agent.nousresearch.com" -_TELEGRAM_ONBOARDING_USER_AGENT = f"HermesDashboard/{__version__}" -_TELEGRAM_USER_ID_RE = re.compile(r"^\d+$") +_WHATSAPP_ONBOARDING_TTL_SECONDS = 600 +_WHATSAPP_ONBOARDING_TERMINAL_STATUSES = {"connected", "error", "expired", "cancelled"} + + +@dataclass +class _WhatsAppOnboardingSession: + proc: subprocess.Popen | None + mode: str + allowed_users: str + session_path: str + expires_at: str + expires_at_ts: float + profile: str | None = None + status: str = "starting" + qr_payload: str | None = None + account_id: str | None = None + account_name: str | None = None + account_phone: str | None = None + error: str | None = None + + +_whatsapp_onboarding_sessions: dict[str, _WhatsAppOnboardingSession] = {} +_whatsapp_onboarding_lock = threading.RLock() + + +def _utc_iso_from_ts(ts: float) -> str: + return datetime.fromtimestamp(ts, timezone.utc).isoformat().replace("+00:00", "Z") + + +def _normalize_whatsapp_onboarding_mode(value: Any) -> str: + mode = str(value or "bot").strip().lower() + if mode not in {"bot", "self-chat"}: + raise HTTPException(status_code=400, detail="WhatsApp mode must be 'bot' or 'self-chat'.") + return mode + + +def _normalize_whatsapp_allowed_users(value: Any) -> str: + raw = str(value or "").strip() + if not raw: + return "" + return ",".join(part.replace(" ", "") for part in raw.split(",") if part.strip()) + + +def _whatsapp_session_path() -> Path: + from hermes_constants import get_hermes_dir + + return get_hermes_dir("platforms/whatsapp/session", "whatsapp/session") + + +def _whatsapp_phone_from_identifier(value: Any) -> str | None: + raw = str(value or "").strip() + if not raw: + return None + candidate = raw.split("@", 1)[0].split(":", 1)[0] + digits = re.sub(r"\D+", "", candidate) + return digits or None + + +def _whatsapp_linked_account_from_session(session_path: Path) -> tuple[str | None, str | None, str | None]: + creds_path = session_path / "creds.json" + try: + payload = json.loads(creds_path.read_text(encoding="utf-8")) + except Exception: + return None, None, None + + account_id: str | None = None + account_name: str | None = None + + def collect(candidate: Any) -> None: + nonlocal account_id, account_name + if not isinstance(candidate, dict): + return + if account_id is None: + for key in ("id", "jid", "lid"): + value = str(candidate.get(key) or "").strip() + if value: + account_id = value + break + if account_name is None: + for key in ("name", "verifiedName", "notify", "pushName"): + value = str(candidate.get(key) or "").strip() + if value: + account_name = value + break + + collect(payload.get("me")) + collect(payload.get("account")) + collect(payload) + return account_id, account_name, _whatsapp_phone_from_identifier(account_id) + + +def _ensure_whatsapp_bridge_dependencies(bridge_dir: Path) -> None: + """Install bridge dependencies when the dashboard is the setup surface.""" + if (bridge_dir / "node_modules").exists(): + return + + from hermes_constants import find_node_executable, with_hermes_node_path + from utils import env_int + + npm = find_node_executable("npm") + if not npm: + raise HTTPException( + status_code=500, + detail="npm was not found. WhatsApp setup needs Node.js and npm.", + ) + + timeout = env_int("WHATSAPP_NPM_INSTALL_TIMEOUT", 300) + try: + result = subprocess.run( + [npm, "install", "--silent"], + cwd=str(bridge_dir), + capture_output=True, + text=True, + timeout=timeout, + env=with_hermes_node_path(), + creationflags=windows_hide_flags(), + ) + except subprocess.TimeoutExpired as exc: + raise HTTPException( + status_code=500, + detail="Installing WhatsApp bridge dependencies timed out.", + ) from exc + except OSError as exc: + raise HTTPException( + status_code=500, + detail=f"Failed to install WhatsApp bridge dependencies: {exc}", + ) from exc + + if result.returncode != 0: + detail = (result.stderr or result.stdout or "").strip() + if detail: + detail = "\n".join(detail.splitlines()[-10:]) + raise HTTPException( + status_code=500, + detail=f"npm install failed for WhatsApp bridge: {detail or 'no output'}", + ) + + +def _spawn_whatsapp_pairing_process(session_path: Path, mode: str) -> subprocess.Popen: + from gateway.platforms.whatsapp_common import resolve_whatsapp_bridge_dir + from hermes_constants import find_node_executable, with_hermes_node_path + + bridge_dir = resolve_whatsapp_bridge_dir() + bridge_script = bridge_dir / "bridge.js" + if not bridge_script.exists(): + raise HTTPException( + status_code=500, + detail=f"WhatsApp bridge script was not found at {bridge_script}.", + ) + node = find_node_executable("node") + if not node: + raise HTTPException( + status_code=500, + detail="Node.js was not found. WhatsApp setup needs Node.js.", + ) + + _ensure_whatsapp_bridge_dependencies(bridge_dir) + session_path.mkdir(parents=True, exist_ok=True) + + env = with_hermes_node_path() + env["WHATSAPP_MODE"] = mode + env["WHATSAPP_DM_POLICY"] = "pairing" + return subprocess.Popen( + [ + node, + str(bridge_script), + "--pair-only", + "--pair-json", + "--session", + str(session_path), + ], + cwd=str(bridge_dir), + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + encoding="utf-8", + errors="replace", + start_new_session=True, + env=env, + creationflags=windows_hide_flags(), + ) + + +def _terminate_whatsapp_pairing(proc: subprocess.Popen | None) -> None: + if proc is None: + return + if proc.poll() is not None: + return + try: + proc.terminate() + proc.wait(timeout=3) + except Exception: + try: + proc.kill() + except Exception: + pass + + +def _watch_whatsapp_pairing(pairing_id: str, proc: subprocess.Popen) -> None: + try: + stream = proc.stdout + if stream is not None: + for line in stream: + raw = line.strip() + if not raw: + continue + try: + payload = json.loads(raw) + except json.JSONDecodeError: + continue + event = str(payload.get("event") or "").strip() + with _whatsapp_onboarding_lock: + record = _whatsapp_onboarding_sessions.get(pairing_id) + if not record or record.proc is not proc: + return + if event == "qr": + qr = str(payload.get("qr") or "").strip() + if qr: + record.qr_payload = qr + record.status = "waiting" + record.error = None + elif event == "connected": + user = payload.get("user") + if isinstance(user, dict): + account_id = str(user.get("id") or "").strip() + account_name = str(user.get("name") or "").strip() + record.account_id = account_id or None + record.account_name = account_name or None + record.account_phone = _whatsapp_phone_from_identifier(account_id) + record.status = "connected" + record.error = None + elif event == "error": + record.status = "error" + record.error = str(payload.get("error") or "WhatsApp pairing failed.") + elif event == "disconnected" and record.status == "starting": + record.status = "waiting" + returncode = proc.wait() + except Exception as exc: + with _whatsapp_onboarding_lock: + record = _whatsapp_onboarding_sessions.get(pairing_id) + if record and record.proc is proc and record.status not in _WHATSAPP_ONBOARDING_TERMINAL_STATUSES: + record.status = "error" + record.error = str(exc) + return + + with _whatsapp_onboarding_lock: + record = _whatsapp_onboarding_sessions.get(pairing_id) + if not record or record.proc is not proc: + return + if record.status in {"connected", "cancelled", "expired"}: + return + record.status = "error" + record.error = ( + "WhatsApp pairing process exited before pairing completed." + if returncode == 0 + else f"WhatsApp pairing process exited with code {returncode}." + ) + + +def _run_whatsapp_pairing(pairing_id: str, session_path: Path, mode: str) -> None: + with _whatsapp_onboarding_lock: + record = _whatsapp_onboarding_sessions.get(pairing_id) + if not record or record.status in _WHATSAPP_ONBOARDING_TERMINAL_STATUSES: + return + record.status = "installing" + + try: + proc = _spawn_whatsapp_pairing_process(session_path, mode) + except Exception as exc: + with _whatsapp_onboarding_lock: + record = _whatsapp_onboarding_sessions.get(pairing_id) + if record and record.status not in _WHATSAPP_ONBOARDING_TERMINAL_STATUSES: + record.status = "error" + record.error = str(exc) + return + + with _whatsapp_onboarding_lock: + record = _whatsapp_onboarding_sessions.get(pairing_id) + if not record or record.status in _WHATSAPP_ONBOARDING_TERMINAL_STATUSES: + _terminate_whatsapp_pairing(proc) + return + record.proc = proc + record.status = "starting" + + _watch_whatsapp_pairing(pairing_id, proc) + + +def _prune_whatsapp_onboarding_sessions() -> None: + now = time.time() + remove_ids: list[str] = [] + for pairing_id, record in _whatsapp_onboarding_sessions.items(): + if ( + record.proc is not None + and record.status not in _WHATSAPP_ONBOARDING_TERMINAL_STATUSES + and record.proc.poll() is not None + ): + record.status = "error" + record.error = "WhatsApp pairing process exited before pairing completed." + if record.expires_at_ts <= now and record.status not in _WHATSAPP_ONBOARDING_TERMINAL_STATUSES: + _terminate_whatsapp_pairing(record.proc) + record.status = "expired" + record.error = "WhatsApp QR setup expired. Start a new setup." + if record.status in _WHATSAPP_ONBOARDING_TERMINAL_STATUSES and record.expires_at_ts + 300 <= now: + remove_ids.append(pairing_id) + for pairing_id in remove_ids: + _whatsapp_onboarding_sessions.pop(pairing_id, None) + + +def _supersede_whatsapp_onboarding_sessions(session_path: Path) -> None: + for existing in _whatsapp_onboarding_sessions.values(): + if existing.session_path == str(session_path) and existing.status not in _WHATSAPP_ONBOARDING_TERMINAL_STATUSES: + existing.status = "cancelled" + existing.error = "Superseded by a newer WhatsApp setup session." + _terminate_whatsapp_pairing(existing.proc) + + +def _whatsapp_onboarding_payload(pairing_id: str, record: _WhatsAppOnboardingSession) -> dict[str, Any]: + return { + "pairing_id": pairing_id, + "status": record.status, + "qr_payload": record.qr_payload, + "expires_at": record.expires_at, + "mode": record.mode, + "allowed_users": record.allowed_users, + "account_id": record.account_id, + "account_name": record.account_name, + "account_phone": record.account_phone, + "error": record.error, + } + + +def _restart_gateway_after_whatsapp_onboarding(profile: Optional[str] = None) -> dict[str, Any]: + try: + proc, reused = _spawn_gateway_restart(profile) + except Exception as exc: + _log.exception("Failed to auto-restart gateway after WhatsApp onboarding") + return { + "restart_started": False, + "restart_error": str(exc), + } + if reused: + _log.info( + "WhatsApp onboarding: reusing in-flight gateway restart (pid %s)", + proc.pid, + ) + return { + "restart_started": True, + "restart_action": "gateway-restart", + "restart_pid": proc.pid, + } + + +@app.post("/api/messaging/whatsapp/onboarding/start") +async def start_whatsapp_onboarding(body: WhatsAppOnboardingStart): + mode = _normalize_whatsapp_onboarding_mode(body.mode) + allowed_users = _normalize_whatsapp_allowed_users(body.allowed_users) + effective_profile = body.profile + + with _config_profile_scope(effective_profile): + session_path = _whatsapp_session_path() + expires_at_ts = time.time() + _WHATSAPP_ONBOARDING_TTL_SECONDS + expires_at = _utc_iso_from_ts(expires_at_ts) + if (session_path / "creds.json").exists(): + pairing_id = secrets.token_urlsafe(16) + account_id, account_name, account_phone = _whatsapp_linked_account_from_session(session_path) + record = _WhatsAppOnboardingSession( + proc=None, + mode=mode, + allowed_users=allowed_users, + session_path=str(session_path), + expires_at=expires_at, + expires_at_ts=expires_at_ts, + profile=effective_profile, + status="connected", + account_id=account_id, + account_name=account_name, + account_phone=account_phone, + ) + with _whatsapp_onboarding_lock: + _prune_whatsapp_onboarding_sessions() + _supersede_whatsapp_onboarding_sessions(session_path) + _whatsapp_onboarding_sessions[pairing_id] = record + return _whatsapp_onboarding_payload(pairing_id, record) + + pairing_id = secrets.token_urlsafe(16) + record = _WhatsAppOnboardingSession( + proc=None, + mode=mode, + allowed_users=allowed_users, + session_path=str(session_path), + expires_at=expires_at, + expires_at_ts=expires_at_ts, + profile=effective_profile, + ) + + with _whatsapp_onboarding_lock: + _prune_whatsapp_onboarding_sessions() + _supersede_whatsapp_onboarding_sessions(session_path) + _whatsapp_onboarding_sessions[pairing_id] = record + + threading.Thread( + target=_run_whatsapp_pairing, + args=(pairing_id, session_path, mode), + daemon=True, + ).start() + + return _whatsapp_onboarding_payload(pairing_id, record) + + +@app.get("/api/messaging/whatsapp/onboarding/{pairing_id}") +async def get_whatsapp_onboarding_status(pairing_id: str): + with _whatsapp_onboarding_lock: + _prune_whatsapp_onboarding_sessions() + record = _whatsapp_onboarding_sessions.get(pairing_id) + if not record: + raise HTTPException( + status_code=404, + detail="WhatsApp setup session was not found. Start a new setup.", + ) + if record.status == "expired": + raise HTTPException(status_code=410, detail=record.error or "WhatsApp setup expired.") + return _whatsapp_onboarding_payload(pairing_id, record) + + +@app.post("/api/messaging/whatsapp/onboarding/{pairing_id}/apply") +async def apply_whatsapp_onboarding( + pairing_id: str, body: WhatsAppOnboardingApply, profile: Optional[str] = None +): + with _whatsapp_onboarding_lock: + _prune_whatsapp_onboarding_sessions() + record = _whatsapp_onboarding_sessions.get(pairing_id) + if not record: + raise HTTPException( + status_code=404, + detail="WhatsApp setup session was not found. Start a new setup.", + ) + if record.status != "connected": + raise HTTPException(status_code=409, detail="WhatsApp setup is not connected yet.") + mode = _normalize_whatsapp_onboarding_mode(body.mode or record.mode) + allowed_users = _normalize_whatsapp_allowed_users( + record.allowed_users if body.allowed_users is None else body.allowed_users + ) + if mode == "self-chat" and not allowed_users: + allowed_users = record.account_phone or record.account_id or "" + record_profile = record.profile + + effective_profile = body.profile or profile or record_profile + try: + with _config_profile_scope(effective_profile): + save_env_value("WHATSAPP_MODE", mode) + save_env_value("WHATSAPP_DM_POLICY", "pairing") + if allowed_users: + save_env_value("WHATSAPP_ALLOWED_USERS", allowed_users) + # Blank means "keep the existing allowlist"; explicit clearing + # still lives in the normal config editor where the field is visible. + save_env_value("WHATSAPP_ENABLED", "true") + _write_platform_enabled("whatsapp", True) + except HTTPException: + raise + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + except Exception as exc: + _log.exception("WhatsApp onboarding apply failed") + raise HTTPException( + status_code=500, + detail="Failed to save WhatsApp setup.", + ) from exc + + with _whatsapp_onboarding_lock: + _whatsapp_onboarding_sessions.pop(pairing_id, None) + + restart_result = _restart_gateway_after_whatsapp_onboarding(effective_profile) + return { + "ok": True, + "platform": "whatsapp", + "needs_restart": not restart_result["restart_started"], + **restart_result, + } + + +@app.delete("/api/messaging/whatsapp/onboarding/{pairing_id}") +async def cancel_whatsapp_onboarding(pairing_id: str): + with _whatsapp_onboarding_lock: + record = _whatsapp_onboarding_sessions.pop(pairing_id, None) + if record: + record.status = "cancelled" + _terminate_whatsapp_pairing(record.proc) + return {"ok": True} + + +_TELEGRAM_ONBOARDING_DEFAULT_URL = "https://setup.hermes-agent.nousresearch.com" +_TELEGRAM_ONBOARDING_USER_AGENT = f"HermesDashboard/{__version__}" +_TELEGRAM_USER_ID_RE = re.compile(r"^\d+$") @dataclass @@ -6233,11 +8023,11 @@ def _anthropic_oauth_status() -> Dict[str, Any]: try: from agent.anthropic_adapter import ( read_hermes_oauth_credentials, - _HERMES_OAUTH_FILE, + _get_hermes_oauth_file, ) except ImportError: read_hermes_oauth_credentials = None # type: ignore - _HERMES_OAUTH_FILE = None # type: ignore + _get_hermes_oauth_file = None # type: ignore hermes_creds = None if read_hermes_oauth_credentials: @@ -6249,7 +8039,7 @@ def _anthropic_oauth_status() -> Dict[str, Any]: return { "logged_in": True, "source": "hermes_pkce", - "source_label": f"Hermes PKCE ({_HERMES_OAUTH_FILE})", + "source_label": f"Hermes PKCE ({_get_hermes_oauth_file() if _get_hermes_oauth_file else None})", "token_preview": _truncate_token(hermes_creds.get("accessToken")), "expires_at": hermes_creds.get("expiresAt"), "has_refresh_token": bool(hermes_creds.get("refreshToken")), @@ -6341,7 +8131,7 @@ def _copilot_acp_status() -> Dict[str, Any]: # ``flow`` describes the OAuth shape so the modal can pick the right UI: # ``pkce`` = open URL + paste callback code, ``device_code`` = show code + # verification URL + poll, ``external`` = read-only (delegated to a third-party -# CLI like Claude Code or Qwen), ``loopback`` = 127.0.0.1 callback listener. +# CLI like Claude Code or Qwen). _OAUTH_PROVIDER_CATALOG: tuple[Dict[str, Any], ...] = ( { "id": "nous", @@ -6383,10 +8173,10 @@ def _copilot_acp_status() -> Dict[str, Any]: { "id": "xai-oauth", "name": "xAI Grok OAuth (SuperGrok / Premium+)", - # Loopback PKCE: the desktop's local backend binds a 127.0.0.1 - # callback server, the client opens the browser, and the redirect - # lands back on the loopback listener — no code to copy/paste. - "flow": "loopback", + # Device code is the default because it works in remote shells, + # containers, and desktop installs without requiring a reachable + # 127.0.0.1 callback. + "flow": "device_code", "cli_command": "hermes auth add xai-oauth", "docs_url": "https://hermes-agent.nousresearch.com/docs/guides/xai-grok-oauth", "status_fn": None, # dispatched via auth.get_xai_oauth_auth_status @@ -6610,7 +8400,7 @@ async def list_oauth_providers(profile: Optional[str] = None): Response shape (per provider): id stable identifier (used in DELETE path) name human label - flow "pkce" | "device_code" | "external" | "loopback" + flow "pkce" | "device_code" | "external" cli_command fallback CLI command for users to run manually disconnect_command shell command that clears an external provider's creds (run in the embedded terminal), else null @@ -6686,9 +8476,10 @@ async def disconnect_oauth_provider( if provider_id == "anthropic": cleared = False try: - from agent.anthropic_adapter import _HERMES_OAUTH_FILE - if _HERMES_OAUTH_FILE.exists(): - _HERMES_OAUTH_FILE.unlink() + from agent.anthropic_adapter import _get_hermes_oauth_file + oauth_file = _get_hermes_oauth_file() + if oauth_file.exists(): + oauth_file.unlink() cleared = True except Exception: pass @@ -6745,19 +8536,6 @@ async def disconnect_oauth_provider( # 4. On "approved" the background thread has already saved creds; UI # refreshes the providers list. # -# Loopback PKCE (xAI Grok): -# 1. POST /api/providers/oauth/xai-oauth/start -# → server binds a 127.0.0.1 callback listener, builds the xAI -# authorize URL, spawns a background worker waiting on the redirect -# → returns { session_id, flow: "loopback", auth_url, expires_in } -# 2. UI opens auth_url in the browser. There is NO user_code/code to -# paste — the redirect lands back on the loopback listener. -# 3. UI polls GET /api/providers/oauth/{provider}/poll/{session_id} -# (same endpoint as device_code) until status != "pending". -# 4. The worker exchanges the code, persists creds, sets "approved". -# DELETE /sessions/{id} cancels: the worker bails before persisting -# and the callback server is shut down to free the port immediately. -# # Sessions are kept in-memory only (single-process FastAPI) and time out # after 15 minutes. A periodic cleanup runs on each /start call to GC # expired sessions so the dict doesn't grow without bound. @@ -6845,32 +8623,22 @@ def _save_anthropic_oauth_creds(access_token: str, refresh_token: str, expires_a Mirrors what auth_commands.add_command does so the dashboard flow leaves the system in the same state as ``hermes auth add anthropic``. """ - from agent.anthropic_adapter import _HERMES_OAUTH_FILE + from agent.anthropic_adapter import _get_hermes_oauth_file + oauth_file = _get_hermes_oauth_file() payload = { "accessToken": access_token, "refreshToken": refresh_token, "expiresAt": expires_at_ms, } - _HERMES_OAUTH_FILE.parent.mkdir(parents=True, exist_ok=True) - tmp_path = _HERMES_OAUTH_FILE.with_name( - f"{_HERMES_OAUTH_FILE.name}.tmp.{os.getpid()}.{secrets.token_hex(8)}" - ) - try: - with tmp_path.open("w", encoding="utf-8") as handle: - handle.write(json.dumps(payload, indent=2)) - handle.flush() - os.fsync(handle.fileno()) - os.replace(tmp_path, _HERMES_OAUTH_FILE) - try: - _HERMES_OAUTH_FILE.chmod(stat.S_IRUSR | stat.S_IWUSR) - except OSError: - pass - finally: - try: - if tmp_path.exists(): - tmp_path.unlink() - except OSError: - pass + # atomic_json_write creates the temp with mode 0o600 (via mkstemp) *before* + # any content is written, then fsyncs and atomically replaces the target. + # The previous os.replace + post-hoc chmod left a TOCTOU window in which the + # OAuth token file was world-readable at the default umask (0o644 on most + # hosts) between the rename and the chmod. atomic_json_write also preserves + # the existing file's owner and cleans up its temp on failure. + from utils import atomic_json_write + + atomic_json_write(oauth_file, payload, indent=2, mode=0o600) # Best-effort credential-pool insert. Failure here doesn't invalidate # the file write — pool registration only matters for the rotation # strategy, not for runtime credential resolution. @@ -7017,7 +8785,7 @@ async def _start_device_code_flow( provider_id: str, profile: Optional[str] = None, ) -> Dict[str, Any]: - """Initiate a device-code flow (Nous, OpenAI Codex, or MiniMax). + """Initiate a device-code flow (Nous, OpenAI Codex, MiniMax, or xAI). Calls the provider's device-auth endpoint via the existing CLI helpers, then spawns a background poller. Returns the user-facing display fields @@ -7186,242 +8954,63 @@ def _do_minimax_request(): "poll_interval": max(2, (sess["interval_ms"] or 2000) // 1000), } - raise HTTPException(status_code=400, detail=f"Provider {provider_id} does not support device-code flow") - - -# xAI Grok OAuth uses a loopback-redirect PKCE flow (RFC 8252). Unlike the -# device-code providers there is no user_code to display: the local backend -# binds a 127.0.0.1 callback server, the client opens the authorize URL in -# the browser, and the redirect lands back on the loopback listener. The -# background worker waits for that callback, exchanges the code, and persists -# the tokens exactly like `hermes auth add xai-oauth`. -_XAI_LOOPBACK_TIMEOUT_SECONDS = 300.0 - - -def _start_xai_loopback_flow(profile: Optional[str] = None) -> Dict[str, Any]: - """Begin the xAI loopback PKCE flow. + if provider_id == "xai-oauth": + from hermes_cli.auth import _xai_oauth_request_device_code + import httpx - Binds the local callback server, builds the authorize URL, and spawns a - background worker that waits for the redirect and finishes the exchange. - Returns the authorize URL for the client to open in the browser. - """ - from hermes_cli import auth as hauth + def _do_xai_device_request(): + with httpx.Client( + timeout=httpx.Timeout(20.0), + headers={"Accept": "application/json"}, + ) as client: + return _xai_oauth_request_device_code(client) - discovery = hauth._xai_oauth_discovery() - server, thread, callback_result, redirect_uri = hauth._xai_start_callback_server() - try: - hauth._xai_validate_loopback_redirect_uri(redirect_uri) - verifier = hauth._oauth_pkce_code_verifier() - challenge = hauth._oauth_pkce_code_challenge(verifier) - state = secrets.token_hex(16) - nonce = secrets.token_hex(16) - authorize_url = hauth._xai_oauth_build_authorize_url( - authorization_endpoint=discovery["authorization_endpoint"], - redirect_uri=redirect_uri, - code_challenge=challenge, - state=state, - nonce=nonce, + device_data = await asyncio.get_running_loop().run_in_executor( + None, _do_xai_device_request ) - except Exception: - # Binding succeeded but URL construction failed — release the socket - # and join the serving thread so we don't leak a listener (or a - # lingering daemon thread) on the loopback port. - try: - server.shutdown() - server.server_close() - except Exception: - pass - try: - thread.join(timeout=1.0) - except Exception: - pass - raise + sid, sess = _new_oauth_session("xai-oauth", "device_code", profile=profile) + sess["device_code"] = str(device_data["device_code"]) + sess["interval"] = int(device_data["interval"]) + sess["expires_at"] = time.time() + int(device_data["expires_in"]) + threading.Thread( + target=_xai_device_poller, + args=(sid,), + daemon=True, + name=f"oauth-poll-{sid[:6]}", + ).start() + return { + "session_id": sid, + "flow": "device_code", + "user_code": str(device_data["user_code"]), + "verification_url": str( + device_data.get("verification_uri_complete") + or device_data["verification_uri"] + ), + "expires_in": int(device_data["expires_in"]), + "poll_interval": int(device_data["interval"]), + } - sid, sess = _new_oauth_session("xai-oauth", "loopback", profile=profile) - sess["server"] = server - sess["thread"] = thread - sess["callback_result"] = callback_result - sess["redirect_uri"] = redirect_uri - sess["verifier"] = verifier - sess["challenge"] = challenge - sess["state"] = state - sess["token_endpoint"] = discovery["token_endpoint"] - sess["discovery"] = discovery - sess["expires_at"] = time.time() + _XAI_LOOPBACK_TIMEOUT_SECONDS - threading.Thread( - target=_xai_loopback_worker, args=(sid,), daemon=True, - name=f"oauth-xai-{sid[:6]}", - ).start() - return { - "session_id": sid, - "flow": "loopback", - "auth_url": authorize_url, - "expires_in": int(_XAI_LOOPBACK_TIMEOUT_SECONDS), - } + raise HTTPException(status_code=400, detail=f"Provider {provider_id} does not support device-code flow") -def _xai_loopback_worker(session_id: str) -> None: - """Wait for the xAI loopback callback, exchange the code, persist tokens.""" +def _nous_poller(session_id: str) -> None: + """Background poller that drives a Nous device-code flow to completion.""" + from hermes_cli.auth import ( + _poll_for_token, + refresh_nous_oauth_from_state, + ) from datetime import datetime, timezone - - from hermes_cli import auth as hauth - + import httpx with _oauth_sessions_lock: sess = _oauth_sessions.get(session_id) if not sess: return - - def _fail(message: str) -> None: - with _oauth_sessions_lock: - s = _oauth_sessions.get(session_id) - if s is not None: - s["status"] = "error" - s["error_message"] = message - - def _cancelled() -> bool: - # The session is removed from the registry when the user cancels - # (DELETE /sessions/{id}). If that happened while we were blocked on - # the callback or token exchange, abort instead of persisting tokens - # the user no longer wants. - with _oauth_sessions_lock: - return session_id not in _oauth_sessions - - try: - callback = hauth._xai_wait_for_callback( - sess["server"], - sess["thread"], - sess["callback_result"], - timeout_seconds=_XAI_LOOPBACK_TIMEOUT_SECONDS, - ) - except Exception as exc: - _fail(f"xAI authorization timed out: {exc}") - return - - if _cancelled(): - return - - if callback.get("error"): - detail = callback.get("error_description") or callback["error"] - _fail(f"xAI authorization failed: {detail}") - return - if callback.get("state") != sess["state"]: - _fail("xAI authorization failed: state mismatch.") - return - code = str(callback.get("code") or "").strip() - if not code: - _fail("xAI authorization failed: missing authorization code.") - return - - try: - payload = hauth._xai_oauth_exchange_code_for_tokens( - token_endpoint=sess["token_endpoint"], - code=code, - redirect_uri=sess["redirect_uri"], - code_verifier=sess["verifier"], - code_challenge=sess["challenge"], - ) - access_token = str(payload.get("access_token", "") or "").strip() - refresh_token = str(payload.get("refresh_token", "") or "").strip() - if not access_token or not refresh_token: - _fail("xAI token exchange did not return the expected tokens.") - return - base_url = hauth._xai_validate_inference_base_url( - os.getenv("HERMES_XAI_BASE_URL", "").strip().rstrip("/") - or os.getenv("XAI_BASE_URL", "").strip().rstrip("/"), - fallback=hauth.DEFAULT_XAI_OAUTH_BASE_URL, - ) - last_refresh = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") - tokens = { - "access_token": access_token, - "refresh_token": refresh_token, - "id_token": str(payload.get("id_token", "") or "").strip(), - "expires_in": payload.get("expires_in"), - "token_type": str(payload.get("token_type") or "Bearer").strip() or "Bearer", - } - if _cancelled(): - return - with _profile_scope(_oauth_session_profile(session_id)): - hauth._save_xai_oauth_tokens( - tokens, - discovery=sess.get("discovery"), - redirect_uri=sess["redirect_uri"], - last_refresh=last_refresh, - ) - _add_xai_oauth_pool_entry(access_token, refresh_token, base_url, last_refresh) - except Exception as exc: - _fail(f"xAI token exchange failed: {exc}") - return - - with _oauth_sessions_lock: - s = _oauth_sessions.get(session_id) - if s is not None: - s["status"] = "approved" - _log.info("oauth/loopback: xai-oauth login completed (session=%s)", session_id) - - -def _add_xai_oauth_pool_entry( - access_token: str, refresh_token: str, base_url: str, last_refresh: str -) -> None: - """Mirror `hermes auth add xai-oauth`'s credential-pool insert. - - Best-effort: the auth-store write in _save_xai_oauth_tokens is the source - of truth for runtime resolution; the pool entry only matters for the - rotation strategy. - """ - try: - import uuid - - from agent.credential_pool import ( - PooledCredential, - load_pool, - AUTH_TYPE_OAUTH, - SOURCE_MANUAL, - ) - pool = load_pool("xai-oauth") - existing = [ - e for e in pool.entries() - if getattr(e, "source", "").startswith(f"{SOURCE_MANUAL}:dashboard_xai_pkce") - ] - for e in existing: - try: - pool.remove_entry(getattr(e, "id", "")) - except Exception: - pass - entry = PooledCredential( - provider="xai-oauth", - id=uuid.uuid4().hex[:6], - label="dashboard PKCE", - auth_type=AUTH_TYPE_OAUTH, - priority=0, - source=f"{SOURCE_MANUAL}:dashboard_xai_pkce", - access_token=access_token, - refresh_token=refresh_token, - base_url=base_url, - last_refresh=last_refresh, - ) - pool.add_entry(entry) - except Exception as e: - _log.warning("xai-oauth pool add (dashboard) failed: %s", e) - - -def _nous_poller(session_id: str) -> None: - """Background poller that drives a Nous device-code flow to completion.""" - from hermes_cli.auth import ( - _poll_for_token, - refresh_nous_oauth_from_state, - ) - from datetime import datetime, timezone - import httpx - with _oauth_sessions_lock: - sess = _oauth_sessions.get(session_id) - if not sess: - return - portal_base_url = sess["portal_base_url"] - client_id = sess["client_id"] - device_code = sess["device_code"] - interval = sess["interval"] - scope = sess.get("scope") - expires_in = max(60, int(sess["expires_at"] - time.time())) + portal_base_url = sess["portal_base_url"] + client_id = sess["client_id"] + device_code = sess["device_code"] + interval = sess["interval"] + scope = sess.get("scope") + expires_in = max(60, int(sess["expires_at"] - time.time())) try: with httpx.Client(timeout=httpx.Timeout(15.0), headers={"Accept": "application/json"}) as client: token_data = _poll_for_token( @@ -7552,6 +9141,118 @@ def _minimax_poller(session_id: str) -> None: sess["error_message"] = str(e) +def _xai_device_poller(session_id: str) -> None: + """Background poller for xAI's OAuth device-code flow.""" + import httpx + from hermes_cli.auth import ( + _save_xai_oauth_tokens, + _xai_oauth_discovery, + _xai_oauth_poll_device_token, + unsuppress_credential_source, + ) + + with _oauth_sessions_lock: + sess = _oauth_sessions.get(session_id) + if not sess: + return + device_code = sess["device_code"] + interval = int(sess["interval"]) + expires_in = max(60, int(sess["expires_at"] - time.time())) + try: + discovery = _xai_oauth_discovery(20.0) + with httpx.Client( + timeout=httpx.Timeout(20.0), + headers={"Accept": "application/json"}, + ) as client: + token_data = _xai_oauth_poll_device_token( + client, + token_endpoint=discovery["token_endpoint"], + device_code=device_code, + expires_in=expires_in, + poll_interval=interval, + ) + tokens = { + "access_token": str(token_data.get("access_token", "") or "").strip(), + "refresh_token": str(token_data.get("refresh_token", "") or "").strip(), + "id_token": str(token_data.get("id_token", "") or "").strip(), + "expires_in": token_data.get("expires_in"), + "token_type": str(token_data.get("token_type") or "Bearer").strip() or "Bearer", + } + with _profile_scope(_oauth_session_profile(session_id)): + _save_xai_oauth_tokens( + tokens, + discovery=discovery, + last_refresh=datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), + auth_mode="oauth_device_code", + ) + # The singleton write above is the single source of truth: the + # credential-pool load seeds it as the canonical ``device_code`` + # entry. Do NOT also insert a parallel ``manual:dashboard_*`` pool + # entry — that duplicates the single-use refresh token across two + # entries and triggers rotation churn / ``refresh_token_reused``. + # An interactive dashboard login is also an explicit re-enable + # signal, so clear any ``device_code`` suppression left by a + # prior ``hermes auth remove xai-oauth`` (mirrors auth_add_command + # and the ``hermes model`` re-login path in _login_xai_oauth). + unsuppress_credential_source("xai-oauth", "device_code") + with _oauth_sessions_lock: + sess["status"] = "approved" + _log.info("oauth/device: xai login completed (session=%s)", session_id) + except Exception as e: + _log.warning("xai device-code poll failed (session=%s): %s", session_id, e) + with _oauth_sessions_lock: + sess["status"] = "error" + sess["error_message"] = str(e) + + +def _http_response_error_detail(resp: Any) -> str: + """Best-effort extraction of a short provider error detail.""" + try: + payload = resp.json() + except Exception: + payload = None + if isinstance(payload, dict): + error = payload.get("error") + if isinstance(error, dict): + parts = [ + str(error.get(key, "")).strip() + for key in ("message", "error_description", "code", "type") + if str(error.get(key, "")).strip() + ] + if parts: + return ": ".join(parts) + if isinstance(error, str) and error.strip(): + return error.strip() + for key in ("detail", "message", "error_description"): + value = payload.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + text = str(getattr(resp, "text", "") or "").strip() + return text[:500] + + +def _codex_device_code_start_error(resp: Any) -> str: + """Dashboard-facing OpenAI Codex device-code start failure.""" + status = getattr(resp, "status_code", "unknown") + detail = _http_response_error_detail(resp) + lower = detail.lower() + if "device" in lower and ("authori" in lower or "enable" in lower): + message = ( + "OpenAI rejected the device-code login request. Your OpenAI " + "account may need device-code authorization enabled before Hermes " + "can start this dashboard login. Enable device-code authorization " + "in OpenAI, then return here and click Login again." + ) + else: + message = ( + "OpenAI rejected the device-code login request. Please try Login " + "again from the dashboard after checking your OpenAI account settings." + ) + if detail: + return f"{message} (HTTP {status}: {detail})" + return f"{message} (HTTP {status})" + + def _codex_full_login_worker(session_id: str) -> None: """Run the complete OpenAI Codex device-code flow. @@ -7584,7 +9285,7 @@ def _codex_full_login_worker(session_id: str) -> None: headers={"Content-Type": "application/json"}, ) if resp.status_code != 200: - raise RuntimeError(f"deviceauth/usercode returned {resp.status_code}") + raise RuntimeError(_codex_device_code_start_error(resp)) device_data = resp.json() user_code = device_data.get("user_code", "") device_auth_id = device_data.get("device_auth_id", "") @@ -7701,10 +9402,6 @@ async def start_oauth_login( return _start_anthropic_pkce(profile=profile) if catalog_entry["flow"] == "device_code": return await _start_device_code_flow(provider_id, profile=profile) - if catalog_entry["flow"] == "loopback" and provider_id == "xai-oauth": - return await asyncio.get_running_loop().run_in_executor( - None, _start_xai_loopback_flow, profile, - ) except HTTPException: raise except Exception as e: @@ -7742,10 +9439,9 @@ async def poll_oauth_session( ): """Poll a session's status (no auth — read-only state). - Shared by the device-code flows (Nous, OpenAI Codex, MiniMax) and the - loopback flow (xAI Grok). Both surface progress through the same - background-worker-updated ``status`` field, so a single poll endpoint - serves them all. + Shared by the device-code flows (Nous, OpenAI Codex, MiniMax, xAI). + Each surfaces progress through the same background-worker-updated + ``status`` field, so a single poll endpoint serves them all. """ with _oauth_sessions_lock: sess = _oauth_sessions.get(session_id) @@ -7773,33 +9469,6 @@ async def cancel_oauth_session( sess = _oauth_sessions.pop(session_id, None) if sess is None: return {"ok": False, "message": "session not found"} - # Loopback sessions own a bound 127.0.0.1 callback server. Without an - # explicit shutdown the worker would keep that port held until - # _xai_wait_for_callback times out (up to 5 min). Free it immediately so - # an orphaned listener can't block a subsequent sign-in attempt. - if sess.get("flow") == "loopback": - # The worker is blocked in _xai_wait_for_callback, which polls - # callback_result rather than the server state. Flag the result as - # cancelled so that loop returns on its next tick instead of spinning - # until the timeout — otherwise repeated cancel/retry piles up daemon - # threads. (_cancelled() in the worker then short-circuits before any - # persist.) - result = sess.get("callback_result") - if isinstance(result, dict): - result["error"] = result.get("error") or "cancelled" - server = sess.get("server") - thread = sess.get("thread") - try: - if server is not None: - server.shutdown() - server.server_close() - except Exception: - pass - try: - if thread is not None: - thread.join(timeout=1.0) - except Exception: - pass return {"ok": True, "session_id": session_id} @@ -7809,14 +9478,12 @@ async def cancel_oauth_session( -def _session_latest_descendant(session_id: str): +def _session_latest_descendant(session_id: str, db): """Resolve a session id to the newest child leaf session. /model may create child sessions. Dashboard refresh should continue the newest child instead of reopening the old parent. """ - from hermes_state import SessionDB - def row_get(row, key, index): if isinstance(row, dict): return row.get(key) @@ -7828,62 +9495,68 @@ def row_get(row, key, index): except Exception: return None - db = SessionDB() - try: - sid = db.resolve_session_id(session_id) - if not sid or not db.get_session(sid): - return None, [] - - conn = ( - getattr(db, "conn", None) - or getattr(db, "_conn", None) - or getattr(db, "connection", None) - or getattr(db, "_connection", None) - ) - - rows = [] - if conn is not None: - raw_rows = conn.execute( - "SELECT id, parent_session_id, started_at FROM sessions" - ).fetchall() - for row in raw_rows: - rows.append({ - "id": row_get(row, "id", 0), - "parent_session_id": row_get(row, "parent_session_id", 1), - "started_at": row_get(row, "started_at", 2), - }) - else: - rows = db.list_sessions_rich(limit=10000, offset=0) + sid = db.resolve_session_id(session_id) + if not sid or not db.get_session(sid): + return None, [] - children = {} - for row in rows: - rid = row.get("id") - parent = row.get("parent_session_id") - if rid and parent: - children.setdefault(parent, []).append(row) + conn = ( + getattr(db, "conn", None) + or getattr(db, "_conn", None) + or getattr(db, "connection", None) + or getattr(db, "_connection", None) + ) - def started(row): - try: - return float(row.get("started_at") or 0) - except Exception: - return 0.0 + rows = [] + if conn is not None: + raw_rows = conn.execute( + """ + WITH RECURSIVE descendants(id, parent_session_id, started_at) AS ( + SELECT id, parent_session_id, started_at FROM sessions WHERE id = ? + UNION + SELECT s.id, s.parent_session_id, s.started_at + FROM sessions s + JOIN descendants d ON s.parent_session_id = d.id + ) + SELECT id, parent_session_id, started_at FROM descendants + """, + (sid,), + ).fetchall() + for row in raw_rows: + rows.append({ + "id": row_get(row, "id", 0), + "parent_session_id": row_get(row, "parent_session_id", 1), + "started_at": row_get(row, "started_at", 2), + }) + else: + rows = db.list_sessions_rich(limit=10000, offset=0, compact_rows=True) - current = sid - path = [sid] - seen = {sid} + children = {} + for row in rows: + rid = row.get("id") + parent = row.get("parent_session_id") + if rid and parent: + children.setdefault(parent, []).append(row) - while children.get(current): - candidates = [r for r in children[current] if r.get("id") not in seen] - if not candidates: - break - candidates.sort(key=started, reverse=True) - current = candidates[0]["id"] - path.append(current) - seen.add(current) + def started(row): + try: + return float(row.get("started_at") or 0) + except Exception: + return 0.0 - return current, path - finally: - db.close() + current = sid + path = [sid] + seen = {sid} + + while children.get(current): + candidates = [r for r in children[current] if r.get("id") not in seen] + if not candidates: + break + candidates.sort(key=started, reverse=True) + current = candidates[0]["id"] + path.append(current) + seen.add(current) + + return current, path # CRITICAL — every literal-path route below MUST be declared BEFORE the @@ -7901,6 +9574,34 @@ class BulkDeleteSessions(BaseModel): profile: Optional[str] = None +class SessionImport(BaseModel): + sessions: List[Dict[str, Any]] + profile: Optional[str] = None + + +# Keep the dashboard import endpoint stream-safe: FastAPI otherwise parses and +# buffers an arbitrarily large JSON body before SessionDB can enforce its own +# per-session and transaction-work limits. +_SESSION_IMPORT_MAX_BYTES = 25 * 1024 * 1024 + + +async def _read_session_import_body(request: Request) -> bytes: + body = bytearray() + async for chunk in request.stream(): + if len(body) + len(chunk) > _SESSION_IMPORT_MAX_BYTES: + raise HTTPException(status_code=413, detail="Session import payload is too large") + body.extend(chunk) + return bytes(body) + + +def _import_sessions_for_profile(profile: Optional[str], sessions: List[Dict[str, Any]]) -> Dict[str, Any]: + db = _open_session_db_for_profile(profile) + try: + return db.import_sessions(sessions) + finally: + db.close() + + @app.post("/api/sessions/bulk-delete") async def bulk_delete_sessions_endpoint(body: BulkDeleteSessions): """Delete every session in ``body.ids`` in a single DB transaction. @@ -7951,6 +9652,32 @@ async def bulk_delete_sessions_endpoint(body: BulkDeleteSessions): db.close() +@app.post("/api/sessions/import") +async def import_sessions_endpoint(request: Request): + """Import one or more sessions exported from the dashboard or CLI. + + This is intentionally separate from ``/api/ops/import``: that endpoint + restores a whole Hermes backup archive, while this endpoint is scoped to + session rows/messages and is safe to use from the Sessions page. + """ + try: + raw_body = await _read_session_import_body(request) + body = SessionImport.model_validate_json(raw_body) + except HTTPException: + raise + except ValueError as exc: + raise HTTPException(status_code=400, detail="Invalid session import payload") from exc + + try: + result = await asyncio.to_thread(_import_sessions_for_profile, body.profile, body.sessions) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + + if not result.get("ok", False): + raise HTTPException(status_code=400, detail=result) + return result + + @app.get("/api/sessions/empty/count") async def count_empty_sessions_endpoint(profile: Optional[str] = None): """Return the number of empty, ended, non-archived sessions. @@ -8009,7 +9736,7 @@ async def get_session_stats(profile: Optional[str] = None): messages = db.message_count() by_source: Dict[str, int] = {} try: - for s in db.list_sessions_rich(limit=10000, include_archived=True): + for s in db.list_sessions_rich(limit=10000, include_archived=True, compact_rows=True): src = str(s.get("source") or "cli") by_source[src] = by_source.get(src, 0) + 1 except Exception: @@ -8057,27 +9784,49 @@ async def get_session_detail(session_id: str, profile: Optional[str] = None): @app.get("/api/sessions/{session_id}/latest-descendant") -async def get_session_latest_descendant(session_id: str): - latest, path = _session_latest_descendant(session_id) - if not latest: - raise HTTPException(status_code=404, detail="Session not found") - return { - "requested_session_id": path[0] if path else session_id, - "session_id": latest, - "path": path, - "changed": bool(path and latest != path[0]), - } +async def get_session_latest_descendant( + session_id: str, + profile: Optional[str] = None, +): + db = _open_session_db_for_profile(profile) + try: + latest, path = _session_latest_descendant(session_id, db) + if not latest: + raise HTTPException(status_code=404, detail="Session not found") + return { + "requested_session_id": path[0] if path else session_id, + "session_id": latest, + "path": path, + "changed": bool(path and latest != path[0]), + } + finally: + db.close() @app.get("/api/sessions/{session_id}/messages") -async def get_session_messages(session_id: str, profile: Optional[str] = None): +async def get_session_messages( + session_id: str, + profile: Optional[str] = None, + limit: Optional[int] = None, + offset: int = 0, +): db = _open_session_db_for_profile(profile) try: sid = db.resolve_session_id(session_id) if not sid: raise HTTPException(status_code=404, detail="Session not found") sid = db.resolve_resume_session_id(sid) - messages = db.get_messages(sid) - return {"session_id": sid, "messages": messages} + # Clamp limit to prevent abuse (max 500 per page) + _limit = min(limit, 500) if limit is not None else None + messages = db.get_messages(sid, limit=_limit, offset=offset) + return { + "session_id": sid, + "messages": messages, + "pagination": { + "limit": _limit, + "offset": offset, + "returned": len(messages), + }, + } finally: db.close() @@ -8166,24 +9915,110 @@ async def export_session_endpoint(session_id: str, profile: Optional[str] = None class SessionPrune(BaseModel): - older_than_days: int = 90 + older_than_days: Optional[float] = 90 source: Optional[str] = None profile: Optional[str] = None + # Extended filters (all optional, AND together — mirrors the CLI flags) + started_before: Optional[float] = None # epoch seconds + started_after: Optional[float] = None # epoch seconds + title_like: Optional[str] = None + end_reason: Optional[str] = None + cwd_prefix: Optional[str] = None + min_messages: Optional[int] = None + max_messages: Optional[int] = None + model_like: Optional[str] = None + provider: Optional[str] = None + user_id: Optional[str] = None + chat_id: Optional[str] = None + chat_type: Optional[str] = None + branch_like: Optional[str] = None + min_tokens: Optional[int] = None + max_tokens: Optional[int] = None + min_cost: Optional[float] = None + max_cost: Optional[float] = None + min_tool_calls: Optional[int] = None + max_tool_calls: Optional[int] = None + include_archived: bool = False + dry_run: bool = False @app.post("/api/sessions/prune") async def prune_sessions_endpoint(body: SessionPrune): - """Delete ended sessions older than N days (mirrors `hermes sessions prune`).""" - if body.older_than_days < 1: + """Delete ended sessions matching filters (mirrors `hermes sessions prune`).""" + has_window = ( + body.started_before is not None or body.started_after is not None + ) + if body.older_than_days is not None and body.older_than_days < 1 and not has_window: raise HTTPException(status_code=400, detail="older_than_days must be >= 1") + # Mirror the CLI: the implicit 90-day cutoff only applies to a truly bare + # prune. Any attribute filter (source, title, model, ...) suppresses it + # unless the caller explicitly sent older_than_days. + _attr_filters_set = any( + getattr(body, f) is not None + for f in ( + "source", "title_like", "end_reason", "cwd_prefix", + "min_messages", "max_messages", "model_like", "provider", + "user_id", "chat_id", "chat_type", "branch_like", + "min_tokens", "max_tokens", "min_cost", "max_cost", + "min_tool_calls", "max_tool_calls", + ) + ) + _older_than_explicit = "older_than_days" in body.model_fields_set + _effective_older_than = body.older_than_days + if has_window or (_attr_filters_set and not _older_than_explicit): + _effective_older_than = None profile_home = _cron_profile_home(body.profile)[1] if body.profile else get_hermes_home() db = _open_session_db_for_profile(body.profile) try: + filters = dict( + older_than_days=_effective_older_than, + source=(body.source or None), + started_before=body.started_before, + started_after=body.started_after, + title_like=(body.title_like or None), + end_reason=(body.end_reason or None), + cwd_prefix=(body.cwd_prefix or None), + min_messages=body.min_messages, + max_messages=body.max_messages, + model_like=(body.model_like or None), + provider=(body.provider or None), + user_id=(body.user_id or None), + chat_id=(body.chat_id or None), + chat_type=(body.chat_type or None), + branch_like=(body.branch_like or None), + min_tokens=body.min_tokens, + max_tokens=body.max_tokens, + min_cost=body.min_cost, + max_cost=body.max_cost, + min_tool_calls=body.min_tool_calls, + max_tool_calls=body.max_tool_calls, + archived=None if body.include_archived else False, + ) + if body.dry_run: + rows = db.list_prune_candidates(**filters) + return { + "ok": True, + "removed": 0, + "matched": len(rows), + # Rows are ordered oldest-first. + "oldest_started_at": rows[0]["started_at"] if rows else None, + "newest_started_at": rows[-1]["started_at"] if rows else None, + "sessions": [ + { + "id": r["id"], + "source": r["source"], + "title": r.get("title"), + "model": r.get("model"), + "started_at": r["started_at"], + "message_count": r["message_count"], + } + for r in rows + ], + } sessions_dir = profile_home / "sessions" removed = db.prune_sessions( - older_than_days=body.older_than_days, - source=(body.source or None), sessions_dir=sessions_dir if sessions_dir.exists() else None, + **filters, ) return {"ok": True, "removed": removed} finally: @@ -8389,9 +10224,6 @@ def _validate_dashboard_cron_context_from( ) -_CRON_PROFILE_LOCK = threading.RLock() - - def _cron_profile_dicts() -> List[Dict[str, Any]]: """Return dashboard profile records, falling back to a directory scan.""" from hermes_cli import profiles as profiles_mod @@ -8429,33 +10261,23 @@ def _annotate_cron_job(job: Dict[str, Any], profile: str, home: Path) -> Dict[st def _call_cron_for_profile(target_profile: Optional[str], func_name: str, *args, **kwargs): """Run cron.jobs helpers against the selected profile's cron directory. - cron.jobs keeps CRON_DIR/JOBS_FILE/OUTPUT_DIR as module globals resolved - from the process HERMES_HOME at import time. The dashboard is a single - process that can inspect many profiles, so temporarily retarget those - globals while holding a lock and restore them immediately after the call. + The dashboard is a single process that can inspect many profiles. Route + storage through cron.jobs' execution-context override so dashboard calls + cannot retarget a concurrent desktop ticker's load/save transaction. """ profile_name, home = _cron_profile_home(target_profile) - with _CRON_PROFILE_LOCK: - from cron import jobs as cron_jobs - from hermes_constants import ( - reset_hermes_home_override, - set_hermes_home_override, - ) - - old_cron_dir = cron_jobs.CRON_DIR - old_jobs_file = cron_jobs.JOBS_FILE - old_output_dir = cron_jobs.OUTPUT_DIR - token = set_hermes_home_override(str(home)) - cron_jobs.CRON_DIR = home / "cron" - cron_jobs.JOBS_FILE = cron_jobs.CRON_DIR / "jobs.json" - cron_jobs.OUTPUT_DIR = cron_jobs.CRON_DIR / "output" - try: + from cron import jobs as cron_jobs + from hermes_constants import ( + reset_hermes_home_override, + set_hermes_home_override, + ) + + token = set_hermes_home_override(str(home)) + try: + with cron_jobs.use_cron_store(home): result = getattr(cron_jobs, func_name)(*args, **kwargs) - finally: - cron_jobs.CRON_DIR = old_cron_dir - cron_jobs.JOBS_FILE = old_jobs_file - cron_jobs.OUTPUT_DIR = old_output_dir - reset_hermes_home_override(token) + finally: + reset_hermes_home_override(token) if isinstance(result, list): return [_annotate_cron_job(j, profile_name, home) for j in result] @@ -8475,8 +10297,7 @@ def _find_cron_job_profile(job_id: str) -> Optional[str]: return None -@app.get("/api/cron/jobs") -async def list_cron_jobs(profile: str = "all"): +def _list_cron_jobs_sync(profile: str = "all"): requested = (profile or "all").strip() if requested.lower() != "all": return _call_cron_for_profile(requested, "list_jobs", True) @@ -8493,8 +10314,22 @@ async def list_cron_jobs(profile: str = "all"): return jobs -@app.get("/api/cron/jobs/{job_id}") -async def get_cron_job(job_id: str, profile: Optional[str] = None): +async def _run_cron_dashboard_io(func, *args, **kwargs): + """Run cron dashboard profile/job I/O outside the FastAPI event loop.""" + if inspect.iscoroutinefunction(func): + raise TypeError("_run_cron_dashboard_io only accepts sync callables") + result = await run_in_threadpool(func, *args, **kwargs) + if inspect.isawaitable(result): + raise TypeError("_run_cron_dashboard_io sync callable returned an awaitable") + return result + + +@app.get("/api/cron/jobs") +async def list_cron_jobs(profile: str = "all"): + return await _run_cron_dashboard_io(_list_cron_jobs_sync, profile) + + +def _get_cron_job_sync(job_id: str, profile: Optional[str] = None): selected = profile or _find_cron_job_profile(job_id) if not selected: raise HTTPException(status_code=404, detail="Job not found") @@ -8504,8 +10339,12 @@ async def get_cron_job(job_id: str, profile: Optional[str] = None): return job -@app.get("/api/cron/jobs/{job_id}/runs") -async def list_cron_job_runs(job_id: str, profile: Optional[str] = None, limit: int = 20): +@app.get("/api/cron/jobs/{job_id}") +async def get_cron_job(job_id: str, profile: Optional[str] = None): + return await _run_cron_dashboard_io(_get_cron_job_sync, job_id, profile) + + +def _list_cron_job_runs_sync(job_id: str, profile: Optional[str] = None, limit: int = 20): """Run sessions produced by a cron job, newest first. Cron runs are stored as ordinary sessions whose id is @@ -8550,8 +10389,12 @@ async def list_cron_job_runs(job_id: str, profile: Optional[str] = None, limit: db.close() -@app.post("/api/cron/jobs") -async def create_cron_job(body: CronJobCreate, profile: str = "default"): +@app.get("/api/cron/jobs/{job_id}/runs") +async def list_cron_job_runs(job_id: str, profile: Optional[str] = None, limit: int = 20): + return await _run_cron_dashboard_io(_list_cron_job_runs_sync, job_id, profile, limit) + + +def _create_cron_job_sync(body: CronJobCreate, profile: str = "default"): try: profile_name, profile_home = _cron_profile_home(profile) script = _normalize_dashboard_cron_script(body.script, profile_home) @@ -8589,6 +10432,11 @@ async def create_cron_job(body: CronJobCreate, profile: str = "default"): raise HTTPException(status_code=400, detail=str(e)) +@app.post("/api/cron/jobs") +async def create_cron_job(body: CronJobCreate, profile: str = "default"): + return await _run_cron_dashboard_io(_create_cron_job_sync, body, profile) + + @app.get("/api/cron/delivery-targets") async def get_cron_delivery_targets(): """Delivery targets the cron dropdown should offer. @@ -8617,8 +10465,7 @@ async def get_cron_delivery_targets(): return {"targets": targets} -@app.put("/api/cron/jobs/{job_id}") -async def update_cron_job(job_id: str, body: CronJobUpdate, profile: Optional[str] = None): +def _update_cron_job_sync(job_id: str, body: CronJobUpdate, profile: Optional[str] = None): selected = profile or _find_cron_job_profile(job_id) if not selected: raise HTTPException(status_code=404, detail="Job not found") @@ -8652,8 +10499,12 @@ async def update_cron_job(job_id: str, body: CronJobUpdate, profile: Optional[st return job -@app.post("/api/cron/jobs/{job_id}/pause") -async def pause_cron_job(job_id: str, profile: Optional[str] = None): +@app.put("/api/cron/jobs/{job_id}") +async def update_cron_job(job_id: str, body: CronJobUpdate, profile: Optional[str] = None): + return await _run_cron_dashboard_io(_update_cron_job_sync, job_id, body, profile) + + +def _pause_cron_job_sync(job_id: str, profile: Optional[str] = None): selected = profile or _find_cron_job_profile(job_id) if not selected: raise HTTPException(status_code=404, detail="Job not found") @@ -8663,8 +10514,12 @@ async def pause_cron_job(job_id: str, profile: Optional[str] = None): return job -@app.post("/api/cron/jobs/{job_id}/resume") -async def resume_cron_job(job_id: str, profile: Optional[str] = None): +@app.post("/api/cron/jobs/{job_id}/pause") +async def pause_cron_job(job_id: str, profile: Optional[str] = None): + return await _run_cron_dashboard_io(_pause_cron_job_sync, job_id, profile) + + +def _resume_cron_job_sync(job_id: str, profile: Optional[str] = None): selected = profile or _find_cron_job_profile(job_id) if not selected: raise HTTPException(status_code=404, detail="Job not found") @@ -8674,8 +10529,12 @@ async def resume_cron_job(job_id: str, profile: Optional[str] = None): return job -@app.post("/api/cron/jobs/{job_id}/trigger") -async def trigger_cron_job(job_id: str, profile: Optional[str] = None): +@app.post("/api/cron/jobs/{job_id}/resume") +async def resume_cron_job(job_id: str, profile: Optional[str] = None): + return await _run_cron_dashboard_io(_resume_cron_job_sync, job_id, profile) + + +def _trigger_cron_job_sync(job_id: str, profile: Optional[str] = None): selected = profile or _find_cron_job_profile(job_id) if not selected: raise HTTPException(status_code=404, detail="Job not found") @@ -8685,8 +10544,12 @@ async def trigger_cron_job(job_id: str, profile: Optional[str] = None): return job -@app.delete("/api/cron/jobs/{job_id}") -async def delete_cron_job(job_id: str, profile: Optional[str] = None): +@app.post("/api/cron/jobs/{job_id}/trigger") +async def trigger_cron_job(job_id: str, profile: Optional[str] = None): + return await _run_cron_dashboard_io(_trigger_cron_job_sync, job_id, profile) + + +def _delete_cron_job_sync(job_id: str, profile: Optional[str] = None): selected = profile or _find_cron_job_profile(job_id) if not selected: raise HTTPException(status_code=404, detail="Job not found") @@ -8699,35 +10562,35 @@ async def delete_cron_job(job_id: str, profile: Optional[str] = None): return {"ok": True} +@app.delete("/api/cron/jobs/{job_id}") +async def delete_cron_job(job_id: str, profile: Optional[str] = None): + return await _run_cron_dashboard_io(_delete_cron_job_sync, job_id, profile) + + def _fire_cron_job_for_profile(profile: str, job_id: str) -> bool: """Run ONE due cron job end-to-end for ``profile`` via the resolved scheduler provider's ``fire_due`` (store CAS claim + ``run_one_job``). - Retargets the ``cron.jobs`` module globals to the profile's cron dir under - the shared lock — same mechanism as ``_call_cron_for_profile`` — so the - claim and the run operate on the right profile's ``jobs.json``. Runs with - no live adapters; delivery falls back to the per-platform send path (the - dashboard process has no gateway adapter handles, exactly like the desktop - cron path above). + Scope both cron storage and the runtime Hermes home so the job's store, + config, credentials, scripts, skills, and output all belong to the selected + profile. Runs with no live adapters; delivery falls back to the per-platform + send path. """ _profile_name, home = _cron_profile_home(profile) - with _CRON_PROFILE_LOCK: - from cron import jobs as cron_jobs - from cron.scheduler_provider import resolve_cron_scheduler - - old_cron_dir = cron_jobs.CRON_DIR - old_jobs_file = cron_jobs.JOBS_FILE - old_output_dir = cron_jobs.OUTPUT_DIR - cron_jobs.CRON_DIR = home / "cron" - cron_jobs.JOBS_FILE = cron_jobs.CRON_DIR / "jobs.json" - cron_jobs.OUTPUT_DIR = cron_jobs.CRON_DIR / "output" - try: + from cron import jobs as cron_jobs + from cron.scheduler_provider import resolve_cron_scheduler + from hermes_constants import ( + reset_hermes_home_override, + set_hermes_home_override, + ) + + token = set_hermes_home_override(str(home)) + try: + with cron_jobs.use_cron_store(home): provider = resolve_cron_scheduler() return bool(provider.fire_due(job_id, adapters=None, loop=None)) - finally: - cron_jobs.CRON_DIR = old_cron_dir - cron_jobs.JOBS_FILE = old_jobs_file - cron_jobs.OUTPUT_DIR = old_output_dir + finally: + reset_hermes_home_override(token) @app.post("/api/cron/fire") @@ -8772,7 +10635,10 @@ async def cron_fire_webhook(request: Request): if not job_id: return JSONResponse({"error": "missing job_id"}, status_code=400) - profile = _find_cron_job_profile(job_id) + # _find_cron_job_profile walks every profile and lists its jobs (file + # I/O per profile) — run it off the event loop like the other cron + # dashboard endpoints. + profile = await _run_cron_dashboard_io(_find_cron_job_profile, job_id) if not profile: # Job is gone (cancelled / completed) — nothing to fire. 200 so NAS # does not retry a fire that is intentionally absent. @@ -8847,7 +10713,11 @@ async def instantiate_blueprint(body: AutomationBlueprintInstantiate, profile: s # Blueprint-created jobs deliver to the dashboard's configured target by # default; the form's deliver slot overrides via spec["deliver"]. spec.pop("origin", None) - return _call_cron_for_profile(profile, "create_job", **spec) + # create_job does per-profile file I/O — keep it off the event loop + # like the sibling cron endpoints (partial avoids **spec keys ever + # colliding with the wrapper's own parameters). + _create = functools.partial(_call_cron_for_profile, profile, "create_job", **spec) + return await _run_cron_dashboard_io(_create) except HTTPException: raise except Exception as e: @@ -8877,6 +10747,12 @@ class MCPServerCreate(BaseModel): profile: Optional[str] = None +class MCPServersReplace(BaseModel): + # Whole-map replace (name → raw server config) for the GUI mcp.json editor. + servers: Dict[str, Dict[str, Any]] = {} + profile: Optional[str] = None + + def _redact_mcp_env(env: Dict[str, Any]) -> Dict[str, str]: """Mask secret-shaped MCP env values for read responses.""" out: Dict[str, str] = {} @@ -8962,6 +10838,25 @@ async def add_mcp_server(body: MCPServerCreate, profile: Optional[str] = None): return _mcp_server_summary(name, server_config) +@app.put("/api/mcp/servers") +async def replace_mcp_servers(body: MCPServersReplace, profile: Optional[str] = None): + """Replace the entire ``mcp_servers`` map (the GUI mcp.json editor's save). + + The generic ``/api/config`` endpoint deep-merges maps, so it can never + delete a server key, drop an ``enabled: false`` flag, or remove a nested + field — edits looked saved but the stale entry survived on disk. This + endpoint sets the whole map so removals actually persist. Storage stays + the config.yaml ``mcp_servers`` key the CLI/TUI already read. + """ + from hermes_cli.mcp_config import _replace_mcp_servers + + with _profile_scope(body.profile or profile): + ok, issues = _replace_mcp_servers(body.servers) + if not ok: + raise HTTPException(status_code=400, detail="; ".join(issues)) + return {"ok": True} + + @app.delete("/api/mcp/servers/{name}") async def remove_mcp_server(name: str, profile: Optional[str] = None): from hermes_cli.mcp_config import _remove_mcp_server @@ -8976,43 +10871,173 @@ async def remove_mcp_server(name: str, profile: Optional[str] = None): @app.post("/api/mcp/servers/{name}/test") async def test_mcp_server(name: str, profile: Optional[str] = None): """Connect to the server, list its tools, disconnect. Returns tool list.""" - from hermes_cli.mcp_config import _get_mcp_servers, _probe_single_server + from hermes_cli.mcp_config import ( + _get_mcp_servers, + _oauth_tokens_present, + _probe_single_server, + ) with _profile_scope(profile): servers = _get_mcp_servers() if name not in servers: raise HTTPException(status_code=404, detail=f"Server '{name}' not found") + details: Dict[str, Any] = {} + # An `auth: oauth` server that serves tools/list anonymously would probe OK + # with no token — a false green. Require a token on disk for it, matching the + # /auth verification (some providers don't enforce auth on tools/list). + needs_oauth_token = servers[name].get("auth") == "oauth" + def _probe_scoped(): - # Re-enter the scope INSIDE the worker thread so call-time - # resolution during the probe — env-placeholder expansion in - # _resolve_mcp_server_config reading the profile's .env — sees the - # selected profile, matching the config the server was saved into. - # (asyncio.to_thread copies contextvars, but entering explicitly - # keeps the lock-protected SKILLS_DIR swap balanced per-thread.) - # The probe's dedicated MCP event-loop thread is covered too: - # _run_on_mcp_loop wraps scheduled coroutines with the caller's - # HERMES_HOME override (see mcp_tool._wrap_with_home_override), so - # OAuth token stores resolve against the selected profile as well. - with _profile_scope(profile): - return _probe_single_server(name, servers[name]) + # Home-only scope (contextvar), NOT _profile_scope. A probe blocks for + # as long as the server takes to spawn/connect — a stdio `npx` cold + # start is many seconds — and _profile_scope holds a process-global + # skills lock for its ENTIRE body. Holding that across the probe + # serialized every other endpoint (config/skills/toolsets all take the + # same lock), so a slow server made unrelated requests time out at 15s. + # The probe touches no skills globals; it only needs the HERMES_HOME + # override for .env interpolation + OAuth token resolution, which the + # contextvar provides (copied into this to_thread worker; and + # _run_on_mcp_loop re-wraps it onto the MCP event-loop thread). + with _config_profile_scope(profile): + tools = _probe_single_server(name, servers[name], details=details) + token_present = _oauth_tokens_present(name) if needs_oauth_token else True + return tools, token_present try: # Probe blocks on a dedicated MCP event loop — run in a thread so the # FastAPI event loop is never blocked. - tools = await asyncio.to_thread(_probe_scoped) + tools, token_present = await asyncio.to_thread(_probe_scoped) except Exception as exc: return { "ok": False, "error": str(exc), "tools": [], } + if not token_present: + return { + "ok": False, + "error": "OAuth authentication required — no token found.", + "tools": [], + } return { "ok": True, "tools": [{"name": t, "description": d} for t, d in tools], + "prompts": details.get("prompts", 0), + "resources": details.get("resources", 0), } +@app.post("/api/mcp/servers/{name}/auth") +async def auth_mcp_server(name: str, profile: Optional[str] = None): + """Run the OAuth flow for an HTTP MCP server (opens the system browser). + + Mirrors ``hermes mcp login``: wipe cached OAuth state so the probe forces + a fresh browser flow, connect, then verify a token actually landed on disk + (some providers serve tools/list unauthenticated — see + ``_reauth_oauth_server``). Blocks until the browser flow completes, so it + runs in a worker thread. ``auth: oauth`` is persisted only on success. + """ + from hermes_cli.mcp_config import ( + _get_mcp_servers, + _oauth_tokens_present, + _probe_single_server, + _save_mcp_server, + ) + + with _profile_scope(profile): + servers = _get_mcp_servers() + if name not in servers: + raise HTTPException(status_code=404, detail=f"Server '{name}' not found") + + cfg = dict(servers[name]) + if not cfg.get("url"): + raise HTTPException( + status_code=400, + detail="stdio servers authenticate via env keys, not OAuth", + ) + # A server carrying `headers` uses API-key/bearer auth; a 401 there is a bad + # key, not an OAuth prompt. Refuse rather than rewrite it to `auth: oauth` + # and corrupt a working header-auth config. (Explicit `auth: oauth` is fine.) + if cfg.get("headers") and cfg.get("auth") != "oauth": + raise HTTPException( + status_code=400, + detail="This server uses header/API-key auth, not OAuth — check its key.", + ) + cfg["auth"] = "oauth" + + def _run(): + from tools.mcp_oauth import HermesTokenStorage, force_interactive_oauth + + # Home-only scope, not _profile_scope: this blocks on the browser flow + # for up to minutes; holding the shared skills lock that whole time + # would freeze every other endpoint. Config writes here (_save_mcp_server) + # resolve HERMES_HOME via the contextvar override, which is all they need. + with _config_profile_scope(profile), force_interactive_oauth(): + storage = HermesTokenStorage(name) + # Snapshot before clearing: a re-auth wipes cached state to force a + # fresh consent, but if the flow fails we must NOT leave the user + # worse off than before — restore the working token on any failure. + backup = storage.snapshot() + try: + from tools.mcp_oauth_manager import get_manager + + get_manager().remove(name) + except Exception: + pass # No cached state to clear — fine. + try: + # The default 30s connect timeout would kill the flow while the + # user is still on the consent screen — give the browser + # round-trip the full callback window (300s in mcp_oauth) plus + # headroom so the connect wrapper can't pre-empt it. Honor a + # larger configured connect_timeout when the user set one. + try: + _cfg_timeout = float(cfg.get("connect_timeout", 0)) + except (TypeError, ValueError): + _cfg_timeout = 0.0 + tools = _probe_single_server( + name, cfg, connect_timeout=max(_cfg_timeout, 315) + ) + except Exception: + storage.restore(backup) + raise + if not _oauth_tokens_present(name): + storage.restore(backup) + return { + "ok": False, + "error": ( + "The server responded, but no OAuth token was obtained — " + "this provider may require a manually-registered OAuth " + "client (see `hermes mcp login`)." + ), + "tools": [], + } + _save_mcp_server(name, cfg) + return { + "ok": True, + "tools": [{"name": t, "description": d} for t, d in tools], + } + + try: + return await asyncio.to_thread(_run) + except Exception as exc: + msg = str(exc) + # Providers that gate RFC 7591 registration to pre-approved clients + # (Figma's MCP catalog, etc.) 403 the register call before any + # authorization URL exists — surface what's actually happening + # instead of a bare "403 Forbidden". + lowered = msg.lower() + if "403" in msg and ("regist" in lowered or "forbidden" in lowered): + msg = ( + f"'{name}' only allows pre-approved OAuth clients — it rejected " + "client registration (403), so no browser flow can start. " + "Options: add a pre-registered client to this server's entry " + "(oauth: {client_id: ..., client_secret: ...}), or use the " + "provider's stdio / API-key server instead." + ) + return {"ok": False, "error": msg, "tools": []} + + class MCPEnabledToggle(BaseModel): enabled: bool profile: Optional[str] = None @@ -9154,16 +11179,20 @@ async def install_mcp_catalog_entry(body: MCPCatalogInstall, profile: Optional[s # action path so the request returns immediately and the UI can tail logs. # The -p subprocess rebinds HERMES_HOME-derived paths in the child. if entry.install is not None: + # Unique per-entry action name: a shared "mcp-install" would let a + # re-click (or a second entry) overwrite the tracked process/log while + # the first clone is still running. + action = _mcp_install_action_name(name) try: proc = _spawn_hermes_action( _profile_cli_args(effective_profile) + ["mcp", "install", name], - "mcp-install", + action, ) except HTTPException: raise except Exception as exc: raise HTTPException(status_code=500, detail=f"Install failed: {exc}") - return {"ok": True, "name": name, "background": True, "action": "mcp-install"} + return {"ok": True, "name": name, "background": True, "action": action} # No git step — install synchronously via the catalog API. install_entry # routes through load_config/save_config + save_env_value, all call-time @@ -9185,8 +11214,17 @@ def _install_scoped(): return {"ok": True, "name": name, "background": False} -# Register the mcp-install action log so /api/actions/mcp-install/status works. -_ACTION_LOG_FILES.setdefault("mcp-install", "action-mcp-install.log") +def _mcp_install_action_name(name: str) -> str: + """Unique per-entry mcp-install action name (+ registered log file), so a + re-click or a second catalog install doesn't overwrite the first's tracked + process/log while its git clone is still running.""" + slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")[:48] or "server" + digest = hashlib.sha1(name.encode()).hexdigest()[:8] + action = f"mcp-install-{slug}-{digest}" + _ACTION_LOG_FILES.setdefault(action, f"action-{action}.log") + return action + + _ACTION_LOG_FILES.setdefault("computer-use-grant", "action-computer-use-grant.log") @@ -9280,6 +11318,7 @@ class WebhookCreate(BaseModel): description: Optional[str] = None events: List[str] = [] prompt: Optional[str] = None + script: Optional[str] = None skills: List[str] = [] deliver: str = "log" deliver_only: bool = False @@ -9296,6 +11335,7 @@ def _webhook_route_summary(name: str, route: Dict[str, Any], base_url: str) -> D "deliver": route.get("deliver", "log"), "deliver_only": bool(route.get("deliver_only")), "prompt": route.get("prompt", ""), + "script": route.get("script", ""), "skills": list(route.get("skills") or []), "created_at": route.get("created_at"), "url": f"{base_url}/webhooks/{name}", @@ -9379,6 +11419,8 @@ async def create_webhook(body: WebhookCreate): "deliver": body.deliver or "log", "created_at": _time.strftime("%Y-%m-%dT%H:%M:%SZ", _time.gmtime()), } + if body.script and body.script.strip(): + route["script"] = body.script.strip() if body.deliver_only: route["deliver_only"] = True if body.deliver_chat_id: @@ -9584,11 +11626,9 @@ async def remove_credential_pool_entry(provider: str, index: int): # --------------------------------------------------------------------------- # Memory provider endpoints — status / list providers / select / disable / reset. # -# Selecting a provider only writes config.memory.provider (full interactive -# provider setup, with its API-key prompts, stays on the CLI via -# `hermes memory setup`). The dashboard covers the common admin actions: -# see which provider is active, switch the built-in store on/off, and wipe -# built-in memory files. +# Provider setup is dashboard-native when a provider exposes get_config_schema(). +# The dashboard never runs interactive provider setup hooks; activation is only +# allowed once the provider is discoverable, available, and has required config. # --------------------------------------------------------------------------- @@ -9604,24 +11644,11 @@ class MemoryReset(BaseModel): @app.get("/api/memory") async def get_memory_status(): - from plugins.memory import discover_memory_providers - cfg = load_config() active = "" mem = cfg.get("memory") if isinstance(mem, dict): - active = str(mem.get("provider") or "") - - providers = [] - try: - for name, description, configured in discover_memory_providers(): - providers.append({ - "name": name, - "description": description, - "configured": bool(configured), - }) - except Exception: - _log.exception("discover_memory_providers failed") + active = _normalize_memory_provider_name(mem.get("provider")) # Built-in memory file sizes (so the UI can show what a reset would erase). mem_dir = get_hermes_home() / "memories" @@ -9632,26 +11659,16 @@ async def get_memory_status(): return { "active": active, - "providers": providers, + "providers": _discover_memory_provider_statuses(), "builtin_files": files, } @app.put("/api/memory/provider") async def set_memory_provider(body: MemoryProviderSelect): - provider = (body.provider or "").strip() - if provider.lower() in {"built-in", "builtin", "none"}: - provider = "" + provider = _normalize_memory_provider_name(body.provider) - if provider: - from plugins.memory import discover_memory_providers - - valid = {name for name, _d, _c in discover_memory_providers()} - if provider not in valid: - raise HTTPException( - status_code=400, - detail=f"Unknown memory provider '{provider}'. Run `hermes memory setup` to configure a new one.", - ) + _require_memory_provider_ready(provider) cfg = load_config() if not isinstance(cfg.get("memory"), dict): @@ -10132,23 +12149,39 @@ def _profile_cli_args(profile: Optional[str]) -> List[str]: return ["-p", profiles_mod.normalize_profile_name(requested)] +def _hub_action_name(verb: str, key: str) -> str: + """Unique per-skill hub action name (+ registered log file). + + ``_spawn_hermes_action`` tracks one process/log per name, so a shared + "skills-install"/"skills-uninstall" would make concurrent row-level actions + overwrite each other's status/log while the UI polls per identifier. Slug + (readable) + hash (collision-proof) keys each action to its own row. + """ + slug = re.sub(r"[^a-z0-9]+", "-", key.lower()).strip("-")[:48] or "skill" + digest = hashlib.sha1(key.encode()).hexdigest()[:8] + name = f"skills-{verb}-{slug}-{digest}" + _ACTION_LOG_FILES.setdefault(name, f"action-{name}.log") + return name + + @app.post("/api/skills/hub/install") async def install_skill_hub(body: SkillInstallRequest, profile: Optional[str] = None): identifier = (body.identifier or "").strip() if not identifier: raise HTTPException(status_code=400, detail="identifier is required") + name = _hub_action_name("install", identifier) try: proc = _spawn_hermes_action( _profile_cli_args(body.profile or profile) + ["skills", "install", identifier, "--yes"], - "skills-install", + name, ) except HTTPException: raise except Exception as exc: _log.exception("Failed to spawn skills install") raise HTTPException(status_code=500, detail=f"Failed to install skill: {exc}") - return {"ok": True, "pid": proc.pid, "name": "skills-install"} + return {"ok": True, "pid": proc.pid, "name": name} class SkillUninstallRequest(BaseModel): @@ -10161,17 +12194,18 @@ async def uninstall_skill_hub(body: SkillUninstallRequest, profile: Optional[str name = (body.name or "").strip() if not name: raise HTTPException(status_code=400, detail="name is required") + action = _hub_action_name("uninstall", name) try: proc = _spawn_hermes_action( _profile_cli_args(body.profile or profile) + ["skills", "uninstall", name, "--yes"], - "skills-uninstall", + action, ) except HTTPException: raise except Exception as exc: _log.exception("Failed to spawn skills uninstall") raise HTTPException(status_code=500, detail=f"Failed to uninstall skill: {exc}") - return {"ok": True, "pid": proc.pid, "name": "skills-uninstall"} + return {"ok": True, "pid": proc.pid, "name": action} class SkillsUpdateRequest(BaseModel): @@ -10268,7 +12302,8 @@ async def list_skills_hub_sources(profile: Optional[str] = None): def _run(): from tools.skills_hub import create_source_router - sources = create_source_router() + with _config_profile_scope(profile): + sources = create_source_router() out = [] index_available = False featured = [] @@ -10299,6 +12334,17 @@ def _run(): except Exception: featured = [] out.append(entry) + # Tell the UI which sources are worth searching individually (for its + # progressive per-source fan-out). Mirror parallel_search_sources: when + # the centralized index is available it already subsumes the external + # API sources, so they're redundant — skipping them avoids ~70 GitHub + # calls per keystroke. Keep this set in sync with that function's + # ``_api_source_ids``. + _api_source_ids = frozenset( + {"github", "skills-sh", "clawhub", "claude-marketplace", "lobehub", "well-known"} + ) + for entry in out: + entry["searchable"] = not (index_available and entry["id"] in _api_source_ids) return { "sources": out, "index_available": index_available, @@ -10333,7 +12379,8 @@ async def search_skills_hub( def _run(): from tools.skills_hub import create_source_router, parallel_search_sources - sources = create_source_router() + with _config_profile_scope(profile): + sources = create_source_router() capped = min(max(limit, 1), 50) all_results, source_counts, timed_out = parallel_search_sources( sources, query=query, source_filter=source or "all", overall_timeout=30 @@ -10366,13 +12413,16 @@ def _run(): @app.get("/api/skills/hub/preview") -async def preview_skill_hub(identifier: str = ""): +async def preview_skill_hub(identifier: str = "", profile: Optional[str] = None): """Fetch a hub skill's SKILL.md content + metadata for in-dashboard reading. Resolves the identifier across configured sources (same path the CLI installer uses), then returns the rendered SKILL.md text and the file manifest WITHOUT installing anything. This is the 'read the actual skill before installing' affordance the Browse-hub tab was missing. + + Scoped to ``profile`` so a non-default profile with different hub taps + resolves against ITS source router, not the default profile's. """ ident = (identifier or "").strip() if not ident: @@ -10382,8 +12432,9 @@ def _run(): from hermes_cli.skills_hub import _resolve_source_meta_and_bundle from tools.skills_hub import create_source_router - sources = create_source_router() - meta, bundle, _src = _resolve_source_meta_and_bundle(ident, sources) + with _config_profile_scope(profile): + sources = create_source_router() + meta, bundle, _src = _resolve_source_meta_and_bundle(ident, sources) if not bundle and not meta: return None @@ -10427,7 +12478,7 @@ def _run(): @app.get("/api/skills/hub/scan") -async def scan_skill_hub(identifier: str = ""): +async def scan_skill_hub(identifier: str = "", profile: Optional[str] = None): """Run the install-time security scan on a hub skill WITHOUT installing it. Fetches the bundle, quarantines it, and runs the same `scan_skill` / @@ -10435,6 +12486,9 @@ async def scan_skill_hub(identifier: str = ""): quarantine. Returns the verdict, per-finding detail, trust tier, and the install-policy decision so the dashboard can show a visual safety result on demand (the 'scan' button the Browse-hub tab was missing). + + Scoped to ``profile`` so the bundle resolves against that profile's hub + source router, matching where an install would pull it from. """ ident = (identifier or "").strip() if not ident: @@ -10447,8 +12501,9 @@ def _run(): from tools.skills_hub import create_source_router, quarantine_bundle from tools.skills_guard import scan_skill, should_allow_install - sources = create_source_router() - meta, bundle, _src = _resolve_source_meta_and_bundle(ident, sources) + with _config_profile_scope(profile): + sources = create_source_router() + meta, bundle, _src = _resolve_source_meta_and_bundle(ident, sources) if not bundle: return None @@ -10890,7 +12945,7 @@ async def create_profile_endpoint(body: ProfileCreate): try: proc = _spawn_hermes_action( ["-p", body.name, "skills", "install", ident, "--yes"], - "skills-install", + _hub_action_name("install", ident), ) hub_installs.append({"identifier": ident, "pid": proc.pid}) except Exception: @@ -11257,12 +13312,31 @@ class SkillToggle(BaseModel): async def get_skills(profile: Optional[str] = None): from tools.skills_tool import _find_all_skills from hermes_cli.skills_config import get_disabled_skills + from tools.skill_usage import ( + _read_bundled_manifest_names, + _read_hub_installed_names, + activity_count, + load_usage, + ) with _profile_scope(profile): config = load_config() disabled = get_disabled_skills(config) skills = _find_all_skills(skip_disabled=True) + usage = load_usage() + # Set-based provenance (same classification as skill_usage.provenance, + # without a per-skill manifest read): hub > bundled > agent, where + # "agent" covers agent-authored AND local hand-made skills — the ones + # the user may edit/delete from the UI. + bundled_names = _read_bundled_manifest_names() + hub_names = _read_hub_installed_names() for s in skills: s["enabled"] = s["name"] not in disabled + s["usage"] = activity_count(usage.get(s["name"], {})) + s["provenance"] = ( + "hub" if s["name"] in hub_names + else "bundled" if s["name"] in bundled_names + else "agent" + ) return skills @@ -11500,6 +13574,176 @@ class ToolsetProviderSelect(BaseModel): profile: Optional[str] = None +# Toolsets whose backends carry a selectable model catalog, mapped to the +# config.yaml section their `model` key lives in. Mirrors the CLI's +# post-selection model pickers (`_configure_imagegen_model_for_plugin` / +# `_configure_videogen_model_for_plugin` in tools_config.py). +_MODEL_CATALOG_TOOLSETS = { + "image_gen": "image_gen", + "video_gen": "video_gen", +} + + +def _resolve_toolset_model_plugin(ts_key: str, provider_row: dict) -> Optional[str]: + """Map a provider picker row to its model-catalog plugin name. + + Plugin-backed rows carry ``image_gen_plugin_name`` / ``video_gen_plugin_name``; + the managed "Nous Subscription" image row instead carries the legacy + ``imagegen_backend: "fal"`` marker (same underlying FAL catalog). + """ + if ts_key == "image_gen": + return provider_row.get("image_gen_plugin_name") or ( + "fal" if provider_row.get("imagegen_backend") else None + ) + if ts_key == "video_gen": + return provider_row.get("video_gen_plugin_name") + return None + + +def _toolset_model_catalog(ts_key: str, plugin_name: str): + """Return ``(catalog_dict, default_model)`` for a toolset's plugin backend.""" + from hermes_cli.tools_config import ( + _plugin_image_gen_catalog, + _plugin_video_gen_catalog, + ) + + if ts_key == "image_gen": + return _plugin_image_gen_catalog(plugin_name) + return _plugin_video_gen_catalog(plugin_name) + + +def _find_toolset_provider_row(ts_key: str, config: dict, provider: Optional[str]) -> Optional[dict]: + """Resolve a provider picker row by name, or the active row when omitted.""" + from hermes_cli.tools_config import ( + TOOL_CATEGORIES, + _is_provider_active, + _visible_providers, + ) + + cat = TOOL_CATEGORIES.get(ts_key) + if cat is None: + return None + rows = _visible_providers(cat, config, force_fresh=True) + if provider: + return next((p for p in rows if p.get("name") == provider), None) + return next( + (p for p in rows if _is_provider_active(p, config, force_fresh=True)), None + ) + + +@app.get("/api/tools/toolsets/{name}/models") +async def get_toolset_models( + name: str, provider: Optional[str] = None, profile: Optional[str] = None +): + """Return the model catalog for a toolset backend (image/video gen). + + The GUI counterpart of the model picker `hermes tools` runs after a + backend is selected — e.g. FAL's multi-model catalog (speed / strengths / + price per model). ``provider`` names a picker row; omitted, the currently + active provider is used. Toolsets without model catalogs return + ``has_models: false``. + """ + section = _MODEL_CATALOG_TOOLSETS.get(name) + if section is None: + return {"name": name, "has_models": False, "models": [], "current": None, "default": None} + + with _profile_scope(profile): + config = load_config() + row = _find_toolset_provider_row(name, config, provider) + plugin = _resolve_toolset_model_plugin(name, row) if row else None + if not plugin: + return { + "name": name, + "has_models": False, + "models": [], + "current": None, + "default": None, + } + + catalog, default_model = _toolset_model_catalog(name, plugin) + section_cfg = config.get(section) + current = None + if isinstance(section_cfg, dict): + raw = section_cfg.get("model") + if isinstance(raw, str) and raw.strip(): + current = raw.strip() + if current not in catalog: + current = default_model if default_model in catalog else None + + models = [ + { + "id": model_id, + "display": meta.get("display", model_id), + "speed": meta.get("speed", ""), + "strengths": meta.get("strengths", ""), + "price": meta.get("price", ""), + } + for model_id, meta in catalog.items() + ] + return { + "name": name, + "has_models": bool(models), + "provider": row.get("name") if row else None, + "plugin": plugin, + "models": models, + "current": current, + "default": default_model, + } + + +class ToolsetModelSelect(BaseModel): + model: str + provider: Optional[str] = None + profile: Optional[str] = None + + +@app.put("/api/tools/toolsets/{name}/model") +async def select_toolset_model( + name: str, body: ToolsetModelSelect, profile: Optional[str] = None +): + """Persist a backend model selection (``image_gen.model`` / ``video_gen.model``). + + Validates the model against the resolved backend's catalog — the same + write the CLI's post-selection model picker performs. Returns 400 for + toolsets without model catalogs or unknown model ids. + """ + section = _MODEL_CATALOG_TOOLSETS.get(name) + if section is None: + raise HTTPException( + status_code=400, detail=f"Toolset has no model catalog: {name}" + ) + + model_id = (body.model or "").strip() + if not model_id: + raise HTTPException(status_code=400, detail="model is required") + + with _profile_scope(body.profile or profile): + config = load_config() + row = _find_toolset_provider_row(name, config, body.provider) + plugin = _resolve_toolset_model_plugin(name, row) if row else None + if not plugin: + raise HTTPException( + status_code=400, + detail=f"No model-capable backend is active for {name}", + ) + + catalog, _default = _toolset_model_catalog(name, plugin) + if model_id not in catalog: + raise HTTPException( + status_code=400, + detail=f"Unknown model {model_id!r} for backend {plugin!r}", + ) + + section_cfg = config.setdefault(section, {}) + if not isinstance(section_cfg, dict): + section_cfg = {} + config[section] = section_cfg + section_cfg["model"] = model_id + save_config(config) + + return {"ok": True, "name": name, "model": model_id, "plugin": plugin} + + @app.put("/api/tools/toolsets/{name}/provider") async def select_toolset_provider( name: str, body: ToolsetProviderSelect, profile: Optional[str] = None @@ -11810,6 +14054,9 @@ async def get_usage_analytics(days: int = 30, profile: Optional[str] = None): "totals": totals, "period_days": days, "skills": skills, + # Per-tool-name call counts (already computed by InsightsEngine); + # the desktop Capabilities page aggregates these per toolset. + "tools": insights_report.get("tools", []), } finally: db.close() @@ -12013,6 +14260,105 @@ class PtyUnavailableError(RuntimeError): # type: ignore[no-redef] _RESIZE_RE = re.compile(rb"\x1b\[RESIZE:(\d+);(\d+)\]") _PTY_READ_CHUNK_TIMEOUT = 0.2 + +# Keep-alive PTY sessions: a terminal connecting with ``?attach=`` is +# bound to a process that survives disconnect/refresh and is reattachable. +from hermes_cli.pty_session import PtySessionRegistry, RegistryFull, run_reaper # noqa: E402 + +PTY_REGISTRY = PtySessionRegistry( + ttl=30 * 60, + max_sessions=16, + buffer_cap=1 * 1024 * 1024, + read_timeout=_PTY_READ_CHUNK_TIMEOUT, +) + + +async def _legacy_pump(ws: "WebSocket", bridge) -> None: + """Original 1:1 socket<->PTY pump: stream until disconnect, then close the + bridge. Used when no ``?attach=`` token is supplied (keep-alive opt-in). + + Behavior is identical to the pre-keep-alive ``pty_ws`` body, including the + #54028 half-open-socket protection (reader EOF → close the WS so the + writer's ``ws.receive()`` unparks) and the #53227 ``to_thread`` offloads + for the blocking ``bridge.close()``. + """ + loop = asyncio.get_running_loop() + + # --- reader task: PTY master → WebSocket ---------------------------- + async def pump_pty_to_ws() -> None: + try: + while True: + chunk = await loop.run_in_executor( + None, bridge.read, _PTY_READ_CHUNK_TIMEOUT + ) + if chunk is None: # EOF + return + if not chunk: # no data this tick; yield control and retry + await asyncio.sleep(0) + continue + try: + await ws.send_bytes(chunk) + except Exception: + return + finally: + # The child has exited (EOF) or the send side broke. Close the + # WebSocket so the writer loop's ``ws.receive()`` returns instead + # of blocking forever — otherwise, when the browser's socket is + # half-open (no FIN delivered, common on macOS/launchd) the + # handler never reaches its ``finally`` and the PTY's fds leak. + # With dashboard auto-reconnect (#52962) every dropped socket then + # stacks a fresh PTY on top of the orphaned one, exhausting fds. + # + # Reap the bridge here too (close() is idempotent): on child EOF the + # writer loop's ``finally`` is the usual closer, but if the handler + # task is cancelled the instant we close the WS, that ``finally`` + # can be skipped, leaking the PTY. Closing from the EOF path makes + # the reap independent of that cancellation race (#54028). + try: + await asyncio.to_thread(bridge.close) + except Exception: + pass + try: + await ws.close() + except Exception: + pass + + reader_task = asyncio.create_task(pump_pty_to_ws()) + + # --- writer loop: WebSocket → PTY master ---------------------------- + try: + while True: + try: + msg = await ws.receive() + except RuntimeError: + # Raised when ws.receive() is called after the socket is + # already disconnected (e.g. closed by the reader task above). + break + if msg.get("type") == "websocket.disconnect": + break + raw = msg.get("bytes") + if raw is None: + text = msg.get("text") + raw = text.encode("utf-8") if isinstance(text, str) else b"" + if not raw: + continue + # Resize escape is consumed locally, never written to the PTY. + match = _RESIZE_RE.match(raw) + if match and match.end() == len(raw): + bridge.resize(cols=int(match.group(1)), rows=int(match.group(2))) + continue + bridge.write(raw) + except WebSocketDisconnect: + pass + finally: + reader_task.cancel() + try: + await reader_task + except (asyncio.CancelledError, Exception): + pass + await asyncio.to_thread(bridge.close) + + _VALID_CHANNEL_RE = re.compile(r"^[A-Za-z0-9._-]{1,128}$") # Starlette's TestClient reports the peer as "testclient"; treat it as # loopback so tests don't need to rewrite request scope. @@ -12315,13 +14661,30 @@ def _resolve_chat_argv( # the dashboard PTY path. env.setdefault("HERMES_TUI_DISABLE_MOUSE", "1") env.setdefault("HERMES_TUI_INLINE", "1") + # The dashboard terminal is xterm.js, which always renders 24-bit RGB. + # But chalk inside the TUI child decides its color depth from the + # SERVER process env — and hosted/cloud deploys run the dashboard under + # a process manager (container init, systemd) with no COLORTERM, so + # chalk downgrades every hex color to the xterm 256 palette. The skin's + # bronze border #CD7F32 snaps to palette 173 (#D7875F, salmon-red) and + # the banner reads red/yellow instead of gold. Local launches dodge + # this only because the operator's interactive terminal leaks + # COLORTERM=truecolor into os.environ. Backfill it for the PTY child; + # setdefault so an explicit operator value still wins. + env.setdefault("COLORTERM", "truecolor") env["HERMES_TUI_DASHBOARD"] = "1" if profile_dir is not None: env["HERMES_HOME"] = str(profile_dir) if resume: - latest_resume, _latest_path = _session_latest_descendant(resume) + _resume_db = _open_session_db_for_profile( + requested if profile_dir is not None else None + ) + try: + latest_resume, _latest_path = _session_latest_descendant(resume, _resume_db) + finally: + _resume_db.close() if latest_resume: resume = latest_resume env["HERMES_TUI_RESUME"] = resume @@ -12343,6 +14706,44 @@ def _resolve_chat_argv( return list(argv), str(cwd) if cwd else None, env +# Hosts that mean "listen on every interface" — the server should bind to +# them, but an in-container client must NOT dial them: dialing 0.0.0.0 +# resolves to "any local interface", which on most platforms routes through +# the kernel's wildcard stack and behind a forward proxy (HTTPS_PROXY with +# a NO_PROXY that doesn't list 0.0.0.0) gets MITM'd into a failed handshake +# (issue #58993). The fix is to use a loopback address for the client +# netloc while leaving the bind host alone. +_WILDCARD_HOSTS = frozenset({"0.0.0.0", "::"}) + + +def _resolve_client_ws_host() -> Optional[str]: + """Return the host the in-container WS client should dial. + + Resolution order: + + 1. Explicit ``HERMES_DASHBOARD_WS_HOST`` env var — wins always. Operators + running the dashboard behind a forward proxy can pin a routable host + (e.g. ``127.0.0.1``, the container's internal IP, or a sidecar DNS + name) and bypass auto-detection entirely. + 2. The configured bind host — if it's a wildcard (``0.0.0.0`` / ``::``), + substitute ``127.0.0.1`` since both the dashboard and its TUI child + run in the same container. + 3. Any other bind host (loopback or LAN IP) — preserved verbatim. + """ + explicit = os.environ.get("HERMES_DASHBOARD_WS_HOST", "").strip() + if explicit: + return explicit + + host = getattr(app.state, "bound_host", None) + if not host: + return None + + if host in _WILDCARD_HOSTS: + return "127.0.0.1" + + return host + + def _build_gateway_ws_url() -> Optional[str]: """ws:// URL the PTY child should attach to for JSON-RPC gateway traffic. @@ -12354,7 +14755,7 @@ def _build_gateway_ws_url() -> Optional[str]: the child reads this URL once at startup and reuses it on every reconnect, and a 30s-TTL ticket can expire before a slow cold boot even dials. """ - host = getattr(app.state, "bound_host", None) + host = _resolve_client_ws_host() port = getattr(app.state, "bound_port", None) if not host or not port: @@ -12421,7 +14822,7 @@ def _build_sidecar_url(channel: str) -> Optional[str]: Connections authenticated this way are recorded under the ``server-internal`` identity in the audit log. """ - host = getattr(app.state, "bound_host", None) + host = _resolve_client_ws_host() port = getattr(app.state, "bound_port", None) if not host or not port: @@ -12443,70 +14844,646 @@ def _build_sidecar_url(channel: str) -> Optional[str]: return f"ws://{netloc}/api/pub?{qs}" -async def _broadcast_event(app: Any, channel: str, payload: str) -> None: - """Fan out one publisher frame to every subscriber on `channel`.""" - event_channels, event_lock = _get_event_state(app) - async with event_lock: - subs = list(event_channels.get(channel, ())) +async def _broadcast_event(app: Any, channel: str, payload: str) -> None: + """Fan out one publisher frame to every subscriber on `channel`.""" + event_channels, event_lock = _get_event_state(app) + async with event_lock: + subs = list(event_channels.get(channel, ())) + + for sub in subs: + try: + await sub.send_text(payload) + except Exception: + # Subscriber went away mid-send; the /api/events finally clause + # will remove it from the registry on its next iteration. + _log.warning("broadcast send failed for subscriber on %s", channel, exc_info=True) + + +def _channel_or_close_code(ws: WebSocket) -> Optional[str]: + """Return the channel id from the query string or None if invalid.""" + channel = ws.query_params.get("channel", "") + + return channel if _VALID_CHANNEL_RE.match(channel) else None + + +def _active_session_file_for_channel(app: "FastAPI", channel: str) -> Path: + """Return the per-channel file where a dashboard TUI writes its active sid.""" + files = _get_pty_active_session_files(app) + existing = files.get(channel) + if existing is not None: + return existing + + fd, raw_path = tempfile.mkstemp(prefix="hermes-pty-active-", suffix=".json") + os.close(fd) + path = Path(raw_path) + files[channel] = path + return path + + +def _read_active_session_file(path: Path) -> Optional[str]: + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return None + + session_id = str(data.get("session_id") or "").strip() + return session_id or None + + +def _forget_active_session_file(path: Path) -> None: + try: + path.unlink(missing_ok=True) + except OSError: + pass + + +def _ws_close_reason(text: str) -> str: + """Clamp a WS close reason to the protocol's 123-byte UTF-8 limit. + + RFC 6455 caps the close-frame reason at 123 bytes; uvicorn raises if a + longer string is passed. Our reasons embed an attacker-controlled origin, + so truncate defensively rather than crash the close handler. + """ + encoded = text.encode("utf-8", "replace") + if len(encoded) <= 123: + return text + return encoded[:120].decode("utf-8", "ignore") + "..." + + +# --------------------------------------------------------------------------- +# /api/console — safe Hermes Console command WebSocket. +# +# Unlike /api/pty, this endpoint never spawns a PTY, shell, or full Hermes CLI +# subprocess. It runs the curated console engine in-process and exchanges +# structured JSON frames with the dashboard xterm overlay. +# --------------------------------------------------------------------------- + +_CONSOLE_PROMPT = "hermes> " +_CONSOLE_COMMAND_TIMEOUT_SECONDS = 60.0 +_CONSOLE_OUTPUT_LIMIT = 50000 + +# Console commands run in a worker thread. On a timeout, asyncio.wait_for cancels +# the *awaitable*, but Python threads aren't preemptible, so a genuinely stuck +# worker keeps running to completion. To keep that from exhausting the shared +# default thread pool (asyncio.to_thread), we run console commands on a small +# dedicated, bounded pool: a leaked worker is capped, and concurrent console +# execution is bounded to a fixed number of threads regardless of reconnects. +_CONSOLE_EXECUTOR_MAX_WORKERS = 4 +_console_executor: Optional[concurrent.futures.ThreadPoolExecutor] = None +_console_executor_lock = threading.Lock() + + +def _get_console_executor() -> concurrent.futures.ThreadPoolExecutor: + """Lazily create the bounded console worker pool (once per process).""" + global _console_executor + if _console_executor is None: + with _console_executor_lock: + if _console_executor is None: + _console_executor = concurrent.futures.ThreadPoolExecutor( + max_workers=_CONSOLE_EXECUTOR_MAX_WORKERS, + thread_name_prefix="hermes-console", + ) + # Ensure the pool is torn down on interpreter exit. Don't wait on + # in-flight workers: a stuck 60s console command must not block + # shutdown (cancel_futures drops anything not yet started). + atexit.register( + lambda: _console_executor + and _console_executor.shutdown(wait=False, cancel_futures=True) + ) + return _console_executor + + +def _dashboard_console_context() -> str: + """Choose local vs hosted command policy for the dashboard console.""" + return "hosted" if _default_hermes_root_is_opt_data() else "local" + + +def _console_profile_from_ws(ws: WebSocket) -> Optional[str]: + profile = (ws.query_params.get("profile") or "").strip() + return profile or None + + +def _execute_console_line( + engine: Any, + line: str, + *, + confirmed: bool, + profile: Optional[str], +) -> Any: + # _profile_scope swaps process-global skill module paths; keep it inside + # the worker thread and never hold it across awaits. + with _profile_scope(profile): + return engine.execute(line, confirmed=confirmed) + + +async def _console_send( + ws: WebSocket, + send_lock: asyncio.Lock, + payload: Dict[str, Any], +) -> None: + async with send_lock: + await ws.send_json(payload) + + +async def _console_send_result( + ws: WebSocket, + send_lock: asyncio.Lock, + result: Any, + *, + command_id: int, +) -> None: + command = result.command or "" + status = result.status + if status == "ok": + if result.output: + await _console_send( + ws, + send_lock, + { + "type": "output", + "id": command_id, + "stream": "stdout", + "data": result.output, + "command": command, + }, + ) + await _console_send( + ws, + send_lock, + { + "type": "complete", + "id": command_id, + "status": "ok", + "command": command, + "prompt": _CONSOLE_PROMPT, + }, + ) + return + + if status == "error": + await _console_send( + ws, + send_lock, + { + "type": "error", + "id": command_id, + "message": result.output or "Command failed.", + "command": command, + }, + ) + await _console_send( + ws, + send_lock, + { + "type": "complete", + "id": command_id, + "status": "error", + "command": command, + "prompt": _CONSOLE_PROMPT, + }, + ) + return + + if status == "confirm_required": + await _console_send( + ws, + send_lock, + { + "type": "confirm_required", + "id": command_id, + "command": command, + "message": result.confirmation_message or f"Run `{command}`?", + "prompt": _CONSOLE_PROMPT, + }, + ) + await _console_send( + ws, + send_lock, + { + "type": "complete", + "id": command_id, + "status": "confirm_required", + "command": command, + "prompt": _CONSOLE_PROMPT, + }, + ) + return + + if status == "clear": + await _console_send(ws, send_lock, {"type": "clear", "id": command_id}) + await _console_send( + ws, + send_lock, + { + "type": "complete", + "id": command_id, + "status": "clear", + "command": command, + "prompt": _CONSOLE_PROMPT, + }, + ) + return + + if status == "exit": + await _console_send( + ws, + send_lock, + { + "type": "complete", + "id": command_id, + "status": "exit", + "command": command, + "prompt": "", + }, + ) + return + + await _console_send( + ws, + send_lock, + { + "type": "error", + "id": command_id, + "message": f"Unknown console result status: {status}", + "command": command, + }, + ) + - for sub in subs: +def _console_json_payload(msg: Any) -> tuple[Optional[dict[str, Any]], Optional[str]]: + raw: str | bytes | None = msg.get("text") + if raw is None: + raw = msg.get("bytes") + if raw is None: + return None, None + if isinstance(raw, bytes): try: - await sub.send_text(payload) - except Exception: - # Subscriber went away mid-send; the /api/events finally clause - # will remove it from the registry on its next iteration. - _log.warning("broadcast send failed for subscriber on %s", channel, exc_info=True) + raw = raw.decode("utf-8") + except UnicodeDecodeError: + return None, "Console frames must be UTF-8 JSON." + try: + payload = json.loads(raw) + except json.JSONDecodeError: + return None, "Console frames must be JSON objects." + if not isinstance(payload, dict): + return None, "Console frames must be JSON objects." + return payload, None -def _channel_or_close_code(ws: WebSocket) -> Optional[str]: - """Return the channel id from the query string or None if invalid.""" - channel = ws.query_params.get("channel", "") +@app.websocket("/api/console") +async def console_ws(ws: WebSocket) -> None: + peer = ws.client.host if ws.client else "?" - return channel if _VALID_CHANNEL_RE.match(channel) else None + if not _DASHBOARD_EMBEDDED_CHAT_ENABLED: + _log.info("console refused: embedded chat disabled peer=%s", peer) + await ws.close(code=4404, reason="embedded chat disabled") + return + + auth_reason, cred = _ws_auth_reason(ws) + mode = _ws_auth_mode() + if auth_reason is not None: + _log.warning( + "console auth rejected reason=%s mode=%s cred=%s peer=%s", + auth_reason, mode, cred, peer, + ) + await ws.close(code=4401, reason=_ws_close_reason(f"auth: {auth_reason}")) + return + host_origin_reason = _ws_host_origin_reason(ws) + if host_origin_reason is not None: + _log.warning("console refused: %s peer=%s", host_origin_reason, peer) + await ws.close(code=4403, reason=_ws_close_reason(host_origin_reason)) + return -def _active_session_file_for_channel(app: "FastAPI", channel: str) -> Path: - """Return the per-channel file where a dashboard TUI writes its active sid.""" - files = _get_pty_active_session_files(app) - existing = files.get(channel) - if existing is not None: - return existing + client_reason = _ws_client_reason(ws) + if client_reason is not None: + _log.warning("console refused: %s", client_reason) + await ws.close(code=4408, reason=_ws_close_reason(client_reason)) + return - fd, raw_path = tempfile.mkstemp(prefix="hermes-pty-active-", suffix=".json") - os.close(fd) - path = Path(raw_path) - files[channel] = path - return path + await ws.accept() + profile = _console_profile_from_ws(ws) + context = _dashboard_console_context() + send_lock = asyncio.Lock() -def _read_active_session_file(path: Path) -> Optional[str]: try: - data = json.loads(path.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError): - return None + from hermes_cli.console_engine import HermesConsoleEngine - session_id = str(data.get("session_id") or "").strip() - return session_id or None + engine = HermesConsoleEngine( + output_limit=_CONSOLE_OUTPUT_LIMIT, + context=context, # type: ignore[arg-type] + ) + if profile and profile.lower() != "current": + _resolve_profile_dir(profile) + except HTTPException as exc: + await _console_send( + ws, + send_lock, + { + "type": "error", + "message": str(exc.detail), + "prompt": "", + }, + ) + await ws.close(code=4400, reason=_ws_close_reason(str(exc.detail))) + return + except Exception as exc: + _log.exception("console failed to initialize") + await _console_send( + ws, + send_lock, + { + "type": "error", + "message": f"Console unavailable: {exc}", + "prompt": "", + }, + ) + await ws.close(code=1011) + return + + _log.info( + "console accepted peer=%s mode=%s cred=%s context=%s profile=%s", + peer, + mode, + cred, + context, + profile or "current", + ) + await _console_send( + ws, + send_lock, + { + "type": "ready", + "context": context, + "profile": profile or "current", + "prompt": _CONSOLE_PROMPT, + }, + ) + active_task: asyncio.Task | None = None + pending_confirmation: Optional[str] = None + command_generation = 0 + + async def run_command(line: str, *, confirmed: bool, command_id: int) -> None: + nonlocal active_task, pending_confirmation, command_generation + try: + loop = asyncio.get_running_loop() + result = await asyncio.wait_for( + loop.run_in_executor( + _get_console_executor(), + functools.partial( + _execute_console_line, + engine, + line, + confirmed=confirmed, + profile=profile, + ), + ), + timeout=_CONSOLE_COMMAND_TIMEOUT_SECONDS, + ) + except asyncio.CancelledError: + raise + except asyncio.TimeoutError: + if command_id == command_generation: + pending_confirmation = None + await _console_send( + ws, + send_lock, + { + "type": "error", + "id": command_id, + "message": ( + "Command timed out. Hermes Console returned to the prompt." + ), + "command": line, + }, + ) + await _console_send( + ws, + send_lock, + { + "type": "complete", + "id": command_id, + "status": "timeout", + "command": line, + "prompt": _CONSOLE_PROMPT, + }, + ) + except Exception as exc: + if command_id == command_generation: + pending_confirmation = None + _log.exception("console command failed") + await _console_send( + ws, + send_lock, + { + "type": "error", + "id": command_id, + "message": str(exc) or exc.__class__.__name__, + "command": line, + }, + ) + await _console_send( + ws, + send_lock, + { + "type": "complete", + "id": command_id, + "status": "error", + "command": line, + "prompt": _CONSOLE_PROMPT, + }, + ) + else: + if command_id != command_generation: + return + pending_confirmation = ( + result.command if result.status == "confirm_required" else None + ) + await _console_send_result( + ws, + send_lock, + result, + command_id=command_id, + ) + if result.status == "exit": + await ws.close(code=1000) + finally: + if command_id == command_generation: + active_task = None + + async def start_command(line: str, *, confirmed: bool = False) -> None: + nonlocal active_task, command_generation + command_generation += 1 + command_id = command_generation + active_task = asyncio.create_task( + run_command(line, confirmed=confirmed, command_id=command_id) + ) -def _forget_active_session_file(path: Path) -> None: try: - path.unlink(missing_ok=True) - except OSError: - pass + while True: + try: + msg = await ws.receive() + except RuntimeError: + break + msg_type = msg.get("type") + if msg_type == "websocket.disconnect": + break + payload, error = _console_json_payload(msg) + if error: + await _console_send( + ws, + send_lock, + { + "type": "error", + "message": error, + "prompt": _CONSOLE_PROMPT, + }, + ) + continue + if payload is None: + continue -def _ws_close_reason(text: str) -> str: - """Clamp a WS close reason to the protocol's 123-byte UTF-8 limit. + frame_type = str(payload.get("type") or "").strip().lower() + if frame_type == "ping": + await _console_send( + ws, + send_lock, + { + "type": "pong", + "prompt": _CONSOLE_PROMPT, + }, + ) + continue - RFC 6455 caps the close-frame reason at 123 bytes; uvicorn raises if a - longer string is passed. Our reasons embed an attacker-controlled origin, - so truncate defensively rather than crash the close handler. - """ - encoded = text.encode("utf-8", "replace") - if len(encoded) <= 123: - return text - return encoded[:120].decode("utf-8", "ignore") + "..." + if frame_type == "cancel": + if active_task and not active_task.done(): + command_generation += 1 + active_task.cancel() + active_task = None + pending_confirmation = None + await _console_send( + ws, + send_lock, + { + "type": "complete", + "status": "cancelled", + "prompt": _CONSOLE_PROMPT, + }, + ) + elif pending_confirmation: + pending_confirmation = None + await _console_send( + ws, + send_lock, + { + "type": "complete", + "status": "cancelled", + "prompt": _CONSOLE_PROMPT, + }, + ) + else: + await _console_send( + ws, + send_lock, + { + "type": "complete", + "status": "idle", + "prompt": _CONSOLE_PROMPT, + }, + ) + continue + + if active_task and not active_task.done(): + await _console_send( + ws, + send_lock, + { + "type": "error", + "message": "A console command is already running.", + "prompt": _CONSOLE_PROMPT, + }, + ) + continue + + if frame_type == "confirm": + command = str(payload.get("command") or pending_confirmation or "").strip() + if not pending_confirmation: + await _console_send( + ws, + send_lock, + { + "type": "error", + "message": "No command is waiting for confirmation.", + "prompt": _CONSOLE_PROMPT, + }, + ) + continue + if command != pending_confirmation: + await _console_send( + ws, + send_lock, + { + "type": "error", + "message": "Confirmation does not match the pending command.", + "prompt": _CONSOLE_PROMPT, + }, + ) + continue + pending_confirmation = None + await start_command(command, confirmed=True) + continue + + if frame_type in {"input", "command"}: + line = str(payload.get("line") or payload.get("command") or "").strip() + if not line: + await _console_send( + ws, + send_lock, + { + "type": "complete", + "status": "ok", + "prompt": _CONSOLE_PROMPT, + }, + ) + continue + if pending_confirmation: + await _console_send( + ws, + send_lock, + { + "type": "error", + "message": ( + "Confirm or cancel the pending command before " + "running another one." + ), + "prompt": _CONSOLE_PROMPT, + }, + ) + continue + await start_command(line) + continue + + await _console_send( + ws, + send_lock, + { + "type": "error", + "message": f"Unsupported console frame: {frame_type or '?'}", + "prompt": _CONSOLE_PROMPT, + }, + ) + except WebSocketDisconnect: + pass + finally: + if active_task and not active_task.done(): + active_task.cancel() + try: + await active_task + except (asyncio.CancelledError, Exception): + pass @app.websocket("/api/pty") @@ -12604,71 +15581,57 @@ async def pty_ws(ws: WebSocket) -> None: return + attach_token = ws.query_params.get("attach") or None + + def _spawn(): + return PtyBridge.spawn(argv, cwd=cwd, env=env) + + if attach_token is None: + # Legacy path: 1:1 socket<->PTY, killed on disconnect (unchanged). + try: + bridge = _spawn() + except PtyUnavailableError as exc: + await ws.send_text(f"\r\n\x1b[31mChat unavailable: {exc}\x1b[0m\r\n") + await ws.close(code=1011) + return + except (FileNotFoundError, OSError) as exc: + await ws.send_text(f"\r\n\x1b[31mChat failed to start: {exc}\x1b[0m\r\n") + await ws.close(code=1011) + return + await _legacy_pump(ws, bridge) + return + + # Keep-alive path: the PTY outlives this socket; reattach by token. try: - bridge = await asyncio.to_thread(PtyBridge.spawn, argv, cwd=cwd, env=env) + session, _created = await PTY_REGISTRY.attach_or_spawn( + attach_token, spawn=_spawn + ) except PtyUnavailableError as exc: await ws.send_text(f"\r\n\x1b[31mChat unavailable: {exc}\x1b[0m\r\n") await ws.close(code=1011) return - except (FileNotFoundError, OSError) as exc: - await ws.send_text(f"\r\n\x1b[31mChat failed to start: {exc}\x1b[0m\r\n") + except (FileNotFoundError, OSError, RegistryFull) as exc: + await ws.send_text(f"\r\n\x1b[31mChat unavailable: {exc}\x1b[0m\r\n") await ws.close(code=1011) return - loop = asyncio.get_running_loop() - - # --- reader task: PTY master → WebSocket ---------------------------- - async def pump_pty_to_ws() -> None: - try: - while True: - chunk = await loop.run_in_executor( - None, bridge.read, _PTY_READ_CHUNK_TIMEOUT - ) - if chunk is None: # EOF - return - if not chunk: # no data this tick; yield control and retry - await asyncio.sleep(0) - continue - try: - await ws.send_bytes(chunk) - except Exception: - return - finally: - # The child has exited (EOF) or the send side broke. Close the - # WebSocket so the writer loop's ``ws.receive()`` returns instead - # of blocking forever — otherwise, when the browser's socket is - # half-open (no FIN delivered, common on macOS/launchd) the - # handler never reaches its ``finally`` and the PTY's fds leak. - # With dashboard auto-reconnect (#52962) every dropped socket then - # stacks a fresh PTY on top of the orphaned one, exhausting fds. - # - # Reap the bridge here too (close() is idempotent): on child EOF the - # writer loop's ``finally`` is the usual closer, but if the handler - # task is cancelled the instant we close the WS, that ``finally`` - # can be skipped, leaking the PTY. Closing from the EOF path makes - # the reap independent of that cancellation race (#54028). - try: - await asyncio.to_thread(bridge.close) - except Exception: - pass - try: - await ws.close() - except Exception: - pass - - reader_task = asyncio.create_task(pump_pty_to_ws()) + await session.attach(ws) # --- writer loop: WebSocket → PTY master ---------------------------- + # No reader task here: the session's drain task (spawned once per PTY, + # inside the registry) forwards PTY output to whichever socket is + # attached and rings-buffers it while detached. On child EOF the drain + # closes the attached socket with 4410, which unparks ``ws.receive()`` + # below — same half-open-socket protection the legacy pump has (#54028). try: while True: try: msg = await ws.receive() except RuntimeError: - # Raised when ws.receive() is called after the socket is - # already disconnected (e.g. closed by the reader task above). + # ws.receive() after the socket is already disconnected + # (e.g. closed by the drain task on process exit). break - msg_type = msg.get("type") - if msg_type == "websocket.disconnect": + if msg.get("type") == "websocket.disconnect": break raw = msg.get("bytes") if raw is None: @@ -12680,21 +15643,16 @@ async def pump_pty_to_ws() -> None: # Resize escape is consumed locally, never written to the PTY. match = _RESIZE_RE.match(raw) if match and match.end() == len(raw): - cols = int(match.group(1)) - rows = int(match.group(2)) - bridge.resize(cols=cols, rows=rows) + session.bridge.resize(cols=int(match.group(1)), rows=int(match.group(2))) continue - bridge.write(raw) + session.bridge.write(raw) except WebSocketDisconnect: pass finally: - reader_task.cancel() - try: - await reader_task - except (asyncio.CancelledError, Exception): - pass - await asyncio.to_thread(bridge.close) + # Detach only — the PTY keeps running for a reattach; the registry + # reaper closes it after the TTL (or immediately on process exit). + PTY_REGISTRY.detach(attach_token, ws) # --------------------------------------------------------------------------- @@ -12837,13 +15795,21 @@ def mount_spa(application: FastAPI): and the SPA's runtime ``__HERMES_BASE_PATH__`` honour that prefix without rebuilding the bundle. """ - if not WEB_DIST.exists(): + # `hermes serve` is the headless backend: it must NEVER serve the browser + # SPA, even if a dist is lying around from a prior `dashboard`/build. Take + # the no-frontend path so only the JSON-RPC/WS/API surface is reachable. + _headless = os.environ.get("HERMES_SERVE_HEADLESS") == "1" + if _headless or not WEB_DIST.exists(): + _msg = ( + "Headless backend (hermes serve): web UI disabled — use " + "`hermes dashboard` for the browser UI." + if _headless + else "Frontend not built. Run: cd web && npm run build" + ) + @application.get("/{full_path:path}") async def no_frontend(full_path: str): - return JSONResponse( - {"error": "Frontend not built. Run: cd web && npm run build"}, - status_code=404, - ) + return JSONResponse({"error": _msg}, status_code=404) return _index_path = WEB_DIST / "index.html" @@ -13453,16 +16419,41 @@ def _get_dashboard_plugins(force_rescan: bool = False) -> list: @app.get("/api/dashboard/plugins") async def get_dashboard_plugins(): - """Return discovered dashboard plugins (excludes user-hidden ones).""" + """Return discovered dashboard plugins (excludes user-hidden and non-enabled ones).""" plugins = _get_dashboard_plugins() # Read user's hidden plugins list from config. config = load_config() hidden: list = cfg_get(config, "dashboard", "hidden_plugins", default=[]) or [] - # Strip internal fields before sending to frontend and filter out hidden. + # Gate: only serve user plugins that are in plugins.enabled and not + # in plugins.disabled. This prevents the frontend from loading JS/CSS + # from plugins the user has not explicitly activated. (#46435) + try: + from hermes_cli.plugins_cmd import _get_enabled_set, _get_disabled_set + enabled_set = _get_enabled_set() + disabled_set = _get_disabled_set() + except Exception: + enabled_set = set() + disabled_set = set() + + def _is_active(p: dict) -> bool: + name = p.get("name", "") + if name in hidden: + return False + if p.get("source") == "user": + if name in disabled_set: + return False + if name not in enabled_set: + return False + elif p.get("source") == "bundled": + if name in disabled_set: + return False + return True + + # Strip internal fields before sending to frontend. return [ {k: v for k, v in p.items() if not k.startswith("_")} for p in plugins - if p["name"] not in hidden + if _is_active(p) ] @@ -13490,7 +16481,6 @@ def _merged_plugins_hub() -> Dict[str, Any]: _get_current_context_engine, _get_current_memory_provider, _discover_context_engines, - _discover_memory_providers, _get_disabled_set, _get_enabled_set, _read_manifest as _read_plugin_manifest_at, @@ -13578,12 +16568,7 @@ def _merged_plugins_hub() -> Dict[str, Any]: if str(p["name"]) not in agent_names ] - memory_providers: List[Dict[str, str]] = [] - try: - for n, desc in _discover_memory_providers(): - memory_providers.append({"name": n, "description": desc}) - except Exception: - memory_providers = [] + memory_providers = _discover_memory_provider_statuses() context_engines: List[Dict[str, str]] = [] try: @@ -13596,7 +16581,7 @@ def _merged_plugins_hub() -> Dict[str, Any]: "plugins": rows, "orphan_dashboard_plugins": orphan_dashboard, "providers": { - "memory_provider": _get_current_memory_provider() or "", + "memory_provider": _normalize_memory_provider_name(_get_current_memory_provider()), "memory_options": memory_providers, "context_engine": _get_current_context_engine(), "context_options": context_engines, @@ -13709,7 +16694,9 @@ async def put_plugin_providers(request: Request, body: _PluginProvidersPutBody): ) if body.memory_provider is not None: - _save_memory_provider(body.memory_provider) + memory_provider = _normalize_memory_provider_name(body.memory_provider) + _require_memory_provider_ready(memory_provider) + _save_memory_provider(memory_provider) if body.context_engine is not None: _save_context_engine(body.context_engine) return {"ok": True} @@ -13759,12 +16746,31 @@ async def serve_plugin_asset(plugin_name: str, file_path: str): allowlist, anyone on the loopback port can curl the ``.py`` source of a private third-party plugin. Reject everything outside the browser-asset set. + + User plugins must be in plugins.enabled before their assets are + served. (#46435, GHSA-mcfc-hp25-cjv7) """ plugins = _get_dashboard_plugins() plugin = next((p for p in plugins if p["name"] == plugin_name), None) if not plugin: raise HTTPException(status_code=404, detail="Plugin not found") + # Gate: user plugins must be enabled to serve assets; + # bundled plugins must not be explicitly disabled. + try: + from hermes_cli.plugins_cmd import _get_enabled_set, _get_disabled_set + enabled_set = _get_enabled_set() + disabled_set = _get_disabled_set() + except Exception: + enabled_set = set() + disabled_set = set() + if plugin.get("source") == "user": + if plugin_name in disabled_set or plugin_name not in enabled_set: + raise HTTPException(status_code=404, detail="Plugin not found") + elif plugin.get("source") == "bundled": + if plugin_name in disabled_set: + raise HTTPException(status_code=404, detail="Plugin not found") + base = Path(plugin["_dir"]) target = (base / file_path).resolve() @@ -13824,11 +16830,52 @@ def _mount_plugin_api_routes(): opens a malicious repo; they can extend the dashboard UI via static JS/CSS but their Python ``api`` file is never auto-imported by the web server. See GHSA-5qr3-c538-wm9j (#29156). + + Additionally, user plugins must be explicitly enabled via the + ``plugins.enabled`` allow-list in config.yaml before their backend + code is imported. Without this gate, an installed-but-not-enabled + plugin's Python code would execute at dashboard startup — a code + execution vector that bypasses the user's intent. (#46435, + GHSA-mcfc-hp25-cjv7) """ + # Load the enabled/disabled sets once for the loop. + try: + from hermes_cli.plugins_cmd import _get_enabled_set, _get_disabled_set + enabled_set = _get_enabled_set() + disabled_set = _get_disabled_set() + except Exception: + enabled_set = set() + disabled_set = set() + for plugin in _get_dashboard_plugins(): api_file_name = plugin.get("_api_file") if not api_file_name: continue + plugin_name = plugin.get("name", "") + # Gate: user plugins must be in plugins.enabled and not in + # plugins.disabled before we import their Python code. + # Bundled plugins are trusted (they ship with the release) but + # still respect an explicit disable. + if plugin.get("source") == "user": + if plugin_name in disabled_set: + _log.debug( + "Plugin %s: skipping API mount (explicitly disabled)", + plugin_name, + ) + continue + if plugin_name not in enabled_set: + _log.debug( + "Plugin %s: skipping API mount (not in plugins.enabled)", + plugin_name, + ) + continue + elif plugin.get("source") == "bundled": + if plugin_name in disabled_set: + _log.debug( + "Plugin %s: skipping API mount (explicitly disabled)", + plugin_name, + ) + continue if plugin.get("source") == "project": _log.warning( "Plugin %s: ignoring backend api=%s (project plugins may " @@ -13998,6 +17045,7 @@ def start_server( open_browser: bool = True, allow_public: bool = False, initial_profile: str = "", + headless: bool = False, ): """Start the web UI server. @@ -14005,6 +17053,10 @@ def start_server( URL as ``?profile=`` so the SPA's profile switcher preselects it — used when a profile alias (`` dashboard``) routes to the machine dashboard. + + ``headless`` is the ``serve`` path: the JSON-RPC/WS backend with no UI + build and no SPA mount (mount_spa() honours ``HERMES_SERVE_HEADLESS``), so + the banner announces the bind rather than a browser URL. """ import uvicorn @@ -14108,13 +17160,24 @@ def start_server( # OSError inside create_server() and exits with a clear error — no # separate preflight probe needed. # Loopback binds are the Desktop case: a single local client, no reverse - # proxy in front. A GIL-heavy agent turn can stall the event loop past 20s, - # and uvicorn's ws keepalive ping runs on that same starved loop — so a - # 20s ping timeout kills an otherwise-healthy local connection over a - # recoverable stall (QW-1). Give loopback a longer 60s timeout / 30s - # interval to ride out those stalls. Non-loopback binds sit behind a - # Cloudflare Tunnel (idle timeout ~100s), so keep them at 20/20 to detect - # half-open connections promptly and stay under the tunnel's idle window. + # proxy in front. uvicorn's ws keepalive ping runs ON the same event loop + # as agent turns, and a single synchronous GIL-holding call on a worker + # thread (e.g. a regex/scrub over a large model output, or a long + # delegate_task subagent turn) can starve that loop for *minutes* — the + # loop cannot process the incoming pong, so uvicorn declares the socket + # dead and closes it, dropping an otherwise-healthy local connection + # (#53773: "event loop stalled 226.3s"; #48445/#50005). A longer timeout + # only raises the threshold — a multi-minute stall sails past any finite + # window. The keepalive ping exists to detect *half-open* connections + # (reverse-proxy 524, dropped tunnels), which cannot happen on loopback: + # there is no network or proxy in the path, and a dead local client tears + # the socket down with a real FIN/RST that starlette surfaces as + # WebSocketDisconnect regardless of the ping. So on loopback the ping + # provides ~no liveness value while actively killing recoverable stalls — + # disable it entirely. Non-loopback binds sit behind a Cloudflare Tunnel + # (idle timeout ~100s) where half-open IS a real failure mode, so keep the + # ping at 20/20 to detect it promptly and stay under the tunnel's idle + # window. _is_loopback = host in ("127.0.0.1", "localhost", "::1") config = uvicorn.Config( app, host=host, port=port, log_level="warning", @@ -14126,12 +17189,12 @@ def start_server( # decide cookie Secure flags, so we flip proxy_headers on for that # mode. proxy_headers=bool(app.state.auth_required), - # Detect half-open WS connections (reverse-proxy 524, dropped - # tunnels) within ~20-40s so WebSocketDisconnect fires the - # disconnect→reap path. 20s stays under Cloudflare Tunnel's idle - # timeout, keeping it warm. Loopback gets a longer window (see above). - ws_ping_interval=30.0 if _is_loopback else 20.0, - ws_ping_timeout=60.0 if _is_loopback else 20.0, + # Half-open detection for public binds only (see above). Loopback + # disables the protocol ping (None) so an event-loop stall can never + # trigger a false disconnect; a genuinely dead local client is still + # reaped via the WebSocketDisconnect → disconnect/reap path. + ws_ping_interval=None if _is_loopback else 20.0, + ws_ping_timeout=None if _is_loopback else 20.0, ) server = uvicorn.Server(config) @@ -14150,8 +17213,17 @@ async def _serve(): app.state.bound_port = actual_port _write_dashboard_ready_file(actual_port) - print(f"HERMES_DASHBOARD_READY port={actual_port}", flush=True) - print(f" Hermes Web UI → http://{host}:{actual_port}") + # Port-discovery sentinel parsed by the desktop spawn. `serve` is a + # plain backend, not a dashboard, so it announces a neutral token; + # `dashboard` keeps the legacy one. The desktop matches either. + ready_token = "HERMES_BACKEND_READY" if headless else "HERMES_DASHBOARD_READY" + print(f"{ready_token} port={actual_port}", flush=True) + if headless: + # No SPA, and the JSON-RPC/WS endpoints are auth-gated — don't + # advertise a paste-and-connect URL, just announce the bind. + print(f" Hermes backend listening on {host}:{actual_port}") + else: + print(f" Hermes Web UI → http://{host}:{actual_port}") _maybe_open_browser(host, actual_port, open_browser, initial_profile) # Collapse the peer-hangup teardown flood (#50005). When the Desktop diff --git a/pyproject.toml b/pyproject.toml index 963210075e0ac..58fb521425d72 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta" [project] name = "hermes-agent" -version = "0.18.0" +version = "0.18.2" description = "The self-improving AI agent — creates skills from experience, improves them during use, and runs anywhere" readme = "README.md" # Upper bound is load-bearing, not cosmetic. uv resolves the project's @@ -156,6 +156,7 @@ fal = ["fal-client==0.13.1"] edge-tts = ["edge-tts==7.2.7"] modal = ["modal==1.3.4"] daytona = ["daytona==0.155.0"] +tenki = ["tenki-sandbox==0.1.1"] hindsight = ["hindsight-client==0.6.1"] dev = ["debugpy==1.8.20", "pytest==9.0.2", "pytest-asyncio==1.3.0", "mcp==1.26.0", "starlette==1.0.1", "ty==0.0.21", "ruff==0.15.10", "setuptools==81.0.0"] # starlette: CVE-2026-48710; setuptools: latest <82 (torch >=2.11 caps setuptools<82) messaging = ["python-telegram-bot[webhooks]==22.6", "discord.py[voice]==2.7.1", "aiohttp==3.14.1", "brotlicffi==1.2.0.1", "slack-bolt==1.27.0", "slack-sdk==3.40.1", "qrcode==7.4.2"] # aiohttp 3.14.1: CVE-2026-34513/34518/34519/34520/34525 + 34993(RCE)/47265 @@ -249,7 +250,7 @@ termux-all = [ "hermes-agent[web]", ] dingtalk = ["dingtalk-stream==0.24.3", "alibabacloud-dingtalk==2.2.42", "qrcode==7.4.2"] -feishu = ["lark-oapi==1.5.3", "qrcode==7.4.2"] +feishu = ["lark-oapi==1.6.8", "qrcode==7.4.2"] google = [ # Required by the google-workspace skill (Gmail, Calendar, Drive, Contacts, # Sheets, Docs). Declared here so packagers (Nix, Homebrew) ship them with @@ -282,7 +283,7 @@ all = [ # # Removed from [all] on 2026-05-12 (covered by lazy-install): # anthropic, exa, firecrawl, parallel-web, fal, edge-tts, - # modal, daytona, messaging (telegram/discord/slack), + # modal, daytona, tenki, messaging (telegram/discord/slack), # matrix, slack, honcho, voice (faster-whisper), # dingtalk, feishu, bedrock, tts-premium (elevenlabs) # diff --git a/scripts/release.py b/scripts/release.py index b03fcb543f5b5..675159235eaa2 100755 --- a/scripts/release.py +++ b/scripts/release.py @@ -45,6 +45,66 @@ # Auto-extracted from noreply emails + manual overrides AUTHOR_MAP = { + "m.guttmann@journaway.com": "mguttmann", # PR #63738 salvage (Anthropic setup-token pool auth normalization) + "VrtxOmega@pm.me": "VrtxOmega", # PR #43809 salvage (desktop: WSL folder-picker path bridge) + "jake.long.vu@vucar.net": "jakelongvu-bot", # PR #36683 partial salvage (approval: honor canonical approvals.timeout in gateway waits) + "luigi@users.noreply.github.com": "Tortugasaur", # PR #43205 salvage (desktop: profile-aware three-way approval mode statusbar control) + "kavi@local.hermes": "kavioavio", # Issue #46544 / PR #47705 evolution (smart DENY exact-operation owner override) + "135129512+ansel-f@users.noreply.github.com": "ansel-f", # PR #62388 salvage (approval: allow exact verifier temp cleanup without broadening rm safety boundary) + "robert@modern-minds.ai": "Hopfensaft", # PR #31933 salvage (dashboard: align approvals.mode dropdown with canonical engine values) + "palmer@dugoutfantasy.com": "professorpalmer", # PR #48591 salvage (sessions: CLI workspace filter + restore-cwd-on-resume) + "true@supersynergy.de": "Supersynergy", # PR #59241 salvage (desktop: workspace path status-bar action) + "me@roryford.com": "roryford", # PR #63132 salvage (compression: fail closed for errors from a resolved lock API, preserving lineage) + "esthon@gmail.com": "esthonjr", # PR #61950 salvage (desktop: legacy non-git workspace grouping + Windows path identity) + "iganapolsky@gmail.com": "IgorGanapolsky", # PR #62125 salvage (compaction anti-thrash threshold verification) + "tturney1@gmail.com": "TheTom", # PR #62696 salvage (gateway: expand @ context references under runtime/session model resolution) + "wilsonkinyuam@gmail.com": "WilsonKinyua", # PR #62052 (tui: persist unflushed conversations on disconnect/restart) + "humphreysun98@gmail.com": "HumphreySun98", # PR #61142 salvage (web: null web/backend config value guards) + "sonxi@nous.local": "17324393074", # PR #53196 salvage (tools_config: known_plugin_toolsets null guard; commit under unlinked local identity) + "lemonwan@users.noreply.github.com": "lemonwan", # PR #59430 sibling salvage (adapter reconnect contract guard) + "luxuguangno1@163.com": "luxuguang-leo", # PR #52966 + #52908 salvage (QQBot reconnect + Feishu Channel signaling) + "grace@weeb.onl": "evelynburger", # PR #57544 salvage (gateway: webhook payload filters + route scripts; commit under unlinked identity) + "contato@siteup.com.br": "SiteupAgencia", # PR #57435 salvage (tui_gateway: back off notification poller when session is busy; #55578) + "164521089+rainbowgits@users.noreply.github.com": "rainbowgore", # PR #59405 salvage (mcp: bound stdio initialize handshake to stop subprocess/FD leak; #59349) + "sage@Sages-Mac-mini.local": "thestudionorth", # PR #60015 salvage (mcp: parent-death watchdog for stdio children; commit under unlinked local identity) + "4087127+vampyren@users.noreply.github.com": "vampyren", # PR #59830 salvage (kanban: grab-to-pan board scrolling; original commit under unlinked local identity) + "spiky02plateau@users.noreply.github.com": "spiky02plateau", # PR #32824 salvage (usage: fetch Codex account limits from the credential pool in pool-only setups; superseded by #60028) + "taylorhp@gmail.com": "hwrdprkns", # PR #36896 salvage (secrets: 1Password op:// secret source + shared _cache substrate, adapted onto the SecretSource interface) + "ishengeqi@163.com": "isheng-eqi", # PR #59428 salvage (cron: reject past one-shot timestamps in update_job fallback + resume_job; #59395). Also PR #59446 salvage (cron: advance one-shot next_run_at before dispatch so concurrent gateway+desktop schedulers can't double-execute; #59229). + "derek2000139@qq.com": "derek2000139", # PR #57838 salvage (desktop/windows: pre-write update marker before quit dwell so the renderer's waitForUpdateToFinish gate parks instead of respawning a backend that re-locks venv .pyd files mid-update) + "AndreasHiltner@users.noreply.github.com": "AndreasHiltner", # PR #56854 salvage (gateway: route multiplex profile responses through the profile's own adapter — 53-site _adapter_for_source sweep) + "AlexFucuson9@users.noreply.github.com": "AlexFucuson9", # PR #61347 salvage (agent: reapply provider headers after model switch; #61099) + "allenliang2022@users.noreply.github.com": "allenliang2022", # PR #56932 test coverage folded into #56909 salvage (408 → retryable timeout) + "nick@luxor.tech": "hashbender", # PR #64190 (tenki cloud sandbox terminal backend) + "m888.braun@hotmail.com": "ManniBr", # PR #57417 partial salvage (gateway: fail-closed adapter resolution for unregistered secondary profiles) + "poowis2011@hotmail.com": "Umi4Life", # PR #47377 salvage (agent: emit one-shot fallback switch notice on successful fallback so gateway users see model/provider change; #35419) + "austin@openvm067.space": "austinlaw076", # PR #57563 partial salvage (auth: lazy per-profile Anthropic OAuth file; gateway: whatsapp_cloud/line added to port-binding platform set) + "sunsky.lau@gmail.com": "liuhao1024", # PR #56993 salvage (gateway: process-level HERMES_HOME for pid/lock/status identity files; #56986) + "gauravsaxena.jaipur@gmail.com": "gauravsaxena1997", # PR #59868 partial salvage (agent: guard response.text against httpx.ResponseNotRead in _summarize_api_error; #59769) + "blueirobin02@gmail.com": "irresi", # PR #59048 salvage (gateway: scope reset banners' session info to the serving profile; #59003) + "jashlee+microsoft@microsoft.com": "s905060", # PR #57943 salvage (photon: auto-reinstall stale sidecar node_modules when lockfile is newer than npm's install marker; #59169) + "lohinth25@proton.me": "l0h1nth", # PR #32210 salvage (mattermost: accept leading-space slash commands from mobile clients; #25184) + "perkintahmaz50@gmail.com": "devatnull", # PR #58704 salvage (whatsapp: native Baileys polls, clarify-as-poll, location pins, structured quoted replies, PTT/audio split, bridge_helpers extraction) + "tim@iteachyouai.com": "tjp2021", # PR #4097 salvage (copilot: per-turn x-initiator header so user prompts bill as premium requests; #3040) + "39274208+falkoro@users.noreply.github.com": "falkoro", # PRs #58519/#58520 salvage (config: env-ref-aware load_config cache invalidation; auxiliary: honor auxiliary..base_url/api_key with explicit provider arg) + "3723267+kevinrajaram@users.noreply.github.com": "kevinrajaram", # PR #3850 salvage (gateway: add POSIX system dirs to PATH so launchctl/systemctl resolve under UV's minimal-PATH bundled Python; #3849) + "lord-dubious@users.noreply.github.com": "lord-dubious", # PR #58453 salvage (preserve static custom provider models declared as dict rows) + "williamumu@users.noreply.github.com": "williamumu", # PR #31041 salvage (pairing: merge split legacy/new pairing store dirs at PairingStore init so approved users aren't re-prompted to pair) + "jonathan@mintrx.com": "JAlmanzarMint", # PR #52688 salvage (vision: rasterize SVG / re-encode unsupported raster formats to PNG before embedding), folded into #57890 + "alex@fireworks.ai": "alex-fireworks", # PR #61182 salvage (Fireworks AI model-provider integration) + "al3060388206@gmail.com": "ooiuuii", # PR #58466/#58377 salvage (redact: fireworks fw-/fpk_ prefixes; telegram: redact bot tokens out of transport error strings). Also PR #58433 salvage (codex: accept recorded final_text when app-server omits turn/completed) and PR #58472 salvage (gateway: cap proxy SSE line buffer at 16MiB). + "Jigoooo@users.noreply.github.com": "Jigoooo", # PR #58474 salvage (auxiliary: fall back to token resolver when anthropic pool has no usable entry) + "root@vmi3351581.contaboserver.net": "ostravajih", # PR #58374 salvage (poolside: coerce integer finish_reason and tool_call id to strings) + "hello@sahil-shubham.in": "sahil-shubham", # PR #58448 salvage (whatsapp_cloud: honor documented WHATSAPP_CLOUD_ALLOWED_USERS / ALLOW_ALL_USERS in the DM intake gate) + "ahmet.tunc@gmail.com": "Ahmett101", # PR #58445 salvage (profiles: allowlist default-export roots + preserve symlinks) + "Ahmett101@users.noreply.github.com": "Ahmett101", # PR #59455 salvage (background-review: guard summarize against list-shaped tool responses; #59437) + "wyuebei@gmail.com": "wyuebei-cloud", # PR #56640 salvage (hermes journey: replace GNU-only %-d strftime with dt.day for Windows) + "yingwaizhiying@gmail.com": "msh01", # PR #58250 salvage (telegram: wall-clock init timeout via daemon-thread deadline + abandon the shielded initialize task on timeout so the retry ladder advances instead of hanging on attempt 1/8 under s6 supervision; #58236). Also covers PR #58276 salvage (compression: preserve a real user turn after compaction; #55677). + "danilo@falcao.org": "danilofalcao", # PR #56674 salvage (update: skip unsupported platform.matrix lazy refresh on native Windows — python-olm has no Windows wheel) + "huanshan5195@users.noreply.github.com": "huanshan5195", # PR #57601 salvage (custom-provider: emit reasoning_effort at the live CustomProfile path so GLM-5.2/ARK/vLLM/Ollama endpoints receive it; + "max" reasoning level) + "infinitycrew39@gmail.com": "infinitycrew39", # PR #56431 salvage (honor live vLLM context limits on local endpoints) + "jonathan.kovacs999@gmail.com": "CocaKova", # PR #57692 salvage (cron: run jobs under the profile secret scope so get_secret does not fail-close with UnscopedSecretError under profile isolation) + "hermes.wanderer@yahoo.com": "trismegistus-wanderer", # PR #31856 salvage (gateway: defer idle-TTL agent-cache eviction until the session store says the session actually expired, so the expiry watcher can still fire MemoryProvider.on_session_end with the live transcript; #11205) "louis@letsfive.io": "Mibayy", # PR #3243 salvage (/compact alias + preview/aggressive flags for /compress) "louis@letsfive.io": "Mibayy", # PR #3176 salvage (api-server: per-client model routing via model_routes) "jneeee@outlook.com": "jneeee", # PR #3526 salvage (extra HTTP headers for LLM API calls via config.yaml) @@ -52,12 +112,15 @@ "r0gersm1th@users.noreply.github.com": "r0gersm1th", # PR #3219 salvage (whatsapp bridge: resolve LID sender IDs to phone numbers in the message payload so phone-based allowlists match; commit authored by collaborator r0gersm1th, PR by @ajmeese7) "louis@letsfive.io": "Mibayy", # PR #3296 salvage (status: provider label honors config.yaml model.base_url, not just OPENAI_BASE_URL env) "me@keslerm.com": "keslerm", # PR #3459 salvage (gateway: 'log' tool_progress mode — silent in chat, tool calls appended to ~/.hermes/logs/tool_calls.log via rotating handler; duplicate of #3458 by @dlkakbs who submitted 4 min earlier — both credited) + "david.d.zhang@gmail.com": "Git-on-my-level", # PR #3659 salvage (gateway: persist per-session /model overrides across gateway restarts) "tarunravi@gmail.com": "tarunravi", # PR #2696 salvage (api-server: inline MEDIA: image tags as base64 data URLs in final responses so remote OpenAI-compatible frontends can render server-local screenshots; the PR's tool-progress-streaming and SSE-sentinel pieces were independently superseded on main) "aqdrgg19@gmail.com": "VolodymyrBg", # PR #2861 salvage (webhook: drop the unused full request payload from retained _delivery_info entries — up to ~1MB dead weight per delivery for the 1h idempotency TTL) "ohyes9711@gmail.com": "CharmingGroot", # PR #2794 salvage (email: guard msg_data[0][1] against malformed IMAP fetch structures so one bad response can't abort the batch and permanently lose seen-marked messages; Message-ID domain falls back to localhost when EMAIL_ADDRESS lacks '@') "sahibzada@fastino.ai": "sahibzada-allahyar", # PR #39227 salvage (desktop: configured terminal.cwd overrides a stale remembered workspace-cwd localStorage value when no session is active; #38855) + "ronaldrj@gmail.com": "rarf", # PR #56966 salvage (desktop chat model picker: hide implicitly discovered providers unless explicitly configured) "jvsantos.cunha@gmail.com": "plcunha", # PR #55300 salvage (gateway: record child gateway peer metadata after a compression session-id rotation and repoint stale sessions.json compression-parent entries to the recovered live child; consolidated in the compression-routing-integrity salvage) "jakepresent1@gmail.com": "jakepresent", # PR #55721 salvage (gateway: identity-guard stale in-flight compression splits — a late run may publish its compressed child only if its run generation is still current and the session key still points at the run's original parent, so an old run can't overwrite a newer /new or moved binding) + "gumclaw@gumroad.com": "gumclaw", # PR #57322 salvage (gateway: close per-delivery webhook sessions on completion so prune_sessions can reap them — fixes unbounded state.db growth from unprunable ended_at=NULL webhook rows) "zhangml@tech.icbc.com.cn": "zmlgit", # PR #54872 salvage (multiplex-profile kanban: route task notifications via the owning profile's adapter + wake the creator agent with a synthetic internal MessageEvent on terminal events) "1079826437@qq.com": "nankingjing", # PR #56404 salvage (gateway: while a state.db compression lock is held for the session, demote busy_input_mode 'interrupt' to 'queue' so a rapid message burst can't interrupt and fork orphaned compression siblings off a stale parent; #56391) "ud@arubangles.com": "udatny", # PR #29433 salvage (subdirectory_hints: catch RuntimeError from Path.expanduser()/Path.home() so a literal ~ in tool-call args — e.g. LLM "~500-700" or ~unknownuser — can't escape the hint walker and crash the conversation loop) @@ -129,6 +192,7 @@ "65363919+coygeek@users.noreply.github.com": "coygeek", # PR #37951 salvage (fail closed when provider env blocklist import fails; #37950) "5261694+djstunami@users.noreply.github.com": "djstunami", # PR #5316 salvage / co-author (suppress transient check_fn flakes so subagents keep file/terminal tools; #21658 / #5304) "jmmaloney4@gmail.com": "jmmaloney4", # PR #25206 salvage (re-select credential pool on primary runtime restore; #25205) + "hmirin@users.noreply.github.com": "hmirin", "dale@dalenguyen.me": "dalenguyen", # PR #53678 salvage (strip VIRTUAL_ENV/CONDA_PREFIX from terminal subprocess env; #23473) "liruixinch@outlook.com": "HexLab98", # PR #53863 salvage (env-only proxy policy for auxiliary OpenAI clients on macOS; #53702) "blaryx@gmail.com": "Blaryxoff", # PR #32602 salvage (deep-merge PUT /api/config to preserve unrelated sections; #13396) @@ -174,11 +238,13 @@ "rayjun0412@gmail.com": "rayjun", # cron model.default salvage co-author (#43952) "96944678+sweetcornna@users.noreply.github.com": "sweetcornna", # cron ticker-liveness salvage co-author (#33849) "izumi0uu@gmail.com": "izumi0uu", # PR #49544 salvage (native rich reply echo; #49534) + "zhangyingliang@outlook.com": "yingliang-zhang", # PR #56084 (setup RPC pool routing; #57335) "dev@pixlmedia.no": "texhy", # PR #27435 salvage (few-but-huge preflight compression gate; #27405) "qdaszx@naver.com": "qdaszx", # PR #29190 salvage (non-blocking OSV malware preflight; #29184) "w31rdm4ch1n3z@protonmail.com": "w31rdm4ch1nZ", "xtpeeps@gmail.com": "x7peeps", "ahmad@madsgency.com": "ahmadashfq", + "182213728+yinkev@users.noreply.github.com": "yinkev", # scratch artifact preservation salvage "rratmansky@gmail.com": "rratmansky", "lkz-de@users.noreply.github.com": "lkz-de", "charles@salesondemand.io": "salesondemandio", @@ -186,6 +252,7 @@ "victor@rocketfueldev.com": "victor-kyriazakos", "87440198+JoaoMarcos44@users.noreply.github.com": "JoaoMarcos44", "joaomarcosdias444@gmail.com": "JoaoMarcos44", + "neoguyver@icloud.com": "neoguyverx", # PR #60526 salvage (fail-closed write syntax gate; #60525) "286497132+srojk34@users.noreply.github.com": "srojk34", "srojk34@users.noreply.github.com": "srojk34", # legacy prefix-less noreply (PR #50098 salvage; #38763) "pinkiilqwq@users.noreply.github.com": "PINKIIILQWQ", # PR #45035 salvage (resume-to-tip; #38763) @@ -211,6 +278,10 @@ "dkobi16@gmail.com": "Diyoncrz18", "arnaud@nolimitdevelopment.com": "ali-nld", "sswdarius@gmail.com": "necoweb3", + "bassisho@Mac-mini-bassis.local": "hydracoco7", # PR #61382 salvage (id-less cron job freeze) + "AlexFucuson9@users.noreply.github.com": "AlexFucuson9", # PR #61209 salvage (hygiene compression data loss) + "email@adambig.gs": "adambiggs", # PR #43819 salvage (holographic shared SQLite connection) + "koho.jung@outlook.com": "kohoj", # PR #61667 salvage (nonce-CSP HTML session export) "t.chen@aftership.com": "cypctlinux", # PR #52403 salvage (Slack bot/workflow auth before no-user-id guard) "30854794+YLChen-007@users.noreply.github.com": "YLChen-007", # PR #26965 (approval remote command substitution) "1078345+egilewski@users.noreply.github.com": "egilewski", # co-author, PR #40663 @@ -254,6 +325,22 @@ "290859878+synapsesx@users.noreply.github.com": "synapsesx", "157689911+itsflownium@users.noreply.github.com": "itsflownium", "dirtyren@users.noreply.github.com": "dirtyren", + "johnmlussier@gmail.com": "John-Lussier", + "chenkun_lws@126.com": "bytesnail", # PR #60360 salvage (--yolo startup ordering; #60328) + "iamgexin@qq.com": "nullptr0807", # PR #60956 salvage (gateway hygiene in-place compaction; #60947) + "embwl0x@users.noreply.github.com": "embwl0x", # PR #60810 salvage (channel directory offload) + "caztronics@yahoo.com": "doncazper", + "30668368+alex107ivanov@users.noreply.github.com": "alex107ivanov", + "210088133+rungmc357@users.noreply.github.com": "rungmc357", + "florian.rutishauser@outlook.com": "flo1t", + "fanyang@microsoft.com": "fanyangCS", + "bigstar0920@gmail.com": "bigstar0920", + "hello@tanmaychoudhary.com": "tanmayxchoudhary", + "285906080+AIalliAI@users.noreply.github.com": "AIalliAI", + "waseemshahwan@users.noreply.github.com": "waseemshahwan", + "hellno@users.noreply.github.com": "hellno", + "perkintahmaz50@gmail.com": "devatnull", + "marxb@protonmail.com": "Marxb85", "153708448+hunjaiboy@users.noreply.github.com": "yyzquwu", # PR #47567 salvage (Matrix: register inbound handlers with wait_sync=True so _dispatch_sync's gather awaits them; without it mautrix fire-and-forgets and inbound intake has no completion point) "jearnest@velocityenergy.com": "jearnest11", # PR #48700 salvage (multi-profile gateway flap: use node symlink's own parent, not .resolve() target, when building systemd/launchd service PATH so one profile's node path can't leak into every unit and force a perpetual daemon-reload restart loop) "tgmerritt@gmail.com": "tgmerritt", # PR #43553 salvage (parse vLLM's token-based output-cap error format so over-cap max_tokens 400s reduce the output cap instead of death-looping into compression) @@ -428,6 +515,7 @@ "simpolism@gmail.com": "simpolism", "jake@nousresearch.com": "simpolism", "mgongzai@gmail.com": "vKongv", + "perkintahmaz50@gmail.com": "devatnull", "0x.badfriend@gmail.com": "discodirector", "altriatree@gmail.com": "TruaShamu", "contact-me@stark-x.cn": "Stark-X", @@ -466,6 +554,7 @@ "Rivuza@users.noreply.github.com": "Rivuza", "annguyenNous@users.noreply.github.com": "annguyenNous", "285874597+annguyenNous@users.noreply.github.com": "annguyenNous", + "perkintahmaz50@gmail.com": "devatnull", "kylekahraman@users.noreply.github.com": "kylekahraman", "130975919+kylekahraman@users.noreply.github.com": "kylekahraman", "seppe@fushia.be": "seppegadeyne", @@ -704,6 +793,7 @@ "hypnus.yuan@gmail.com": "Hypnus-Yuan", "15558128926@qq.com": "xsfX20", "binhnt.ht.92@gmail.com": "binhnt92", + "li.long15@xydigit.com": "Alix-007", # PR #54620 salvage (sms: bound Twilio webhook body reads) "johnny@Jons-MBA-M4.local": "acesjohnny", "1581133593@qq.com": "liu-collab", "haidaoe@proton.me": "haidao1919", @@ -788,6 +878,10 @@ "maks.mir@yahoo.com": "say8hi", "27719690+Mirac1eSky@users.noreply.github.com": "Mirac1eSky", "web3blind@users.noreply.github.com": "web3blind", + "264741654+web3blind@users.noreply.github.com": "web3blind", + # Sessions export format cluster (July 2026): HTML + prompt-only salvages + "840004959@qq.com": "simplast", + "catbearlove1@gmail.com": "catbearlove1-lang", "julia@alexland.us": "alexg0bot", "christian@scheid.tech": "scheidti", # Moonshot schema anyOf+enum salvage (May 2026) @@ -830,6 +924,7 @@ "kshitijk4poor@gmail.com": "kshitijk4poor", "1294707+Tosko4@users.noreply.github.com": "Tosko4", "keira.voss94@gmail.com": "keiravoss94", + "vadim.veroslavov@mail.ru": "veradim", # PR #41201 salvage (Z.AI endpoint persist) "16443023+stablegenius49@users.noreply.github.com": "stablegenius49", "fqsy1416@gmail.com": "EKKOLearnAI", "octo-patch@github.com": "octo-patch", @@ -870,6 +965,7 @@ "jezzahehn@gmail.com": "JezzaHehn", "barnacleboy.jezzahehn@agentmail.to": "JezzaHehn", "254021826+dodo-reach@users.noreply.github.com": "dodo-reach", + "edder@example.com": "EdderTalmor", # PR #41575 salvage (prompt-size: pass platform-resolved enabled_toolsets + agent.disabled_toolsets into the inspection agent; #41445) "259807879+Bartok9@users.noreply.github.com": "Bartok9", "123342691+banditburai@users.noreply.github.com": "banditburai", "9063726+Kyzcreig@users.noreply.github.com": "Kyzcreig", @@ -998,6 +1094,8 @@ "alexazzjjtt@163.com": "alexzhu0", "pub_forgreatagent@antgroup.com": "AntAISecurityLab", "252620095+briandevans@users.noreply.github.com": "briandevans", + "51974392+tcconnally@users.noreply.github.com": "tcconnally", + "jan@mg5.org": "mijanx", "incharge.automation@gmail.com": "inchargeautomation-lab", "danielrpike9@gmail.com": "Bartok9", "96944678+ymylive@users.noreply.github.com": "sweetcornna", @@ -1129,6 +1227,7 @@ "hata1234@gmail.com": "hata1234", "hmbown@gmail.com": "Hmbown", "iacobs@m0n5t3r.info": "m0n5t3r", + "iacobs@webflakes.com": "m0n5t3r", "jiayuw794@gmail.com": "JiayuuWang", "jinhyuk9714@gmail.com": "sjh9714", "jonny@nousresearch.com": "yoniebans", @@ -1171,12 +1270,18 @@ "cine.dreamer.one@gmail.com": "LeonSGP43", "Lubrsy706@users.noreply.github.com": "Lubrsy706", "niyant@spicefi.xyz": "spniyant", + "256398740+nicha16@users.noreply.github.com": "nicha16", # PR #54139 partial salvage (re-register tools after park revival) "olafthiele@gmail.com": "olafthiele", "oncuevtv@gmail.com": "sprmn24", "programming@olafthiele.com": "olafthiele", "r2668940489@gmail.com": "r266-tech", "r266-tech@users.noreply.github.com": "r266-tech", # PR #55780 salvage (dead-target not_found blast radius) "s5460703@gmail.com": "BlackishGreen33", + "84022+gnodet@users.noreply.github.com": "gnodet", # PR #37598 salvage (MCP preflight POST probe fallback) + "kaishi00@users.noreply.github.com": "kaishi00", # PR #55203 salvage (skip_preflight opt-out) + "setclock@Marins-Mac-mini.local": "setclock", # PR #27052 salvage (MCP session-expired retry waits for a distinct fresh session) + "sberan@gmail.com": "sberan", # PR #54494 salvage (--connect-timeout flag on hermes mcp add) + "michaelmusser@users.noreply.github.com": "labsobsidian", # PR #56699 salvage (MCP OAuth login connect_timeout floor) "saul.jj.wu@gmail.com": "SaulJWu", "shenhaocheng19990111@gmail.com": "hcshen0111", "sjtuwbh@gmail.com": "Cygra", @@ -1383,6 +1488,7 @@ "holynn@placeholder.local": "holynn-q", "agent@hermes.local": "jacdevos", "sunsky.lau@gmail.com": "liuhao1024", + "suninrain086@gmail.com": "suninrain086", # PR #57651 salvage of #50685 (vision custom-endpoint creds) "mohamed.origami@gmail.com": "mohamedorigami-jpg", # PR #32117 (cron storage root anchor; #32091) "58446328+sherman-yang@users.noreply.github.com": "sherman-yang", # PR #32788 (cron per-job MCP merge; #23997) "rob@rbrtbn.com": "rbrtbn", @@ -1421,6 +1527,8 @@ "daniuxie88@proton.me": "DaniuXie", "panchanler@gmail.com": "ChanlerDev", "252620095+briandevans@users.noreply.github.com": "briandevans", + "51974392+tcconnally@users.noreply.github.com": "tcconnally", + "jan@mg5.org": "mijanx", "141889580+h0tp-ftw@users.noreply.github.com": "h0tp-ftw", "chinadbo@foxmail.com": "chinadbo", "82637225+kshitijk4poor@users.noreply.github.com": "kshitijk4poor", @@ -1754,6 +1862,7 @@ "vanthinh6886@gmail.com": "vanthinh6886", # PR #28018 salvage (yaml/flock/atomic write guards) "erik.engervall@gmail.com": "erikengervall", # PR #28774 (firecrawl integration tag) "egilewski@egilewski.com": "egilewski", # PR #30432 (MEDIA path traversal fix, GHSA-jmf9-9729-7pp8) + "andrew@hndl.app": "andrewhomeyer", # PR #20056 (snapshot owner-only perms, co-author on #57386 salvage) "edison@mcclean.codes": "McClean-Edison", # PR #29817 (register_auxiliary_task plugin API) "OYLFLMH@users.noreply.github.com": "OYLFLMH", # PR #48312 salvage (cli_refresh_interval config, #48309) "zhangsamuel12@gmail.com": "SamuelZ12", # PR #7480 (show recap after in-session resume) @@ -1791,6 +1900,7 @@ # batch salvage PR #35758 (perf micro-fixes) "116212274+amathxbt@users.noreply.github.com": "amathxbt", # PR #22155 (cache tool_output_limits) "takis312@hotmail.com": "ErnestHysa", # PRs #32636/#32708 (MCP asyncio.sleep + O(n^2) watcher drain) + "adrian@Adrians-MacBook-Pro.local": "alastraz", # PR #41383 salvage (cua EAGAIN CLI-transport fallback) "me@simontaggart.com": "SiTaggart", # PR #35583 (docker_forward_env empty-secret .env fallback) "2663402852@qq.com": "x1am1", # PR #35098 (chown root-owned top-level HERMES_HOME state files) "nicsequenzy@gmail.com": "polnikale", # PR #35717 (discover Playwright headless_shell browser) @@ -1849,6 +1959,16 @@ "poli.koltsova@gmail.com": "wnuuee1", # commit 9fd2b2cb PR author "yosapol@jitrak.dev": "Eji4h", # direct email match "kiljadn@gmail.com": "designnotdrum", # PR #56480 salvage (toolset static-inference fix) + "lavya@loom.local": "LavyaTandel", # PR #57893 salvage local git identity (envelope-layout cache markers on tool/empty-assistant messages; #57845) + "601709253@qq.com": "SquabbyZ", # PR #59682 salvage (in-container dashboard WS loopback host; #58993) + "rodisoft1@gmail.com": "0disoft", # PR #53511 salvage (gateway PID probe TTL cache) + "craigs.seller.sixx@gmail.com": "0-CYBERDYNE-SYSTEMS-0", # PR #53966 salvage (session DB reads off event loop) + "sebastianlutycz@users.noreply.github.com": "sebastianlutycz", # PR #39140 salvage (descendant CTE); bare noreply (no NNN+ prefix) needs explicit mapping + "wafy.081107@gmail.com": "mahdiwafy", # PR #60347 salvage (session messages pagination) + "codeforgenet@icloud.com": "CodeForgeNet", # PR #47437 salvage (compact_rows blob skip) + "i@dex.moe": "dexhunter", # PR #60339 salvage (skills snapshot manifest speedup) + "1torhan@protonmail.com": "uzaylisak", # PR #29988 salvage (detect_local_server_type process-lifetime cache) + "zhchl@hermes-agent.local": "8294", # PR #50572 salvage (honor config context_length on banner) } @@ -2332,7 +2452,7 @@ def main(): return print(f"{'='*60}") - print(f" Hermes Agent Release Preview") + print(" Hermes Agent Release Preview") print(f"{'='*60}") print(f" CalVer tag: {tag_name}") print(f" SemVer: v{current_version} → v{new_version}") @@ -2381,7 +2501,7 @@ def main(): if commit_result.returncode != 0: print(f" ✗ Failed to commit version bump: {commit_result.stderr.strip()}") return - print(f" ✓ Committed version bump") + print(" ✓ Committed version bump") # Create annotated tag tag_result = git_result( @@ -2396,7 +2516,7 @@ def main(): # Push push_result = git_result("push", "origin", "HEAD", "--tags") if push_result.returncode == 0: - print(f" ✓ Pushed to origin") + print(" ✓ Pushed to origin") else: print(f" ✗ Failed to push to origin: {push_result.stderr.strip()}") print(" Continue manually after fixing access:") @@ -2441,7 +2561,7 @@ def main(): else: print(f" ✗ GitHub release failed: {result.stderr.strip()}") print(f" Release notes kept at: {changelog_file}") - print(f" Tag was created locally. Create the release manually:") + print(" Tag was created locally. Create the release manually:") print( f" gh release create {tag_name} --title 'Hermes Agent v{new_version} ({calver_date})' " f"--notes-file .release_notes.md {' '.join(str(path) for path in artifacts)}" @@ -2449,8 +2569,8 @@ def main(): print(f"\n ✓ Release artifacts prepared for manual publish: v{new_version} ({tag_name})") else: print(f"\n{'='*60}") - print(f" Dry run complete. To publish, add --publish") - print(f" Example: python scripts/release.py --bump minor --publish") + print(" Dry run complete. To publish, add --publish") + print(" Example: python scripts/release.py --bump minor --publish") print(f"{'='*60}") diff --git a/tests/gateway/test_config_cwd_bridge.py b/tests/gateway/test_config_cwd_bridge.py index 299b7e6b3bef1..e865dced77fbf 100644 --- a/tests/gateway/test_config_cwd_bridge.py +++ b/tests/gateway/test_config_cwd_bridge.py @@ -12,6 +12,9 @@ import os import json +from gateway.cwd_placeholder import CWD_PLACEHOLDERS, resolve_placeholder_terminal_cwd +from tools.terminal_tool import _is_ssh_remote_tilde_cwd + def _simulate_config_bridge(cfg: dict, initial_env: dict | None = None): """Simulate the gateway config bridge logic from gateway/run.py. @@ -19,6 +22,9 @@ def _simulate_config_bridge(cfg: dict, initial_env: dict | None = None): Returns the resulting env dict (only TERMINAL_* and MESSAGING_CWD keys). """ env = dict(initial_env or {}) + from hermes_cli.config import _normalize_terminal_backend_defaults + + cfg = _normalize_terminal_backend_defaults(cfg, cfg) # --- Replicate lines 54-56: generic top-level bridge (for context) --- for key, val in cfg.items(): @@ -28,6 +34,9 @@ def _simulate_config_bridge(cfg: dict, initial_env: dict | None = None): # --- Replicate lines 59-87: terminal config bridge --- terminal_cfg = cfg.get("terminal", {}) if terminal_cfg and isinstance(terminal_cfg, dict): + terminal_backend = str( + terminal_cfg.get("backend") or env.get("TERMINAL_ENV") or "" + ).strip().lower() terminal_env_map = { "backend": "TERMINAL_ENV", "cwd": "TERMINAL_CWD", @@ -37,6 +46,7 @@ def _simulate_config_bridge(cfg: dict, initial_env: dict | None = None): "container_cpu": "TERMINAL_CONTAINER_CPU", "container_memory": "TERMINAL_CONTAINER_MEMORY", "container_disk": "TERMINAL_CONTAINER_DISK", + "docker_mount_cwd_to_workspace": "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", } for cfg_key, env_var in terminal_env_map.items(): if cfg_key in terminal_cfg: @@ -45,10 +55,13 @@ def _simulate_config_bridge(cfg: dict, initial_env: dict | None = None): # TERMINAL_CWD. Mirrors the fix in gateway/run.py. if cfg_key == "cwd" and str(val) in {".", "auto", "cwd"}: continue - # Expand shell tilde so subprocess.Popen never receives a literal - # "~/" which the kernel rejects. + # Expand shell tilde for local/container backends so subprocess.Popen + # never receives a literal "~/" which the kernel rejects. SSH cwd is + # interpreted by the remote shell, so preserve "~" / "~/..." there. + # Uses the same production predicate as gateway/run.py. if cfg_key == "cwd" and isinstance(val, str): - val = os.path.expanduser(val) + if not _is_ssh_remote_tilde_cwd(terminal_backend, val.strip()): + val = os.path.expanduser(val) if isinstance(val, list): env[env_var] = json.dumps(val) else: @@ -67,11 +80,23 @@ def _simulate_config_bridge(cfg: dict, initial_env: dict | None = None): alias_val = os.path.expanduser(alias_val) env[alias_env] = alias_val.strip() - # --- Replicate lines 144-147: MESSAGING_CWD fallback --- + # --- Replicate gateway/run.py placeholder TERMINAL_CWD resolution --- configured_cwd = env.get("TERMINAL_CWD", "") - if not configured_cwd or configured_cwd in {".", "auto", "cwd"}: - messaging_cwd = env.get("MESSAGING_CWD") or "/root" # Path.home() for root - env["TERMINAL_CWD"] = messaging_cwd + if not configured_cwd or configured_cwd in CWD_PLACEHOLDERS: + resolved = resolve_placeholder_terminal_cwd( + configured_cwd=configured_cwd, + terminal_backend=env.get("TERMINAL_ENV", ""), + messaging_cwd=env.get("MESSAGING_CWD"), + docker_mount_cwd_to_workspace=env.get( + "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", "false" + ).lower() + in {"true", "1", "yes"}, + home_fallback="/root", + ) + if resolved is None: + env.pop("TERMINAL_CWD", None) + else: + env["TERMINAL_CWD"] = resolved return env @@ -89,6 +114,12 @@ def test_top_level_backend_sets_terminal_env(self): result = _simulate_config_bridge(cfg) assert result["TERMINAL_ENV"] == "docker" + def test_tenki_backend_defaults_to_terminate_only_over_stale_env(self): + cfg = {"terminal": {"backend": "tenki"}} + result = _simulate_config_bridge(cfg, {"TERMINAL_CONTAINER_PERSISTENT": "true"}) + assert result["TERMINAL_ENV"] == "tenki" + assert result["TERMINAL_CONTAINER_PERSISTENT"] == "False" + def test_top_level_cwd_and_backend(self): cfg = {"backend": "local", "cwd": "/home/hermes/projects"} result = _simulate_config_bridge(cfg) @@ -214,7 +245,44 @@ def test_non_cwd_terminal_keys_still_bridge(self): result = _simulate_config_bridge(cfg, {"MESSAGING_CWD": "/from/env"}) assert result["TERMINAL_ENV"] == "docker" assert result["TERMINAL_TIMEOUT"] == "300" - assert result["TERMINAL_CWD"] == "/from/env" + assert result.get("TERMINAL_CWD") is None + + def test_docker_placeholder_does_not_inherit_host_home(self): + """terminal.cwd: '.' + docker + mount off must not resolve to host home.""" + cfg = { + "terminal": { + "cwd": ".", + "backend": "docker", + "docker_mount_cwd_to_workspace": False, + }, + } + result = _simulate_config_bridge(cfg, {"MESSAGING_CWD": "/home/user"}) + assert "TERMINAL_CWD" not in result + + def test_docker_placeholder_mount_on_preserves_messaging_cwd(self): + """Mount-enabled docker still needs the host cwd signal for /workspace.""" + cfg = { + "terminal": { + "cwd": ".", + "backend": "docker", + "docker_mount_cwd_to_workspace": True, + }, + } + result = _simulate_config_bridge( + cfg, {"MESSAGING_CWD": "/host/project"} + ) + assert result["TERMINAL_CWD"] == "/host/project" + assert result["TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE"] == "True" + + def test_ssh_placeholder_does_not_inherit_host_home(self): + cfg = {"terminal": {"cwd": "auto", "backend": "ssh"}} + result = _simulate_config_bridge(cfg, {"MESSAGING_CWD": "/home/user"}) + assert "TERMINAL_CWD" not in result + + def test_local_placeholder_still_falls_back_to_messaging_cwd(self): + cfg = {"terminal": {"cwd": ".", "backend": "local"}} + result = _simulate_config_bridge(cfg, {"MESSAGING_CWD": "/home/user"}) + assert result["TERMINAL_CWD"] == "/home/user" def test_terminal_home_mode_bridges_to_env(self): cfg = {"terminal": {"home_mode": "profile"}} @@ -249,3 +317,26 @@ def test_tilde_with_nested_precedence(self): } result = _simulate_config_bridge(cfg) assert result["TERMINAL_CWD"] == os.path.expanduser("~/nested") + + def test_ssh_terminal_cwd_tilde_preserved_for_remote_shell(self, monkeypatch): + """SSH cwd '~' must mean the remote user's home, not the gateway host HOME.""" + monkeypatch.setenv("HOME", "/opt/data") + cfg = {"terminal": {"backend": "ssh", "cwd": "~"}} + result = _simulate_config_bridge(cfg) + assert result["TERMINAL_ENV"] == "ssh" + assert result["TERMINAL_CWD"] == "~" + + def test_ssh_terminal_cwd_tilde_child_preserved_for_remote_shell(self, monkeypatch): + """SSH cwd '~/x' must survive until the SSH shell expands remote HOME.""" + monkeypatch.setenv("HOME", "/opt/data") + cfg = {"terminal": {"backend": "ssh", "cwd": "~/work"}} + result = _simulate_config_bridge(cfg) + assert result["TERMINAL_CWD"] == "~/work" + + def test_ssh_terminal_placeholder_cwd_does_not_fallback_to_host_home(self, monkeypatch): + """SSH placeholder cwd should let terminal_tool use its remote-home default.""" + monkeypatch.setenv("HOME", "/opt/data") + cfg = {"terminal": {"backend": "ssh", "cwd": "auto"}} + result = _simulate_config_bridge(cfg, {"MESSAGING_CWD": "/host/project"}) + assert result["TERMINAL_ENV"] == "ssh" + assert "TERMINAL_CWD" not in result diff --git a/tests/hermes_cli/test_config_env_expansion.py b/tests/hermes_cli/test_config_env_expansion.py index 435a47668780d..4738c180dc272 100644 --- a/tests/hermes_cli/test_config_env_expansion.py +++ b/tests/hermes_cli/test_config_env_expansion.py @@ -1,5 +1,7 @@ """Tests for ${ENV_VAR} substitution in config.yaml values.""" +import os + import pytest from hermes_cli.config import _expand_env_vars, load_config @@ -94,9 +96,74 @@ def test_load_config_unresolved_kept_verbatim(self, tmp_path, monkeypatch): assert config["model"]["api_key"] == "${NOT_SET_XYZ_123}" +class TestLoadConfigCacheEnvStaleness: + """The load_config() cache must not pin expansions made against a stale + environment (#58514): a load before load_hermes_dotenv() runs, or an env + var rotated in-process, must not keep serving the old expansion.""" + + def test_env_var_appearing_after_first_load_invalidates_cache(self, tmp_path, monkeypatch): + config_yaml = "auxiliary:\n vision:\n api_key: ${LATE_DOTENV_KEY_58514}\n" + config_file = tmp_path / "config.yaml" + config_file.write_text(config_yaml) + + monkeypatch.delenv("LATE_DOTENV_KEY_58514", raising=False) + monkeypatch.setitem(load_config.__globals__, "get_config_path", lambda: config_file) + + # First load happens before the var exists (pre-dotenv): literal kept. + assert load_config()["auxiliary"]["vision"]["api_key"] == "${LATE_DOTENV_KEY_58514}" + + # .env load brings the var in — same file mtime/size, env changed. + monkeypatch.setenv("LATE_DOTENV_KEY_58514", "nvapi-real") + assert load_config()["auxiliary"]["vision"]["api_key"] == "nvapi-real" + + def test_env_var_rotation_invalidates_cache(self, tmp_path, monkeypatch): + config_yaml = "providers:\n mistral:\n api_key: ${ROTATED_KEY_58514}\n" + config_file = tmp_path / "config.yaml" + config_file.write_text(config_yaml) + + monkeypatch.setenv("ROTATED_KEY_58514", "key-v1") + monkeypatch.setitem(load_config.__globals__, "get_config_path", lambda: config_file) + + assert load_config()["providers"]["mistral"]["api_key"] == "key-v1" + + monkeypatch.setenv("ROTATED_KEY_58514", "key-v2") + assert load_config()["providers"]["mistral"]["api_key"] == "key-v2" + + def test_unchanged_env_still_serves_cache(self, tmp_path, monkeypatch): + config_yaml = "providers:\n mistral:\n api_key: ${STABLE_KEY_58514}\n" + config_file = tmp_path / "config.yaml" + config_file.write_text(config_yaml) + + monkeypatch.setenv("STABLE_KEY_58514", "key-stable") + monkeypatch.setitem(load_config.__globals__, "get_config_path", lambda: config_file) + + load_config() + # load_config_readonly() returns the cached object itself, so object + # identity across calls proves the cache-hit path was taken (a rebuild + # would produce a fresh dict). + readonly = load_config.__globals__["load_config_readonly"] + first = readonly() + second = readonly() + + assert first is second + assert first["providers"]["mistral"]["api_key"] == "key-stable" + + class TestLoadCliConfigExpansion: """Verify that load_cli_config() also expands ${VAR} references.""" + def test_cli_config_ignores_empty_terminal_section(self, tmp_path, monkeypatch): + config_file = tmp_path / "config.yaml" + config_file.write_text("terminal:\n") + + monkeypatch.setattr("cli._hermes_home", tmp_path) + + from cli import load_cli_config + config = load_cli_config() + + assert isinstance(config["terminal"], dict) + assert config["terminal"]["env_type"] == "local" + def test_cli_config_expands_auxiliary_api_key(self, tmp_path, monkeypatch): config_yaml = ( "auxiliary:\n" @@ -131,3 +198,19 @@ def test_cli_config_unresolved_kept_verbatim(self, tmp_path, monkeypatch): config = load_cli_config() assert config["auxiliary"]["vision"]["api_key"] == "${UNSET_CLI_VAR_ABC}" + + def test_cli_tenki_backend_overrides_stale_persistent_env(self, tmp_path, monkeypatch): + config_yaml = "terminal:\n backend: tenki\n" + config_file = tmp_path / "config.yaml" + config_file.write_text(config_yaml) + + monkeypatch.setenv("TERMINAL_CONTAINER_PERSISTENT", "true") + monkeypatch.setattr("cli._hermes_home", tmp_path) + + from cli import load_cli_config + config = load_cli_config() + + assert config["terminal"]["container_persistent"] is False + assert config["terminal"]["env_type"] == "tenki" + assert config["terminal"]["backend"] == "tenki" + assert os.environ["TERMINAL_CONTAINER_PERSISTENT"] == "False" diff --git a/tests/hermes_cli/test_setup.py b/tests/hermes_cli/test_setup.py index 9cf2f737eb22b..a84f74d6069f6 100644 --- a/tests/hermes_cli/test_setup.py +++ b/tests/hermes_cli/test_setup.py @@ -491,6 +491,37 @@ def fake_prompt_choice(question, choices, default=0): assert config["terminal"]["modal_mode"] == "direct" +def test_tenki_setup_switch_resets_inherited_persistent_container(monkeypatch): + config = { + "terminal": { + "backend": "docker", + "container_persistent": True, + "cwd": "/workspace", + } + } + + def fake_prompt_choice(question, choices, default=0): + if question == "Select terminal backend:": + assert "Tenki Agent - Tenki cloud sandbox" in choices + return choices.index("Tenki Agent - Tenki cloud sandbox") + raise AssertionError(f"Unexpected prompt_choice call: {question}") + + monkeypatch.setitem(sys.modules, "tenki_sandbox", types.ModuleType("tenki_sandbox")) + monkeypatch.setenv("TENKI_AUTH_TOKEN", "tok") + monkeypatch.setattr("hermes_cli.setup.prompt_choice", fake_prompt_choice) + monkeypatch.setattr("hermes_cli.setup.prompt", lambda *args, **kwargs: "") + monkeypatch.setattr("hermes_cli.setup.save_config", lambda _config: None) + monkeypatch.setattr("hermes_cli.setup.save_env_value", lambda *_args, **_kwargs: None) + + from hermes_cli.setup import setup_terminal_backend + + setup_terminal_backend(config) + + assert config["terminal"]["backend"] == "tenki" + assert config["terminal"]["container_persistent"] is False + assert config["terminal"]["cwd"] == "/home/tenki" + + # test_setup_slack_* moved to tests/gateway/test_slack_plugin_setup.py — the # _setup_slack wizard migrated to the slack plugin's interactive_setup (#41112). @@ -539,4 +570,3 @@ def _interrupt(*_a, **_k): with pytest.raises(SystemExit): setup_mod.prompt_yes_no("Install it now?", True) - diff --git a/tests/tools/test_container_cwd_sanitize.py b/tests/tools/test_container_cwd_sanitize.py index 833d11404f10f..2f06b60ae2908 100644 --- a/tests/tools/test_container_cwd_sanitize.py +++ b/tests/tools/test_container_cwd_sanitize.py @@ -66,6 +66,31 @@ def test_container_backends_set(self): ) +class TestBackendGuestSubpath: + """The Tenki guest home /home/tenki (and its subtree) is a real sandbox + path, so it must be exempt from the host-path guard even though it shares + the /home/ prefix that other backends reject.""" + + def test_tenki_guest_home_root_is_subpath(self): + assert tt._is_backend_guest_subpath("tenki", "/home/tenki") is True + + def test_tenki_guest_home_child_is_subpath(self): + assert tt._is_backend_guest_subpath("tenki", "/home/tenki/project") is True + + def test_tenki_unrelated_home_is_not_subpath(self): + # A different user's home is still a host path even on tenki. + assert tt._is_backend_guest_subpath("tenki", "/home/someoneelse") is False + + def test_docker_has_no_guest_home_exemption(self): + # Docker's default cwd is /root, so /home/... stays a rejected host path. + assert tt._is_backend_guest_subpath("docker", "/home/tenki/project") is False + + def test_tenki_guest_subpath_survives_full_guard(self): + # The combined check the call sites use: unusable-by-prefix but exempt. + assert tt._is_unusable_container_cwd("/home/tenki/project") is True + assert tt._is_backend_guest_subpath("tenki", "/home/tenki/project") is True + + class TestOverrideCwdSanitizedAtCallSite: """E2E pin: a per-task cwd OVERRIDE that is a host path must NOT reach the container builder. This is the actual reported bug — the gateway/TUI @@ -145,6 +170,62 @@ def test_valid_container_override_is_preserved(self, monkeypatch): cwd = self._run_and_capture_cwd(monkeypatch, "/workspace/task42") assert cwd == "/workspace/task42" + def _run_tenki_and_capture_cwd(self, monkeypatch, override_cwd): + """Drive terminal_tool() on the tenki backend with a cwd override and + return the cwd that reached _create_environment.""" + captured = {} + config = { + "env_type": "tenki", + "tenki_image": "", + "cwd": "/home/tenki", + "host_cwd": None, + "timeout": 180, + "lifetime_seconds": 300, + "container_cpu": 1, + "container_memory": 5120, + "container_disk": 51200, + "container_persistent": False, + "modal_mode": "auto", + } + + class _DummyEnv: + cwd = "/home/tenki" + + def execute(self, *a, **k): + return {"output": "", "exit_code": 0} + + def fake_create_environment(env_type, image, cwd, timeout, **kwargs): + captured["cwd"] = cwd + return _DummyEnv() + + monkeypatch.setattr(tt, "_get_env_config", lambda: config) + monkeypatch.setattr(tt, "_start_cleanup_thread", lambda: None) + monkeypatch.setattr(tt, "_check_all_guards", lambda *a, **k: {"approved": True}) + monkeypatch.setattr(tt, "_create_environment", fake_create_environment) + monkeypatch.setattr(tt, "_active_environments", {}) + monkeypatch.setattr(tt, "_last_activity", {}) + + task_id = "sess-tenki-cwd" + tt.register_task_env_overrides(task_id, {"cwd": override_cwd}) + try: + tt.terminal_tool(command="pwd", task_id=task_id) + finally: + tt.clear_task_env_overrides(task_id) + tt._active_environments.pop(task_id, None) + tt._active_environments.pop("default", None) + return captured.get("cwd") + + def test_tenki_guest_subpath_override_is_preserved(self, monkeypatch): + # A real Tenki guest path registered as a per-task override must NOT be + # collapsed to /home/tenki (the #9b override-path fix). + cwd = self._run_tenki_and_capture_cwd(monkeypatch, "/home/tenki/project") + assert cwd == "/home/tenki/project" + + def test_tenki_foreign_host_override_still_sanitized(self, monkeypatch): + # A genuine host path is still discarded on tenki. + cwd = self._run_tenki_and_capture_cwd(monkeypatch, "/home/someoneelse/x") + assert cwd == "/home/tenki" + class TestFileOpsCwdSanitizedAtCallSite: """E2E pin: file tools (_get_file_ops) must sanitize a host/relative cwd @@ -171,6 +252,18 @@ def _run_and_capture_cwd(self, monkeypatch, override_cwd, env_type="docker", "singularity_image": "docker://pytorch/pytorch:latest", "modal_image": "pytorch/pytorch:latest", "daytona_image": "pytorch/pytorch:latest", + "tenki_image": "", + "tenki_api_endpoint": "", + "tenki_workspace_id": "", + "tenki_project_id": "", + "tenki_name_prefix": "hermes", + "tenki_allow_inbound": False, + "tenki_allow_outbound": True, + "tenki_max_duration": 3600, + "tenki_idle_timeout": 0, + "tenki_pause_retention": 0, + "tenki_sync_hermes_home": False, + "tenki_forward_env": [], "cwd": config_cwd, "host_cwd": None, "timeout": 180, @@ -255,3 +348,15 @@ def test_host_override_sanitized_on_modal(self, monkeypatch): cwd = self._run_and_capture_cwd( monkeypatch, "/Users/me/workspace", env_type="modal") assert cwd == "/workspace" + + def test_tenki_guest_subpath_override_is_preserved(self, monkeypatch): + # File tools must honor the same Tenki guest-home exemption as the + # terminal tool: /home/tenki/project is a real sandbox path. + cwd = self._run_and_capture_cwd( + monkeypatch, "/home/tenki/project", env_type="tenki", config_cwd="/home/tenki") + assert cwd == "/home/tenki/project" + + def test_tenki_foreign_host_override_still_sanitized(self, monkeypatch): + cwd = self._run_and_capture_cwd( + monkeypatch, "/home/someoneelse/x", env_type="tenki", config_cwd="/home/tenki") + assert cwd == "/home/tenki" diff --git a/tests/tools/test_docker_network_config.py b/tests/tools/test_docker_network_config.py new file mode 100644 index 0000000000000..ced0c8c00a809 --- /dev/null +++ b/tests/tools/test_docker_network_config.py @@ -0,0 +1,196 @@ +"""Regression tests for the Docker terminal network toggle. + +Ported from NanoClaw PR #2713's opt-in egress lockdown idea. Hermes already +has DockerEnvironment(network=False), but the terminal config path did not +expose it, so operators could not request networkless Docker execution from +config.yaml. +""" + +import tools.terminal_tool as terminal_tool +from tools.environments import docker as docker_env + + +def test_terminal_env_config_reads_docker_network_toggle(monkeypatch): + monkeypatch.setenv("TERMINAL_DOCKER_NETWORK", "false") + + config = terminal_tool._get_env_config() + + assert config["docker_network"] is False + + +def test_create_environment_passes_docker_network_toggle(monkeypatch): + captured = {} + sentinel = object() + + def _fake_docker_environment(**kwargs): + captured.update(kwargs) + return sentinel + + monkeypatch.setattr(terminal_tool, "_DockerEnvironment", _fake_docker_environment) + + env = terminal_tool._create_environment( + env_type="docker", + image="python:3.11", + cwd="/workspace", + timeout=60, + container_config={"docker_network": False}, + ) + + assert env is sentinel + assert captured["network"] is False + + +def test_docker_environment_adds_network_none_when_disabled(monkeypatch): + commands = [] + + def fake_run(cmd, *args, **kwargs): + commands.append(cmd) + + class Result: + returncode = 0 + stdout = "fake-container-id\n" if len(cmd) > 1 and cmd[1] == "run" else "" + stderr = "" + + return Result() + + monkeypatch.setattr(docker_env, "find_docker", lambda: "/usr/bin/docker") + monkeypatch.setattr(docker_env.subprocess, "run", fake_run) + monkeypatch.setattr(docker_env.DockerEnvironment, "_storage_opt_supported", lambda self: False) + + env = docker_env.DockerEnvironment( + image="python:3.11", + cwd="/workspace", + timeout=60, + task_id="network-none-test", + network=False, + ) + + run_cmd = next(cmd for cmd in commands if len(cmd) > 2 and cmd[1:3] == ["run", "-d"]) + assert "--network=none" in run_cmd + env.cleanup() + + +def test_docker_network_config_is_bridged_everywhere(): + from tests.tools.test_terminal_config_env_sync import ( + _cli_env_map_keys, + _gateway_env_map_keys, + _save_config_env_sync_keys, + _terminal_tool_env_var_names, + ) + + assert "docker_network" in _cli_env_map_keys() + assert "docker_network" in _gateway_env_map_keys() + assert "docker_network" in _save_config_env_sync_keys() + assert "TERMINAL_DOCKER_NETWORK" in _terminal_tool_env_var_names() + + +def test_sibling_container_config_sites_carry_docker_network(): + """Every container_config construction site must carry docker_network — + otherwise that code path silently falls back to networked containers + while the terminal path honors the lockdown (the probe/exec asymmetry + reported on issue #46358). + + The sibling tool modules build their container_config through the shared + _container_config_from_env_config() helper, so a site is either an inline + dict (which must carry docker_network alongside docker_run_as_host_user) + or a call to that helper (whose output is asserted below). + """ + import ast + import inspect + + import tools.code_execution_tool as code_execution_tool + import tools.file_tools as file_tools + + assert terminal_tool._container_config_from_env_config({})["docker_network"] is True + assert ( + terminal_tool._container_config_from_env_config({"docker_network": False})[ + "docker_network" + ] + is False + ) + + for module in (terminal_tool, file_tools, code_execution_tool): + tree = ast.parse(inspect.getsource(module)) + sites = 0 + for node in ast.walk(tree): + if isinstance(node, ast.Dict): + keys = {k.value for k in node.keys if isinstance(k, ast.Constant)} + if "docker_run_as_host_user" in keys: + sites += 1 + assert "docker_network" in keys, ( + f"{module.__name__} builds a container_config with " + f"docker_run_as_host_user but without docker_network " + f"(line {node.lineno})" + ) + elif isinstance(node, ast.Call): + func = node.func + name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "") + if name == "_container_config_from_env_config": + sites += 1 + assert sites >= 1, f"expected at least one container_config site in {module.__name__}" + + +def _reuse_guard_harness(monkeypatch, *, existing_mode: str, network: bool): + """Drive DockerEnvironment through the cross-process reuse path with a + fake existing container whose NetworkMode is *existing_mode*. + + Returns the list of docker commands issued. + """ + commands = [] + + def fake_run(cmd, *args, **kwargs): + commands.append(cmd) + + class Result: + returncode = 0 + stderr = "" + stdout = "" + + if len(cmd) > 1 and cmd[1] == "ps": + Result.stdout = "existing-container-id\trunning\n" + elif len(cmd) > 1 and cmd[1] == "inspect": + Result.stdout = f"{existing_mode}\n" + elif len(cmd) > 1 and cmd[1] == "run": + Result.stdout = "fresh-container-id\n" + return Result() + + monkeypatch.setattr(docker_env, "find_docker", lambda: "/usr/bin/docker") + monkeypatch.setattr(docker_env.subprocess, "run", fake_run) + monkeypatch.setattr(docker_env.DockerEnvironment, "_storage_opt_supported", lambda self: False) + + docker_env.DockerEnvironment( + image="python:3.11", + cwd="/workspace", + timeout=60, + task_id="reuse-guard-test", + network=network, + persist_across_processes=True, + ) + return commands + + +def test_reuse_rejects_networked_container_when_lockdown_requested(monkeypatch): + commands = _reuse_guard_harness(monkeypatch, existing_mode="bridge", network=False) + + assert any(cmd[1:3] == ["rm", "-f"] for cmd in commands), ( + "bridge-networked container must be removed when docker_network=false" + ) + run_cmd = next(cmd for cmd in commands if len(cmd) > 2 and cmd[1:3] == ["run", "-d"]) + assert "--network=none" in run_cmd + + +def test_reuse_keeps_airgapped_container_when_lockdown_requested(monkeypatch): + commands = _reuse_guard_harness(monkeypatch, existing_mode="none", network=False) + + assert not any(cmd[1] == "rm" for cmd in commands) + assert not any(cmd[1] == "run" for cmd in commands), "matching container must be reused" + + +def test_reuse_skips_inspect_when_network_enabled(monkeypatch): + commands = _reuse_guard_harness(monkeypatch, existing_mode="none", network=True) + + # Default-network config never churns containers, even air-gapped ones + # (operators may have created them via docker_extra_args). + assert not any(cmd[1] == "inspect" for cmd in commands) + assert not any(cmd[1] == "rm" for cmd in commands) + assert not any(cmd[1] == "run" for cmd in commands) diff --git a/tests/tools/test_file_tools_container_config.py b/tests/tools/test_file_tools_container_config.py index f8a79a37e4edb..3a010504a51b4 100644 --- a/tests/tools/test_file_tools_container_config.py +++ b/tests/tools/test_file_tools_container_config.py @@ -1,6 +1,8 @@ """Tests for docker container_config key propagation in file_tools.""" +import threading from unittest.mock import patch, MagicMock +import tools.code_execution_tool as code_execution_tool import tools.file_tools as file_tools @@ -21,6 +23,21 @@ def _make_env_config(**overrides): "docker_volumes": [], "docker_mount_cwd_to_workspace": True, "docker_forward_env": ["MY_SECRET", "API_KEY"], + "docker_env": {"A": "B"}, + "docker_extra_args": ["--shm-size=1g"], + "docker_persist_across_processes": False, + "docker_orphan_reaper": False, + "tenki_api_endpoint": "https://api.tenki.test", + "tenki_workspace_id": "ws-123", + "tenki_project_id": "prj-456", + "tenki_name_prefix": "agent", + "tenki_allow_inbound": True, + "tenki_allow_outbound": False, + "tenki_max_duration": 7200, + "tenki_idle_timeout": 600, + "tenki_pause_retention": 3600, + "tenki_sync_hermes_home": True, + "tenki_forward_env": ["GITHUB_TOKEN"], } base.update(overrides) return base @@ -73,6 +90,26 @@ def test_docker_forward_env_defaults_to_empty_list(self): cc = self._run(cfg, "t4").get("container_config", {}) assert cc.get("docker_forward_env") == [] + def test_shared_container_config_fields_are_forwarded(self): + """File tools use the same container-config builder as terminal execution.""" + cc = self._run(_make_env_config(), "t5").get("container_config", {}) + + assert cc.get("docker_env") == {"A": "B"} + assert cc.get("docker_extra_args") == ["--shm-size=1g"] + assert cc.get("docker_persist_across_processes") is False + assert cc.get("docker_orphan_reaper") is False + assert cc.get("tenki_name_prefix") == "agent" + assert cc.get("tenki_api_endpoint") == "https://api.tenki.test" + assert cc.get("tenki_workspace_id") == "ws-123" + assert cc.get("tenki_project_id") == "prj-456" + assert cc.get("tenki_allow_inbound") is True + assert cc.get("tenki_allow_outbound") is False + assert cc.get("tenki_max_duration") == 7200 + assert cc.get("tenki_idle_timeout") == 600 + assert cc.get("tenki_pause_retention") == 3600 + assert cc.get("tenki_sync_hermes_home") is True + assert cc.get("tenki_forward_env") == ["GITHUB_TOKEN"] + def test_cwd_only_raw_task_override_reaches_file_environment(self): """CWD-only task overrides collapse to default but must keep their cwd.""" captured = self._run( @@ -83,3 +120,49 @@ def test_cwd_only_raw_task_override_reaches_file_environment(self): assert captured["task_id"] == "default" assert captured["cwd"] == "/workspace/session" + + +class TestExecuteCodeContainerConfig: + def test_execute_code_uses_shared_container_config_for_tenki(self): + captured = {} + mock_env = MagicMock() + env_config = _make_env_config( + env_type="tenki", + tenki_image="tenki-image", + cwd="/home/tenki", + ) + + def fake_create_env(**kwargs): + captured.update(kwargs) + return mock_env + + with patch("tools.terminal_tool._get_env_config", return_value=env_config), \ + patch("tools.terminal_tool._task_env_overrides", {}), \ + patch("tools.terminal_tool._active_environments", {}), \ + patch("tools.terminal_tool._last_activity", {}), \ + patch("tools.terminal_tool._env_lock", threading.Lock()), \ + patch("tools.terminal_tool._creation_locks", {}), \ + patch("tools.terminal_tool._creation_locks_lock", threading.Lock()), \ + patch("tools.terminal_tool._create_environment", side_effect=fake_create_env), \ + patch("tools.terminal_tool._start_cleanup_thread"): + env, env_type = code_execution_tool._get_or_create_env("exec-tenki") + + assert env is mock_env + assert env_type == "tenki" + assert captured["env_type"] == "tenki" + assert captured["image"] == "tenki-image" + assert captured["cwd"] == "/home/tenki" + assert captured["task_id"] == "default" + cc = captured["container_config"] + assert cc["container_persistent"] is False + assert cc["tenki_api_endpoint"] == "https://api.tenki.test" + assert cc["tenki_workspace_id"] == "ws-123" + assert cc["tenki_project_id"] == "prj-456" + assert cc["tenki_name_prefix"] == "agent" + assert cc["tenki_allow_inbound"] is True + assert cc["tenki_allow_outbound"] is False + assert cc["tenki_max_duration"] == 7200 + assert cc["tenki_idle_timeout"] == 600 + assert cc["tenki_pause_retention"] == 3600 + assert cc["tenki_sync_hermes_home"] is True + assert cc["tenki_forward_env"] == ["GITHUB_TOKEN"] diff --git a/tests/tools/test_hardline_blocklist.py b/tests/tools/test_hardline_blocklist.py index e084e61fe8f4e..2c8cee7b4ab76 100644 --- a/tests/tools/test_hardline_blocklist.py +++ b/tests/tools/test_hardline_blocklist.py @@ -150,6 +150,16 @@ "rm -rf $HOME/tmp", "rm foo.txt", "rm -rf some/path", + # Literal root-level directories that only LOOK like root-collapse + # spellings. Each inter-slash segment must be exactly "." or ".." to + # count as a collapse back to "/" — "/..." is a dir literally named + # "..." and "/.foo" is an ordinary root dotfile. These must NOT be + # swept into the "recursive delete of root filesystem" hardline rule + # (regression guard for the collapse-spelling tightening). + "rm -rf /...", + "rm -rf /....", + "rm -rf /.foo", + "rm -rf /.config/foo", # A dangerous-looking command embedded as a quoted *argument* to another # command must not trip the floor: the path is immediately followed by a # closing quote with no matching opening quote of its own, so the @@ -401,7 +411,8 @@ def test_root_collapse_pattern_leaves_real_paths_alone(clean_session): be pulled onto the hardline floor by the "collapse to /" broadening. """ for cmd in ["rm -rf /tmp", "rm -rf /home/user/x", "rm -rf /.ssh", - "rm -rf /.config", "rm -rf ./build", "rm -rf /opt/foo"]: + "rm -rf /.config", "rm -rf ./build", "rm -rf /opt/foo", + "rm -rf /...", "rm -rf /....", "rm -rf /.foo"]: is_hl, _ = detect_hardline_command(cmd) assert not is_hl, f"{cmd!r} must not be hardline-blocked (over-match)" @@ -502,7 +513,7 @@ def test_container_backends_still_bypass(clean_session): Hardline only protects environments with real host impact (local, ssh). """ - for env in ("docker", "singularity", "modal", "daytona"): + for env in ("docker", "singularity", "modal", "daytona", "tenki"): r1 = check_dangerous_command("rm -rf /", env) assert r1["approved"] is True, f"container {env} should still bypass" r2 = check_all_command_guards("rm -rf /", env) @@ -633,7 +644,7 @@ def test_sudo_stdin_guard_not_blocked_by_yolo(clean_session, monkeypatch): def test_sudo_stdin_guard_container_bypass(clean_session): """Containerized backends still bypass — they can't touch the host.""" - for env in ("docker", "singularity", "modal", "daytona"): + for env in ("docker", "singularity", "modal", "daytona", "tenki"): for cmd in _SUDO_STDIN_BLOCK: result = check_all_command_guards(cmd, env) assert result["approved"] is True, f"container {env} should bypass sudo guard on {cmd!r}" diff --git a/tests/tools/test_local_env_blocklist.py b/tests/tools/test_local_env_blocklist.py index 2e8332470ae86..890bb04a2845c 100644 --- a/tests/tools/test_local_env_blocklist.py +++ b/tests/tools/test_local_env_blocklist.py @@ -210,6 +210,8 @@ def test_tool_and_gateway_vars_are_stripped(self): "MODAL_TOKEN_ID": "modal-id", "MODAL_TOKEN_SECRET": "modal-secret", "DAYTONA_API_KEY": "daytona-key", + "TENKI_AUTH_TOKEN": "tenki-token", + "TENKI_API_KEY": "tenki-key", } result_env = _run_with_env(extra_os_env=leaked_vars) @@ -459,6 +461,8 @@ def test_gateway_runtime_vars_are_in_blocklist(self): "MODAL_TOKEN_ID", "MODAL_TOKEN_SECRET", "DAYTONA_API_KEY", + "TENKI_AUTH_TOKEN", + "TENKI_API_KEY", } assert extras.issubset(_HERMES_PROVIDER_ENV_BLOCKLIST) diff --git a/tests/tools/test_modal_sandbox_fixes.py b/tests/tools/test_modal_sandbox_fixes.py index 7546762fc8497..d8ac891b2b2a3 100644 --- a/tests/tools/test_modal_sandbox_fixes.py +++ b/tests/tools/test_modal_sandbox_fixes.py @@ -357,6 +357,7 @@ def test_should_skip_container_guards(self): def test_isolated_docker_keeps_fast_path(self, monkeypatch): """Isolated Docker still bypasses dangerous-command approval.""" import tools.approval as A + self._isolate_approval_state(monkeypatch) monkeypatch.setenv("HERMES_EXEC_ASK", "1") monkeypatch.setattr( "tools.tirith_security.check_command_security", @@ -365,9 +366,26 @@ def test_isolated_docker_keeps_fast_path(self, monkeypatch): has_host_access=False) assert res["approved"] is True + @staticmethod + def _isolate_approval_state(monkeypatch): + """Clear approval state that leaks in from the real user config. + + ``tools.approval`` loads ``command_allowlist`` into module-level + ``_permanent_approved`` at import time. This file imports + ``tools.terminal_tool`` at module level (collection time — BEFORE the + hermetic HERMES_HOME fixture runs), so on a dev machine whose real + config permanently allowlists e.g. "delete in root path" the guard + under test silently approves and the assertions flip. CI never has + such an allowlist, making this a local-only flake. + """ + import tools.approval as A + monkeypatch.setattr(A, "_permanent_approved", set()) + monkeypatch.setattr(A, "_session_approved", {}) + def test_host_bound_docker_requires_approval(self, monkeypatch): """Host-bound Docker dangerous command escalates instead of bypassing.""" import tools.approval as A + self._isolate_approval_state(monkeypatch) monkeypatch.setenv("HERMES_EXEC_ASK", "1") monkeypatch.setattr( "tools.tirith_security.check_command_security", @@ -381,6 +399,7 @@ def test_host_bound_docker_requires_approval(self, monkeypatch): def test_execute_code_isolated_docker_keeps_fast_path(self, monkeypatch): """Isolated Docker execute_code still bypasses the guard.""" import tools.approval as A + self._isolate_approval_state(monkeypatch) monkeypatch.setenv("HERMES_EXEC_ASK", "1") res = A.check_execute_code_guard("import os", "docker", has_host_access=False) @@ -389,6 +408,7 @@ def test_execute_code_isolated_docker_keeps_fast_path(self, monkeypatch): def test_execute_code_host_bound_docker_requires_approval(self, monkeypatch): """Host-bound Docker execute_code does not get the container fast-path.""" import tools.approval as A + self._isolate_approval_state(monkeypatch) monkeypatch.setenv("HERMES_EXEC_ASK", "1") res = A.check_execute_code_guard( "import os; os.system('rm -rf /workspace')", "docker", diff --git a/tests/tools/test_parse_env_var.py b/tests/tools/test_parse_env_var.py index 8cbbce6985827..e495217a3efbb 100644 --- a/tests/tools/test_parse_env_var.py +++ b/tests/tools/test_parse_env_var.py @@ -39,6 +39,45 @@ def test_get_env_config_parses_docker_forward_env_json(self): config = _tt_mod._get_env_config() assert config["docker_forward_env"] == ["GITHUB_TOKEN", "NPM_TOKEN"] + def test_get_env_config_parses_tenki_forward_env_json(self): + with patch.dict("os.environ", { + "TERMINAL_ENV": "tenki", + "TERMINAL_TENKI_FORWARD_ENV": '["GITHUB_TOKEN", "GH_TOKEN"]', + }, clear=False): + config = _tt_mod._get_env_config() + assert config["tenki_forward_env"] == ["GITHUB_TOKEN", "GH_TOKEN"] + + def test_get_env_config_parses_tenki_numeric_settings(self): + with patch.dict("os.environ", { + "TERMINAL_ENV": "tenki", + "TERMINAL_TENKI_MAX_DURATION": "7200", + "TERMINAL_TENKI_IDLE_TIMEOUT": "600", + "TERMINAL_TENKI_PAUSE_RETENTION": "300", + }, clear=False): + config = _tt_mod._get_env_config() + assert config["tenki_max_duration"] == 7200 + assert config["tenki_idle_timeout"] == 600 + assert config["tenki_pause_retention"] == 300 + + def test_stale_invalid_tenki_value_does_not_break_local_backend(self): + # A stale/invalid tenki value bridged from config.yaml must not abort + # _get_env_config() for a local session that never uses tenki. + with patch.dict("os.environ", { + "TERMINAL_ENV": "local", + "TERMINAL_TENKI_MAX_DURATION": "not-a-number", + }, clear=False): + config = _tt_mod._get_env_config() + assert config["env_type"] == "local" + assert config["tenki_max_duration"] == 3600 + + def test_invalid_tenki_value_raises_when_tenki_backend_active(self): + with patch.dict("os.environ", { + "TERMINAL_ENV": "tenki", + "TERMINAL_TENKI_MAX_DURATION": "not-a-number", + }, clear=False): + with pytest.raises(ValueError, match="TERMINAL_TENKI_MAX_DURATION"): + _tt_mod._get_env_config() + def test_create_environment_passes_docker_forward_env(self): fake_env = object() with patch.object(_tt_mod, "_DockerEnvironment", return_value=fake_env) as mock_docker: @@ -53,6 +92,22 @@ def test_create_environment_passes_docker_forward_env(self): assert result is fake_env assert mock_docker.call_args.kwargs["forward_env"] == ["GITHUB_TOKEN"] + def test_create_environment_passes_tenki_forward_env(self): + import tools.environments.tenki as tenki_module + + fake_env = object() + with patch.object(tenki_module, "TenkiEnvironment", return_value=fake_env) as mock_tenki: + result = _tt_mod._create_environment( + "tenki", + image="", + cwd="/home/tenki", + timeout=180, + container_config={"tenki_forward_env": ["GITHUB_TOKEN", "GH_TOKEN"]}, + ) + + assert result is fake_env + assert mock_tenki.call_args.kwargs["forward_env"] == ["GITHUB_TOKEN", "GH_TOKEN"] + def test_falls_back_to_default(self): with patch.dict("os.environ", {}, clear=False): # Remove the var if it exists, rely on default diff --git a/tests/tools/test_tenki_environment.py b/tests/tools/test_tenki_environment.py index aa6fcd5256f87..23a06e24b5db8 100644 --- a/tests/tools/test_tenki_environment.py +++ b/tests/tools/test_tenki_environment.py @@ -1,9 +1,37 @@ from __future__ import annotations import sys +import threading +import time import types from types import SimpleNamespace +import pytest + + +class _FakeFS: + def __init__(self): + self.mkdir_calls: list[tuple[tuple, dict]] = [] + self.upload_calls: list[tuple[str, str]] = [] + self.download_calls: list[tuple[str, str]] = [] + + @staticmethod + def _assert_remote_path(path: str) -> None: + if path.startswith("/") and path != "/home/tenki" and not path.startswith("/home/tenki/"): + raise AssertionError(f"Tenki fs path must be under /home/tenki, got {path!r}") + + def mkdir(self, path, **kwargs): + self._assert_remote_path(str(path)) + self.mkdir_calls.append(((path,), kwargs)) + + def upload(self, local_path, remote_path, **_kwargs): + self._assert_remote_path(str(remote_path)) + self.upload_calls.append((str(local_path), str(remote_path))) + + def download(self, remote_path, local_path, **_kwargs): + self._assert_remote_path(str(remote_path)) + self.download_calls.append((str(remote_path), str(local_path))) + class _FakeResult: def __init__(self, stdout: str = "", stderr: str = "", exit_code: int = 0): @@ -12,6 +40,35 @@ def __init__(self, stdout: str = "", stderr: str = "", exit_code: int = 0): self.exit_code = exit_code +class _FakeProcess: + def __init__( + self, + result: _FakeResult, + *, + stdin_data: str | None = None, + block_until_killed: bool = False, + ): + self._result = result + self.stdin_data = stdin_data + self.closed_stdin = False + self.killed = False + self._block_until_killed = block_until_killed + self._done = threading.Event() + + def close_stdin(self): + self.closed_stdin = True + + def kill(self): + self.killed = True + self._done.set() + + def wait(self, *_args, **_kwargs): + if self._block_until_killed: + self._done.wait(timeout=5) + return _FakeResult(stdout="", exit_code=143) + return self._result + + class _FakeSandbox: def __init__( self, @@ -21,27 +78,45 @@ def __init__( metadata: dict | None = None, ): self.exec_calls: list[tuple[tuple, dict]] = [] + self.start_calls: list[tuple[tuple, dict]] = [] + self.last_process: _FakeProcess | None = None + self.snapshots: list[tuple[str | None, bool]] = [] self.terminated = False self.paused = False self.resumed = False self.waited = False + self.refreshed = False self.id = "sb-test" self.name = name self.state = state self.info = SimpleNamespace(name=name, metadata=metadata or {}) - self.fs = SimpleNamespace( - mkdir=lambda *_args, **_kwargs: None, - upload=lambda *_args, **_kwargs: None, - download=lambda *_args, **_kwargs: None, - ) + self.fs = _FakeFS() - def exec(self, *args, **kwargs): - self.exec_calls.append((args, kwargs)) + @staticmethod + def _result_for_command(args): command = args[-1] if args else "" if "echo \"$HOME\"" in command: return _FakeResult(stdout="/home/tenki\n") return _FakeResult(stdout="ran\n", exit_code=0) + def exec(self, *args, **kwargs): + self.exec_calls.append((args, kwargs)) + return self._result_for_command(args) + + def start(self, *args, **kwargs): + self.start_calls.append((args, kwargs)) + command = args[-1] if args else "" + self.last_process = _FakeProcess( + self._result_for_command(args), + stdin_data=kwargs.get("stdin"), + block_until_killed="sleep infinity" in command, + ) + return self.last_process + + def refresh(self): + self.refreshed = True + return self.info + def terminate(self): self.terminated = True self.state = "TERMINATED" @@ -57,13 +132,48 @@ def resume(self): def wait_ready(self, *_args, **_kwargs): self.waited = True + def snapshot(self, *, name=None, wait=True): + self.snapshots.append((name, wait)) + return SimpleNamespace(id=f"snap-{self.name}") + + +def _last_started_command(sandbox: _FakeSandbox) -> str: + return sandbox.start_calls[-1][0][-1] + + +class _FakeSnapshotNotFoundError(Exception): + """Mirrors tenki_sandbox.SnapshotNotFoundError for the fake SDK.""" + + +class _FakeRegistryArtifactNotFoundError(Exception): + """Mirrors tenki_sandbox.RegistryArtifactNotFoundError for the fake SDK.""" + + +class _FakeSnapshotNotDurableError(Exception): + """Mirrors tenki_sandbox.SnapshotNotDurableError for the fake SDK.""" + + +class _FakeInvalidStateError(Exception): + """Mirrors tenki_sandbox.InvalidStateError for the fake SDK.""" + class _FakeSandboxFactory: created_kwargs: list[dict] = [] + failed_kwargs: list[dict] = [] sandboxes: list[_FakeSandbox] = [] + fail_snapshot_ids: set[str] = set() + # When a snapshot id is in fail_snapshot_ids, raise this exception type with + # this message. Defaults to the confirmed-not-found error; tests set them to + # a transient error / generic message to prove the pointer is preserved, or + # to a snapshot-specific InvalidStateError to prove base-image fallback. + snapshot_error: type[Exception] = _FakeSnapshotNotFoundError + snapshot_error_msg: str = "restore failed" @classmethod def create(cls, **kwargs): + if kwargs.get("snapshot_id") in cls.fail_snapshot_ids: + cls.failed_kwargs.append(kwargs) + raise cls.snapshot_error(cls.snapshot_error_msg) sandbox = _FakeSandbox( name=kwargs.get("name", "sb-test"), metadata=kwargs.get("metadata", {}), @@ -79,6 +189,7 @@ class _FakeClient: def __init__(self, **kwargs): self.kwargs = kwargs + self.snapshots = SimpleNamespace(wait_durable=lambda *_args, **_kwargs: None) def create(self, **kwargs): return _FakeSandboxFactory.create(**kwargs) @@ -99,11 +210,19 @@ def close(self): def _install_fake_tenki(monkeypatch): module = types.ModuleType("tenki_sandbox") _FakeSandboxFactory.created_kwargs = [] + _FakeSandboxFactory.failed_kwargs = [] _FakeSandboxFactory.sandboxes = [] + _FakeSandboxFactory.fail_snapshot_ids = set() + _FakeSandboxFactory.snapshot_error = _FakeSnapshotNotFoundError + _FakeSandboxFactory.snapshot_error_msg = "restore failed" _FakeClient.listed_sandboxes = [] _FakeClient.closed_count = 0 module.Client = _FakeClient module.Sandbox = _FakeSandboxFactory + module.SnapshotNotFoundError = _FakeSnapshotNotFoundError + module.RegistryArtifactNotFoundError = _FakeRegistryArtifactNotFoundError + module.SnapshotNotDurableError = _FakeSnapshotNotDurableError + module.InvalidStateError = _FakeInvalidStateError monkeypatch.setitem(sys.modules, "tenki_sandbox", module) @@ -112,6 +231,16 @@ def _clear_tenki_auth_env(monkeypatch): monkeypatch.delenv("TENKI_API_KEY", raising=False) +def _clear_env_passthrough_cache(): + try: + import tools.env_passthrough as env_passthrough + + env_passthrough.clear_env_passthrough() + env_passthrough._config_passthrough = None + except Exception: + pass + + def test_tenki_cli_auth_token_is_normalized_for_sdk_cookie_auth(monkeypatch, tmp_path): _clear_tenki_auth_env(monkeypatch) monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) @@ -147,6 +276,7 @@ def test_tenki_environment_uses_cli_config_and_terminates_by_default(monkeypatch _install_fake_tenki(monkeypatch) _clear_tenki_auth_env(monkeypatch) monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) (tmp_path / "config.yaml").write_text( "\n".join( @@ -173,10 +303,19 @@ def test_tenki_environment_uses_cli_config_and_terminates_by_default(monkeypatch ) kwargs = _FakeSandboxFactory.created_kwargs[0] + # The control-plane credential is used host-side to create the sandbox... assert kwargs["base_url"] == "https://api.tenki.test" assert kwargs["workspace_id"] == "ws-123" assert kwargs["project_id"] == "prj-456" assert kwargs["auth_token"] == "cookie:tok-secret" + # ...but is NEVER injected into the model-controlled guest environment + # (an empty env is omitted from the create kwargs entirely). + guest_env = kwargs.get("env", {}) + assert "TENKI_AUTH_TOKEN" not in guest_env + assert "TENKI_API_KEY" not in guest_env + assert "TENKI_API_ENDPOINT" not in guest_env + assert "TENKI_WORKSPACE_ID" not in guest_env + assert "TENKI_PROJECT_ID" not in guest_env assert kwargs["allow_inbound"] is False assert kwargs["allow_outbound"] is True assert kwargs["cpu_cores"] == 1 @@ -184,51 +323,381 @@ def test_tenki_environment_uses_cli_config_and_terminates_by_default(monkeypatch assert "idle_timeout_minutes" not in kwargs assert "pause_retention" not in kwargs assert kwargs["metadata"]["hermes_backend"] == "tenki" - assert kwargs["name"].startswith("hermes-session-1") + assert kwargs["metadata"]["hermes_profile"] + assert kwargs["name"].startswith("hermes-") + assert kwargs["name"].endswith("session-1") output, exit_code = env._exec_raw("echo ok", timeout=5) assert output == "ran\n" assert exit_code == 0 sandbox = _FakeSandboxFactory.sandboxes[0] + assert "TENKI_AUTH_TOKEN" not in sandbox.exec_calls[-1][1]["env"] env.cleanup() assert sandbox.terminated is True assert sandbox.paused is False -def test_tenki_environment_pauses_when_persistent(monkeypatch, tmp_path): +def test_tenki_environment_does_not_inject_control_plane_token_by_default(monkeypatch, tmp_path): + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + _clear_env_passthrough_cache() + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "missing.yaml")) + monkeypatch.setenv("TENKI_API_KEY", "sk-test-key") + + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + env = TenkiEnvironment(task_id="api-key") + + kwargs = _FakeSandboxFactory.created_kwargs[0] + # Host-side create still authenticates with the credential... + assert kwargs["auth_token"] == "sk-test-key" + # ...but the guest never receives it unless explicitly forwarded. + guest_env = kwargs.get("env", {}) + assert "TENKI_AUTH_TOKEN" not in guest_env + assert "TENKI_API_KEY" not in guest_env + env.cleanup() + _clear_env_passthrough_cache() + + +def test_tenki_environment_forwards_control_plane_token_only_when_opted_in(monkeypatch, tmp_path): + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + _clear_env_passthrough_cache() + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "missing.yaml")) + monkeypatch.setenv("TENKI_API_KEY", "sk-test-key") + + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + # Nested-sandbox support: the operator explicitly forwards the credential. + env = TenkiEnvironment(task_id="api-key", forward_env=["TENKI_API_KEY"]) + + kwargs = _FakeSandboxFactory.created_kwargs[0] + assert kwargs["env"]["TENKI_API_KEY"] == "sk-test-key" + env.cleanup() + _clear_env_passthrough_cache() + + +def test_tenki_environment_honors_tenki_forward_env_from_process_env(monkeypatch, tmp_path): + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + _clear_env_passthrough_cache() + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + monkeypatch.setenv("GH_TOKEN", "gho-process") + (tmp_path / "config.yaml").write_text( + "auth_token: tok-secret\n", + encoding="utf-8", + ) + + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + env = TenkiEnvironment(task_id="gh-token", forward_env=["GH_TOKEN"]) + + assert _FakeSandboxFactory.created_kwargs[0]["env"]["GH_TOKEN"] == "gho-process" + env.execute("echo ok", timeout=5) + assert env._sandbox.start_calls[-1][1]["env"]["GH_TOKEN"] == "gho-process" + env.cleanup() + _clear_env_passthrough_cache() + + +def test_tenki_environment_honors_tenki_forward_env_from_hermes_dotenv(monkeypatch, tmp_path): + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + _clear_env_passthrough_cache() + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + monkeypatch.delenv("GITHUB_TOKEN", raising=False) + (tmp_path / ".env").write_text("GITHUB_TOKEN=ghp-dotenv\n", encoding="utf-8") + (tmp_path / "config.yaml").write_text( + "auth_token: tok-secret\n", + encoding="utf-8", + ) + + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + env = TenkiEnvironment(task_id="github-token", forward_env=["GITHUB_TOKEN"]) + + assert _FakeSandboxFactory.created_kwargs[0]["env"]["GITHUB_TOKEN"] == "ghp-dotenv" + env.execute("echo ok", timeout=5) + assert env._sandbox.start_calls[-1][1]["env"]["GITHUB_TOKEN"] == "ghp-dotenv" + env.cleanup() + _clear_env_passthrough_cache() + + +def test_tenki_forwarded_env_prefers_profile_scope_over_process_env(monkeypatch, tmp_path): + """Under a multiplexed profile scope, a forwarded credential must resolve + to the active profile's value, never another profile's raw os.environ.""" + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + _clear_env_passthrough_cache() + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + # Another profile's value leaking through the process environment... + monkeypatch.setenv("GH_TOKEN", "gho-other-profile") + + from agent import secret_scope + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setattr(secret_scope, "_MULTIPLEX_ACTIVE", True) + token = secret_scope.set_secret_scope({"GH_TOKEN": "gho-this-profile"}) + try: + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + env = TenkiEnvironment(task_id="scoped", forward_env=["GH_TOKEN"]) + # ...must be overridden by the active profile scope. + assert _FakeSandboxFactory.created_kwargs[0]["env"]["GH_TOKEN"] == "gho-this-profile" + env.cleanup() + finally: + secret_scope.reset_secret_scope(token) + _clear_env_passthrough_cache() + + +def test_tenki_auth_token_prefers_profile_scope_over_process_env(monkeypatch, tmp_path): + _clear_tenki_auth_env(monkeypatch) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "missing.yaml")) + monkeypatch.setenv("TENKI_AUTH_TOKEN", "tok-other-profile") + + from agent import secret_scope + from tools.tenki_config import resolve_tenki_auth_token + + monkeypatch.setattr(secret_scope, "_MULTIPLEX_ACTIVE", True) + tok = secret_scope.set_secret_scope({"TENKI_AUTH_TOKEN": "tok-this-profile"}) + try: + assert resolve_tenki_auth_token() == "tok-this-profile" + finally: + secret_scope.reset_secret_scope(tok) + + +def test_tenki_auth_token_fails_closed_when_multiplex_active_and_unscoped(monkeypatch, tmp_path): + """Multiplex on + no scope installed: an os.environ token must NOT leak + through (fail closed), rather than serving another profile's value.""" + _clear_tenki_auth_env(monkeypatch) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "missing.yaml")) + monkeypatch.setenv("TENKI_AUTH_TOKEN", "tok-leaked-from-process-env") + + from agent import secret_scope + from tools.tenki_config import resolve_tenki_auth_token + + monkeypatch.setattr(secret_scope, "_MULTIPLEX_ACTIVE", True) + # No set_secret_scope() — this is the fail-closed branch. + assert secret_scope.current_secret_scope() is None + assert resolve_tenki_auth_token() == "" + + +def test_tenki_forwarded_env_fails_closed_when_multiplex_active_and_unscoped(monkeypatch, tmp_path): _install_fake_tenki(monkeypatch) _clear_tenki_auth_env(monkeypatch) + _clear_env_passthrough_cache() monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + monkeypatch.setenv("GH_TOKEN", "gho-leaked-from-process-env") + from agent import secret_scope from tools.environments.tenki import TenkiEnvironment + monkeypatch.setattr(secret_scope, "_MULTIPLEX_ACTIVE", True) + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + env = TenkiEnvironment(task_id="scoped", forward_env=["GH_TOKEN"]) + + # No scope installed while multiplexing → the process-env value is not leaked. + assert "GH_TOKEN" not in _FakeSandboxFactory.created_kwargs[0].get("env", {}) + env.cleanup() + _clear_env_passthrough_cache() + + +def test_tenki_control_plane_token_forwarded_from_cli_config_when_opted_in(monkeypatch, tmp_path): + """The opt-in must work even when auth came from `tenki login` (CLI config), + whose secret never lands in os.environ.""" + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + _clear_env_passthrough_cache() + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + # Credential lives ONLY in the Tenki CLI config, not the environment. + (tmp_path / "config.yaml").write_text("auth_token: tok-cli-login\n", encoding="utf-8") + + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + env = TenkiEnvironment(task_id="nested", forward_env=["TENKI_AUTH_TOKEN"]) + + guest_env = _FakeSandboxFactory.created_kwargs[0].get("env", {}) + assert guest_env["TENKI_AUTH_TOKEN"] == "cookie:tok-cli-login" + env.cleanup() + _clear_env_passthrough_cache() + + +def test_tenki_environment_honors_safe_env_passthrough(monkeypatch, tmp_path): + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + _clear_env_passthrough_cache() + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + monkeypatch.setenv("CUSTOM_TASK_ENV", "task-value") + (tmp_path / "config.yaml").write_text( + "auth_token: tok-secret\n" + "terminal:\n" + " env_passthrough:\n" + " - CUSTOM_TASK_ENV\n", + encoding="utf-8", + ) + + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + env = TenkiEnvironment(task_id="safe-passthrough") + + assert _FakeSandboxFactory.created_kwargs[0]["env"]["CUSTOM_TASK_ENV"] == "task-value" + env.execute("echo ok", timeout=5) + assert env._sandbox.start_calls[-1][1]["env"]["CUSTOM_TASK_ENV"] == "task-value" + env.cleanup() + _clear_env_passthrough_cache() + + +def test_tenki_environment_snapshots_when_persistent(monkeypatch, tmp_path): + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) env = TenkiEnvironment(task_id="persist", persistent_filesystem=True) sandbox = _FakeSandboxFactory.sandboxes[0] env.cleanup() + assert len(sandbox.snapshots) == 1 + snap_name, snap_wait = sandbox.snapshots[0] + assert snap_name.endswith("persist") and snap_wait is True + assert sandbox.paused is False + assert sandbox.terminated is True + + env = TenkiEnvironment(task_id="persist", image="base-image", persistent_filesystem=True) + assert _FakeSandboxFactory.created_kwargs[-1]["snapshot_id"].endswith("persist") + assert "image" not in _FakeSandboxFactory.created_kwargs[-1] + env.cleanup() + + +def test_tenki_environment_falls_back_when_persistent_snapshot_is_stale(monkeypatch, tmp_path): + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + + from tools.environments import tenki as tenki_module + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + tenki_module._store_snapshot("persist", "snap-stale") + _FakeSandboxFactory.fail_snapshot_ids = {"snap-stale"} + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + + env = TenkiEnvironment(task_id="persist", image="base-image", persistent_filesystem=True) + + assert _FakeSandboxFactory.failed_kwargs[0]["snapshot_id"] == "snap-stale" + assert _FakeSandboxFactory.created_kwargs[0]["image"] == "base-image" + assert tenki_module._get_snapshot_restore_candidate("persist") == (None, False) + env.cleanup() + + +def test_tenki_environment_preserves_snapshot_on_transient_restore_error(monkeypatch, tmp_path): + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + + from tools.environments import tenki as tenki_module + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + tenki_module._store_snapshot("persist", "snap-transient") + _FakeSandboxFactory.fail_snapshot_ids = {"snap-transient"} + # A transient failure (not a confirmed not-found) must NOT boot a blank + # base image or drop the recovery pointer. + _FakeSandboxFactory.snapshot_error = RuntimeError + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + + with pytest.raises(RuntimeError): + TenkiEnvironment(task_id="persist", image="base-image", persistent_filesystem=True) + + # No base-image fallback happened, and the snapshot pointer is retained. + assert _FakeSandboxFactory.created_kwargs == [] + assert tenki_module._get_snapshot_restore_candidate("persist") == ("snap-transient", False) + + +def test_tenki_environment_skips_snapshot_when_not_durable(monkeypatch, tmp_path): + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + + from tools.environments import tenki as tenki_module + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + + def _fail_durable(*_args, **_kwargs): + raise RuntimeError("not durable yet") + + def _init(self, **kw): + self.kwargs = kw + self.snapshots = SimpleNamespace(wait_durable=_fail_durable) + + monkeypatch.setattr(_FakeClient, "__init__", _init) + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + env = TenkiEnvironment(task_id="persist", persistent_filesystem=True) + sandbox = _FakeSandboxFactory.sandboxes[0] + + env.cleanup() + + # Durability failed → do NOT record the snapshot and do NOT terminate the + # live sandbox; pause it so state is preserved for recovery. assert sandbox.paused is True assert sandbox.terminated is False + assert tenki_module._get_snapshot_restore_candidate("persist") == (None, False) def test_tenki_environment_resumes_existing_persistent_sandbox(monkeypatch, tmp_path): _install_fake_tenki(monkeypatch) _clear_tenki_auth_env(monkeypatch) monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + + from tools.environments import tenki as tenki_module + from tools.environments.tenki import TenkiEnvironment + + token = tenki_module._profile_token() existing = _FakeSandbox( - name="hermes-persist", + name=f"hermes-{token}-persist", state="PAUSED", - metadata={"hermes_task_id": "persist"}, + metadata={"hermes_task_id": "persist", "hermes_profile": token}, ) _FakeClient.listed_sandboxes = [existing] - from tools.environments.tenki import TenkiEnvironment - monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) env = TenkiEnvironment(task_id="persist", persistent_filesystem=True) @@ -236,6 +705,256 @@ def test_tenki_environment_resumes_existing_persistent_sandbox(monkeypatch, tmp_ assert existing.resumed is True assert existing.waited is True assert _FakeSandboxFactory.created_kwargs == [] + # The resumed guest never receives the control-plane credential either. + assert "TENKI_AUTH_TOKEN" not in existing.exec_calls[-1][1]["env"] + env.cleanup() + + +def test_tenki_environment_does_not_reuse_other_profiles_sandbox(monkeypatch, tmp_path): + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + + from tools.environments.tenki import TenkiEnvironment + + # A live sandbox on the same Tenki account belonging to a DIFFERENT profile + # (foreign token) with the same task id must never be resumed. + foreign = _FakeSandbox( + name="hermes-deadbeef00-persist", + state="PAUSED", + metadata={"hermes_task_id": "persist", "hermes_profile": "deadbeef00"}, + ) + _FakeClient.listed_sandboxes = [foreign] + + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + env = TenkiEnvironment(task_id="persist", persistent_filesystem=True) + + assert env._sandbox is not foreign + assert foreign.resumed is False + assert _FakeSandboxFactory.created_kwargs, "should create its own sandbox" + env.cleanup() + + +def test_tenki_reuse_rejects_name_match_with_foreign_profile_metadata(monkeypatch, tmp_path): + """Defense-in-depth: even if a candidate's NAME matches, a differing + hermes_profile in metadata must block reuse.""" + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + + from tools.environments import tenki as tenki_module + from tools.environments.tenki import TenkiEnvironment + + token = tenki_module._profile_token() + # Same name (as if a token collision), but metadata says a different profile. + collider = _FakeSandbox( + name=f"hermes-{token}-persist", + state="PAUSED", + metadata={"hermes_task_id": "persist", "hermes_profile": "foreign-token"}, + ) + _FakeClient.listed_sandboxes = [collider] + + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + env = TenkiEnvironment(task_id="persist", persistent_filesystem=True) + + assert env._sandbox is not collider + assert collider.resumed is False + env.cleanup() + + +def test_tenki_restore_falls_back_on_nondurable_snapshot(monkeypatch, tmp_path): + """A snapshot that EXISTS but is permanently unusable (non-durable) must + drop the pointer and boot the base image, not wedge the task forever.""" + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + + from tools.environments import tenki as tenki_module + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + tenki_module._store_snapshot("persist", "snap-nondurable") + _FakeSandboxFactory.fail_snapshot_ids = {"snap-nondurable"} + _FakeSandboxFactory.snapshot_error = _FakeSnapshotNotDurableError + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + + env = TenkiEnvironment(task_id="persist", image="base-image", persistent_filesystem=True) + + assert _FakeSandboxFactory.failed_kwargs[0]["snapshot_id"] == "snap-nondurable" + assert _FakeSandboxFactory.created_kwargs[0]["image"] == "base-image" + assert tenki_module._get_snapshot_restore_candidate("persist") == (None, False) + env.cleanup() + + +def test_tenki_restore_preserves_pointer_on_invalid_state_error(monkeypatch, tmp_path): + """InvalidStateError is a generic precondition failure, NOT snapshot-gone, + so it must be treated as transient: preserve the pointer, do not base-boot.""" + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + + from tools.environments import tenki as tenki_module + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + tenki_module._store_snapshot("persist", "snap-invalidstate") + _FakeSandboxFactory.fail_snapshot_ids = {"snap-invalidstate"} + _FakeSandboxFactory.snapshot_error = _FakeInvalidStateError + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + + with pytest.raises(_FakeInvalidStateError): + TenkiEnvironment(task_id="persist", image="base-image", persistent_filesystem=True) + + assert _FakeSandboxFactory.created_kwargs == [] + assert tenki_module._get_snapshot_restore_candidate("persist") == ("snap-invalidstate", False) + + +def test_tenki_restore_falls_back_on_snapshot_specific_invalid_state(monkeypatch, tmp_path): + """A generic InvalidStateError whose message identifies the snapshot (the + SDK's collapsed representation of a bad/non-durable snapshot on restore) + IS unrecoverable → drop the pointer and boot the base image.""" + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + + from tools.environments import tenki as tenki_module + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + tenki_module._store_snapshot("persist", "snap-badstate") + _FakeSandboxFactory.fail_snapshot_ids = {"snap-badstate"} + _FakeSandboxFactory.snapshot_error = _FakeInvalidStateError + _FakeSandboxFactory.snapshot_error_msg = "snapshot is not durable" + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + + env = TenkiEnvironment(task_id="persist", image="base-image", persistent_filesystem=True) + + assert _FakeSandboxFactory.created_kwargs[0]["image"] == "base-image" + assert tenki_module._get_snapshot_restore_candidate("persist") == (None, False) + env.cleanup() + + +def test_tenki_snapshot_store_bound_to_construction_profile(monkeypatch, tmp_path): + """Cleanup (which may run in a background thread without the per-turn + HERMES_HOME contextvar) must write the snapshot pointer to the profile that + was active at construction, not whatever home is ambient at cleanup time.""" + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + + from tools.environments import tenki as tenki_module + from tools.environments.tenki import TenkiEnvironment + + home_a = tmp_path / "profiles" / "a" + home_b = tmp_path / "profiles" / "b" + home_a.mkdir(parents=True) + home_b.mkdir(parents=True) + + monkeypatch.setenv("HERMES_HOME", str(home_a)) + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + env = TenkiEnvironment(task_id="persist", persistent_filesystem=True) + + # Simulate a background cleanup running under the WRONG ambient home. + monkeypatch.setenv("HERMES_HOME", str(home_b)) + env.cleanup() + + # Pointer landed in profile A's store (construction-time), not B's. + assert (home_a / "tenki_snapshots.json").exists() + assert not (home_b / "tenki_snapshots.json").exists() + + +def test_tenki_persistent_not_terminated_when_snapshot_and_pause_both_fail(monkeypatch, tmp_path): + """Durability failed AND pause failed: the sandbox must be left live (not + terminated), so the only copy of un-snapshotted state is preserved.""" + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + + def _fail_durable(*_args, **_kwargs): + raise RuntimeError("not durable") + + def _init(self, **kw): + self.kwargs = kw + self.snapshots = SimpleNamespace(wait_durable=_fail_durable) + + monkeypatch.setattr(_FakeClient, "__init__", _init) + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + env = TenkiEnvironment(task_id="persist", persistent_filesystem=True) + sandbox = _FakeSandboxFactory.sandboxes[0] + + def _fail_pause(): + raise RuntimeError("pause unavailable") + + sandbox.pause = _fail_pause + + env.cleanup() + + # Neither snapshot durable nor pause succeeded → sandbox left live. + assert sandbox.terminated is False + + +def test_tenki_environment_resumes_paused_cached_sandbox_before_execute(monkeypatch, tmp_path): + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + env = TenkiEnvironment(task_id="paused-cache") + sandbox = env._sandbox + sandbox.state = "PAUSED" + + env.execute("echo ok", timeout=5) + + assert sandbox.refreshed is True + assert sandbox.resumed is True + assert sandbox.waited is True + assert env._sandbox is sandbox + env.cleanup() + + +def test_tenki_environment_recreates_terminated_cached_sandbox(monkeypatch, tmp_path): + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + env = TenkiEnvironment(task_id="terminated-cache") + first = env._sandbox + first.state = "TERMINATED" + + env.execute("echo ok", timeout=5) + + assert len(_FakeSandboxFactory.sandboxes) == 2 + assert env._sandbox is _FakeSandboxFactory.sandboxes[1] + assert env._sandbox is not first env.cleanup() @@ -259,7 +978,7 @@ def test_tenki_environment_ignores_mismatched_persistent_sandbox(monkeypatch, tm env = TenkiEnvironment(task_id="persist", persistent_filesystem=True) assert _FakeSandboxFactory.created_kwargs - assert _FakeSandboxFactory.created_kwargs[0]["name"] == "hermes-persist" + assert _FakeSandboxFactory.created_kwargs[0]["name"].endswith("persist") env.cleanup() @@ -356,6 +1075,156 @@ def sync_back(self): assert ("sync_back", None) in calls +def test_tenki_bulk_sync_stages_tar_under_home_not_tmp(monkeypatch, tmp_path): + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + env = TenkiEnvironment(task_id="bulk-sync") + host_file = tmp_path / "skill.md" + host_file.write_text("content", encoding="utf-8") + + env._tenki_bulk_upload([(str(host_file), "/home/tenki/.hermes/skills/skill.md")]) + + remote_tar = env._sandbox.fs.upload_calls[-1][1] + assert remote_tar.startswith("/home/tenki/.hermes_tenki_sync.") + assert not remote_tar.startswith("/tmp/") + env.cleanup() + + +def test_tenki_bulk_sync_uses_documented_fs_root_when_home_differs(monkeypatch, tmp_path): + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + env = TenkiEnvironment(task_id="root-home") + env._remote_home = "/root" + + assert env._remote_transfer_path(".hermes_tenki_sync").startswith("/home/tenki/") + env.cleanup() + + +def test_tenki_cleanup_sync_back_uses_original_sandbox(monkeypatch, tmp_path): + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + env = TenkiEnvironment(task_id="cleanup-sync") + original = env._sandbox + created_before = len(_FakeSandboxFactory.created_kwargs) + + class FakeSyncManager: + def sync_back(self): + env._tenki_bulk_download(tmp_path / "sync-back.tar") + + env._sync_manager = FakeSyncManager() + env.cleanup() + + assert len(_FakeSandboxFactory.created_kwargs) == created_before + assert original.fs.download_calls + remote_tar = original.fs.download_calls[-1][0] + assert remote_tar.startswith("/home/tenki/.hermes_tenki_sync_back.") + assert original.terminated is True + + +def test_tenki_cleanup_blocks_public_execution_while_syncing(monkeypatch, tmp_path): + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + env = TenkiEnvironment(task_id="cleanup-guard") + created_before = len(_FakeSandboxFactory.created_kwargs) + + with env._lock: + env._cleanup_in_progress = True + env._cleanup_sandbox = env._sandbox + try: + try: + env.execute("echo should-not-run", timeout=5) + except RuntimeError as exc: + assert "cleanup" in str(exc) + else: + raise AssertionError("execute should fail while cleanup is in progress") + assert len(_FakeSandboxFactory.created_kwargs) == created_before + finally: + with env._lock: + env._cleanup_in_progress = False + env._cleanup_sandbox = None + env.cleanup() + + +def test_tenki_execute_passes_stdin_natively_not_as_heredoc(monkeypatch, tmp_path): + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + env = TenkiEnvironment(task_id="stdin") + large_stdin = "x" * 200_000 + + env.execute("cat > /home/tenki/out.txt", stdin_data=large_stdin, timeout=5) + + sandbox = env._sandbox + command = _last_started_command(sandbox) + assert large_stdin not in command + assert "HERMES_STDIN_" not in command + assert sandbox.start_calls[-1][1]["stdin"] == large_stdin + assert "TENKI_AUTH_TOKEN" not in sandbox.start_calls[-1][1]["env"] + env.cleanup() + + +def test_tenki_cancel_kills_process_without_tearing_down_sandbox(monkeypatch, tmp_path): + _install_fake_tenki(monkeypatch) + _clear_tenki_auth_env(monkeypatch) + monkeypatch.setattr("tools.lazy_deps.ensure", lambda *_args, **_kwargs: None) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "config.yaml")) + (tmp_path / "config.yaml").write_text("auth_token: tok-secret\n", encoding="utf-8") + + from tools.environments.tenki import TenkiEnvironment + + monkeypatch.setattr(TenkiEnvironment, "init_session", lambda self: None) + env = TenkiEnvironment(task_id="cancel-process") + sandbox = env._sandbox + handle = env._run_bash("sleep infinity", timeout=30) + for _ in range(100): + if sandbox.last_process is not None: + break + time.sleep(0.01) + + handle.kill() + handle.wait(timeout=1) + + assert sandbox.last_process is not None + assert sandbox.last_process.killed is True + assert sandbox.terminated is False + assert sandbox.paused is False + env.cleanup() + + def test_tenki_non_sudo_command_does_not_probe_sudo(monkeypatch, tmp_path): _install_fake_tenki(monkeypatch) _clear_tenki_auth_env(monkeypatch) @@ -399,7 +1268,7 @@ def fail_prompt(*_args, **_kwargs): env = TenkiEnvironment(task_id="sudo-nopasswd") env.execute("sudo whoami", timeout=5) - command = _FakeSandboxFactory.sandboxes[0].exec_calls[-1][0][-1] + command = _last_started_command(_FakeSandboxFactory.sandboxes[0]) assert "sudo whoami" in command assert "sudo -S" not in command assert "sudo -n whoami" not in command @@ -428,7 +1297,7 @@ def fail_prompt(*_args, **_kwargs): env = TenkiEnvironment(task_id="sudo-no-nopasswd") env.execute("sudo whoami", timeout=5) - command = _FakeSandboxFactory.sandboxes[0].exec_calls[-1][0][-1] + command = _last_started_command(_FakeSandboxFactory.sandboxes[0]) assert "sudo -n whoami" in command assert "sudo -S" not in command assert "host-secret" not in command diff --git a/tests/tools/test_terminal_config_env_sync.py b/tests/tools/test_terminal_config_env_sync.py index da63e83af3e69..94bb361709fb9 100644 --- a/tests/tools/test_terminal_config_env_sync.py +++ b/tests/tools/test_terminal_config_env_sync.py @@ -254,6 +254,59 @@ def test_docker_extra_args_is_bridged_everywhere(): assert "TERMINAL_DOCKER_EXTRA_ARGS" in _terminal_tool_env_var_names() +def test_tenki_config_backend_defaults_to_terminate_only(monkeypatch, tmp_path): + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + + from hermes_cli import config as hc_config + + hc_config._LOAD_CONFIG_CACHE.clear() + (tmp_path / "config.yaml").write_text("terminal:\n backend: tenki\n", encoding="utf-8") + + cfg = hc_config.load_config() + assert cfg["terminal"]["container_persistent"] is False + + env = {} + hc_config.apply_terminal_config_to_env(env=env, config=cfg) + assert env["TERMINAL_CONTAINER_PERSISTENT"] == "False" + + hc_config._LOAD_CONFIG_CACHE.clear() + (tmp_path / "config.yaml").write_text( + "terminal:\n backend: tenki\n container_persistent: true\n", + encoding="utf-8", + ) + + cfg = hc_config.load_config() + assert cfg["terminal"]["container_persistent"] is True + + +def test_tenki_managed_persistence_survives_env_bridge(monkeypatch, tmp_path): + home = tmp_path / "home" + managed = tmp_path / "managed" + home.mkdir() + managed.mkdir() + monkeypatch.setenv("HERMES_HOME", str(home)) + monkeypatch.setenv("HERMES_MANAGED_DIR", str(managed)) + + from hermes_cli import config as hc_config + from hermes_cli import managed_scope + + hc_config._LOAD_CONFIG_CACHE.clear() + hc_config._RAW_CONFIG_CACHE.clear() + managed_scope.invalidate_managed_cache() + (home / "config.yaml").write_text("terminal:\n backend: tenki\n", encoding="utf-8") + (managed / "config.yaml").write_text( + "terminal:\n container_persistent: true\n", + encoding="utf-8", + ) + + cfg = hc_config.load_config() + assert cfg["terminal"]["container_persistent"] is True + + env = {"TERMINAL_CONTAINER_PERSISTENT": "false"} + hc_config.apply_terminal_config_to_env(env=env, config=cfg, override=True) + assert env["TERMINAL_CONTAINER_PERSISTENT"] == "True" + + def test_docker_persist_across_processes_is_bridged_everywhere(): """Regression pin for the cross-process container reuse toggle. @@ -338,6 +391,7 @@ def test_tenki_config_is_bridged_everywhere(): "tenki_idle_timeout": "TERMINAL_TENKI_IDLE_TIMEOUT", "tenki_pause_retention": "TERMINAL_TENKI_PAUSE_RETENTION", "tenki_sync_hermes_home": "TERMINAL_TENKI_SYNC_HERMES_HOME", + "tenki_forward_env": "TERMINAL_TENKI_FORWARD_ENV", } for key, env_var in tenki_keys.items(): assert key in _cli_env_map_keys() diff --git a/tests/tools/test_terminal_tool_requirements.py b/tests/tools/test_terminal_tool_requirements.py index 4608fe868aece..c1a56765069e4 100644 --- a/tests/tools/test_terminal_tool_requirements.py +++ b/tests/tools/test_terminal_tool_requirements.py @@ -65,6 +65,35 @@ def test_terminal_and_execute_code_tools_resolve_for_managed_modal(self, monkeyp assert "terminal" in names assert "execute_code" in names + def test_tenki_requires_auth_only_for_plain_sessions(self, monkeypatch, tmp_path): + original_find_spec = terminal_tool_module.importlib.util.find_spec + + def fake_find_spec(name): + if name == "tenki_sandbox": + return object() + return original_find_spec(name) + + monkeypatch.setattr(terminal_tool_module.importlib.util, "find_spec", fake_find_spec) + monkeypatch.setenv("TENKI_CONFIG_PATH", str(tmp_path / "missing.yaml")) + monkeypatch.delenv("TENKI_WORKSPACE_ID", raising=False) + monkeypatch.delenv("TENKI_WORKSPACE", raising=False) + monkeypatch.delenv("TENKI_PROJECT_ID", raising=False) + monkeypatch.delenv("TENKI_PROJECT", raising=False) + monkeypatch.setattr( + terminal_tool_module, + "_get_env_config", + lambda: { + "env_type": "tenki", + "tenki_workspace_id": "", + "tenki_project_id": "", + }, + ) + + assert terminal_tool_module.check_terminal_requirements() is False + + monkeypatch.setenv("TENKI_AUTH_TOKEN", "tok") + assert terminal_tool_module.check_terminal_requirements() is True + class TestCheckFnTransientFailureSuppression: """The check_fn TTL cache should absorb transient probe failures. diff --git a/tools/approval.py b/tools/approval.py index 53519b5c04808..7545353fd01ff 100644 --- a/tools/approval.py +++ b/tools/approval.py @@ -11,11 +11,13 @@ import contextvars import fnmatch import functools +import hashlib import logging import os import re import shlex import sys +import tempfile import threading import time import unicodedata @@ -118,6 +120,53 @@ def _fire_approval_hook(hook_name: str, **kwargs) -> None: logger.debug("Approval hook %s dispatch failed: %s", hook_name, exc) +def _prepare_smart_approval_observer( + *, + command: str, + description: str, + pattern_key: str, + pattern_keys: list[str], + session_key: str, +) -> dict | None: + """Redact and emit the pre-decision smart approval observer hook. + + Redaction is part of observer payload preparation, not approval policy. If + it fails, skip all observability rather than leaking raw data or preventing + the auxiliary LLM from making its decision. + """ + try: + from agent.redact import redact_sensitive_text + + hook_command = redact_sensitive_text(command, force=True) + hook_description = redact_sensitive_text(description, force=True) + except Exception as exc: + logger.debug("Smart approval hook redaction failed: %s", exc) + return + + payload = { + "command": hook_command, + "description": hook_description, + "pattern_key": pattern_key, + "pattern_keys": list(pattern_keys), + "session_key": session_key, + "surface": "smart", + } + _fire_approval_hook("pre_approval_request", **payload) + return payload + + +def _observe_smart_approval_verdict(payload: dict | None, verdict: str) -> None: + """Emit a smart verdict after the auxiliary LLM decision, if safe.""" + if payload is None or verdict not in {"approve", "deny"}: + return + _fire_approval_hook( + "post_approval_response", + **payload, + choice=f"smart_{verdict}", + decided_by="aux_llm", + ) + + def set_current_session_key(session_key: str) -> contextvars.Token[str]: """Bind the active approval session key to the current context.""" @@ -293,7 +342,7 @@ def _is_gateway_approval_context() -> bool: # # Hardline only applies to environments that can actually damage the host # (local, ssh, container-host cron). Containerized backends (docker, -# singularity, modal, daytona) already bypass the dangerous-command layer +# singularity, modal, daytona, tenki) already bypass the dangerous-command layer # because nothing they do can touch the host, so we leave that behavior # alone. # @@ -370,15 +419,16 @@ def _hardline_rm_path(path_alt: str, tail: str = r'(?:\s|$|[)`;|&])') -> str: # # The path token matches any root-anchored path whose components collapse # back to "/" in the shell: a bare "/", repeated slashes ("//"), and - # "."/".." current/parent segments ("/.", "/./", "/..") all resolve to - # root, optionally followed by a trailing glob ("/*", "//*"). The earlier - # "/|/\*|/ \*" form only caught the literal "/" / "/*" spellings, so - # `rm -rf //`, `rm -rf /.`, `rm -rf /./`, `rm -rf /..` and `rm -rf //*` - # silently slipped the hardline floor and executed under --yolo / - # approvals.mode=off / cron approve-mode. A trailing real segment - # (e.g. "/tmp", "/home", "/.ssh") still fails to match here and stays - # with the softer DANGEROUS_PATTERNS / system-directory rules. - (_RM_FLAG_PREFIX + _hardline_rm_path(r'/[/.]*\**'), "recursive delete of root filesystem"), + # "."/".." current/parent segments ("/.", "/./", "/..", "/../..") all + # resolve to root, optionally followed by a trailing glob ("/*", "//*"). + # Each inter-slash segment must be exactly "." or "..", so a longer dot + # run or any real name is a literal directory, NOT root — "/tmp", "/home", + # "/.ssh", "/.config" and even "/..." (a dir literally named "...") fall + # through to the softer DANGEROUS_PATTERNS / system-directory rules + # instead of being unconditionally hardline-blocked. The explicit "/ \*" + # alt preserves the slash-space-glob spelling (`rm -rf / *`, which the + # shell sees as 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"), # Filesystem format @@ -461,6 +511,53 @@ def detect_hardline_command(command: str) -> tuple: return (False, None) +def _match_user_deny_rule(command: str) -> str | None: + """Return the matching ``approvals.deny`` glob, or None. + + ``approvals.deny`` in config.yaml is a user-defined list of fnmatch + globs that block a command unconditionally — like the hardline floor, + a deny match fires BEFORE the yolo / mode=off bypass. It is the + user-editable counterpart to the code-shipped hardline blocklist: + "never let the agent run this, even under yolo". + + Matching is case-insensitive and runs over the same normalized / + deobfuscated command variants the dangerous-pattern detector uses, so + quoting tricks (``r\\m``, ``git st""atus``) can't sidestep a rule any + more easily than they sidestep detection. Empty/absent list = no-op. + """ + try: + deny_patterns = _get_approval_config().get("deny") or [] + except Exception: + return None + if not deny_patterns: + return None + globs = [p.strip() for p in deny_patterns + if isinstance(p, str) and p.strip()] + if not globs: + return None + for command_variant in _command_detection_variants(command): + candidate = command_variant.lower().strip() + for pattern in globs: + if fnmatch.fnmatchcase(candidate, pattern.lower()): + return pattern + return None + + +def _user_deny_block_result(pattern: str) -> dict: + """Build the standard block result for an ``approvals.deny`` match.""" + return { + "approved": False, + "user_deny": True, + "message": ( + f"BLOCKED: this command matches the user-defined deny rule " + f"'{pattern}' (approvals.deny in config.yaml). It cannot be " + "executed via the agent — not even with --yolo, /yolo, or " + "approvals.mode=off. Do NOT retry or rephrase this command; " + "the user has explicitly forbidden it." + ), + } + + def _hardline_block_result(description: str) -> dict: """Build the standard block result for a hardline match.""" return { @@ -1334,12 +1431,36 @@ def _command_detection_variants(command: str): 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) + if operand != os.path.join(temp_dir, basename): + return False + + target = os.path.realpath(operand) + if os.path.dirname(target) != temp_dir: + return False + return re.fullmatch(r"hermes-(?:verify|ad-hoc)-[A-Za-z0-9_.-]+", basename) is not None + + def detect_dangerous_command(command: str) -> tuple: """Check if a command matches any dangerous patterns. Returns: (is_dangerous, pattern_key, description) or (False, None, None) """ + 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: @@ -1370,12 +1491,16 @@ def detect_dangerous_command(command: str) -> tuple: class _ApprovalEntry: """One pending dangerous-command approval inside a gateway session.""" - __slots__ = ("event", "data", "result") + __slots__ = ("event", "data", "result", "reason") def __init__(self, data: dict): self.event = threading.Event() self.data = data # command, description, pattern_keys, … self.result: Optional[str] = None # "once"|"session"|"always"|"deny" + # Optional free-text reason supplied with an explicit deny + # (``/deny ``) so the agent can adapt instead of only + # hearing "denied". Ported from qwibitai/nanoclaw#2832. + self.reason: Optional[str] = None _gateway_queues: dict[str, list] = {} # session_key → [_ApprovalEntry, …] @@ -1408,7 +1533,8 @@ def unregister_gateway_notify(session_key: str) -> None: def resolve_gateway_approval(session_key: str, choice: str, - resolve_all: bool = False) -> int: + resolve_all: bool = False, + reason: Optional[str] = None) -> int: """Called by the gateway's /approve or /deny handler to unblock waiting agent thread(s). @@ -1416,6 +1542,10 @@ def resolve_gateway_approval(session_key: str, choice: str, resolved at once (``/approve all``). Otherwise only the oldest one is resolved (FIFO). + *reason* is an optional free-text explanation attached to an explicit + deny (``/deny ``). It is relayed back to the agent in the + BLOCKED message so it can adapt instead of only hearing "denied". + Returns the number of approvals resolved (0 means nothing was pending). """ with _lock: @@ -1432,6 +1562,8 @@ def resolve_gateway_approval(session_key: str, choice: str, for entry in targets: entry.result = choice + if reason: + entry.reason = reason entry.event.set() return len(targets) @@ -1603,16 +1735,21 @@ def save_permanent_allowlist(patterns: set): def prompt_dangerous_approval(command: str, description: str, timeout_seconds: int | None = None, allow_permanent: bool = True, - approval_callback=None) -> str: + approval_callback=None, + *, smart_denied: bool = False) -> str: """Prompt the user to approve a dangerous command (CLI only). Args: allow_permanent: When False, hide the [a]lways option (used when tirith warnings are present, since broad permanent allowlisting is inappropriate for content-level security findings). + smart_denied: When True, this is an owner override of a Smart DENY. + Offer only one-operation approval or denial. approval_callback: Optional callback registered by the CLI for prompt_toolkit integration. Signature: - (command, description, *, allow_permanent=True) -> str. + (command, description, *, allow_permanent=True, + smart_denied=False) -> str. Legacy callback signatures remain + supported when ``smart_denied`` is false. Returns: 'once', 'session', 'always', or 'deny' """ @@ -1629,8 +1766,12 @@ def prompt_dangerous_approval(command: str, description: str, if approval_callback is not None: try: - return approval_callback(display_command, display_description, - allow_permanent=allow_permanent) + callback_kwargs = {"allow_permanent": allow_permanent} + if smart_denied: + callback_kwargs["smart_denied"] = True + return approval_callback( + display_command, display_description, **callback_kwargs + ) except Exception as e: logger.error("Approval callback failed: %s", e, exc_info=True) return "deny" @@ -1672,7 +1813,9 @@ def prompt_dangerous_approval(command: str, description: str, print(f" {t('approval.dangerous_header', description=display_description)}") print(f" {display_command}") print() - if allow_permanent: + if smart_denied: + print(t("approval.choose_smart_deny")) + elif allow_permanent: print(t("approval.choose_long")) else: print(t("approval.choose_short")) @@ -1683,7 +1826,10 @@ def prompt_dangerous_approval(command: str, description: str, def get_input(): try: - prompt = t("approval.prompt_long") if allow_permanent else t("approval.prompt_short") + if smart_denied: + prompt = t("approval.prompt_smart_deny") + else: + prompt = t("approval.prompt_long") if allow_permanent else t("approval.prompt_short") result["choice"] = input(prompt).strip().lower() except (EOFError, OSError): result["choice"] = "" @@ -1697,6 +1843,21 @@ def get_input(): return "deny" choice = result["choice"] + if smart_denied: + choice_map = { + **{ + value: "once" + for value in t("approval.smart_deny_once_inputs").split(",") + }, + **{ + value: "deny" + for value in t("approval.smart_deny_deny_inputs").split(",") + }, + } + decision = choice_map.get(choice, "deny") + print(t("approval.allowed_once" if decision == "once" else "approval.denied")) + return decision + if choice in {'o', 'once'}: print(t("approval.allowed_once")) return "once" @@ -1936,6 +2097,224 @@ def _smart_approve(command: str, description: str) -> str: return "escalate" +def _run_approval_gate( + *, + pattern_key: str, + description: str, + display_target: str, + approval_callback=None, + cron_deny_message: str, + autoapprove_log_prefix: str, + fail_closed_when_no_human: bool = False, + no_human_block_message: str = "", +) -> dict: + """Shared human-approval gate for a flagged action (command or tool). + + This is the single decision core reused by both + :func:`check_dangerous_command` (dangerous shell patterns) and + :func:`request_tool_approval` (plugin ``pre_tool_call`` ``approve`` + escalations). Extracting it keeps the fail-closed / cron / gateway / + persist policy in ONE place so the two entry points can never drift. + + Ordering mirrors the historical ``check_dangerous_command`` tail: + yolo bypass → session-cache short-circuit → interactive/gateway/cron + branch → prompt → ``deny/session/always`` persistence. The caller is + responsible for the checks that are specific to its input shape + (hardline detection, command-string permanent allowlist, dangerous- + pattern detection) BEFORE calling this gate. + + Args: + pattern_key: Allowlist/session key this decision is stored under. + description: Human-facing reason shown in the prompt. + display_target: The command string or synthetic tool label shown + to the user (redacted by ``prompt_dangerous_approval``). + approval_callback: Optional CLI prompt callback. When ``None`` the + per-thread callback registered via + ``tools.terminal_tool.set_approval_callback`` is used. + cron_deny_message: Message returned when a cron job hits this gate + under ``cron_mode: deny``. + autoapprove_log_prefix: Log line prefix for the non-interactive + auto-approve warning (identifies command vs plugin origin). + fail_closed_when_no_human: When True, a non-interactive non-gateway + context that is NOT a cron session (e.g. a bare script with + HERMES_INTERACTIVE unset) BLOCKS instead of auto-approving. The + dangerous-command path keeps its historical fail-open default + (False); the plugin-escalation path opts in to fail-closed so a + plugin-flagged action never runs ungated without a human. + no_human_block_message: Message returned when + ``fail_closed_when_no_human`` blocks. + + Returns: + ``{"approved": bool, "message": str|None, ...}`` — shape shared with + ``check_dangerous_command`` so all callers handle it uniformly. + """ + # --yolo bypasses all approval prompts (session- or process-scoped). + # Hardline blocks are handled by the caller BEFORE this gate, so yolo + # here only skips the recoverable approval layer. + if _YOLO_MODE_FROZEN or is_current_session_yolo_enabled(): + return {"approved": True, "message": None} + + session_key = get_current_session_key() + if is_approved(session_key, pattern_key): + return {"approved": True, "message": None} + + if approval_callback is None: + try: + from tools.terminal_tool import _get_approval_callback + approval_callback = _get_approval_callback() + except Exception: + approval_callback = None + + is_cli = _is_interactive_cli() + is_gateway = _is_gateway_approval_context() + + if not is_cli and not is_gateway: + # Cron sessions: respect cron_mode config + if env_var_enabled("HERMES_CRON_SESSION"): + if _get_cron_approval_mode() == "deny": + return { + "approved": False, + "message": cron_deny_message, + "pattern_key": pattern_key, + "description": description, + } + # cron_mode: approve — fall through to auto-approve below. + elif fail_closed_when_no_human: + # Non-cron, non-interactive, no gateway: no human can answer. + # The plugin-escalation path opts in to fail-closed here so a + # plugin-flagged action never runs ungated. (The dangerous- + # command path keeps the historical fail-open default.) + logger.warning( + "%s (pattern: %s): %s — no interactive user/gateway present; " + "BLOCKED (fail-closed). Set HERMES_INTERACTIVE or " + "HERMES_GATEWAY_SESSION to answer the prompt.", + autoapprove_log_prefix, pattern_key, description, + ) + return { + "approved": False, + "message": no_human_block_message or ( + f"BLOCKED: approval required ({description}) but no " + "interactive user or gateway is present to approve it." + ), + "pattern_key": pattern_key, + "description": description, + } + logger.warning( + "%s (pattern: %s): %s — set HERMES_INTERACTIVE or " + "HERMES_GATEWAY_SESSION to require approval.", + autoapprove_log_prefix, pattern_key, description, + ) + return {"approved": True, "message": None} + + if is_gateway or env_var_enabled("HERMES_EXEC_ASK"): + # Interactive gateway round-trip when a notify callback is + # registered for this session (Discord/Telegram/Slack embed + + # buttons, same mechanism as check_dangerous_command). Blocks the + # agent thread until the user answers; the agent never sees + # "approval_required" on this path — it gets a definitive + # approved/BLOCKED outcome. + notify_cb = None + with _lock: + notify_cb = _gateway_notify_cbs.get(session_key) + + if notify_cb is not None: + from agent.redact import redact_sensitive_text + approval_data = { + "command": redact_sensitive_text(display_target), + "pattern_key": pattern_key, + "pattern_keys": [pattern_key], + "description": redact_sensitive_text(description), + "allow_permanent": True, + } + decision = _await_gateway_decision( + session_key, notify_cb, approval_data, surface="gateway" + ) + if decision.get("notify_failed"): + return { + "approved": False, + "message": "BLOCKED: Failed to send approval request to user. Do NOT retry.", + "pattern_key": pattern_key, + "description": description, + } + resolved = decision["resolved"] + choice = decision["choice"] + deny_reason = decision.get("reason") + + if not resolved or choice is None or choice == "deny": + if not resolved: + reason = "timed out without user response" + timeout_addendum = " Silence is not consent." + else: + reason = "denied by user" + timeout_addendum = "" + reason_addendum = "" + if resolved and deny_reason: + reason_addendum = f' Reason given by the user: "{deny_reason}".' + return { + "approved": False, + "message": ( + f"BLOCKED: Action {reason}.{reason_addendum} The user " + f"has NOT consented to this action. Do NOT retry it, " + f"do NOT rephrase it, and do NOT attempt the same " + f"outcome via a different path.{timeout_addendum}" + ), + "pattern_key": pattern_key, + "description": description, + "user_consent": False, + } + + if choice == "session": + approve_session(session_key, pattern_key) + elif choice == "always": + approve_session(session_key, pattern_key) + approve_permanent(pattern_key) + save_permanent_allowlist(_permanent_approved) + return {"approved": True, "message": None} + + # No notify callback (e.g. API server without an attached chat): + # queue for /approve /deny review, agent sees approval_required. + submit_pending(session_key, { + "command": display_target, + "pattern_key": pattern_key, + "description": description, + }) + return { + "approved": False, + "pattern_key": pattern_key, + "status": "approval_required", + "command": display_target, + "description": description, + "message": ( + f"⚠️ This action is potentially dangerous ({description}). " + f"Asking the user for approval.\n\n**Target:**\n```\n{display_target}\n```" + ), + } + + choice = prompt_dangerous_approval(display_target, description, + approval_callback=approval_callback) + + if choice == "deny": + return { + "approved": False, + "message": ( + f"BLOCKED: User denied this potentially dangerous action " + f"(matched '{description}'). Do NOT retry — the user has " + "explicitly rejected it." + ), + "pattern_key": pattern_key, + "description": description, + } + + if choice == "session": + approve_session(session_key, pattern_key) + elif choice == "always": + approve_session(session_key, pattern_key) + approve_permanent(pattern_key) + save_permanent_allowlist(_permanent_approved) + + return {"approved": True, "message": None} + + def _should_skip_container_guards(env_type: str, has_host_access: bool = False) -> bool: """Return True when the backend is isolated enough to skip dangerous-command prompts. @@ -1947,7 +2326,7 @@ def _should_skip_container_guards(env_type: str, has_host_access: bool = False) """ if env_type == "docker": return not has_host_access - return env_type in ("singularity", "modal", "daytona") + return env_type in ("singularity", "modal", "daytona", "tenki") def check_dangerous_command(command: str, env_type: str, @@ -1981,6 +2360,15 @@ def check_dangerous_command(command: str, env_type: str, logger.warning("Hardline block: %s (command: %s)", hardline_desc, command[:200]) return _hardline_block_result(hardline_desc) + # User-defined deny rules (approvals.deny in config.yaml): like the + # hardline floor, these fire BEFORE the yolo bypass — a deny rule is the + # user saying "never, even under yolo". + deny_pattern = _match_user_deny_rule(command) + if deny_pattern is not None: + logger.warning("User deny rule %r blocked command: %s", + deny_pattern, command[:200]) + return _user_deny_block_result(deny_pattern) + # --yolo: bypass all approval prompts. Gateway /yolo is session-scoped; # CLI --yolo remains process-scoped via the env var for local use. if _YOLO_MODE_FROZEN or is_current_session_yolo_enabled(): @@ -1993,71 +2381,109 @@ def check_dangerous_command(command: str, env_type: str, if not is_dangerous: return {"approved": True, "message": None} - session_key = get_current_session_key() - if is_approved(session_key, pattern_key): - return {"approved": True, "message": None} - - is_cli = _is_interactive_cli() - is_gateway = _is_gateway_approval_context() - - if not is_cli and not is_gateway: - # Cron sessions: respect cron_mode config - if env_var_enabled("HERMES_CRON_SESSION"): - if _get_cron_approval_mode() == "deny": - return { - "approved": False, - "message": ( - f"BLOCKED: Command flagged as dangerous ({description}) " - "but cron jobs run without a user present to approve it. " - "Find an alternative approach that avoids this command. " - "To allow dangerous commands in cron jobs, set " - "approvals.cron_mode: approve in config.yaml." - ), - } - logger.warning( - "AUTO-APPROVED dangerous command in non-interactive non-gateway context " - "(pattern: %s): %s — set HERMES_INTERACTIVE or HERMES_GATEWAY_SESSION to require approval.", - description, command[:200], - ) - return {"approved": True, "message": None} - - if is_gateway or env_var_enabled("HERMES_EXEC_ASK"): - submit_pending(session_key, { - "command": command, - "pattern_key": pattern_key, - "description": description, - }) - return { - "approved": False, - "pattern_key": pattern_key, - "status": "approval_required", - "command": command, - "description": description, - "message": ( - f"⚠️ This command is potentially dangerous ({description}). " - f"Asking the user for approval.\n\n**Command:**\n```\n{command}\n```" - ), - } + return _run_approval_gate( + pattern_key=pattern_key, + description=description, + display_target=command, + approval_callback=approval_callback, + cron_deny_message=( + f"BLOCKED: Command flagged as dangerous ({description}) " + "but cron jobs run without a user present to approve it. " + "Find an alternative approach that avoids this command. " + "To allow dangerous commands in cron jobs, set " + "approvals.cron_mode: approve in config.yaml." + ), + autoapprove_log_prefix=( + "AUTO-APPROVED dangerous command in non-interactive non-gateway context" + ), + ) - choice = prompt_dangerous_approval(command, description, - approval_callback=approval_callback) - if choice == "deny": - return { - "approved": False, - "message": f"BLOCKED: User denied this potentially dangerous command (matched '{description}' pattern). Do NOT retry this command - the user has explicitly rejected it.", - "pattern_key": pattern_key, - "description": description, - } +def request_tool_approval( + tool_name: str, + reason: str, + *, + rule_key: str = "", + approval_callback=None, +) -> dict: + """Escalate an arbitrary tool call to the human-approval gate. + + This is the entry point for a plugin ``pre_tool_call`` hook that returns + ``{"action": "approve", "message": ...}``: instead of the plugin vetoing + the call (``action: block``) or silently allowing it, it asks the SAME + human gate that Tier-2 dangerous shell patterns use. The LLM cannot skip + or bypass this — the tool call is intercepted before execution. + + It reuses the existing approval primitives (session/permanent allowlist, + ``prompt_dangerous_approval`` for CLI, ``submit_pending`` for the gateway + callback, ``[o]nce/[s]ession/[a]lways/[d]eny``, timeout fail-closed) so + behavior is identical to a dangerous-command match — only the trigger + (a plugin rule on any tool) differs. - if choice == "session": - approve_session(session_key, pattern_key) - elif choice == "always": - approve_session(session_key, pattern_key) - approve_permanent(pattern_key) - save_permanent_allowlist(_permanent_approved) + Args: + tool_name: The tool being gated (e.g. ``"write_file"``, ``"terminal"``). + reason: Human-facing message from the plugin explaining why approval + is needed (rendered in the prompt). + rule_key: Optional stable identifier the plugin can supply to control + the ``[a]lways`` allowlist grain. When empty, the key is derived + from ``tool_name`` + a hash of ``reason`` so that DISTINCT reasons + on the same tool persist independently (answering ``[a]lways`` to + "write to ~/.ssh" does NOT auto-approve a later "send email" rule + on the same tool). + approval_callback: Optional CLI callback for interactive prompts + (same contract as ``check_dangerous_command``). - return {"approved": True, "message": None} + Returns: + ``{"approved": True, "message": None}`` when allowed, or + ``{"approved": False, "message": , ...}`` when denied / + blocked. Shape matches ``check_dangerous_command`` so callers handle + both paths identically. + + Non-interactive contexts: cron jobs honor ``approvals.cron_mode`` (parity + with dangerous commands); any OTHER non-interactive non-gateway context + (a bare script with no ``HERMES_INTERACTIVE``) fails CLOSED — a plugin- + flagged action never runs ungated without a human. + """ + description = reason or f"Plugin requires approval for {tool_name}" + # Allowlist grain: an explicit plugin rule_key wins; otherwise derive from + # tool + a short hash of the reason so distinct reasons on the same tool + # get independent [a]lways entries (Finding: rule_key=tool_name alone was + # too coarse — one "always" would blanket every rule on that tool). + if rule_key: + key_suffix = rule_key + else: + _reason_hash = hashlib.sha256(description.encode("utf-8")).hexdigest()[:12] + key_suffix = f"{tool_name}:{_reason_hash}" + # Synthetic pattern key so plugin-rule approvals live in the same + # session/permanent allowlist machinery as command patterns, namespaced + # to avoid ever colliding with a real command pattern key. + pattern_key = f"plugin_rule:{key_suffix}" + # A synthetic "command" string for the display/allowlist layer. It never + # executes; it only labels the gate. Namespaced identically. + display_target = f"<{tool_name}> (plugin approval rule)" + + return _run_approval_gate( + pattern_key=pattern_key, + description=description, + display_target=display_target, + approval_callback=approval_callback, + cron_deny_message=( + f"BLOCKED: Tool '{tool_name}' requires approval ({description}) " + "but cron jobs run without a user present to approve it. Find an " + "alternative approach. To allow flagged actions in cron jobs, set " + "approvals.cron_mode: approve in config.yaml." + ), + autoapprove_log_prefix=( + f"plugin-escalated tool call '{tool_name}' in " + "non-interactive non-gateway context" + ), + fail_closed_when_no_human=True, + no_human_block_message=( + f"BLOCKED: Tool '{tool_name}' requires approval ({description}) " + "but no interactive user or gateway is present to approve it. " + "A plugin flagged this action for human confirmation." + ), + ) # ========================================================================= @@ -2143,15 +2569,12 @@ def _drop_entry() -> None: _drop_entry() return {"resolved": False, "choice": None, "notify_failed": True} - # Block until the user responds or timeout (default 5 min). Poll in short - # slices so we can fire activity heartbeats every ~10s to the agent's - # inactivity tracker — otherwise the gateway watchdog kills the agent - # while the user is still responding. Mirrors _wait_for_process() cadence. - timeout = _get_approval_config().get("gateway_timeout", 300) - try: - timeout = int(timeout) - except (ValueError, TypeError): - timeout = 300 + # Block until the user responds or the canonical approval timeout elapses + # (default 60s). Poll in short slices so we can fire activity heartbeats + # every ~10s to the agent's inactivity tracker — otherwise the gateway + # watchdog kills the agent while the user is still responding. Mirrors + # _wait_for_process() cadence. + timeout = _get_approval_timeout() try: from tools.environments.base import touch_activity_if_due @@ -2206,7 +2629,7 @@ def _drop_entry() -> None: surface=surface, choice=_outcome, ) - return {"resolved": resolved, "choice": choice} + return {"resolved": resolved, "choice": choice, "reason": entry.reason} def check_all_command_guards(command: str, env_type: str, @@ -2248,6 +2671,15 @@ def check_all_command_guards(command: str, env_type: str, sudo_guess_desc, command[:200]) return _sudo_stdin_block_result(sudo_guess_desc) + # User-defined deny rules (approvals.deny in config.yaml): like the + # hardline floor, these fire BEFORE the yolo / mode=off bypass — a deny + # rule is the user saying "never, even under yolo". + deny_pattern = _match_user_deny_rule(command) + if deny_pattern is not None: + logger.warning("User deny rule %r blocked command: %s", + deny_pattern, command[:200]) + return _user_deny_block_result(deny_pattern) + # --yolo or approvals.mode=off: bypass all approval prompts. # Gateway /yolo is session-scoped; CLI --yolo remains process-scoped. approval_mode = _get_approval_mode() @@ -2407,27 +2839,38 @@ def check_all_command_guards(command: str, env_type: str, # When approvals.mode=smart, ask the aux LLM before prompting the user. # Inspired by OpenAI Codex's Smart Approvals guardian subagent # (openai/codex#13860). + smart_denied_for_owner = False if approval_mode == "smart": combined_desc_for_llm = "; ".join(desc for _, desc, _ in warnings) + observer_payload = _prepare_smart_approval_observer( + command=command, + description=combined_desc_for_llm, + pattern_key=warnings[0][0], + pattern_keys=[key for key, _, _ in warnings], + session_key=session_key, + ) verdict = _smart_approve(command, combined_desc_for_llm) + _observe_smart_approval_verdict(observer_payload, verdict) if verdict == "approve": - # Auto-approve and grant session-level approval for these patterns - for key, _, _ in warnings: - approve_session(session_key, key) + # Approve this command only. Pattern-level persistence would let one + # benign command suppress review of later commands that happen to + # match the same broad detector category. logger.debug("Smart approval: auto-approved '%s' (%s)", command[:60], combined_desc_for_llm) return {"approved": True, "message": None, "smart_approved": True, "description": combined_desc_for_llm} - elif verdict == "deny": - combined_desc_for_llm = "; ".join(desc for _, desc, _ in warnings) + elif verdict == "deny" and not (is_cli or is_gateway or is_ask): return { "approved": False, "message": f"BLOCKED by smart approval: {combined_desc_for_llm}. " "The command was assessed as genuinely dangerous. Do NOT retry.", "smart_denied": True, } - # verdict == "escalate" → fall through to manual prompt + elif verdict == "deny": + smart_denied_for_owner = True + # An interactive owner may override DENY for this operation only. + # ESCALATE follows the normal, potentially persistent manual behavior. # --- Phase 3: Approval --- @@ -2464,10 +2907,12 @@ def check_all_command_guards(command: str, env_type: str, "pattern_key": primary_key, "pattern_keys": all_keys, "description": redact_sensitive_text(combined_desc), - # Mirror the CLI's allow_permanent gate: a tirith warning downgrades - # "always" to session scope below, so the UI must not offer it. - "allow_permanent": not has_tirith, + # Smart DENY overrides are one-operation decisions, so the UI + # must not offer a permanent scope. + "allow_permanent": not has_tirith and not smart_denied_for_owner, } + if smart_denied_for_owner: + approval_data["smart_denied"] = True decision = _await_gateway_decision( session_key, notify_cb, approval_data, surface="gateway" ) @@ -2480,6 +2925,7 @@ def check_all_command_guards(command: str, env_type: str, } resolved = decision["resolved"] choice = decision["choice"] + deny_reason = decision.get("reason") if not resolved or choice is None or choice == "deny": # Consent contract: silence is NOT consent, and an explicit @@ -2495,33 +2941,41 @@ def check_all_command_guards(command: str, env_type: str, reason = "denied by user" timeout_addendum = "" outcome = "denied" + # An explicit deny may carry a free-text reason + # (``/deny ``) so the agent can adapt rather than only + # hearing "denied". Relayed verbatim; generic attribution. + reason_addendum = "" + if outcome == "denied" and deny_reason: + reason_addendum = f' Reason given by the user: "{deny_reason}".' return { "approved": False, "message": ( - f"BLOCKED: Command {reason}. The user has NOT consented " - f"to this action. Do NOT retry this command, do NOT " - f"rephrase it, and do NOT attempt the same outcome via " - f"a different command. Stop the current workflow and " - f"wait for the user to respond before taking any " - f"further destructive or irreversible action." - f"{timeout_addendum}" + f"BLOCKED: Command {reason}.{reason_addendum} The user " + f"has NOT consented to this action. Do NOT retry this " + f"command, do NOT rephrase it, and do NOT attempt the " + f"same outcome via a different command. Stop the " + f"current workflow and wait for the user to respond " + f"before taking any further destructive or " + f"irreversible action.{timeout_addendum}" ), "pattern_key": primary_key, "description": combined_desc, "outcome": outcome, "user_consent": False, + "deny_reason": deny_reason, } - # User approved — persist based on scope (same logic as CLI) - for key, _, is_tirith in warnings: - if choice == "session" or (choice == "always" and is_tirith): - approve_session(session_key, key) - elif choice == "always": - approve_session(session_key, key) - approve_permanent(key) - save_permanent_allowlist(_permanent_approved) - # choice == "once": no persistence — command allowed this - # single time only, matching the CLI's behavior. + # A smart-DENY owner override is always one operation, even if an + # older client returns "session" or "always". Manual and ESCALATE + # choices retain their existing persistence semantics. + if not smart_denied_for_owner: + for key, _, is_tirith in warnings: + if choice == "session" or (choice == "always" and is_tirith): + approve_session(session_key, key) + elif choice == "always": + approve_session(session_key, key) + approve_permanent(key) + save_permanent_allowlist(_permanent_approved) return {"approved": True, "message": None, "user_approved": True, "description": combined_desc} @@ -2533,13 +2987,16 @@ def check_all_command_guards(command: str, env_type: str, from agent.redact import redact_sensitive_text _disp_command = redact_sensitive_text(command) _disp_combined_desc = redact_sensitive_text(combined_desc) - submit_pending(session_key, { + pending_data = { "command": _disp_command, "pattern_key": primary_key, "pattern_keys": all_keys, "description": _disp_combined_desc, - }) - return { + } + if smart_denied_for_owner: + pending_data.update(smart_denied=True, allow_permanent=False) + submit_pending(session_key, pending_data) + result = { "approved": False, "pattern_key": primary_key, "status": "pending_approval", @@ -2550,6 +3007,9 @@ def check_all_command_guards(command: str, env_type: str, f"⚠️ {_disp_combined_desc}. Asking the user for approval.\n\n**Command:**\n```\n{_disp_command}\n```" ), } + if smart_denied_for_owner: + result.update(smart_denied=True, allow_permanent=False) + return result # CLI interactive: single combined prompt # Hide [a]lways when any tirith warning is present @@ -2562,9 +3022,13 @@ def check_all_command_guards(command: str, env_type: str, session_key=session_key, surface="cli", ) - choice = prompt_dangerous_approval(command, combined_desc, - allow_permanent=not has_tirith, - approval_callback=approval_callback) + choice = prompt_dangerous_approval( + command, + combined_desc, + allow_permanent=not has_tirith and not smart_denied_for_owner, + smart_denied=smart_denied_for_owner, + approval_callback=approval_callback, + ) _fire_approval_hook( "post_approval_response", command=command, @@ -2593,16 +3057,18 @@ def check_all_command_guards(command: str, env_type: str, "user_consent": False, } - # Persist approval for each warning individually - for key, _, is_tirith in warnings: - if choice == "session" or (choice == "always" and is_tirith): - # tirith: session only (no permanent broad allowlisting) - approve_session(session_key, key) - elif choice == "always": - # dangerous patterns: permanent allowed - approve_session(session_key, key) - approve_permanent(key) - save_permanent_allowlist(_permanent_approved) + # Smart-DENY owner overrides are one-operation scoped. Preserve existing + # persistence for manual mode and smart ESCALATE. + if not smart_denied_for_owner: + for key, _, is_tirith in warnings: + if choice == "session" or (choice == "always" and is_tirith): + # tirith: session only (no permanent broad allowlisting) + approve_session(session_key, key) + elif choice == "always": + # dangerous patterns: permanent allowed + approve_session(session_key, key) + approve_permanent(key) + save_permanent_allowlist(_permanent_approved) return {"approved": True, "message": None, "user_approved": True, "description": combined_desc} @@ -2684,17 +3150,6 @@ def check_execute_code_guard(code: str, env_type: str, # paths don't pay to copy a potentially-large script into this string. command = f"execute_code <<'PY'\n{code}\nPY" - # Redacted copies for user-visible rendering only. An execute_code script - # can embed credentials (e.g. api_key = "sk-..."), and the gateway renders - # this payload directly to Discord/Slack — those messages are - # screenshottable. The raw `command`/`code` are still what get assessed by - # smart approval and executed; redaction is display-only. Approval - # persistence keys off pattern_key, so the allowlist is unaffected. - from agent.redact import redact_sensitive_text - display_command = redact_sensitive_text(command) - display_code = redact_sensitive_text(code) - display_description = redact_sensitive_text(description) - # Check session/permanent approval — same gate as check_all_command_guards. # Without this, "Approve session" / "Always" choices are stored but never # consulted, so every execute_code call re-prompts the user (#39275). @@ -2704,14 +3159,23 @@ def check_execute_code_guard(code: str, env_type: str, # Smart mode: ask the aux LLM about the whole script. An APPROVE here only # suppresses the redundant whole-script prompt; the per-call terminal() # guards (restored by context propagation) still run independently. + smart_denied_for_owner = False if approval_mode == "smart": + observer_payload = _prepare_smart_approval_observer( + command=command, + description=description, + pattern_key=pattern_key, + pattern_keys=[pattern_key], + session_key=session_key, + ) verdict = _smart_approve(command, description) + _observe_smart_approval_verdict(observer_payload, verdict) if verdict == "approve": logger.debug("Smart approval: auto-approved execute_code for session %s", session_key) return {"approved": True, "message": None, "smart_approved": True, "description": description} - if verdict == "deny": + if verdict == "deny" and not (is_gateway or is_ask): return { "approved": False, "message": ("BLOCKED by smart approval: execute_code script " @@ -2723,7 +3187,21 @@ def check_execute_code_guard(code: str, env_type: str, "outcome": "denied", "user_consent": False, } - # verdict == "escalate" → fall through to manual approval + if verdict == "deny": + smart_denied_for_owner = True + # Interactive DENY falls through to one-operation human approval; + # ESCALATE retains the normal manual approval behavior. + + # Redacted copies for user-visible rendering only. An execute_code script + # can embed credentials (e.g. api_key = "sk-..."), and the gateway renders + # this payload directly to Discord/Slack — those messages are + # screenshottable. The raw `command`/`code` are still what get assessed by + # smart approval and executed; redaction is display-only. Approval + # persistence keys off pattern_key, so the allowlist is unaffected. + from agent.redact import redact_sensitive_text + display_command = redact_sensitive_text(command) + display_code = redact_sensitive_text(code) + display_description = redact_sensitive_text(description) notify_cb = None with _lock: @@ -2732,13 +3210,16 @@ def check_execute_code_guard(code: str, env_type: str, if notify_cb is None: # No gateway callback registered (e.g. ask-mode without a notifier): # surface a pending approval for backward compatibility. - submit_pending(session_key, { + pending_data = { "command": display_command, "pattern_key": pattern_key, "pattern_keys": [pattern_key], "description": display_description, - }) - return { + } + if smart_denied_for_owner: + pending_data.update(smart_denied=True, allow_permanent=False) + submit_pending(session_key, pending_data) + result = { "approved": False, "pattern_key": pattern_key, "status": "pending_approval", @@ -2750,13 +3231,19 @@ def check_execute_code_guard(code: str, env_type: str, f"**Code:**\n```python\n{display_code}\n```" ), } + if smart_denied_for_owner: + result.update(smart_denied=True, allow_permanent=False) + return result approval_data = { "command": display_command, "pattern_key": pattern_key, "pattern_keys": [pattern_key], "description": display_description, + "allow_permanent": not smart_denied_for_owner, } + if smart_denied_for_owner: + approval_data["smart_denied"] = True decision = _await_gateway_decision( session_key, notify_cb, approval_data, surface="gateway" ) @@ -2773,31 +3260,39 @@ def check_execute_code_guard(code: str, env_type: str, resolved = decision["resolved"] choice = decision["choice"] + deny_reason = decision.get("reason") if not resolved or choice is None or choice == "deny": reason = "timed out without user response" if not resolved else "denied by user" addendum = " Silence is not consent." if not resolved else "" + reason_addendum = "" + if resolved and choice == "deny" and deny_reason: + reason_addendum = f' Reason given by the user: "{deny_reason}".' return { "approved": False, "message": ( - f"BLOCKED: execute_code script {reason}. The user has NOT " - f"consented to running this code. Do NOT retry, do NOT rephrase " - f"the script, and do NOT attempt the same outcome via a " - f"different tool.{addendum}" + f"BLOCKED: execute_code script {reason}.{reason_addendum} The " + f"user has NOT consented to running this code. Do NOT retry, " + f"do NOT rephrase the script, and do NOT attempt the same " + f"outcome via a different tool.{addendum}" ), "pattern_key": pattern_key, "description": description, "outcome": "timeout" if not resolved else "denied", "user_consent": False, + "deny_reason": deny_reason, } - # Approved — persist based on scope (same logic as check_all_command_guards). - if choice == "session": - approve_session(session_key, pattern_key) - elif choice == "always": - approve_session(session_key, pattern_key) - approve_permanent(pattern_key) - save_permanent_allowlist(_permanent_approved) + # Never persist a smart-DENY override under the coarse execute_code key; + # doing so would approve unrelated future scripts. Manual and ESCALATE + # decisions preserve their existing session/permanent behavior. + if not smart_denied_for_owner: + if choice == "session": + approve_session(session_key, pattern_key) + elif choice == "always": + approve_session(session_key, pattern_key) + approve_permanent(pattern_key) + save_permanent_allowlist(_permanent_approved) # choice == "once": no persistence — approval lasts this single call only. return {"approved": True, "message": None, diff --git a/tools/browser_tool.py b/tools/browser_tool.py index 82c248a3f715a..0ec35075db190 100644 --- a/tools/browser_tool.py +++ b/tools/browser_tool.py @@ -795,7 +795,7 @@ def _is_local_backend() -> bool: and network access on the same machine, so the check adds no security value. - However, when the terminal runs in a container (docker, modal, daytona, + However, when the terminal runs in a container (docker, modal, daytona, tenki, ssh, singularity), the browser on the host can access internal networks that the terminal cannot. In this case, SSRF protection should be enabled even though the browser is technically "local". diff --git a/tools/code_execution_tool.py b/tools/code_execution_tool.py index a7f3fc93ef8bf..2a1a97e65516d 100644 --- a/tools/code_execution_tool.py +++ b/tools/code_execution_tool.py @@ -34,6 +34,7 @@ import logging import os import platform +import secrets import shlex import socket import subprocess @@ -381,7 +382,11 @@ def _connect(): def _call(tool_name, args): """Send a tool call to the parent process and return the parsed result.""" - request = json.dumps({"tool": tool_name, "args": args}) + "\\n" + request = json.dumps({ + "tool": tool_name, + "args": args, + "token": os.environ.get("HERMES_RPC_TOKEN", ""), + }) + "\\n" with _call_lock: conn = _connect() conn.sendall(request.encode()) @@ -434,7 +439,12 @@ def _call(tool_name, args): # non-ASCII chars in tool args when encoding them as JSON. tmp = req_file + ".tmp" with open(tmp, "w", encoding="utf-8") as f: - json.dump({"tool": tool_name, "args": args, "seq": seq}, f) + json.dump({ + "tool": tool_name, + "args": args, + "seq": seq, + "token": os.environ.get("HERMES_RPC_TOKEN", ""), + }, f) os.rename(tmp, req_file) # Wait for response with adaptive polling @@ -482,6 +492,7 @@ def _rpc_server_loop( max_tool_calls: int, allowed_tools: frozenset, stop_event: threading.Event, + rpc_token: str, ): """ Accept one client connection and dispatch tool-call requests until @@ -527,6 +538,13 @@ def _rpc_server_loop( conn.sendall((resp + "\n").encode()) continue + if not rpc_token or not secrets.compare_digest( + str(request.get("token") or ""), rpc_token + ): + resp = json.dumps({"error": "Unauthorized RPC request"}) + conn.sendall((resp + "\n").encode()) + continue + tool_name = request.get("tool", "") tool_args = request.get("args", {}) @@ -618,6 +636,8 @@ def _get_or_create_env(task_id: str): _get_env_config, _last_activity, _start_cleanup_thread, _creation_locks, _creation_locks_lock, _task_env_overrides, _resolve_container_task_id, + _CONTAINER_BACKENDS, + _container_config_from_env_config, ) effective_task_id = _resolve_container_task_id(task_id) @@ -660,25 +680,8 @@ def _get_or_create_env(task_id: str): cwd = overrides.get("cwd") or config["cwd"] container_config = None - if env_type in {"docker", "singularity", "modal", "daytona", "tenki"}: - container_config = { - "container_cpu": config.get("container_cpu", 1), - "container_memory": config.get("container_memory", 5120), - "container_disk": config.get("container_disk", 51200), - "container_persistent": config.get("container_persistent", True), - "docker_volumes": config.get("docker_volumes", []), - "docker_run_as_host_user": config.get("docker_run_as_host_user", False), - "tenki_api_endpoint": config.get("tenki_api_endpoint", ""), - "tenki_workspace_id": config.get("tenki_workspace_id", ""), - "tenki_project_id": config.get("tenki_project_id", ""), - "tenki_name_prefix": config.get("tenki_name_prefix", "hermes"), - "tenki_allow_inbound": config.get("tenki_allow_inbound", False), - "tenki_allow_outbound": config.get("tenki_allow_outbound", True), - "tenki_max_duration": config.get("tenki_max_duration", 3600), - "tenki_idle_timeout": config.get("tenki_idle_timeout", 0), - "tenki_pause_retention": config.get("tenki_pause_retention", 0), - "tenki_sync_hermes_home": config.get("tenki_sync_hermes_home", False), - } + if env_type in _CONTAINER_BACKENDS: + container_config = _container_config_from_env_config(config) ssh_config = None if env_type == "ssh": @@ -762,6 +765,7 @@ def _rpc_poll_loop( max_tool_calls: int, allowed_tools: frozenset, stop_event: threading.Event, + rpc_token: str, ): """Poll the remote filesystem for tool call requests and dispatch them. @@ -815,6 +819,13 @@ def _rpc_poll_loop( env.execute(f"rm -f {quoted_req_file}", cwd="/", timeout=5) continue + if not rpc_token or not secrets.compare_digest( + str(request.get("token") or ""), rpc_token + ): + logger.debug("Unauthorized RPC request in %s", req_file) + env.execute(f"rm -f {quoted_req_file}", cwd="/", timeout=5) + continue + tool_name = request.get("tool", "") tool_args = request.get("args", {}) seq = request.get("seq", 0) @@ -954,6 +965,8 @@ def _execute_remote( f"mkdir -p {quoted_rpc_dir}", cwd="/", timeout=10, ) + rpc_token = secrets.token_urlsafe(32) + # Generate and ship files tools_src = generate_hermes_tools_module( list(sandbox_tools), transport="file", @@ -969,7 +982,7 @@ def _execute_remote( args=( env, f"{sandbox_dir}/rpc", effective_task_id, tool_call_log, tool_call_counter, max_tool_calls, - sandbox_tools, stop_event, + sandbox_tools, stop_event, rpc_token, ), daemon=True, ) @@ -978,6 +991,7 @@ def _execute_remote( # Build environment variable prefix for the script env_prefix = ( f"HERMES_RPC_DIR={shlex.quote(f'{sandbox_dir}/rpc')} " + f"HERMES_RPC_TOKEN={shlex.quote(rpc_token)} " f"PYTHONDONTWRITEBYTECODE=1" ) tz = os.getenv("HERMES_TIMEZONE", "").strip() @@ -1148,6 +1162,16 @@ def execute_code( "duration_seconds": 0, }, ensure_ascii=False) + # Clean interrupt slate for a user-approved script before EITHER dispatch + # path spawns it: drop a stale bit that landed on this thread during the + # blocking approval-wait so it can't kill the just-approved run on the first + # poll (local _wait_for_process loop, or remote/ssh env.execute which routes + # through the same poll loop). A genuine post-clear interrupt re-sets the + # bit and is still caught downstream. + if _guard.get("user_approved"): + from tools.interrupt import clear_current_thread_interrupt + clear_current_thread_interrupt() + if env_type != "local": return _execute_remote(code, task_id, enabled_tools) @@ -1216,6 +1240,7 @@ def execute_code( f.write(code) # --- Start RPC server --- + rpc_token = secrets.token_urlsafe(32) # Two transports: # POSIX: AF_UNIX stream socket on sock_path, chmod 0600 for # owner-only access. Filesystem permissions gate the socket. @@ -1242,7 +1267,7 @@ def execute_code( target=propagate_context_to_thread(_rpc_server_loop), args=( server_sock, task_id, tool_call_log, - tool_call_counter, max_tool_calls, sandbox_tools, stop_event, + tool_call_counter, max_tool_calls, sandbox_tools, stop_event, rpc_token, ), daemon=True, ) @@ -1260,6 +1285,7 @@ def execute_code( # or spawn a subprocess. See ``_scrub_child_env`` for the rules. child_env = _scrub_child_env(os.environ) child_env["HERMES_RPC_SOCKET"] = rpc_endpoint + child_env["HERMES_RPC_TOKEN"] = rpc_token child_env["PYTHONDONTWRITEBYTECODE"] = "1" # Force UTF-8 for the child's stdio and default file encoding. # diff --git a/tools/env_probe.py b/tools/env_probe.py index f96f408498232..25b0fb851c2ca 100644 --- a/tools/env_probe.py +++ b/tools/env_probe.py @@ -241,8 +241,35 @@ def get_environment_probe_line(*, force_refresh: bool = False) -> str: return line +_warm_started = False + + +def warm_environment_probe_async() -> None: + """Kick off the probe in a background thread so the first + system-prompt build doesn't pay the ~0.5s of subprocess calls + (python3/pip/PEP-668 version checks) on the time-to-first-token + critical path. + + Idempotent and fail-safe. The prompt-build call to + ``get_environment_probe_line`` takes the same ``_CACHE_LOCK``, so it + blocks only for whatever remains of an in-flight warm instead of + recomputing. Called from agent init (all platforms); safe to call + from anywhere. + """ + global _warm_started + if _warm_started or _CACHED_LINE is not None: + return + _warm_started = True + threading.Thread( + target=get_environment_probe_line, + name="env-probe-warm", + daemon=True, + ).start() + + def _reset_cache_for_tests() -> None: """Test helper — clear the cache between probe scenarios.""" - global _CACHED_LINE + global _CACHED_LINE, _warm_started with _CACHE_LOCK: _CACHED_LINE = None + _warm_started = False diff --git a/tools/environments/base.py b/tools/environments/base.py index ef5b683aad2cd..5d69683b73408 100644 --- a/tools/environments/base.py +++ b/tools/environments/base.py @@ -189,7 +189,7 @@ def _file_mtime_key(host_path: str) -> tuple[float, int] | None: class ProcessHandle(Protocol): """Duck type that every backend's _run_bash() must return. - subprocess.Popen satisfies this natively. SDK backends (Modal, Daytona) + subprocess.Popen satisfies this natively. SDK backends (Modal, Daytona, Tenki) return _ThreadedProcessHandle which adapts their blocking calls. """ @@ -205,7 +205,7 @@ def returncode(self) -> int | None: ... class _ThreadedProcessHandle: - """Adapter for SDK backends (Modal, Daytona) that have no real subprocess. + """Adapter for SDK backends (Modal, Daytona, Tenki) that have no real subprocess. Wraps a blocking ``exec_fn() -> (output_str, exit_code)`` in a background thread and exposes a ProcessHandle-compatible interface. An optional @@ -367,15 +367,14 @@ def init_session(self): # Without this the snapshot bootstrap ``cd`` below fails on Windows and # ``pwd -P`` captures the login shell's directory, not ``terminal.cwd``. _quoted_cwd = self._quote_cwd_for_cd(self.cwd) - # Quote the snapshot / cwd-file paths so Git Bash on Windows handles - # ``C:/Users/...``-shaped paths without glob-splitting the colon or - # tripping on drive letters. On POSIX this is a no-op (no colons / - # special chars in a /tmp path). Previously unquoted interpolation - # caused ``C:/Users/.../hermes-snap-*.sh: No such file or directory`` - # errors on Windows, leaking via stderr (merged into stdout on Linux - # backends) into every terminal-tool response. - _quoted_snap = shlex.quote(self._snapshot_path) - _quoted_cwd_file = shlex.quote(self._cwd_file) + # Quote snapshot / cwd-file paths via ``_quote_shell_path`` so the + # LocalEnvironment override can rewrite ``C:/...`` (and mixed + # ``/c/Users\\...``) to ``/c/...`` before quoting — bare drive paths + # in the bootstrap script trip MSYS into the + # ``Directory \\drivers\\etc does not exist`` failure class. + # On POSIX this is plain ``shlex.quote``. + _quoted_snap = self._quote_shell_path(self._snapshot_path) + _quoted_cwd_file = self._quote_shell_path(self._cwd_file) # Use atomic file replacement: assemble the snapshot in a temp file, # then mv it over the final path. This prevents concurrent source() # calls from reading a half-written snapshot when another terminal @@ -391,10 +390,11 @@ def init_session(self): # mid-write, and mv would then publish a torn file (the corruption is # only narrowed, not closed). ``$BASHPID`` is the actual subshell PID # and is genuinely unique per writer, which closes the race. The - # static path is shlex-quoted (Windows/Git-Bash drive letters, spaces) + # static path is shell-quoted (Windows/Git-Bash drive letters, spaces) # with ``$BASHPID`` left outside the quotes so it still expands. - _snap_tmp = shlex.quote(self._snapshot_path + ".tmp.") + "$BASHPID" + _snap_tmp = self._quote_shell_path(self._snapshot_path + ".tmp.") + "$BASHPID" bootstrap = ( + f"umask 077\n" f"export -p > {_snap_tmp}\n" # Dump function definitions, filtering out private (``_``-prefixed) # helpers — mainly bash-completion internals (``_git``, ``_make``…) @@ -460,25 +460,32 @@ def _quote_cwd_for_cd(cwd: str) -> str: return f"$HOME/{shlex.quote(cwd[2:])}" return shlex.quote(cwd) + def _quote_shell_path(self, path: str) -> str: + """Quote *path* for interpolation into a bash script. + + LocalEnvironment overrides this to rewrite native/mixed Windows + paths to ``/c/...`` before quoting. Remote backends leave paths + as-is (they already speak POSIX). + """ + return shlex.quote(path) + def _wrap_command(self, command: str, cwd: str) -> str: """Build the full bash script that sources snapshot, cd's, runs command, re-dumps env vars, and emits CWD markers.""" escaped = command.replace("'", "'\\''") - # Quote the snapshot / cwd-file paths so Git Bash on Windows handles - # ``C:/Users/...``-shaped paths without glob-splitting the colon or - # tripping on drive letters. POSIX paths are unaffected. See - # :meth:`init_session` for the same fix on the bootstrap block. - _quoted_snap = shlex.quote(self._snapshot_path) - _quoted_cwd_file = shlex.quote(self._cwd_file) + # Quote snapshot/cwd-file paths (see init_session — LocalEnvironment + # rewrites ``C:/...`` to ``/c/...`` so MSYS doesn't mangle them). + _quoted_snap = self._quote_shell_path(self._snapshot_path) + _quoted_cwd_file = self._quote_shell_path(self._cwd_file) # Use atomic file replacement for env snapshot updates (issue #38249). # Assemble into a per-writer-unique temp file, then mv to atomically # replace the snapshot so concurrent source() calls never read a # truncated/half-written file. ``$BASHPID`` (not ``$$``) is the actual # subshell PID — unique per concurrent ``&``-launched writer — so two # writers never share a temp name and clobber each other before the mv. - # Static path shlex-quoted (Windows/spaces); ``$BASHPID`` left to expand. - _snap_tmp = shlex.quote(self._snapshot_path + ".tmp.") + "$BASHPID" + # Static path shell-quoted (Windows/spaces); ``$BASHPID`` left to expand. + _snap_tmp = self._quote_shell_path(self._snapshot_path + ".tmp.") + "$BASHPID" parts = [] @@ -502,6 +509,9 @@ def _wrap_command(self, command: str, cwd: str) -> str: # Run the actual command parts.append(f"eval '{escaped}'") parts.append("__hermes_ec=$?") + # Restrict Hermes metadata files without changing the user's command + # umask. Snapshot files may contain env-carried secrets. + parts.append("umask 077") # Re-dump env vars to snapshot (atomic replacement to avoid races). # Chain mv on the export succeeding so a failed/partial dump never @@ -838,7 +848,7 @@ def _extract_cwd_from_output(self, result: dict): """Parse the __HERMES_CWD_{session}__ marker from stdout output. Updates self.cwd and strips the marker from result["output"]. - Used by remote backends (Docker, SSH, Modal, Daytona, Singularity). + Used by remote backends (Docker, SSH, Modal, Daytona, Tenki, Singularity). """ output = result.get("output", "") marker = self._cwd_marker @@ -875,7 +885,7 @@ def _extract_cwd_from_output(self, result: dict): def _before_execute(self) -> None: """Hook called before each command execution. - Remote backends (SSH, Modal, Daytona) override this to trigger + Remote backends (SSH, Modal, Daytona, Tenki) override this to trigger their FileSyncManager. Bind-mount backends (Docker, Singularity) and Local don't need file sync — the host filesystem is directly visible inside the container/process. diff --git a/tools/environments/local.py b/tools/environments/local.py index 6c518b54b64f0..56dd1dde29dd0 100644 --- a/tools/environments/local.py +++ b/tools/environments/local.py @@ -25,16 +25,24 @@ def _msys_to_windows_path(cwd: str) -> str: native Windows form (``C:\\Users\\x``) so ``os.path.isdir`` and ``subprocess.Popen(..., cwd=...)`` can find it. + Also accepts the Cygwin (``/cygdrive/c/...``) and WSL-mount + (``/mnt/c/...``) spellings of a drive root. Multi-segment POSIX paths + like ``/home/x`` or ``/tmp/foo`` are left untouched. + No-ops on non-Windows hosts or for paths that aren't in MSYS form. Returns the input unchanged when no translation applies. This is idempotent — calling it on an already-Windows path returns it as-is. """ if not _IS_WINDOWS or not cwd: return cwd - # Match leading "//" or exactly "/" (bare drive root). - m = re.match(r'^/([a-zA-Z])(/.*)?$', cwd) + # Match leading "//" or exactly "/" (bare drive root), + # plus /cygdrive//... and /mnt//... variants. + m = re.match(r'^/(?:(?:cygdrive|mnt)/)?([a-zA-Z])(/.*)?$', cwd) if not m: return cwd + # Reject /cygdrive or /mnt with no drive letter — the optional group above + # already requires the letter. Multi-char first segments (/home, /tmp) + # fail the single-letter capture and fall through as no-ops. drive = m.group(1).upper() tail = (m.group(2) or "").replace('/', '\\') return f"{drive}:{tail or chr(92)}" # chr(92) = backslash, avoid raw-string escape @@ -58,6 +66,35 @@ def _windows_to_msys_path(cwd: str) -> str: return f"/{drive}/{tail}" if tail else f"/{drive}/" +def _bash_safe_path(path: str) -> str: + """Return *path* in a form safe to embed in a Git Bash script. + + Native ``C:\\Users\\x`` / ``C:/Users/x`` → ``/c/Users/x`` via + :func:`_windows_to_msys_path`. Mixed MSYS leftovers + (``/c/Users\\Alexander\\Documents``) get backslashes normalized so + bash does not eat ``\\U`` and trip the ``Directory \\drivers\\etc`` + failure class. No-op off Windows and for empty input. + + ``get_temp_dir`` already emits forward-slash ``C:/...`` forms for + Python compatibility; those still need the ``/c/...`` rewrite — + MSYS argument conversion treats ``C:/...`` as a Windows path and + can corrupt the login-shell ``drivers\\etc`` lookup. + """ + if not _IS_WINDOWS or not path: + return path + path = _windows_to_msys_path(path) + if "\\" in path: + path = path.replace("\\", "/") + return path + + +def _quote_bash_path(path: str) -> str: + """Quote *path* for safe interpolation into a Git Bash script on Windows.""" + import shlex + + return shlex.quote(_bash_safe_path(path)) + + def _resolve_safe_cwd(cwd: str) -> str: """Return ``cwd`` if it exists as a directory, else the nearest existing ancestor. Falls back to ``tempfile.gettempdir()`` only if walking up the @@ -207,6 +244,8 @@ def _build_provider_env_blocklist() -> frozenset: "MODAL_TOKEN_ID", "MODAL_TOKEN_SECRET", "DAYTONA_API_KEY", + "TENKI_AUTH_TOKEN", + "TENKI_API_KEY", "GATEWAY_RELAY_ID", "GATEWAY_RELAY_SECRET", "GATEWAY_RELAY_DELIVERY_KEY", @@ -383,6 +422,8 @@ def _sanitize_subprocess_env(base_env: dict | None, extra_env: dict | None = Non for _marker in _ACTIVE_VENV_MARKER_VARS: sanitized.pop(_marker, None) + _apply_windows_msys_bash_env_defaults(sanitized) + return sanitized @@ -426,6 +467,8 @@ def _sanitize_subprocess_env(base_env: dict | None, extra_env: dict | None = Non "MODAL_TOKEN_ID", "MODAL_TOKEN_SECRET", "DAYTONA_API_KEY", + "TENKI_AUTH_TOKEN", + "TENKI_API_KEY", }) @@ -493,6 +536,8 @@ def hermes_subprocess_env(*, inherit_credentials: bool = False) -> dict[str, str for _marker in _ACTIVE_VENV_MARKER_VARS: env.pop(_marker, None) + _apply_windows_msys_bash_env_defaults(env) + # Cross-session leak guard, same as the terminal spawn paths: this helper # copies os.environ, whose HERMES_SESSION_* mirror is a last-writer-wins # global under a concurrent multi-session host. A caller that re-binds the @@ -746,6 +791,29 @@ def _append_missing_sane_path_entries(existing_path: str) -> str: return ":".join(ordered_entries) +def _apply_windows_msys_bash_env_defaults(env: dict) -> None: + """Disable MSYS argument path conversion for Git Bash subprocesses. + + Git Bash rewrites arguments that look like Unix paths (``/FO``, ``/TN``, + ``/Create``) into ``C:/.../git/FO``-style paths, which breaks native + Windows commands such as ``tasklist``, ``schtasks``, and ``wmic``. Hermes + runs terminal commands through bash on Windows, so set the standard MSYS + opt-out by default. Users who need conversion can override in their env. + Refs #56700. + + ``MSYS_NO_PATHCONV`` is honored by Git for Windows bash only. MSYS2-proper + and Cygwin bash (which ``_find_bash`` can still return via the final + ``shutil.which`` fallback) ignore it and honor ``MSYS2_ARG_CONV_EXCL`` + instead, so set both. ``*`` disables all argv conversion — the semantic + equivalent of ``MSYS_NO_PATHCONV=1``. Also fixes ``cmd /c`` mangling + (#56147). + """ + if not _IS_WINDOWS: + return + env.setdefault("MSYS_NO_PATHCONV", "1") + env.setdefault("MSYS2_ARG_CONV_EXCL", "*") + + def _path_env_key(run_env: dict) -> str | None: """Return the PATH env key to update without altering Windows casing. @@ -804,6 +872,8 @@ def _make_run_env(env: dict) -> dict: for _marker in _ACTIVE_VENV_MARKER_VARS: run_env.pop(_marker, None) + _apply_windows_msys_bash_env_defaults(run_env) + return run_env @@ -957,6 +1027,10 @@ def _quote_cwd_for_cd(cwd: str) -> str: """Use native paths for Python, but Git Bash-friendly paths for cd.""" return BaseEnvironment._quote_cwd_for_cd(_windows_to_msys_path(cwd)) + def _quote_shell_path(self, path: str) -> str: + """Rewrite native/mixed Windows paths before quoting for Git Bash.""" + return _quote_bash_path(path) + def _run_bash(self, cmd_string: str, *, login: bool = False, timeout: int = 120, stdin_data: str | None = None) -> subprocess.Popen: diff --git a/tools/environments/tenki.py b/tools/environments/tenki.py index c7fcd4b591627..958aa34311f7d 100644 --- a/tools/environments/tenki.py +++ b/tools/environments/tenki.py @@ -2,6 +2,7 @@ from __future__ import annotations +import hashlib import inspect import logging import math @@ -14,7 +15,13 @@ from pathlib import Path from typing import Any -from tools.environments.base import BaseEnvironment, _ThreadedProcessHandle +from hermes_constants import get_hermes_home +from tools.environments.base import ( + BaseEnvironment, + _ThreadedProcessHandle, + _load_json_store, + _save_json_store, +) from tools.environments.file_sync import ( FileSyncManager, iter_sync_files, @@ -30,6 +37,109 @@ ) logger = logging.getLogger(__name__) +_SNAPSHOT_NAMESPACE = "direct" +_ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") + + +def _snapshot_store_path() -> Path: + """Resolve the snapshot registry path for the *active* profile. + + Resolved per call (not frozen at import) so the multiplexing gateway, + which overrides ``HERMES_HOME`` per turn, writes each profile's snapshot + pointers into that profile's own home instead of whichever profile + happened to import this module first. + """ + return get_hermes_home() / "tenki_snapshots.json" + + +def _profile_token() -> str: + """Short, stable identifier for the active Hermes profile. + + Two profiles sharing one Tenki account must get distinct sandbox + names/metadata so they can never attach to or restore each other's + sandbox. Prefer the canonical ``HERMES_PROFILE`` id, which is stable across + machines and survives a home-directory move; only fall back to a + *normalized* ``HERMES_HOME`` path when no profile id is set (the default + profile). Resolving per call handles the multiplexing gateway's per-turn + ``HERMES_HOME`` override (same reason as :func:`_snapshot_store_path`). + """ + profile = os.getenv("HERMES_PROFILE", "").strip() + if profile: + basis = f"profile:{profile}" + else: + try: + basis = str(get_hermes_home().resolve()) + except Exception: + basis = str(get_hermes_home()) + return hashlib.sha1(basis.encode("utf-8")).hexdigest()[:10] + + +def _load_snapshots(store_path: Path | None = None) -> dict: + return _load_json_store(store_path or _snapshot_store_path()) + + +def _save_snapshots(data: dict, store_path: Path | None = None) -> None: + _save_json_store(store_path or _snapshot_store_path(), data) + + +def _snapshot_key(task_id: str) -> str: + return f"{_SNAPSHOT_NAMESPACE}:{task_id}" + + +def _get_snapshot_restore_candidate( + task_id: str, store_path: Path | None = None +) -> tuple[str | None, bool]: + snapshots = _load_snapshots(store_path) + namespaced_key = _snapshot_key(task_id) + snapshot_id = snapshots.get(namespaced_key) + if isinstance(snapshot_id, str) and snapshot_id: + return snapshot_id, False + legacy_snapshot_id = snapshots.get(task_id) + if isinstance(legacy_snapshot_id, str) and legacy_snapshot_id: + return legacy_snapshot_id, True + return None, False + + +def _store_snapshot(task_id: str, snapshot_id: str, store_path: Path | None = None) -> None: + snapshots = _load_snapshots(store_path) + snapshots[_snapshot_key(task_id)] = snapshot_id + snapshots.pop(task_id, None) + _save_snapshots(snapshots, store_path) + + +def _delete_snapshot( + task_id: str, snapshot_id: str | None = None, store_path: Path | None = None +) -> None: + snapshots = _load_snapshots(store_path) + updated = False + for key in (_snapshot_key(task_id), task_id): + value = snapshots.get(key) + if value is None: + continue + if snapshot_id is None or value == snapshot_id: + snapshots.pop(key, None) + updated = True + if updated: + _save_snapshots(snapshots, store_path) + + +def _normalize_forward_env_names(forward_env: list[str] | None) -> list[str]: + normalized: list[str] = [] + seen: set[str] = set() + for item in forward_env or []: + if not isinstance(item, str): + logger.warning("Ignoring non-string tenki_forward_env entry: %r", item) + continue + name = item.strip() + if not name: + continue + if not _ENV_NAME_RE.match(name): + logger.warning("Ignoring invalid tenki_forward_env entry: %r", item) + continue + if name not in seen: + normalized.append(name) + seen.add(name) + return normalized def _safe_name(value: str, *, fallback: str = "default", max_len: int = 48) -> str: @@ -157,12 +267,14 @@ def _rewrite_sudo_noninteractive(command: str) -> tuple[str, int]: class TenkiEnvironment(BaseEnvironment): """Tenki sandbox backend. - Tenki's SDK exposes blocking command execution, so this adapts it to the - normal Hermes ``ProcessHandle`` contract with ``_ThreadedProcessHandle``. + Tenki's SDK exposes process handles inside a remote sandbox, so this adapts + them to the normal Hermes ``ProcessHandle`` contract with + ``_ThreadedProcessHandle``. """ - _stdin_mode = "heredoc" + _stdin_mode = "pipe" _snapshot_timeout = 60 + _terminal_states = frozenset({"TERMINATING", "TERMINATED", "DELETED", "FAILED", "ERROR"}) def __init__( self, @@ -184,6 +296,7 @@ def __init__( idle_timeout: int = 0, pause_retention: int = 0, sync_hermes_home: bool = False, + forward_env: list[str] | None = None, ): super().__init__(cwd=cwd, timeout=timeout) @@ -206,7 +319,18 @@ def __init__( self._persistent = persistent_filesystem self._sync_hermes_home = sync_hermes_home self._sync_manager: FileSyncManager | None = None + self._cleanup_in_progress = False + self._cleanup_sandbox = None self._task_id = task_id + self._profile_token = _profile_token() + # Bind the profile's snapshot-store path at construction, while the + # correct HERMES_HOME context is active. Cleanup (and the idle-reaper + # snapshot save) can run in a background thread that does NOT inherit + # the per-turn HERMES_HOME contextvar, so re-resolving there would write + # the pointer into the wrong profile's home. + self._snapshot_store = _snapshot_store_path() + self._snapshot_restore_id: str | None = None + self._snapshot_restore_from_legacy_key = False self._image = image self._cpu = cpu self._memory = memory @@ -221,7 +345,12 @@ def __init__( self._max_duration = max_duration self._idle_timeout = idle_timeout self._pause_retention = pause_retention + self._forward_env = _normalize_forward_env_names(forward_env) self._remote_home = "/home/tenki" + if self._persistent: + self._snapshot_restore_id, self._snapshot_restore_from_legacy_key = ( + _get_snapshot_restore_candidate(self._task_id, self._snapshot_store) + ) self._ensure_sandbox() self._resolve_remote_home() @@ -245,10 +374,13 @@ def _sandbox_create_signature(self) -> inspect.Signature | None: def _create_kwargs(self) -> dict[str, Any]: sig = self._sandbox_create_signature() kwargs: dict[str, Any] = {} - sandbox_name = f"{self._name_prefix}-{_safe_name(self._task_id)}" + sandbox_name = self._sandbox_name() _add_supported(kwargs, sig, ("name",), sandbox_name) - _add_supported(kwargs, sig, ("image", "template"), self._image) + if self._snapshot_restore_id: + _add_supported(kwargs, sig, ("snapshot_id",), self._snapshot_restore_id) + else: + _add_supported(kwargs, sig, ("image", "template"), self._image) cpu_cores = max(1, math.ceil(float(self._cpu))) if self._cpu else None _add_supported(kwargs, sig, ("cpu_cores", "cpu"), cpu_cores) _add_supported(kwargs, sig, ("memory_mb", "memory"), self._memory) @@ -271,6 +403,7 @@ def _create_kwargs(self) -> dict[str, Any]: _add_supported(kwargs, sig, ("project_id",), self._project_id) _add_supported(kwargs, sig, ("base_url", "api_endpoint"), self._api_endpoint) _add_supported(kwargs, sig, ("auth_token", "api_key"), self._auth_token) + _add_supported(kwargs, sig, ("env",), self._sandbox_env()) _add_supported( kwargs, sig, @@ -278,13 +411,99 @@ def _create_kwargs(self) -> dict[str, Any]: { "hermes_task_id": self._task_id, "hermes_backend": "tenki", + "hermes_profile": self._profile_token, }, ) _add_supported(kwargs, sig, ("tags",), ["hermes-agent"]) _add_supported(kwargs, sig, ("wait",), True) - _add_supported(kwargs, sig, ("timeout",), max(60, self.timeout)) + # Do NOT emit a create-time ``timeout`` here: the SDK's Sandbox.create + # pops ``timeout`` into the *Client* (HTTP) timeout, while Client.create + # treats ``timeout`` as the *wait-for-ready* budget — so the same value + # would mean two different things across the two create paths. The HTTP + # timeout is set explicitly in _create_client(); readiness uses the + # SDK's default wait budget. return kwargs + def _sandbox_env(self) -> dict[str, str]: + """Environment variables injected into Tenki sandbox processes. + + The supervisor's Tenki control-plane credential is used host-side to + create and manage the sandbox (see ``_create_kwargs`` / + ``_create_client``); it is deliberately NOT injected into the guest. + Guest code is model-controlled and can print, exfiltrate, or reuse + whatever is in its environment, and the sandbox is billed against the + supervisor's account — so a leaked ``TENKI_AUTH_TOKEN`` would let guest + code create, terminate, and bill account resources outside the + parent's configured limits. Nested-sandbox support is still available + as an explicit opt-in: list ``TENKI_AUTH_TOKEN`` (or ``TENKI_API_KEY``) + in ``terminal.tenki_forward_env``. + + ``terminal.tenki_forward_env`` is the explicit allowlist for + task-specific credentials such as GitHub tokens; the generic + ``terminal.env_passthrough`` allowlist is also honored for skill + variables that are not protected by Hermes' provider-secret blocklist. + """ + env: dict[str, str] = {} + env.update(self._resolve_forwarded_env(self._forward_env)) + env.update(self._passthrough_env()) + # If the operator explicitly opted into forwarding the control-plane + # credential (for nested-sandbox creation), supply the already-resolved + # token. Re-reading the env var here would miss a `tenki login` + # credential, which lives in the Tenki CLI config, not the environment — + # so the documented opt-in would silently forward nothing. + if self._auth_token: + for key in ("TENKI_AUTH_TOKEN", "TENKI_API_KEY"): + if key in self._forward_env and not env.get(key): + env[key] = self._auth_token + logger.warning( + "Tenki: forwarding the control-plane credential %s into the " + "sandbox as requested by terminal.tenki_forward_env. Guest code " + "can read it and create/terminate/bill account resources. Note " + "that forwarded credentials are NOT profile-isolated under the " + "multiplexing gateway's shared terminal cache.", + key, + ) + return env + + @staticmethod + def _resolve_forwarded_env(keys: list[str] | set[str] | tuple[str, ...]) -> dict[str, str]: + if not keys: + return {} + from tools.tenki_config import _global_credential_fallback_allowed, _scoped_env + + get_env_value = None + if _global_credential_fallback_allowed(): + try: + from hermes_cli.config import get_env_value + except Exception: + get_env_value = None + + env: dict[str, str] = {} + for key in keys: + # Scope-aware read first: under a multiplexed profile turn this + # resolves the active profile's value, never another profile's raw + # os.environ. The ~/.hermes/.env fallback is consulted only when no + # profile scope is authoritative. + value = _scoped_env(key) + if not value and get_env_value is not None: + try: + value = get_env_value(key) or "" + except Exception: + value = "" + if value: + env[key] = value + return env + + @staticmethod + def _passthrough_env() -> dict[str, str]: + try: + from tools.env_passthrough import get_all_passthrough + + keys = sorted(get_all_passthrough()) + except Exception: + keys = [] + return TenkiEnvironment._resolve_forwarded_env(keys) + def _create_client(self): if self._client is None: self._client = self._Client( @@ -295,7 +514,9 @@ def _create_client(self): return self._client def _sandbox_name(self) -> str: - return f"{self._name_prefix}-{_safe_name(self._task_id)}" + # The profile token namespaces the name so two profiles sharing one + # Tenki account never collide on a name or reuse each other's sandbox. + return f"{self._name_prefix}-{self._profile_token}-{_safe_name(self._task_id)}" @staticmethod def _sandbox_state(sandbox: Any) -> str: @@ -315,6 +536,12 @@ def _sandbox_matches_task(self, sandbox: Any) -> bool: if name != self._sandbox_name(): return False metadata = getattr(info, "metadata", {}) if info is not None else {} + # Never reuse another profile's sandbox: if the candidate carries a + # profile token it must match ours (the name already encodes it, but + # metadata is the authoritative, defense-in-depth check). + if isinstance(metadata, dict) and metadata.get("hermes_profile"): + if metadata.get("hermes_profile") != self._profile_token: + return False if isinstance(metadata, dict) and metadata.get("hermes_task_id"): return metadata.get("hermes_task_id") == self._task_id return True @@ -339,7 +566,7 @@ def _find_persistent_sandbox(self): if not self._sandbox_matches_task(sandbox): continue state = self._sandbox_state(sandbox) - if state in {"TERMINATING", "TERMINATED"}: + if state in self._terminal_states: continue usable.append((state, sandbox)) if not usable: @@ -351,37 +578,169 @@ def _resume_persistent_sandbox(self): sandbox = self._find_persistent_sandbox() if sandbox is None: return None - state = self._sandbox_state(sandbox) - if state != "RUNNING": - resume = getattr(sandbox, "resume", None) - if callable(resume): - resume() - wait_ready = getattr(sandbox, "wait_ready", None) - if callable(wait_ready): - wait_ready(max(60, self.timeout)) + if not self._ensure_sandbox_ready(sandbox): + logger.info( + "Tenki: existing sandbox for task %s is no longer reusable; creating a fresh sandbox", + self._task_id, + ) + return None sandbox_id = getattr(sandbox, "id", None) or getattr(sandbox, "sandbox_id", None) logger.info("Tenki: resumed sandbox %s for task %s", sandbox_id or "", self._task_id) return sandbox + def _ensure_sandbox_ready(self, sandbox: Any) -> bool: + refresh = getattr(sandbox, "refresh", None) + if callable(refresh): + try: + refresh() + except Exception as exc: + logger.info("Tenki: sandbox refresh failed for task %s: %s", self._task_id, exc) + return False + + state = self._sandbox_state(sandbox) + if state in self._terminal_states: + return False + + try: + if state and state != "RUNNING": + resume = getattr(sandbox, "resume", None) + if callable(resume): + resume() + wait_ready = getattr(sandbox, "wait_ready", None) + if callable(wait_ready): + wait_ready(max(60, self.timeout)) + except Exception as exc: + logger.info("Tenki: could not make sandbox ready for task %s: %s", self._task_id, exc) + return False + + return self._sandbox_state(sandbox) not in self._terminal_states + def _ensure_sandbox(self) -> None: with self._lock: + if self._cleanup_in_progress: + raise RuntimeError("Tenki cleanup is in progress") if self._sandbox is not None: - return + if self._ensure_sandbox_ready(self._sandbox): + return + self._sandbox = None self._sandbox = self._resume_persistent_sandbox() if self._sandbox is not None: return - kwargs = self._create_kwargs() - if self._persistent: - client = self._create_client() - create_kwargs = dict(kwargs) - for key in ("auth_token", "api_key", "base_url", "api_endpoint"): - create_kwargs.pop(key, None) - self._sandbox = client.create(**create_kwargs) - else: - self._sandbox = self._Sandbox.create(**kwargs) + self._sandbox = self._create_sandbox_with_snapshot_fallback() sandbox_id = getattr(self._sandbox, "id", None) or getattr(self._sandbox, "sandbox_id", None) logger.info("Tenki: created sandbox %s for task %s", sandbox_id or "", self._task_id) + def _create_sandbox_from_kwargs(self, kwargs: dict[str, Any]): + if self._persistent: + client = self._create_client() + create_kwargs = dict(kwargs) + for key in ("auth_token", "api_key", "base_url", "api_endpoint"): + create_kwargs.pop(key, None) + return client.create(**create_kwargs) + return self._Sandbox.create(**kwargs) + + # Snapshot errors that mean the recorded snapshot can never restore, so + # dropping the pointer and booting the base image is the right recovery. + # A *transient* failure (network, rate-limit, ambiguous) is NOT in this set: + # it must propagate with the pointer intact so a later attempt can still + # recover the persistent state instead of silently booting an empty sandbox. + # Snapshot-specific error type names that mean the snapshot can never + # restore. Note InvalidStateError is intentionally NOT here: the restore RPC + # maps a generic FAILED_PRECONDITION (workspace/policy/etc.) to it, so it is + # only unrecoverable when its message points at the snapshot itself + # (handled by message inspection below); a bare InvalidStateError stays + # transient so an unrelated precondition can't destroy a valid pointer. + _UNRECOVERABLE_SNAPSHOT_ERRORS = frozenset({ + "SnapshotNotFoundError", # snapshot is gone + "RegistryArtifactNotFoundError", # backing artifact is gone + "SnapshotNotDurableError", # explicitly never reached durability + }) + + @classmethod + def _snapshot_unrecoverable(cls, exc: BaseException) -> bool: + """True when the error confirms the snapshot can never restore. + + Covers "gone" (not-found), "explicitly non-durable", and a generic + ``InvalidStateError`` whose message identifies the snapshot as the + failing precondition (the SDK's restore RPC collapses a bad/non-durable + snapshot into a generic FAILED_PRECONDITION → InvalidStateError). Only + these justify discarding the recovery pointer and booting a base image; + every other error (including a bare InvalidStateError, rate-limit, + quota, auth blip, or network failure) is transient and re-raised with + the pointer preserved. + """ + def _is_snapshot_specific_invalid_state(e: BaseException, invalid_state_cls) -> bool: + if invalid_state_cls is not None and not isinstance(e, invalid_state_cls): + return False + if invalid_state_cls is None and type(e).__name__ != "InvalidStateError": + return False + msg = str(e).lower() + return "snapshot" in msg or "durable" in msg + + try: + from tenki_sandbox import ( + InvalidStateError, + RegistryArtifactNotFoundError, + SnapshotNotDurableError, + SnapshotNotFoundError, + ) + + if isinstance( + exc, + (SnapshotNotFoundError, RegistryArtifactNotFoundError, SnapshotNotDurableError), + ): + return True + if _is_snapshot_specific_invalid_state(exc, InvalidStateError): + return True + return False + except Exception: + pass + # Name-based fallback for SDK builds that don't export every class. + for typ in type(exc).__mro__: + if typ.__name__ in cls._UNRECOVERABLE_SNAPSHOT_ERRORS: + return True + return _is_snapshot_specific_invalid_state(exc, None) + + def _create_sandbox_with_snapshot_fallback(self): + kwargs = self._create_kwargs() + try: + sandbox = self._create_sandbox_from_kwargs(kwargs) + except Exception as exc: + if not self._snapshot_restore_id: + raise + if not self._snapshot_unrecoverable(exc): + # Ambiguous/transient failure — keep the snapshot pointer so a + # later attempt can still recover, rather than deleting it and + # booting a blank base image (silent loss of persistent state). + logger.warning( + "Tenki: snapshot restore %s for task %s failed transiently (%s); " + "preserving it for retry", + self._snapshot_restore_id, + self._task_id, + exc, + ) + raise + logger.warning( + "Tenki: snapshot %s for task %s is unrecoverable; creating from base image: %s", + self._snapshot_restore_id, + self._task_id, + exc, + ) + _delete_snapshot(self._task_id, self._snapshot_restore_id, self._snapshot_store) + self._snapshot_restore_id = None + self._snapshot_restore_from_legacy_key = False + sandbox = self._create_sandbox_from_kwargs(self._create_kwargs()) + else: + if self._snapshot_restore_id and self._snapshot_restore_from_legacy_key: + _store_snapshot(self._task_id, self._snapshot_restore_id, self._snapshot_store) + return sandbox + + def _remote_transfer_path(self, prefix: str) -> str: + base = (self._remote_home or "/home/tenki").rstrip("/") or "/home/tenki" + if base != "/home/tenki" and not base.startswith("/home/tenki/"): + base = "/home/tenki" + return f"{base}/{prefix}.{os.getpid()}.{self._session_id}.tar" + def _resolve_remote_home(self) -> None: try: result = self._exec_raw("echo \"$HOME\"", timeout=15) @@ -408,7 +767,7 @@ def _tenki_bulk_upload(self, files: list[tuple[str, str]]) -> None: if parents: self._exec_raw(quoted_mkdir_command(parents), timeout=30) - remote_tar = f"/tmp/.hermes_tenki_sync.{os.getpid()}.{self._session_id}.tar" + remote_tar = self._remote_transfer_path(".hermes_tenki_sync") with tempfile.NamedTemporaryFile(suffix=".tar") as tmp: with tarfile.open(fileobj=tmp, mode="w") as tar: for host_path, remote_path in files: @@ -430,23 +789,30 @@ def _tenki_bulk_upload(self, files: list[tuple[str, str]]) -> None: pass def _tenki_bulk_download(self, dest: Path) -> None: - self._ensure_sandbox() - remote_tar = f"/tmp/.hermes_tenki_sync_back.{os.getpid()}.{self._session_id}.tar" + sandbox = self._transfer_sandbox() + remote_tar = self._remote_transfer_path(".hermes_tenki_sync_back") rel_base = f"{self._remote_home}/.hermes".lstrip("/") try: - output, exit_code = self._exec_raw( + output, exit_code = self._exec_raw_on_sandbox( + sandbox, f"tar cf {shlex.quote(remote_tar)} -C / {shlex.quote(rel_base)}", timeout=120, ) if exit_code != 0: raise RuntimeError(f"Tenki bulk download failed (exit {exit_code}): {output}") - self._sandbox.fs.download(remote_tar, dest) + sandbox.fs.download(remote_tar, str(dest)) finally: try: - self._exec_raw(f"rm -f {shlex.quote(remote_tar)}", timeout=10) + self._exec_raw_on_sandbox(sandbox, f"rm -f {shlex.quote(remote_tar)}", timeout=10) except Exception: pass + def _transfer_sandbox(self): + if self._cleanup_in_progress and self._cleanup_sandbox is not None: + return self._cleanup_sandbox + self._ensure_sandbox() + return self._sandbox + def _tenki_delete(self, remote_paths: list[str]) -> None: if not remote_paths: return @@ -454,8 +820,22 @@ def _tenki_delete(self, remote_paths: list[str]) -> None: def _exec_raw(self, command: str, *, login: bool = False, timeout: int = 120) -> tuple[str, int]: self._ensure_sandbox() + return self._exec_raw_on_sandbox(self._sandbox, command, login=login, timeout=timeout) + + def _exec_raw_on_sandbox( + self, + sandbox: Any, + command: str, + *, + login: bool = False, + timeout: int = 120, + ) -> tuple[str, int]: flag = "-lc" if login else "-c" - result = self._sandbox.exec("bash", flag, command, timeout=timeout) + result = sandbox.exec("bash", flag, command, timeout=timeout, env=self._sandbox_env()) + return self._result_to_output(result) + + @staticmethod + def _result_to_output(result: Any) -> tuple[str, int]: stdout = _text(_result_attr(result, ("stdout_text", "stdout", "output", "result", "text"))) stderr = _text(_result_attr(result, ("stderr_text", "stderr"))) exit_code = _result_attr(result, ("exit_code", "returncode", "status_code")) @@ -468,6 +848,42 @@ def _exec_raw(self, command: str, *, login: bool = False, timeout: int = 120) -> output = stdout + stderr return output, int(exit_code) + def _start_process( + self, + cmd_string: str, + *, + login: bool, + timeout: int, + stdin_data: str | None, + process_ref: dict[str, Any] | None = None, + ) -> tuple[str, int]: + self._ensure_sandbox() + flag = "-lc" if login else "-c" + start = getattr(self._sandbox, "start", None) + if not callable(start): + kwargs: dict[str, Any] = {"timeout": timeout, "env": self._sandbox_env()} + if stdin_data is not None: + kwargs["input"] = stdin_data + result = self._sandbox.exec("bash", flag, cmd_string, **kwargs) + return self._result_to_output(result) + + process = start( + "bash", + flag, + cmd_string, + timeout=timeout, + stdin=stdin_data, + env=self._sandbox_env(), + ) + if process_ref is not None: + process_ref["process"] = process + if stdin_data is None: + close_stdin = getattr(process, "close_stdin", None) + if callable(close_stdin): + close_stdin() + result = process.wait(timeout=timeout + 5 if timeout is not None else None) + return self._result_to_output(result) + def _sudo_nopasswd_works(self) -> bool: try: _output, exit_code = self._exec_raw("sudo -n true", timeout=10) @@ -502,13 +918,38 @@ def _run_bash( timeout: int = 120, stdin_data: str | None = None, ): + process_ref: dict[str, Any] = {} + def cancel() -> None: + process = process_ref.get("process") + kill = getattr(process, "kill", None) + if callable(kill): + try: + kill() + return + except Exception: + pass with self._lock: sandbox = self._sandbox + # Drop our reference so the next command resumes (persistent) or + # recreates (ephemeral) a sandbox instead of reusing a torn-down + # one. self._sandbox = None if sandbox is None: return - for method_name in ("terminate", "stop", "close"): + # For a persistent sandbox, pause (preserve the filesystem) instead of + # terminating: an interrupted or timed-out command must not destroy + # state the user asked to keep. The paused sandbox is re-discovered and + # resumed on the next command via _resume_persistent_sandbox(). + if self._persistent: + pause = getattr(sandbox, "pause", None) + if callable(pause): + try: + pause() + return + except Exception: + pass # fall through to terminate if pause is unavailable + for method_name in ("terminate", "close"): method = getattr(sandbox, method_name, None) if callable(method): try: @@ -518,62 +959,129 @@ def cancel() -> None: return def exec_fn() -> tuple[str, int]: - return self._exec_raw(cmd_string, login=login, timeout=timeout) + return self._start_process( + cmd_string, + login=login, + timeout=timeout, + stdin_data=stdin_data, + process_ref=process_ref, + ) return _ThreadedProcessHandle(exec_fn, cancel_fn=cancel) def cleanup(self): with self._lock: sandbox = self._sandbox - self._sandbox = None sync_manager = self._sync_manager self._sync_manager = None client = self._client - self._client = None + self._cleanup_in_progress = True + self._cleanup_sandbox = sandbox if sandbox is None: - if client is not None: - close = getattr(client, "close", None) - if callable(close): - close() + self._close_client(client) + with self._lock: + if self._client is client: + self._client = None + self._cleanup_in_progress = False + self._cleanup_sandbox = None return - if sync_manager: - logger.info("Tenki: syncing files from sandbox...") - try: - sync_manager.sync_back() - except Exception as exc: - logger.warning("Tenki: sync_back failed: %s", exc) + try: + if sync_manager: + logger.info("Tenki: syncing files from sandbox...") + try: + sync_manager.sync_back() + except Exception as exc: + logger.warning("Tenki: sync_back failed: %s", exc) - if self._persistent: - pause = getattr(sandbox, "pause", None) - if callable(pause): + snapshot_saved = False + if self._persistent: + snapshot_saved = self._save_persistent_snapshot(sandbox) + + if self._persistent and not snapshot_saved: + # Persistent state was NOT durably snapshotted. Terminating now + # would destroy the only copy, so prefer pause; and if pause + # fails, still do NOT terminate — leave the sandbox live for a + # later recovery attempt (the max-duration / idle reaper bounds + # the cost). Terminating here would break the preservation + # guarantee that the durability gate exists to uphold. + pause = getattr(sandbox, "pause", None) + if callable(pause): + try: + pause() + logger.info("Tenki: paused sandbox for task %s", self._task_id) + except Exception as exc: + logger.warning( + "Tenki: pause failed for task %s; leaving sandbox live to " + "preserve un-snapshotted state (not terminating): %s", + self._task_id, exc, + ) + else: + logger.warning( + "Tenki: no durable snapshot and no pause support for task %s; " + "leaving sandbox live to preserve state (not terminating)", + self._task_id, + ) + return + + for method_name in ("terminate", "close"): + method = getattr(sandbox, method_name, None) + if not callable(method): + continue try: - pause() - logger.info("Tenki: paused sandbox for task %s", self._task_id) - if client is not None: - close = getattr(client, "close", None) - if callable(close): - close() - return + method() + logger.info("Tenki: terminated sandbox for task %s", self._task_id) + except Exception as exc: + logger.warning("Tenki: cleanup failed: %s", exc) + return + finally: + self._close_client(client) + with self._lock: + if self._sandbox is sandbox: + self._sandbox = None + if self._client is client: + self._client = None + self._cleanup_in_progress = False + self._cleanup_sandbox = None + + def _save_persistent_snapshot(self, sandbox: Any) -> bool: + snapshot_id: str | None = None + try: + snapshot = sandbox.snapshot(name=self._sandbox_name(), wait=True) + snapshot_id = getattr(snapshot, "id", None) or getattr(snapshot, "snapshot_id", None) + except Exception as exc: + logger.warning("Tenki: filesystem snapshot failed: %s", exc) + return False + if not snapshot_id: + logger.warning("Tenki: snapshot completed without an id; preserving paused sandbox instead") + return False + # snapshot(wait=True) only waits for READY; durability is a separate, + # required gate. If durability is not confirmed the snapshot may not be + # a safe recovery copy, so we must NOT record it as the persistent + # pointer or let the caller terminate the live sandbox. Return False so + # cleanup pauses the sandbox and the prior (known-durable) snapshot + # pointer is left intact for recovery. + if self._client is not None: + snapshots = getattr(self._client, "snapshots", None) + wait_durable = getattr(snapshots, "wait_durable", None) + if callable(wait_durable): + try: + wait_durable(snapshot_id, timeout=300) except Exception as exc: - logger.warning("Tenki: pause failed; terminating instead: %s", exc) + logger.warning( + "Tenki: snapshot %s for task %s did not reach durability (%s); " + "preserving paused sandbox and prior snapshot instead", + snapshot_id, self._task_id, exc, + ) + return False + _store_snapshot(self._task_id, snapshot_id, self._snapshot_store) + logger.info("Tenki: saved filesystem snapshot %s for task %s", snapshot_id, self._task_id) + return True - for method_name in ("terminate", "delete", "close"): - method = getattr(sandbox, method_name, None) - if not callable(method): - continue - try: - method() - logger.info("Tenki: terminated sandbox for task %s", self._task_id) - except Exception as exc: - logger.warning("Tenki: cleanup failed: %s", exc) - finally: - if client is not None: - close = getattr(client, "close", None) - if callable(close): - close() + @staticmethod + def _close_client(client: Any) -> None: + if client is None: return - if client is not None: - close = getattr(client, "close", None) - if callable(close): - close() + close = getattr(client, "close", None) + if callable(close): + close() diff --git a/tools/file_operations.py b/tools/file_operations.py index 3626be5d93d8a..9741579dce1ac 100644 --- a/tools/file_operations.py +++ b/tools/file_operations.py @@ -614,6 +614,18 @@ def _lint_yaml_inproc(content: str) -> tuple[bool, str]: """In-process YAML syntax check. Returns (ok, error_message). Skipped gracefully if PyYAML isn't installed — YAML parsing is optional. + + Deliberately a *syntax-only* scan (``yaml.parse``), not ``safe_load``: + loading rejects perfectly valid YAML that merely isn't a single plain + document — multi-document streams (``---``-separated Kubernetes + manifests raise ``ComposerError``) and application-defined tags + (CloudFormation ``!Sub``/``!Ref``, Ansible ``!vault`` raise + ``ConstructorError``). Those are content conventions for whatever + consumes the file, not syntax errors, and this linter's verdict is + used as a fail-closed WRITE gate in ``write_file`` — a false positive + here refuses a legitimate write outright. ``yaml.parse`` still + catches real scanner/parser failures (unclosed quotes, bad + indentation, tab-mangled block maps). """ try: import yaml as _yaml @@ -621,7 +633,8 @@ def _lint_yaml_inproc(content: str) -> tuple[bool, str]: # PyYAML not available — skip silently, caller treats as no linter. return True, "__SKIP__" try: - _yaml.safe_load(content) + for _event in _yaml.parse(content): + pass return True, "" except _yaml.YAMLError as e: return False, f"YAMLError: {e}" @@ -677,6 +690,21 @@ def _lint_python_inproc(content: str) -> tuple[bool, str]: '.toml': _lint_toml_inproc, } +# Subset of LINTERS_INPROC that the pre-write fail-closed gate in +# ``write_file`` (see below) refuses on, rather than merely reporting. +# Deliberately excludes ``.py``: unlike JSON/YAML/TOML (atomic structured +# data blobs where "doesn't parse" always means "corrupt"), ``.py`` is +# used throughout this codebase's own test fixtures as a generic +# stand-in extension for arbitrary non-Python text content (e.g. +# ``tests/tools/test_file_operations.py``'s +# ``TestPatchReplacePostWriteVerification`` writes "hello world" / +# "hi world" through a ``*.py`` path purely to exercise write-mechanics, +# not Python validity). Hard-refusing on invalid Python would treat that +# established, exercised pattern as an error and break it. Python source +# keeps the existing (unchanged) post-write lint-delta *report* — still +# visible to the caller, just not a write-blocking refusal. +_FAIL_CLOSED_INPROC_EXTS = frozenset({'.json', '.yaml', '.yml', '.toml'}) + # Max limits for read operations MAX_LINES = 2000 MAX_LINE_LENGTH = 2000 @@ -930,7 +958,19 @@ def _expand_path(self, path: str) -> str: return path def _escape_shell_arg(self, arg: str) -> str: - """Escape a string for safe use in shell commands.""" + """Escape a string for safe use in shell commands. + + On Windows native drive paths (``C:\\Users\\x`` / ``C:/Users/x``) + and mixed MSYS leftovers (``/c/Users\\x``) are rewritten to the + Git Bash ``/c/Users/x`` form via ``_bash_safe_path``: bash eats + backslashes and MSYS otherwise mangles drive paths into the + ``Directory \\drivers\\etc does not exist`` failure class. Reuses + the env-layer translator so shell file ops and the terminal ``cd`` + agree on the path form. No-op off Windows and for plain POSIX paths. + """ + from tools.environments.local import _bash_safe_path + + arg = _bash_safe_path(arg) # Use single quotes and escape any single quotes in the string return "'" + arg.replace("'", "'\"'\"'") + "'" @@ -1316,12 +1356,21 @@ def write_file(self, path: str, content: str) -> WriteResult: files. The content never appears in the shell command string — only the file path does. - After the write, runs a post-first / pre-lazy lint check via - ``_check_lint_delta()``. If the new content is clean, the lint - call is O(one parse). If the new content has errors, the pre-write - content is linted too and only errors newly introduced by this - write are surfaced — pre-existing problems are filtered out so - the agent isn't distracted chasing them. + Before anything touches disk, a fail-closed syntax gate runs + against the CANDIDATE content: if ``path``'s extension is in + ``_FAIL_CLOSED_INPROC_EXTS`` (JSON/YAML/TOML — structured data + formats where a parse failure always means corruption) and the + candidate content doesn't parse, the write is refused outright. + No temp file, no rename, nothing on disk changes. + + After a write that clears the gate, runs a post-first / pre-lazy + lint check via ``_check_lint_delta()``. If the new content is + clean, the lint call is O(one parse). If the new content has + errors the gate didn't already catch (i.e. errors from a linter + outside ``_FAIL_CLOSED_INPROC_EXTS``, such as Python), the + pre-write content is linted too and only errors newly introduced + by this write are surfaced — pre-existing problems are filtered + out so the agent isn't distracted chasing them. Args: path: File path to write @@ -1337,6 +1386,44 @@ def write_file(self, path: str, content: str) -> WriteResult: if _is_write_denied(path): return WriteResult(error=f"Write denied: '{path}' is a protected system/credential file.") + # ── Fail-closed pre-write syntax gate ─────────────────────────── + # Validate the CANDIDATE content BEFORE any bytes touch disk — + # previously this only ran as a post-write lint *report* that the + # caller could ignore (or that ``files_modified`` gating wouldn't + # catch, since a lint failure never set the top-level ``error`` + # key). A structured-format write that doesn't even parse (mashed + # quotes, truncated generation, wrong indentation dialect) is a + # corrupt write, not a style nit — refuse it outright instead of + # writing first and reporting the damage afterward. + # + # Scope: only extensions in ``_FAIL_CLOSED_INPROC_EXTS`` (JSON/ + # YAML/TOML). ``.py`` deliberately keeps its pre-existing, + # non-blocking lint-delta *report* instead of a hard refusal — see + # ``_FAIL_CLOSED_INPROC_EXTS``'s docstring above for why. Extensions + # with no in-process linter at all (including ones only covered by + # a shell linter) are completely unaffected — this gate never runs + # for them, so behavior there is unchanged. + # + # Checked against the raw ``content`` argument, before the + # BOM/CRLF preservation shims below run. Those shims exist purely + # to match the on-disk file's existing conventions; linting + # post-shim would false-positive a JSONDecodeError on a + # legitimately BOM-marked JSON file purely because this method + # re-adds the marker the read layer strips — see + # ``_file_has_bom``/``_UTF8_BOM`` below. + ext = os.path.splitext(path)[1].lower() + inproc_linter = LINTERS_INPROC.get(ext) if ext in _FAIL_CLOSED_INPROC_EXTS else None + if inproc_linter is not None: + _ok, _lint_err = inproc_linter(content) + if not _ok and _lint_err != "__SKIP__": + return WriteResult( + error=( + f"Refusing to write '{path}': candidate content fails " + f"{ext} syntax validation ({_lint_err}). The file was " + "NOT created or modified. Fix the content and retry." + ) + ) + # Capture pre-write content. Two consumers want it: # # 1. The lint-delta layer (for in-process linters like ast.parse @@ -1352,7 +1439,6 @@ def write_file(self, path: str, content: str) -> WriteResult: # the UNION of in-process lint coverage and LSP coverage. For # extensions outside both sets (binaries, opaque formats), # skipping the read keeps the hot path fast. - ext = os.path.splitext(path)[1].lower() pre_content: Optional[str] = None want_pre = ext in LINTERS_INPROC or self._lsp_handles_extension(ext) if want_pre: diff --git a/tools/file_tools.py b/tools/file_tools.py index 7bf51aa900734..0312c145ce0f8 100644 --- a/tools/file_tools.py +++ b/tools/file_tools.py @@ -5,8 +5,10 @@ import json import logging import os +import posixpath +import sys import threading -from pathlib import Path +from pathlib import Path, PurePosixPath from agent.file_safety import get_read_block_error from tools.binary_extensions import has_binary_extension @@ -81,6 +83,51 @@ def _get_max_read_chars() -> int: _max_read_chars_cached = _DEFAULT_MAX_READ_CHARS return _max_read_chars_cached + +def _truncate_to_char_budget(content: str, max_chars: int) -> tuple[str, int, bool]: + """Trim line-numbered ``read_file`` content to fit a char budget. + + Ported in spirit from nearai/ironclaw#5029 (dual line/byte cap on + ``read_file``). Where hermes previously hard-rejected an oversized read + (forcing the model to guess a smaller ``limit`` and burn a round-trip + returning nothing), this trims the content to the last *complete line* + that fits within ``max_chars`` and reports how many lines were kept so + the caller can offer a ``next_offset`` continuation. + + ``content`` is the gutter-rendered text (``LINE_NUM|CONTENT`` joined by + ``\\n``). Individual lines are already clamped to ``get_max_line_length()`` + upstream, so a single line never blows the whole budget on its own; the + overflow this handles is the *accumulation* of many lines under the + line-count limit (logs, wide CSV rows, minified data). + + Returns ``(kept_text, lines_kept, truncated)``. When ``content`` already + fits, returns it unchanged with ``truncated=False``. If not even the + first line fits, that single line is clamped on a code-point boundary + (Python ``str`` slicing never splits a code point) so the read never + returns empty and the cursor can still advance. + """ + if len(content) <= max_chars: + return content, (content.count("\n") + 1 if content else 0), False + + lines = content.split("\n") + kept: list[str] = [] + running = 0 + for line in lines: + # +1 for the "\n" that rejoins this line to the previous one. + addition = len(line) + (1 if kept else 0) + if running + addition > max_chars: + break + kept.append(line) + running += addition + + if not kept: + # First line alone exceeds the budget. Clamp on a code-point + # boundary rather than emitting nothing. + kept.append(lines[0][:max_chars]) + + return "\n".join(kept), len(kept), True + + # If the total file size exceeds this AND the caller didn't specify a narrow # range (limit <= 200), we include a hint encouraging targeted reads. _LARGE_FILE_HINT_BYTES = 512_000 # 512 KB @@ -101,7 +148,7 @@ def _get_max_read_chars() -> int: }) -def _resolve_path(filepath: str, task_id: str = "default") -> Path: +def _resolve_path(filepath: str, task_id: str = "default") -> Path | PurePosixPath: """Resolve a path relative to TERMINAL_CWD (the worktree base directory) instead of the main repository root. """ @@ -117,6 +164,62 @@ def _resolve_path(filepath: str, task_id: str = "default") -> Path: # (gateway/run.py); the file/terminal-tool layer must do likewise so CLI # sessions get the same protection. See references/worktree-cwd-discipline.md. _TERMINAL_CWD_SENTINELS = frozenset({"", ".", "./", "auto", "cwd"}) +_CONTAINER_PATH_BACKENDS_FALLBACK = frozenset({"docker", "singularity", "modal", "daytona"}) + + +def _terminal_env_type_for_task(task_id: str = "default") -> str: + """Best-effort terminal backend type for path-resolution decisions.""" + try: + from tools.terminal_tool import ( + _active_environments, + _env_lock, + _get_env_config, + _resolve_container_task_id, + ) + + try: + container_key = _resolve_container_task_id(task_id) + except Exception: + container_key = task_id + with _env_lock: + env = _active_environments.get(container_key) or _active_environments.get(task_id) + if env is not None: + name = env.__class__.__name__.lower() + if "local" in name: + return "local" + if "ssh" in name: + return "ssh" + if "docker" in name: + return "docker" + if "singularity" in name: + return "singularity" + if "modal" in name: + return "modal" + if "daytona" in name: + return "daytona" + cfg = _get_env_config() + return str(cfg.get("env_type") or os.getenv("TERMINAL_ENV") or "local").lower() + except Exception: + return str(os.getenv("TERMINAL_ENV") or "local").lower() + + +def _uses_container_paths(task_id: str = "default") -> bool: + try: + from tools.terminal_tool import _CONTAINER_BACKENDS + container_backends = _CONTAINER_BACKENDS + except Exception: + container_backends = _CONTAINER_PATH_BACKENDS_FALLBACK + return _terminal_env_type_for_task(task_id) in container_backends + + +def _normalize_without_host_deref(path: str | Path | PurePosixPath) -> PurePosixPath: + """Normalize path syntax without following host symlinks. + + Container backends use paths that are meaningful inside the sandbox. Calling + ``Path.resolve()`` on the host can dereference a host-side symlink such as + ``/workspace`` and rewrite the path before Docker sees it. + """ + return PurePosixPath(posixpath.normpath(str(path))) def _sentinel_free_abs_cwd(raw: str | None) -> str | None: @@ -266,7 +369,11 @@ def _authoritative_workspace_root(task_id: str = "default") -> str | None: return _configured_terminal_cwd() -def _resolve_base_dir(task_id: str = "default") -> Path: +def _resolve_base_dir( + task_id: str = "default", + *, + container_paths: bool | None = None, +) -> Path | PurePosixPath: """Return the ABSOLUTE base directory for resolving relative paths. Resolution order: @@ -290,10 +397,28 @@ def _resolve_base_dir(task_id: str = "default") -> Path: the process cwd only as a last resort, deterministically. """ root = _authoritative_workspace_root(task_id) + if container_paths is None: + container_paths = _uses_container_paths(task_id) if root: - base = Path(_expand_tilde(root)) + base_text = _expand_tilde(root) else: - base = Path(os.getcwd()) + base_text = os.getcwd() + if container_paths: + if not posixpath.isabs(base_text): + base_text = posixpath.join(os.getcwd(), base_text) + return _normalize_without_host_deref(base_text) + # Git Bash ``pwd -P`` reports ``/c/Users/...``; translate before Path so + # relative file-tool paths don't anchor under a nonexistent ``\\c\\Users``. + from tools.environments.local import _msys_to_windows_path + + base_text = _msys_to_windows_path(base_text) + if sys.platform == "win32": + import ntpath + + if not ntpath.isabs(base_text): + base_text = ntpath.join(os.getcwd(), base_text) + return Path(ntpath.normpath(base_text)) + base = Path(base_text) if not base.is_absolute(): # Last-resort anchoring: a live cwd should already be absolute, but if a # terminal backend ever reports a relative cwd, anchor it to the process @@ -302,16 +427,41 @@ def _resolve_base_dir(task_id: str = "default") -> Path: return base.resolve() -def _resolve_path_for_task(filepath: str, task_id: str = "default") -> Path: +def _resolve_path_for_task(filepath: str, task_id: str = "default") -> Path | PurePosixPath: """Resolve *filepath* against the task's absolute base directory. See :func:`_resolve_base_dir` for how the base is chosen. Absolute input paths are returned resolved-but-unanchored. + + On native Windows, Git Bash / MSYS drive paths (``/c/Users/...``) are + translated to ``C:\\Users\\...`` before resolution so file tools don't + treat them as relative ``\\c\\Users\\...`` under the process cwd. """ - p = Path(_expand_tilde(filepath)) + container_paths = _uses_container_paths(task_id) + if container_paths: + expanded = _expand_tilde(filepath) + if posixpath.isabs(expanded): + return _normalize_without_host_deref(expanded) + resolved = _resolve_base_dir(task_id, container_paths=True) / expanded + return _normalize_without_host_deref(resolved) + + # Host paths only — never rewrite Linux paths inside a container/WSL env. + from tools.environments.local import _msys_to_windows_path + + expanded = _expand_tilde(_msys_to_windows_path(filepath)) + if sys.platform == "win32": + import ntpath + + if ntpath.isabs(expanded): + return Path(ntpath.normpath(expanded)) + joined = ntpath.join(str(_resolve_base_dir(task_id, container_paths=False)), expanded) + return Path(ntpath.normpath(joined)) + + p = Path(expanded) if p.is_absolute(): return p.resolve() - return (_resolve_base_dir(task_id) / p).resolve() + resolved = _resolve_base_dir(task_id, container_paths=False) / p + return resolved.resolve() def _path_resolution_warning(filepath: str, resolved: Path, task_id: str = "default") -> str | None: @@ -335,7 +485,10 @@ def _path_resolution_warning(filepath: str, resolved: Path, task_id: str = "defa workspace_root = _authoritative_workspace_root(task_id) if not workspace_root: return None # No authoritative workspace root to compare against. - root = Path(_expand_tilde(workspace_root)).resolve() + if _uses_container_paths(task_id): + root = _normalize_without_host_deref(Path(_expand_tilde(workspace_root))) + else: + root = Path(_expand_tilde(workspace_root)).resolve() # Is `resolved` inside `root`? try: resolved.relative_to(root) @@ -899,7 +1052,9 @@ def _get_file_ops(task_id: str = "default") -> ShellFileOperations: _creation_locks_lock, _resolve_container_task_id, _is_unusable_container_cwd, + _is_backend_guest_subpath, _CONTAINER_BACKENDS, + _container_config_from_env_config, ) import time @@ -957,6 +1112,8 @@ def _get_file_ops(task_id: str = "default") -> ShellFileOperations: image = overrides.get("modal_image") or config["modal_image"] elif env_type == "daytona": image = overrides.get("daytona_image") or config["daytona_image"] + elif env_type == "tenki": + image = overrides.get("tenki_image") or config["tenki_image"] else: image = "" @@ -973,7 +1130,11 @@ def _get_file_ops(task_id: str = "default") -> ShellFileOperations: # bypass the guard. Valid in-container override paths (RL/benchmark # sandboxes that set cwd to /workspace, /root, etc.) are absolute # non-host paths and pass through untouched. - if env_type in _CONTAINER_BACKENDS and _is_unusable_container_cwd(cwd): + if ( + env_type in _CONTAINER_BACKENDS + and _is_unusable_container_cwd(cwd) + and not _is_backend_guest_subpath(env_type, cwd) + ): if cwd != config["cwd"]: logger.info( "Ignoring host/relative cwd override %r for %s backend " @@ -984,17 +1145,8 @@ def _get_file_ops(task_id: str = "default") -> ShellFileOperations: logger.info("Creating new %s environment for task %s...", env_type, task_id[:8]) container_config = None - if env_type in {"docker", "singularity", "modal", "daytona"}: - container_config = { - "container_cpu": config.get("container_cpu", 1), - "container_memory": config.get("container_memory", 5120), - "container_disk": config.get("container_disk", 51200), - "container_persistent": config.get("container_persistent", True), - "docker_volumes": config.get("docker_volumes", []), - "docker_mount_cwd_to_workspace": config.get("docker_mount_cwd_to_workspace", False), - "docker_forward_env": config.get("docker_forward_env", []), - "docker_run_as_host_user": config.get("docker_run_as_host_user", False), - } + if env_type in _CONTAINER_BACKENDS: + container_config = _container_config_from_env_config(config) ssh_config = None if env_type == "ssh": @@ -1097,17 +1249,30 @@ def read_file_tool(path: str, offset: int = 1, limit: int = 500, task_id: str = content_len = len(result_dict["content"]) max_chars = _get_max_read_chars() if content_len > max_chars: - return json.dumps({ - "error": ( - f"Read produced {content_len:,} characters which exceeds " - f"the safety limit ({max_chars:,} chars). " - "Use offset and limit to read a smaller range. " - f"The document has {total_lines} lines of extracted text." - ), - "path": path, - "total_lines": total_lines, - "file_size": result_dict["file_size"], - }, ensure_ascii=False) + # Graceful char-budget truncation (nearai/ironclaw#5029): + # trim to the last complete line that fits and offer a + # next_offset rather than rejecting the whole extraction. + trimmed, lines_kept, _ = _truncate_to_char_budget( + result_dict["content"], max_chars + ) + next_offset = offset + lines_kept + shown_end = offset + lines_kept - 1 + result_dict["content"] = trimmed + result_dict["truncated"] = True + result_dict["truncated_by"] = "bytes" + result_dict["next_offset"] = next_offset + result_dict["hint"] = ( + f"Output truncated at the {max_chars:,}-char read budget " + f"after {lines_kept} line(s) (showing lines {offset}-" + f"{shown_end} of {total_lines}). Use offset={next_offset} " + "to continue." + ) + if len(trimmed.split("\n", 1)[0]) >= max_chars: + result_dict["hint"] += ( + " Note: the first line alone exceeded the budget and " + "was clamped mid-line; its remainder is not " + "retrievable via offset." + ) if result_dict["content"]: result_dict["content"] = redact_sensitive_text(result_dict["content"], file_read=True) return json.dumps(result_dict, ensure_ascii=False) @@ -1210,18 +1375,36 @@ def read_file_tool(path: str, offset: int = 1, limit: int = 500, task_id: str = file_size = result_dict.get("file_size", 0) max_chars = _get_max_read_chars() if content_len > max_chars: + # Graceful char-budget truncation (ported from nearai/ironclaw#5029). + # Instead of rejecting the whole read — which forces the model to + # guess a smaller `limit` and wastes a round-trip returning nothing + # — trim to the last complete line that fits and offer a + # `next_offset` so the model can paginate forward. This rescues the + # "few but very long lines" case (logs, wide CSVs, minified data) + # that sails past the line-count `limit` but blows the char budget. total_lines = result_dict.get("total_lines", "unknown") - return json.dumps({ - "error": ( - f"Read produced {content_len:,} characters which exceeds " - f"the safety limit ({max_chars:,} chars). " - "Use offset and limit to read a smaller range. " - f"The file has {total_lines} lines total." - ), - "path": path, - "total_lines": total_lines, - "file_size": file_size, - }, ensure_ascii=False) + trimmed, lines_kept, _ = _truncate_to_char_budget( + result.content or "", max_chars + ) + next_offset = offset + lines_kept + shown_end = offset + lines_kept - 1 + result.content = trimmed + result_dict["content"] = trimmed + result_dict["truncated"] = True + result_dict["truncated_by"] = "bytes" + result_dict["next_offset"] = next_offset + result_dict["hint"] = ( + f"Output truncated at the {max_chars:,}-char read budget after " + f"{lines_kept} line(s) (showing lines {offset}-{shown_end} of " + f"{total_lines}). Use offset={next_offset} to continue." + ) + if len(trimmed.split("\n", 1)[0]) >= max_chars: + result_dict["hint"] += ( + " Note: the first line alone exceeded the budget and was " + "clamped mid-line; its remainder is not retrievable via " + "offset." + ) + content_len = len(trimmed) # ── Redact secrets (after guard check to skip oversized content) ── if result.content: @@ -1856,7 +2039,7 @@ def _check_file_reqs(): READ_FILE_SCHEMA = { "name": "read_file", - "description": "Read a text file with line numbers and pagination. Use this instead of cat/head/tail in terminal. Output format: 'LINE_NUM|CONTENT'. Suggests similar filenames if not found. Use offset and limit for large files. Reads exceeding ~100K characters are rejected; use offset and limit to read specific sections of large files. Jupyter notebooks (.ipynb), Word documents (.docx), and Excel workbooks (.xlsx) are auto-extracted to readable text. NOTE: Cannot read images or other binary files — use vision_analyze for images.", + "description": "Read a text file with line numbers and pagination. Use this instead of cat/head/tail in terminal. Output format: 'LINE_NUM|CONTENT'. Suggests similar filenames if not found. Use offset and limit for large files. Reads exceeding ~100K characters are truncated on a line boundary and return a next_offset; continue with offset to read the rest. Jupyter notebooks (.ipynb), Word documents (.docx), and Excel workbooks (.xlsx) are auto-extracted to readable text. NOTE: Cannot read images or other binary files — use vision_analyze for images.", "parameters": { "type": "object", "properties": { diff --git a/tools/lazy_deps.py b/tools/lazy_deps.py index c69b5374a6322..232ac714c21a7 100644 --- a/tools/lazy_deps.py +++ b/tools/lazy_deps.py @@ -99,6 +99,10 @@ "provider.anthropic": ("anthropic==0.87.0",), # CVE-2026-34450, CVE-2026-34452 # AWS Bedrock provider "provider.bedrock": ("boto3==1.42.89",), + # Google Vertex AI provider — OAuth2 token minting for the Gemini + # OpenAI-compatible endpoint. Only loaded when provider=vertex is selected; + # google-auth is NOT in [all] so plain installs don't carry it. + "provider.vertex": ("google-auth==2.55.1",), # Microsoft Foundry — Entra ID auth (managed identity, workload identity, # service principal, az login, VS Code, azd, PowerShell). Only loaded # when model.auth_mode=entra_id is selected; key-based azure-foundry @@ -184,7 +188,7 @@ "qrcode==7.4.2", ), "platform.feishu": ( - "lark-oapi==1.5.3", + "lark-oapi==1.6.8", "qrcode==7.4.2", ), # WeCom callback-mode adapter — parses untrusted XML POST bodies. Pulls @@ -200,6 +204,7 @@ # ─── Terminal backends ───────────────────────────────────────────────── "terminal.modal": ("modal==1.3.4",), "terminal.daytona": ("daytona==0.155.0",), + "terminal.tenki": ("tenki-sandbox==0.1.1",), # ─── Skills ──────────────────────────────────────────────────────────── "skill.google_workspace": ( @@ -234,6 +239,8 @@ "mcp==1.26.0", "starlette==1.0.1", # CVE-2026-48710 — keep in sync with pyproject [computer-use] ), + # HF Agent Trace Viewer upload (hermes trace upload / /upload-trace). + "tool.trace_upload": ("huggingface-hub==1.2.3",), } @@ -449,6 +456,22 @@ def _allow_lazy_installs() -> bool: return True +def _unsupported_feature_reason(feature: str) -> Optional[str]: + """Return why a lazy feature cannot work on this host, or ``None``. + + This is a platform capability gate, not a security policy gate. It keeps + known-impossible installs out of both first-use lazy installation and the + ``hermes update`` lazy-refresh pass. + """ + 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.""" if not spec or len(spec) > 200: @@ -735,6 +758,10 @@ def ensure(feature: str, *, prompt: bool = True) -> None: if not missing: return + unsupported = _unsupported_feature_reason(feature) + if unsupported: + raise FeatureUnavailable(feature, missing, unsupported) + # Validate every spec against the allowlist + safety regex. Belt and # braces — the keys-in-LAZY_DEPS check above already constrains this. for spec in missing: @@ -865,13 +892,24 @@ def refresh_active_features(*, prompt: bool = False) -> dict[str, str]: if not missing: results[feature] = "current" continue + + unsupported = _unsupported_feature_reason(feature) + if unsupported: + results[feature] = f"skipped: {unsupported}" + continue + try: ensure(feature, prompt=prompt) results[feature] = "refreshed" except FeatureUnavailable as e: - # Distinguish "user opted out" from "install failed" so the - # update command can render the right message. - if "lazy installs disabled" in str(e) or "declined" in str(e): + # Distinguish "user opted out" or platform-incompatible features + # from install failures so the update command can render the + # right non-error message. + if ( + "lazy installs disabled" in str(e) + or "declined" in str(e) + or e.reason.startswith("unsupported ") + ): results[feature] = f"skipped: {e.reason}" else: results[feature] = f"failed: {e.reason}" diff --git a/tools/skills_tool.py b/tools/skills_tool.py index 95fc668ff2d09..823a08cd48f7d 100644 --- a/tools/skills_tool.py +++ b/tools/skills_tool.py @@ -68,6 +68,7 @@ import json import logging +import time from hermes_constants import get_hermes_home, display_hermes_home import os @@ -86,12 +87,76 @@ logger = logging.getLogger(__name__) +# Per-session skill discovery cache. _find_all_skills() re-reads every +# SKILL.md on every call; with hundreds of skills this is wasteful. +# Cache validation (mirrors hermes_cli/profiles.py::_count_skills, d5eee133e): +# - signature = per-dir max mtime of the dir AND its immediate children +# (one scandir per dir; catches skill add/remove inside categories, +# which does NOT bump the root dir's mtime), plus the disabled-set +# (config-driven — changes with no filesystem mtime bump at all) +# - a short TTL bounds staleness from in-place SKILL.md edits, which +# bump only the file's mtime, invisible to any directory signature. +# skip_disabled True/False are cached separately. +_SKILLS_CACHE: dict = {} # {cache_key: (signature, timestamp, skills_list)} +_SKILLS_CACHE_TTL_SECONDS = 30.0 +_SKILLS_CACHE_KEY_DISABLED = "with_disabled" +_SKILLS_CACHE_KEY_FILTERED = "filtered" + + +def _skills_scan_signature(dirs_to_scan, disabled) -> tuple: + """Cheap change-signature for the skill scan inputs. + + O(#dirs + #categories) stat calls, not a recursive walk. Includes the + platform the scan's ``skill_matches_platform`` filter will use (read + from ``agent.skill_utils``'s ``sys`` so test patches of that module + are honored) — the scan result is platform-dependent. + """ + from agent import skill_utils as _skill_utils + + platform = getattr(getattr(_skill_utils, "sys", None), "platform", "") + sig = [] + for d in dirs_to_scan: + try: + m = d.stat().st_mtime + except OSError: + continue + try: + with os.scandir(d) as it: + for entry in it: + try: + if entry.is_dir(follow_symlinks=False): + em = entry.stat(follow_symlinks=False).st_mtime + if em > m: + m = em + except OSError: + continue + except OSError: + pass + sig.append((str(d), m)) + return (tuple(sig), frozenset(disabled), platform) + # All skills live in ~/.hermes/skills/ (seeded from bundled skills/ on install). # This is the single source of truth -- agent edits, hub installs, and bundled # skills all coexist here without polluting the git repo. HERMES_HOME = get_hermes_home() SKILLS_DIR = HERMES_HOME / "skills" +_SKILLS_DIR_AT_IMPORT = SKILLS_DIR + + +def _skills_dir() -> Path: + """Return the active profile's skills directory at call time. + + Some long-lived runtimes import this module before the active profile has + set HERMES_HOME. Keep the legacy SKILLS_DIR module attribute for tests and + external patchers, but when it has not been patched, resolve from the live + profile-scoped HERMES_HOME on every call. + """ + configured = Path(SKILLS_DIR) + if configured != _SKILLS_DIR_AT_IMPORT: + return configured + return get_hermes_home() / "skills" + # Anthropic-recommended limits for progressive disclosure efficiency MAX_NAME_LENGTH = 64 @@ -501,9 +566,9 @@ def _get_category_from_path(skill_path: Path) -> Optional[str]: For paths like: ~/.hermes/skills/mlops/axolotl/SKILL.md -> "mlops" Also works for external skill dirs configured via skills.external_dirs. """ - # Try the module-level SKILLS_DIR first (respects monkeypatching in tests), + # Try the active profile skills dir first (respects monkeypatching in tests), # then fall back to external dirs from config. - dirs_to_check = [SKILLS_DIR] + dirs_to_check = [_skills_dir()] try: from agent.skill_utils import get_external_skills_dirs dirs_to_check.extend(get_external_skills_dirs()) @@ -611,21 +676,47 @@ def _find_all_skills(*, skip_disabled: bool = False) -> List[Dict[str, Any]]: Returns: List of skill metadata dicts (name, description, category). + + Results are cached per-session; the cache is invalidated when the scan + signature changes (dir/category mtimes or the disabled-set) and expires + after a short TTL to bound staleness from in-place SKILL.md edits. """ from agent.skill_utils import get_external_skills_dirs, iter_skill_index_files - skills = [] - seen_names: set = set() + cache_key = _SKILLS_CACHE_KEY_DISABLED if skip_disabled else _SKILLS_CACHE_KEY_FILTERED - # Load disabled set once (not per-skill) + # Load disabled set once (not per-skill). Part of the cache signature: + # disabling a skill is a config change with no filesystem mtime bump. disabled = set() if skip_disabled else _get_disabled_skill_names() - # Scan local dir first, then external dirs (local takes precedence) - dirs_to_scan = [] - if SKILLS_DIR.exists(): - dirs_to_scan.append(SKILLS_DIR) + # Collect directories to scan — same resolution as the scan loop below + # (_skills_dir() resolves the LIVE profile HERMES_HOME; the module-level + # SKILLS_DIR can be stale in long-lived runtimes). + dirs_to_scan: list = [] + active_skills_dir = _skills_dir() + if active_skills_dir.exists(): + dirs_to_scan.append(active_skills_dir) dirs_to_scan.extend(get_external_skills_dirs()) + signature = _skills_scan_signature(dirs_to_scan, disabled) + now = time.monotonic() + + cached = _SKILLS_CACHE.get(cache_key) + if ( + cached is not None + and cached[0] == signature + and (now - cached[1]) < _SKILLS_CACHE_TTL_SECONDS + ): + # Per-call shallow copies: callers mutate the returned dicts + # (e.g. web_server annotates s["enabled"]/s["usage"]) — handing + # out the cached objects would poison the cache for everyone else. + return [dict(s) for s in cached[2]] + + skills = [] + seen_names: set = set() + + # Scan local dir first, then external dirs (local takes precedence) — + # dirs_to_scan already resolved above for the signature. for scan_dir in dirs_to_scan: for skill_md in iter_skill_index_files(scan_dir, "SKILL.md"): if any(part in _EXCLUDED_SKILL_DIRS for part in skill_md.parts): @@ -678,7 +769,12 @@ def _find_all_skills(*, skip_disabled: bool = False) -> List[Dict[str, Any]]: ) continue - return skills + # Store in cache keyed by the scan signature computed BEFORE the scan + # (a write racing the scan changes the signature, so the next call + # re-scans rather than serving the torn result past the TTL). Same + # shallow-copy contract as the hit path — the caller may mutate. + _SKILLS_CACHE[cache_key] = (signature, now, skills) + return [dict(s) for s in skills] def _sort_skills(skills: List[Dict[str, Any]]) -> List[Dict[str, Any]]: @@ -701,8 +797,9 @@ def skills_list(category: str = None, task_id: str = None) -> str: JSON string with minimal skill info: name, description, category """ try: - if not SKILLS_DIR.exists(): - SKILLS_DIR.mkdir(parents=True, exist_ok=True) + active_skills_dir = _skills_dir() + if not active_skills_dir.exists(): + active_skills_dir.mkdir(parents=True, exist_ok=True) return json.dumps( { "success": True, @@ -984,8 +1081,9 @@ def skill_view( # Build list of all skill directories to search all_dirs = [] - if SKILLS_DIR.exists(): - all_dirs.append(SKILLS_DIR) + active_skills_dir = _skills_dir() + if active_skills_dir.exists(): + all_dirs.append(active_skills_dir) all_dirs.extend(get_external_skills_dirs()) if not all_dirs: @@ -1135,7 +1233,7 @@ def _record(sd: Optional[Path], smd: Path) -> None: # Security: warn if skill is loaded from outside trusted directories # (local skills dir + configured external_dirs are all trusted) _outside_skills_dir = True - _trusted_dirs = [SKILLS_DIR.resolve()] + _trusted_dirs = [active_skills_dir.resolve()] try: _trusted_dirs.extend(d.resolve() for d in all_dirs[1:]) except Exception: @@ -1375,7 +1473,7 @@ def _record(sd: Optional[Path], smd: Path) -> None: linked_files["scripts"] = script_files try: - rel_path = str(skill_md.relative_to(SKILLS_DIR)) + rel_path = str(skill_md.relative_to(active_skills_dir)) except ValueError: # External skill — use path relative to the skill's own parent dir rel_path = str(skill_md.relative_to(skill_md.parent.parent)) if skill_md.parent.parent else skill_md.name diff --git a/tools/tenki_config.py b/tools/tenki_config.py index 9ec3bf1e8c288..78f07771d9d8c 100644 --- a/tools/tenki_config.py +++ b/tools/tenki_config.py @@ -48,6 +48,40 @@ def _string(value: Any) -> str: return value.strip() if isinstance(value, str) else "" +def _scoped_env(name: str) -> str: + """Read a credential env var honoring the active profile secret scope. + + Under a multiplexed gateway turn a profile scope is installed, and the + token must come from *that* profile's secrets — never from a raw + ``os.environ`` read that could hold another profile's value. When no + multiplexing is active this behaves exactly like ``os.getenv``. + """ + try: + from agent.secret_scope import get_secret + + return _string(get_secret(name, "")) + except Exception: + # Fail closed: an unscoped read under active multiplexing (or any + # resolution error) must NOT silently leak a process-global value. + return "" + + +def _global_credential_fallback_allowed() -> bool: + """Whether machine-global credential sources (the shared Tenki CLI login) + may be consulted. + + Skipped whenever a profile secret scope is authoritative — a multiplexed + profile without its own Tenki token must not borrow the machine-global + ``tenki login`` credential that another profile may be relying on. + """ + try: + from agent.secret_scope import current_secret_scope, is_multiplex_active + + return current_secret_scope() is None and not is_multiplex_active() + except Exception: + return True + + def _first_string(data: dict[str, Any], keys: tuple[str, ...]) -> str: for key in keys: value = _string(data.get(key)) @@ -91,49 +125,75 @@ def _find_secret_value(data: Any) -> str: def resolve_tenki_api_endpoint(explicit: str = "") -> str: - """Resolve the Tenki API endpoint from config/env/CLI defaults.""" + """Resolve the Tenki API endpoint from config/env/CLI defaults. + + Scope-aware (see :func:`_scoped_env`): under a multiplexed profile turn the + active profile's setting wins, and the shared machine Tenki CLI config is + consulted only when no profile scope is authoritative. + """ explicit = _string(explicit) if explicit: return explicit for env_name in ("TENKI_API_ENDPOINT", "TENKI_API_URL"): - value = _string(os.getenv(env_name)) + value = _scoped_env(env_name) if value: return value - cfg = load_tenki_cli_config() - return _first_string(cfg, ("api_endpoint", "api_url", "endpoint")) or TENKI_DEFAULT_API_ENDPOINT + if _global_credential_fallback_allowed(): + cfg = load_tenki_cli_config() + endpoint = _first_string(cfg, ("api_endpoint", "api_url", "endpoint")) + if endpoint: + return endpoint + return TENKI_DEFAULT_API_ENDPOINT def resolve_tenki_workspace_id(explicit: str = "") -> str: + """Resolve the Tenki workspace id. Scope-aware; workspace/project decide + where sandboxes are created, so a multiplexed profile must not silently + borrow the machine-global workspace of another tenant.""" explicit = _string(explicit) if explicit: return explicit for env_name in ("TENKI_WORKSPACE_ID", "TENKI_WORKSPACE"): - value = _string(os.getenv(env_name)) + value = _scoped_env(env_name) if value: return value + if not _global_credential_fallback_allowed(): + return "" return _first_string(load_tenki_cli_config(), ("current_workspace_id", "workspace_id", "workspace")) def resolve_tenki_project_id(explicit: str = "") -> str: + """Resolve the Tenki project id. Scope-aware for the same reason as + :func:`resolve_tenki_workspace_id`.""" explicit = _string(explicit) if explicit: return explicit for env_name in ("TENKI_PROJECT_ID", "TENKI_PROJECT"): - value = _string(os.getenv(env_name)) + value = _scoped_env(env_name) if value: return value + if not _global_credential_fallback_allowed(): + return "" return _first_string(load_tenki_cli_config(), ("current_project_id", "project_id", "project")) def resolve_tenki_auth_token(explicit: str = "") -> str: - """Resolve a Tenki auth token/API key without logging or persisting it.""" + """Resolve a Tenki auth token/API key without logging or persisting it. + + Reads are profile-scope-aware (see :func:`_scoped_env`): under a + multiplexed gateway turn the active profile's secrets win, and the shared + machine ``tenki login`` credential is consulted only when no profile scope + is authoritative. + """ explicit = _string(explicit) if explicit: return explicit for env_name in ("TENKI_AUTH_TOKEN", "TENKI_API_KEY"): - value = _string(os.getenv(env_name)) + value = _scoped_env(env_name) if value: return value + if not _global_credential_fallback_allowed(): + return "" return _find_secret_value(load_tenki_cli_config()) diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py index 1e36776e65f4c..e788538e459e0 100644 --- a/tools/terminal_tool.py +++ b/tools/terminal_tool.py @@ -893,7 +893,7 @@ def _transform_sudo_command(command: str | None) -> tuple[str | None, str | None should prepend sudo_stdin to their stdin_data and pass the merged bytes to Popen's stdin pipe. - Callers that cannot pipe subprocess stdin (modal, daytona, tenki) must embed + Callers that cannot pipe subprocess stdin (modal, daytona) must embed the password in the command string themselves; see their execute() methods for how they handle the non-None sudo_stdin case. @@ -1217,6 +1217,35 @@ def _safe_getcwd() -> str: _CONTAINER_BACKENDS = frozenset({"docker", "singularity", "modal", "daytona", "tenki"}) +# Guest-home roots whose subtree is a valid container cwd even though the root +# shares a host-looking prefix. Tenki's guest home is /home/tenki, so +# /home/tenki/project is a real sandbox path, not a host path to discard. +_CONTAINER_GUEST_HOME_ROOTS = {"tenki": "/home/tenki"} + + +def _is_backend_guest_subpath(env_type: str, cwd: str) -> bool: + """True when *cwd* is the backend's guest-home root or a path beneath it.""" + root = _CONTAINER_GUEST_HOME_ROOTS.get(env_type) + if not root or not cwd: + return False + return cwd == root or cwd.startswith(root.rstrip("/") + "/") + + +def _is_ssh_remote_tilde_cwd(backend: str, cwd: str) -> bool: + """Return True when *cwd* is a tilde path that the remote SSH shell must + expand itself, so the Hermes host/container must NOT ``expanduser`` it. + + SSH ``cwd`` is interpreted by the *remote* shell (``cd ~`` / ``cd ~/x`` + over ``ssh ... bash -c``). Expanding ``~`` locally would rewrite it to the + Hermes host HOME (often ``/opt/data`` under Docker) and inject a + nonexistent path into the remote session. Only ``~`` / ``~/...`` on the + ``ssh`` backend qualify; absolute remote paths still pass through + unchanged, and every other backend keeps expanding locally. + """ + if (backend or "").strip().lower() != "ssh": + return False + return cwd == "~" or cwd.startswith("~/") + def _is_unusable_container_cwd(cwd: str) -> bool: """Return True if *cwd* is a host/relative path that won't work as the @@ -1273,6 +1302,22 @@ def _get_env_config() -> Dict[str, Any]: docker_env = {} docker_extra_args = [] + # Tenki settings may be bridged from config.yaml even when the active + # backend is local/ssh. Do not parse their numeric/JSON payloads until the + # tenki backend is selected; a stale or invalid value must not make the + # local terminal unusable (mirrors the container_/docker_ guards above). + tenki_backend = env_type == "tenki" + if tenki_backend: + tenki_forward_env = _parse_env_var("TERMINAL_TENKI_FORWARD_ENV", "[]", json.loads, "valid JSON") + tenki_max_duration = _parse_env_var("TERMINAL_TENKI_MAX_DURATION", "3600") + tenki_idle_timeout = _parse_env_var("TERMINAL_TENKI_IDLE_TIMEOUT", "0") + tenki_pause_retention = _parse_env_var("TERMINAL_TENKI_PAUSE_RETENTION", "0") + else: + tenki_forward_env = [] + tenki_max_duration = 3600 + tenki_idle_timeout = 0 + tenki_pause_retention = 0 + # Default cwd: local uses the host's current directory, ssh uses the # remote home, and everything else starts in the backend's default # root-like cwd. @@ -1290,7 +1335,7 @@ def _get_env_config() -> Dict[str, Any]: # /workspace and track the original host path separately. Otherwise keep the # normal sandbox behavior and discard host paths. cwd = os.getenv("TERMINAL_CWD", default_cwd) - if cwd: + if cwd and not _is_ssh_remote_tilde_cwd(env_type, cwd): cwd = os.path.expanduser(cwd) host_cwd = None if env_type == "docker" and mount_docker_cwd: @@ -1303,8 +1348,10 @@ def _get_env_config() -> Dict[str, Any]: host_cwd = candidate cwd = "/workspace" elif env_type in _CONTAINER_BACKENDS and cwd: - # Host paths and relative paths that won't work inside containers - if _is_unusable_container_cwd(cwd) and cwd != default_cwd: + # Host paths and relative paths that won't work inside containers. A + # path inside the backend's own guest-home subtree is valid even though + # it may share a host-looking prefix (see _is_backend_guest_subpath). + if _is_unusable_container_cwd(cwd) and not _is_backend_guest_subpath(env_type, cwd): logger.info("Ignoring TERMINAL_CWD=%r for %s backend " "(host/relative path won't work in sandbox). Using %r instead.", cwd, env_type, default_cwd) @@ -1325,10 +1372,11 @@ def _get_env_config() -> Dict[str, Any]: "tenki_name_prefix": os.getenv("TERMINAL_TENKI_NAME_PREFIX", "hermes"), "tenki_allow_inbound": os.getenv("TERMINAL_TENKI_ALLOW_INBOUND", "false").lower() in {"true", "1", "yes"}, "tenki_allow_outbound": os.getenv("TERMINAL_TENKI_ALLOW_OUTBOUND", "true").lower() in {"true", "1", "yes"}, - "tenki_max_duration": _parse_env_var("TERMINAL_TENKI_MAX_DURATION", "3600"), - "tenki_idle_timeout": _parse_env_var("TERMINAL_TENKI_IDLE_TIMEOUT", "0"), - "tenki_pause_retention": _parse_env_var("TERMINAL_TENKI_PAUSE_RETENTION", "0"), + "tenki_max_duration": tenki_max_duration, + "tenki_idle_timeout": tenki_idle_timeout, + "tenki_pause_retention": tenki_pause_retention, "tenki_sync_hermes_home": os.getenv("TERMINAL_TENKI_SYNC_HERMES_HOME", "false").lower() in {"true", "1", "yes"}, + "tenki_forward_env": tenki_forward_env, "cwd": cwd, "host_cwd": host_cwd, "docker_mount_cwd_to_workspace": mount_docker_cwd, @@ -1359,6 +1407,7 @@ def _get_env_config() -> Dict[str, Any]: "docker_volumes": docker_volumes, "docker_env": docker_env, "docker_run_as_host_user": os.getenv("TERMINAL_DOCKER_RUN_AS_HOST_USER", "false").lower() in {"true", "1", "yes"}, + "docker_network": os.getenv("TERMINAL_DOCKER_NETWORK", "true").lower() in {"true", "1", "yes"}, "docker_extra_args": docker_extra_args, # Cross-process container reuse (issue #20561). The docs claim # "ONE long-lived container shared across sessions" — this toggle @@ -1388,6 +1437,37 @@ def _get_modal_backend_state(modal_mode: object | None) -> Dict[str, Any]: ) +def _container_config_from_env_config(config: Dict[str, Any]) -> Dict[str, Any]: + """Build the shared container-backend config passed to _create_environment.""" + return { + "container_cpu": config.get("container_cpu", 1), + "container_memory": config.get("container_memory", 5120), + "container_disk": config.get("container_disk", 51200), + "container_persistent": config.get("container_persistent", True), + "modal_mode": config.get("modal_mode", "auto"), + "docker_volumes": config.get("docker_volumes", []), + "docker_mount_cwd_to_workspace": config.get("docker_mount_cwd_to_workspace", False), + "docker_forward_env": config.get("docker_forward_env", []), + "docker_env": config.get("docker_env", {}), + "docker_run_as_host_user": config.get("docker_run_as_host_user", False), + "docker_extra_args": config.get("docker_extra_args", []), + "docker_network": config.get("docker_network", True), + "docker_persist_across_processes": config.get("docker_persist_across_processes", True), + "docker_orphan_reaper": config.get("docker_orphan_reaper", True), + "tenki_api_endpoint": config.get("tenki_api_endpoint", ""), + "tenki_workspace_id": config.get("tenki_workspace_id", ""), + "tenki_project_id": config.get("tenki_project_id", ""), + "tenki_name_prefix": config.get("tenki_name_prefix", "hermes"), + "tenki_allow_inbound": config.get("tenki_allow_inbound", False), + "tenki_allow_outbound": config.get("tenki_allow_outbound", True), + "tenki_max_duration": config.get("tenki_max_duration", 3600), + "tenki_idle_timeout": config.get("tenki_idle_timeout", 0), + "tenki_pause_retention": config.get("tenki_pause_retention", 0), + "tenki_sync_hermes_home": config.get("tenki_sync_hermes_home", False), + "tenki_forward_env": config.get("tenki_forward_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, @@ -1419,6 +1499,7 @@ def _create_environment(env_type: str, image: str, cwd: str, timeout: int, docker_forward_env = cc.get("docker_forward_env", []) docker_env = cc.get("docker_env", {}) docker_extra_args = cc.get("docker_extra_args", []) + docker_network = cc.get("docker_network", True) if env_type == "local": return _LocalEnvironment(cwd=cwd, timeout=timeout) @@ -1441,6 +1522,7 @@ def _create_environment(env_type: str, image: str, cwd: str, timeout: int, forward_env=docker_forward_env, env=docker_env, run_as_host_user=cc.get("docker_run_as_host_user", False), + network=docker_network, extra_args=docker_extra_args, persist_across_processes=cc.get("docker_persist_across_processes", True), ) @@ -1541,6 +1623,7 @@ def _create_environment(env_type: str, image: str, cwd: str, timeout: int, idle_timeout=cc.get("tenki_idle_timeout", 0), pause_retention=cc.get("tenki_pause_retention", 0), sync_hermes_home=cc.get("tenki_sync_hermes_home", False), + forward_env=cc.get("tenki_forward_env", []), ) elif env_type == "ssh": @@ -2130,7 +2213,11 @@ def terminal_tool( # Valid in-container override paths (RL/benchmark sandboxes that set # cwd to /workspace, /root, etc.) are absolute non-host paths and pass # through untouched. - if env_type in _CONTAINER_BACKENDS and _is_unusable_container_cwd(cwd): + if ( + env_type in _CONTAINER_BACKENDS + and _is_unusable_container_cwd(cwd) + and not _is_backend_guest_subpath(env_type, cwd) + ): if cwd != config["cwd"]: logger.info( "Ignoring host/relative cwd override %r for %s backend " @@ -2224,31 +2311,7 @@ def terminal_tool( container_config = None if env_type in _CONTAINER_BACKENDS: - container_config = { - "container_cpu": config.get("container_cpu", 1), - "container_memory": config.get("container_memory", 5120), - "container_disk": config.get("container_disk", 51200), - "container_persistent": config.get("container_persistent", True), - "modal_mode": config.get("modal_mode", "auto"), - "docker_volumes": config.get("docker_volumes", []), - "docker_mount_cwd_to_workspace": config.get("docker_mount_cwd_to_workspace", False), - "docker_forward_env": config.get("docker_forward_env", []), - "docker_env": config.get("docker_env", {}), - "docker_run_as_host_user": config.get("docker_run_as_host_user", False), - "docker_extra_args": config.get("docker_extra_args", []), - "docker_persist_across_processes": config.get("docker_persist_across_processes", True), - "docker_orphan_reaper": config.get("docker_orphan_reaper", True), - "tenki_api_endpoint": config.get("tenki_api_endpoint", ""), - "tenki_workspace_id": config.get("tenki_workspace_id", ""), - "tenki_project_id": config.get("tenki_project_id", ""), - "tenki_name_prefix": config.get("tenki_name_prefix", "hermes"), - "tenki_allow_inbound": config.get("tenki_allow_inbound", False), - "tenki_allow_outbound": config.get("tenki_allow_outbound", True), - "tenki_max_duration": config.get("tenki_max_duration", 3600), - "tenki_idle_timeout": config.get("tenki_idle_timeout", 0), - "tenki_pause_retention": config.get("tenki_pause_retention", 0), - "tenki_sync_hermes_home": config.get("tenki_sync_hermes_home", False), - } + container_config = _container_config_from_env_config(config) local_config = None if env_type == "local": @@ -2307,6 +2370,11 @@ def terminal_tool( # Pre-exec security checks (tirith + dangerous command detection) # Skip check if force=True (user has confirmed they want to run it) approval_note = None + # True when the user explicitly approved this run (or pre-confirmed via + # force). Drives the clean-interrupt-slate clear before env.execute so + # an approved command can't be SIGINT-killed by a bit that landed during + # the approval-wait (see clear_current_thread_interrupt). + _approved_run = bool(force) if not force: approval = _check_all_guards( command, env_type, @@ -2324,6 +2392,8 @@ def terminal_tool( "command": approval.get("command", command), "description": approval.get("description", "command flagged"), "pattern_key": approval.get("pattern_key", ""), + "smart_denied": approval.get("smart_denied", False), + "allow_permanent": approval.get("allow_permanent", True), }, ensure_ascii=False) # Command was blocked desc = approval.get("description", "command flagged") @@ -2341,6 +2411,7 @@ def terminal_tool( if approval.get("user_approved"): desc = approval.get("description", "flagged as dangerous") approval_note = f"Command required approval ({desc}) and was approved by the user." + _approved_run = True elif approval.get("smart_approved"): desc = approval.get("description", "flagged as dangerous") approval_note = f"Command was flagged ({desc}) and auto-approved by smart approval." @@ -2422,6 +2493,9 @@ def terminal_tool( "exit_code": 0, "error": None, } + # Background spawns detached and returns exit_code 0 immediately; + # it never inline-polls is_interrupted(), so the stale-bit kill + # cannot occur here and this note never co-occurs with rc=130. if approval_note: result_data["approval"] = approval_note if pty_disabled_reason: @@ -2635,7 +2709,17 @@ def terminal_tool( retry_count = 0 result = None command_cwd = None - + + # Clean interrupt slate for an approved command, ONCE before the + # retry loop: drop a stale bit that landed on this thread during the + # approval-wait so it can't SIGINT the just-approved run. Do NOT + # re-clear inside the loop -- a genuine interrupt arriving during the + # backoff sleep between retries must survive and abort the command + # (caught by the next attempt's _wait_for_process poll loop -> 130). + if _approved_run: + from tools.interrupt import clear_current_thread_interrupt + clear_current_thread_interrupt() + while retry_count <= max_retries: try: command_cwd = _resolve_command_cwd( @@ -2777,7 +2861,19 @@ def terminal_tool( except Exception: logger.debug("verification evidence recording failed", exc_info=True) if approval_note: - result_dict["approval"] = approval_note + # Treat rc=130 as an interrupt only when the executor's marker is + # present. A command can legitimately exit 130 on its own + # (e.g. `bash -c 'exit 130'`); _wait_for_process returns the + # child's natural returncode there with no marker, and that must + # NOT be relabelled as a user interrupt in the audit note. + if returncode == 130 and "[Command interrupted]" in output: + # Approved command was interrupted mid-run by a genuine Stop. + # Keep the audit trail but never imply success: the bare + # "...approved by the user." note must not co-occur with the + # interrupt exit code (satisfies the 3-part-signature DONE). + result_dict["approval"] = approval_note.rstrip(".") + ", then interrupted." + else: + result_dict["approval"] = approval_note if exit_note: result_dict["exit_code_meaning"] = exit_note if sudo_auth_failed: diff --git a/uv.lock b/uv.lock index b51daeca10d3e..07dde5e690152 100644 --- a/uv.lock +++ b/uv.lock @@ -1516,7 +1516,7 @@ wheels = [ [[package]] name = "hermes-agent" -version = "0.18.0" +version = "0.18.2" source = { editable = "." } dependencies = [ { name = "certifi" }, @@ -1683,6 +1683,9 @@ teams = [ { name = "aiohttp" }, { name = "microsoft-teams-apps" }, ] +tenki = [ + { name = "tenki-sandbox" }, +] termux = [ { name = "agent-client-protocol" }, { name = "honcho-ai" }, @@ -1794,7 +1797,7 @@ requires-dist = [ { name = "honcho-ai", marker = "extra == 'honcho'", specifier = "==2.0.1" }, { name = "httpx", extras = ["socks"], specifier = "==0.28.1" }, { name = "jinja2", specifier = "==3.1.6" }, - { name = "lark-oapi", marker = "extra == 'feishu'", specifier = "==1.5.3" }, + { name = "lark-oapi", marker = "extra == 'feishu'", specifier = "==1.6.8" }, { name = "markdown", specifier = "==3.10.2" }, { name = "mautrix", extras = ["encryption"], marker = "extra == 'matrix'", specifier = "==0.21.0" }, { name = "mcp", marker = "extra == 'computer-use'", specifier = "==1.26.0" }, @@ -1845,6 +1848,7 @@ requires-dist = [ { name = "starlette", marker = "extra == 'web'", specifier = "==1.0.1" }, { name = "supermemory", marker = "extra == 'supermemory'", specifier = "==3.50.0" }, { name = "tenacity", specifier = "==9.1.4" }, + { name = "tenki-sandbox", marker = "extra == 'tenki'", specifier = "==0.1.1" }, { name = "ty", marker = "extra == 'dev'", specifier = "==0.0.21" }, { name = "tzdata", marker = "sys_platform == 'win32'", specifier = "==2025.3" }, { name = "urllib3", specifier = ">=2.7.0,<3" }, @@ -1853,7 +1857,7 @@ requires-dist = [ { name = "websockets", specifier = "==15.0.1" }, { name = "youtube-transcript-api", marker = "extra == 'youtube'", specifier = "==1.2.4" }, ] -provides-extras = ["anthropic", "exa", "firecrawl", "parallel-web", "fal", "edge-tts", "modal", "daytona", "hindsight", "dev", "messaging", "cron", "slack", "matrix", "wecom", "cli", "tts-premium", "voice", "pty", "honcho", "supermemory", "mem0", "vision", "mcp", "nemo-relay", "homeassistant", "sms", "teams", "computer-use", "acp", "mistral", "bedrock", "vertex", "azure-identity", "termux", "termux-all", "dingtalk", "feishu", "google", "youtube", "web", "all"] +provides-extras = ["anthropic", "exa", "firecrawl", "parallel-web", "fal", "edge-tts", "modal", "daytona", "tenki", "hindsight", "dev", "messaging", "cron", "slack", "matrix", "wecom", "cli", "tts-premium", "voice", "pty", "honcho", "supermemory", "mem0", "vision", "mcp", "nemo-relay", "homeassistant", "sms", "teams", "computer-use", "acp", "mistral", "bedrock", "vertex", "azure-identity", "termux", "termux-all", "dingtalk", "feishu", "google", "youtube", "web", "all"] [[package]] name = "hf-xet" @@ -2184,7 +2188,7 @@ wheels = [ [[package]] name = "lark-oapi" -version = "1.5.3" +version = "1.6.8" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "httpx" }, @@ -2194,7 +2198,7 @@ dependencies = [ { name = "websockets" }, ] wheels = [ - { url = "https://files.pythonhosted.org/packages/bf/ff/2ece5d735ebfa2af600a53176f2636ae47af2bf934e08effab64f0d1e047/lark_oapi-1.5.3-py3-none-any.whl", hash = "sha256:fda6b32bb38d21b6bdaae94979c600b94c7c521e985adade63a54e4b3e20cc36", size = 6993016, upload-time = "2026-01-27T08:21:49.307Z" }, + { url = "https://files.pythonhosted.org/packages/4a/ad/1ab04db5d549ad1a7a2cd33682b1c38dee1d65019cb24fd7a23270e6337d/lark_oapi-1.6.8-py3-none-any.whl", hash = "sha256:9b443a5d47a7d204dd42dc40896c8b75087cc35788e45c48c140806d7df7e5e8", size = 7798300, upload-time = "2026-06-02T07:40:05.492Z" }, ] [[package]] @@ -4061,6 +4065,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d7/c1/eb8f9debc45d3b7918a32ab756658a0904732f75e555402972246b0b8e71/tenacity-9.1.4-py3-none-any.whl", hash = "sha256:6095a360c919085f28c6527de529e76a06ad89b23659fa881ae0649b867a9d55", size = 28926, upload-time = "2026-02-07T10:45:32.24Z" }, ] +[[package]] +name = "tenki-sandbox" +version = "0.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "grpcio" }, + { name = "protobuf" }, + { name = "websocket-client" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/35/7f/6e59a084acece58d2349c80d95996cfc4971dcbc61038d6cc9a822edf3dc/tenki_sandbox-0.1.1.tar.gz", hash = "sha256:2748d3cb381c1f955163b368189899517aa04f70e59d64fb06a999f400dfb0b6", size = 107483, upload-time = "2026-06-10T09:23:28.337Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/6b/9e3a0eaf5064d47e3ec1115ba9585d117feb5507312e195d15ee9a9bba28/tenki_sandbox-0.1.1-py3-none-any.whl", hash = "sha256:826ab21db80b3ebe74c9a67f3eeb09f8d880535677f8d5dc3d03ad402210f97c", size = 94883, upload-time = "2026-06-10T09:23:26.958Z" }, +] + [[package]] name = "termcolor" version = "3.3.0" @@ -4395,6 +4413,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/68/5a/199c59e0a824a3db2b89c5d2dade7ab5f9624dbf6448dc291b46d5ec94d3/wcwidth-0.6.0-py3-none-any.whl", hash = "sha256:1a3a1e510b553315f8e146c54764f4fb6264ffad731b3d78088cdb1478ffbdad", size = 94189, upload-time = "2026-02-06T19:19:39.646Z" }, ] +[[package]] +name = "websocket-client" +version = "1.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2c/41/aa4bf9664e4cda14c3b39865b12251e8e7d239f4cd0e3cc1b6c2ccde25c1/websocket_client-1.9.0.tar.gz", hash = "sha256:9e813624b6eb619999a97dc7958469217c3176312b3a16a4bd1bc7e08a46ec98", size = 70576, upload-time = "2025-10-07T21:16:36.495Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/34/db/b10e48aa8fff7407e67470363eac595018441cf32d5e1001567a7aeba5d2/websocket_client-1.9.0-py3-none-any.whl", hash = "sha256:af248a825037ef591efbf6ed20cc5faa03d3b47b9e5a2230a529eeee1c1fc3ef", size = 82616, upload-time = "2025-10-07T21:16:34.951Z" }, +] + [[package]] name = "websockets" version = "15.0.1" diff --git a/website/docs/developer-guide/architecture.md b/website/docs/developer-guide/architecture.md index de4c8f598c7cf..6ec69cb6f14b3 100644 --- a/website/docs/developer-guide/architecture.md +++ b/website/docs/developer-guide/architecture.md @@ -231,7 +231,7 @@ Long-running process with 20 platform adapters, unified session routing, user au Three discovery sources: `~/.hermes/plugins/` (user), `.hermes/plugins/` (project), and pip entry points. Plugins register tools, hooks, and CLI commands through a context API. Two specialized plugin types exist: memory providers (`plugins/memory/`) and context engines (`plugins/context_engine/`). Both are single-select — only one of each can be active at a time, configured via `hermes plugins` or `config.yaml`. -→ [Plugin Guide](/guides/build-a-hermes-plugin), [Memory Provider Plugin](./memory-provider-plugin.md) +→ [Plugin Guide](/developer-guide/plugins), [Memory Provider Plugin](./memory-provider-plugin.md) ### Cron diff --git a/website/docs/guides/tips.md b/website/docs/guides/tips.md index 77a50ae066f0d..4c792c9c93366 100644 --- a/website/docs/guides/tips.md +++ b/website/docs/guides/tips.md @@ -133,7 +133,7 @@ Memory is a frozen snapshot — changes made during a session don't appear in th ### Don't Break the Prompt Cache -Most LLM providers cache the system prompt prefix. If you keep your system prompt stable (same context files, same memory), subsequent messages in a session get **cache hits** that are significantly cheaper. Avoid changing the model or system prompt mid-session. +Most LLM providers cache the conversation prefix (system prompt + history). If you keep your system prompt stable (same context files, same memory), subsequent messages in a session get **cache hits** that are significantly cheaper. The cache is keyed to the model and account — so an explicit `/model` switch, an [automatic provider fallback](../user-guide/features/fallback-providers.md), or a [credential-pool rotation](../user-guide/features/credential-pools.md) all force the next turn to re-read the entire conversation at full input price. Occasional switches are fine; frequent switching in a long session multiplies your cost. ### Use /compress Before Hitting Limits @@ -149,7 +149,7 @@ Instead of running terminal commands one at a time, ask the agent to write a scr ### Choose the Right Model -Use `/model` to switch models mid-session. Use a frontier model (Claude Sonnet/Opus, GPT-4o) for complex reasoning and architecture decisions. Switch to a faster model for simple tasks like formatting, renaming, or boilerplate generation. +Use `/model` to switch models mid-session. Use a frontier model (Claude Sonnet/Opus, GPT-4o) for complex reasoning and architecture decisions. Switch to a faster model for simple tasks like formatting, renaming, or boilerplate generation. Keep in mind each switch resets the prompt cache (see above), so on long sessions it's often cheaper to start a fresh session on the other model than to bounce back and forth. :::tip Run `/usage` periodically to see your token consumption. Run `/insights` for a broader view of usage patterns over the last 30 days. @@ -174,7 +174,7 @@ Instead of manually collecting user IDs for allowlists, enable DM pairing. When Use `/verbose` to control how much tool activity you see. In messaging platforms, less is usually more — keep it on "new" to see just new tool calls. In the CLI, "all" gives you a satisfying live view of everything the agent does. :::tip -On messaging platforms, sessions auto-reset after idle time (default: 24 hours) or daily at 4 AM. Adjust per-platform in `~/.hermes/config.yaml` if you need longer sessions. +By default, messaging sessions never auto-reset — context lives until you `/reset` or compression kicks in. If you want sessions to reset automatically (after idle time or daily at a fixed hour), opt in via the `session_reset` section in `~/.hermes/config.yaml`. ::: ## Security diff --git a/website/docs/reference/environment-variables.md b/website/docs/reference/environment-variables.md index 9480f3d0845d3..97d7470ff8cdf 100644 --- a/website/docs/reference/environment-variables.md +++ b/website/docs/reference/environment-variables.md @@ -14,6 +14,7 @@ Hermes reads environment variables from the process environment and, for user-ma |----------|-------------| | `OPENROUTER_API_KEY` | OpenRouter API key (recommended for flexibility) | | `OPENROUTER_BASE_URL` | Override the OpenRouter-compatible base URL | +| `FIREWORKS_API_KEY` | Fireworks AI API key ([app.fireworks.ai](https://app.fireworks.ai/settings/users/api-keys)). Configure endpoint overrides with `model.base_url` in `config.yaml`. | | `HERMES_OPENROUTER_CACHE` | Enable OpenRouter response caching (`1`/`true`/`yes`/`on`). Overrides `openrouter.response_cache` in config.yaml. See [Response Caching](https://openrouter.ai/docs/guides/features/response-caching). | | `HERMES_OPENROUTER_CACHE_TTL` | Cache TTL in seconds (1-86400). Overrides `openrouter.response_cache_ttl` in config.yaml. | | `NOUS_BASE_URL` | Override Nous Portal base URL (rarely needed; development/testing only) | @@ -162,6 +163,10 @@ For native Anthropic auth, Hermes prefers Claude Code's own credential files whe | `SUPERMEMORY_API_KEY` | Semantic long-term memory with profile recall and session ingest ([supermemory.ai](https://supermemory.ai)) | | `DAYTONA_API_KEY` | Daytona cloud sandboxes ([daytona.io](https://daytona.io/)) | | `TENKI_AUTH_TOKEN` / `TENKI_API_KEY` | Tenki cloud sandboxes ([tenki.cloud](https://tenki.cloud)); alternatively run `tenki login` | +| `TENKI_CONFIG_PATH` | Override the Tenki CLI config path Hermes reads for auth, workspace, and project defaults | +| `TENKI_API_ENDPOINT` / `TENKI_API_URL` | Direct Tenki API endpoint override used when terminal config is blank | +| `TENKI_WORKSPACE_ID` / `TENKI_WORKSPACE` | Direct Tenki workspace ID override used when terminal config is blank | +| `TENKI_PROJECT_ID` / `TENKI_PROJECT` | Direct Tenki project ID override used when terminal config is blank | ### Skill API Keys @@ -218,12 +223,14 @@ These variables configure the [Tool Gateway](/user-guide/features/tool-gateway) | `TERMINAL_TENKI_API_ENDPOINT` | Tenki API endpoint (default: `https://api.tenki.cloud`) | | `TERMINAL_TENKI_WORKSPACE_ID` | Tenki workspace ID; blank falls back to Tenki CLI config | | `TERMINAL_TENKI_PROJECT_ID` | Tenki project ID; blank falls back to Tenki CLI config | +| `TERMINAL_TENKI_NAME_PREFIX` | Prefix for Hermes-created Tenki sandbox names (default: `hermes`) | | `TERMINAL_TENKI_ALLOW_INBOUND` | Allow inbound network access in Tenki sandboxes (`true`/`false`, default: `false`) | | `TERMINAL_TENKI_ALLOW_OUTBOUND` | Allow outbound network access in Tenki sandboxes (`true`/`false`, default: `true`) | | `TERMINAL_TENKI_MAX_DURATION` | Tenki sandbox maximum duration in seconds (default: `3600`) | | `TERMINAL_TENKI_IDLE_TIMEOUT` | Tenki sandbox idle timeout in seconds; converted to minutes for the SDK (`0` disables explicit idle timeout) | | `TERMINAL_TENKI_PAUSE_RETENTION` | Tenki pause retention duration in seconds (`0` uses Tenki default) | | `TERMINAL_TENKI_SYNC_HERMES_HOME` | Opt-in sync of selected `~/.hermes` credentials, skills, and cache files into Tenki sandboxes (`true`/`false`, default: `false`) | +| `TERMINAL_TENKI_FORWARD_ENV` | JSON array of env var names to explicitly forward into Tenki sandboxes. Use this for task credentials such as `GITHUB_TOKEN`; values are resolved from the shell first, then `~/.hermes/.env`. | | `TERMINAL_TIMEOUT` | Command timeout in seconds | | `TERMINAL_LIFETIME_SECONDS` | Max lifetime for terminal sessions in seconds | | `TERMINAL_CWD` | Deprecated direct override for gateway/cron terminal sessions. Prefer `terminal.cwd` in `config.yaml`; CLI still uses the launch directory. | @@ -248,7 +255,7 @@ For cloud sandbox backends, persistence is filesystem-oriented. `TERMINAL_LIFETI | `TERMINAL_CONTAINER_CPU` | CPU cores (default: 1) | | `TERMINAL_CONTAINER_MEMORY` | Memory in MB (default: 5120) | | `TERMINAL_CONTAINER_DISK` | Disk in MB (default: 51200) | -| `TERMINAL_CONTAINER_PERSISTENT` | Persist container filesystem across sessions (default: `true`) | +| `TERMINAL_CONTAINER_PERSISTENT` | Persist container filesystem across sessions (default: `true`; Tenki defaults to `false` unless explicitly set) | | `TERMINAL_SANDBOX_DIR` | Host directory for workspaces and overlays (default: `~/.hermes/sandboxes/`) | ## Persistent Shell @@ -683,6 +690,7 @@ Advanced per-platform knobs for throttling the outbound message batcher. Most us | `HERMES_TELEGRAM_MEDIA_BATCH_DELAY_SECONDS` | Grace window before flushing queued Telegram media (default: `0.6`). | | `HERMES_TELEGRAM_FOLLOWUP_GRACE_SECONDS` | Delay before sending a follow-up after the agent finishes, to avoid racing the last stream chunk. | | `HERMES_TELEGRAM_HTTP_CONNECT_TIMEOUT` / `_READ_TIMEOUT` / `_WRITE_TIMEOUT` / `_POOL_TIMEOUT` | Override the underlying `python-telegram-bot` HTTP timeouts (seconds). | +| `HERMES_TELEGRAM_INIT_TIMEOUT` | Per-attempt cap (seconds) on the Telegram `initialize()` connect chain during gateway startup, so an unreachable fallback-IP chain can't block startup indefinitely (default: `30`). | | `HERMES_TELEGRAM_HTTP_POOL_SIZE` | Max concurrent HTTP connections to the Telegram API. | | `HERMES_TELEGRAM_DISABLE_FALLBACK_IPS` | Disable the hard-coded Cloudflare fallback IPs used when DNS fails (`true`/`false`). | | `HERMES_DISCORD_TEXT_BATCH_DELAY_SECONDS` | Grace window before flushing a queued Discord text chunk (default: `0.6`). | @@ -726,7 +734,7 @@ Advanced per-platform knobs for throttling the outbound message batcher. Most us | `HERMES_ACCEPT_HOOKS` | Auto-approve any unseen shell hooks declared in `config.yaml` without a TTY prompt. Equivalent to `--accept-hooks` or `hooks_auto_accept: true`. | | `HERMES_IGNORE_USER_CONFIG` | Skip `~/.hermes/config.yaml` and use built-in defaults (credentials in `.env` still load). Equivalent to `--ignore-user-config`. | | `HERMES_IGNORE_RULES` | Skip auto-injection of `AGENTS.md`, `SOUL.md`, `.cursorrules`, memory, and preloaded skills. Equivalent to `--ignore-rules`. | -| `HERMES_SAFE_MODE` | Troubleshooting mode: disable ALL customizations — skips plugin discovery and MCP server loading. Set automatically by `--safe-mode` (which also sets the two flags above). | +| `HERMES_SAFE_MODE` | Troubleshooting mode: disable ALL customizations — skips plugin discovery, MCP server loading, and shell-hook registration. Set automatically by `--safe-mode` (which also sets the two flags above). | | `HERMES_MD_NAMES` | Comma-separated list of rules-file names to auto-inject (default: `AGENTS.md,CLAUDE.md,.cursorrules,SOUL.md`). | | `HERMES_TOOL_PROGRESS` | Deprecated compatibility variable for tool progress display. Prefer `display.tool_progress` in `config.yaml`. | | `HERMES_TOOL_PROGRESS_MODE` | Deprecated compatibility variable for tool progress mode. Prefer `display.tool_progress` in `config.yaml`. | @@ -741,6 +749,7 @@ Advanced per-platform knobs for throttling the outbound message batcher. Most us | `HERMES_STREAM_READ_TIMEOUT` | Streaming socket read timeout in seconds (default: `120`). Auto-increased to `HERMES_API_TIMEOUT` for local providers. Increase if local LLMs time out during long code generation. | | `HERMES_STREAM_STALE_TIMEOUT` | Stale stream detection timeout in seconds (default: `180`). Auto-disabled for local providers. Triggers connection kill if no chunks arrive within this window. | | `HERMES_STREAM_RETRIES` | Number of mid-stream reconnect attempts on transient network errors (default: `3`). | +| `HERMES_STREAM_STALE_GIVEUP` | Cross-turn circuit breaker: after this many consecutive stale kills (streaming or non-streaming) with no completed response, abort each call immediately with an actionable error instead of re-waiting out the stale timeout (default: `5`, `0` disables). Resets on any completed response, `/model` switch, fallback activation, or turn-start primary restore. | | `HERMES_AGENT_TIMEOUT` | Gateway inactivity timeout for a running agent in seconds (default: `1800`, 30 minutes). Resets on every tool call and streamed token. Set to `0` to disable. | | `HERMES_AGENT_TIMEOUT_WARNING` | Gateway: send a warning message after this many seconds of inactivity (default: 75% of `HERMES_AGENT_TIMEOUT`). | | `HERMES_AGENT_NOTIFY_INTERVAL` | Gateway: interval in seconds between progress notifications on long-running agent turns. | diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md index bcc77f25e7362..e2e00b7a03200 100644 --- a/website/docs/user-guide/configuration.md +++ b/website/docs/user-guide/configuration.md @@ -108,11 +108,11 @@ Before that stash step, Hermes also restores tracked `package-lock.json` diffs l ## Terminal Backend Configuration -Hermes supports six terminal backends. Each determines where the agent's shell commands actually execute — your local machine, a Docker container, a remote server via SSH, a Modal cloud sandbox (direct or via the Nous-managed gateway), a Daytona workspace, or a Singularity/Apptainer container. +Hermes supports seven terminal backends. Each determines where the agent's shell commands actually execute — your local machine, a Docker container, a remote server via SSH, a Modal cloud sandbox (direct or via the Nous-managed gateway), a Daytona workspace, a Tenki sandbox, or a Singularity/Apptainer container. ```yaml terminal: - backend: local # local | docker | ssh | modal | daytona | singularity + backend: local # local | docker | ssh | modal | daytona | tenki | singularity cwd: "." # Gateway/cron working directory (CLI always uses launch dir) timeout: 180 # Per-command timeout in seconds home_mode: auto # auto | real | profile — subprocess HOME policy @@ -120,9 +120,15 @@ terminal: singularity_image: "docker://nikolaik/python-nodejs:python3.11-nodejs20" # Container image for Singularity backend modal_image: "nikolaik/python-nodejs:python3.11-nodejs20" # Container image for Modal backend daytona_image: "nikolaik/python-nodejs:python3.11-nodejs20" # Container image for Daytona backend + tenki_image: "" # Optional Tenki image/template; blank uses Tenki default + tenki_api_endpoint: "https://api.tenki.cloud" + tenki_workspace_id: "" # Blank falls back to Tenki CLI config + tenki_project_id: "" # Blank falls back to Tenki CLI config + tenki_sync_hermes_home: false # Opt-in sync of selected ~/.hermes files + tenki_forward_env: [] # Explicit host env vars to forward into Tenki ``` -For cloud sandboxes such as Modal and Daytona, `container_persistent: true` means Hermes will try to preserve filesystem state across sandbox recreation. It does not promise that the same live sandbox, PID space, or background processes will still be running later. +For cloud sandboxes such as Modal, Daytona, and Tenki, `container_persistent: true` means Hermes will try to preserve filesystem state across sandbox recreation. It does not promise that the same live sandbox, PID space, or background processes will still be running later. Tenki defaults to `container_persistent: false` so sandboxes are terminated when Hermes cleans them up; when persistence is enabled, Hermes pauses and later resumes the matching Tenki sandbox. ### Backend Overview @@ -133,6 +139,7 @@ For cloud sandboxes such as Modal and Daytona, `container_persistent: true` mean | **ssh** | Remote server via SSH | Network boundary | Remote dev, powerful hardware | | **modal** | Modal cloud sandbox | Full (cloud VM) | Ephemeral cloud compute, evals | | **daytona** | Daytona workspace | Full (cloud container) | Managed cloud dev environments | +| **tenki** | Tenki sandbox | Full (cloud sandbox) | On-demand cloud compute | | **singularity** | Singularity/Apptainer container | Namespaces (--containall) | HPC clusters, shared machines | ### Local Backend @@ -219,6 +226,7 @@ terminal: docker_extra_args: # Extra flags appended verbatim to `docker run` - "--gpus=all" - "--network=host" + docker_network: true # false = air-gap the container (--network=none) # Resource limits container_cpu: 1 # CPU cores (0 = unlimited) @@ -240,6 +248,8 @@ terminal: **`terminal.docker_extra_args`** (also overridable via `TERMINAL_DOCKER_EXTRA_ARGS='["--gpus=all"]'`) lets you pass arbitrary `docker run` flags that Hermes doesn't surface as first-class keys — `--gpus`, `--network`, `--add-host`, alternative `--security-opt` overrides, etc. Each entry must be a string; the list is appended last to the assembled `docker run` invocation so it can override Hermes' defaults if needed. Use sparingly — flags that conflict with the sandbox hardening (capability drops, `--user`, the workspace bind mount) will silently weaken isolation. +**`terminal.docker_network`** (default `true`; env: `TERMINAL_DOCKER_NETWORK`) — set to `false` to run the sandbox container with `--network=none`, cutting off all network egress from agent commands. This applies to the execution container used by `terminal`, `execute_code`, and the file tools. Because containers persist across Hermes processes, flipping this to `false` while an older networked container exists will remove that container and start a fresh air-gapped one (a warning is logged); background processes running inside it are lost. Prefer this key over passing `--network=none` through `docker_extra_args`. + **Requirements:** Docker Desktop or Docker Engine installed and running. Hermes probes `$PATH` plus common macOS install locations (`/usr/local/bin/docker`, `/opt/homebrew/bin/docker`, Docker Desktop app bundle). Podman is supported out of the box: set `HERMES_DOCKER_BINARY=podman` (or the full path) to force it when both are installed. #### Container lifecycle @@ -291,6 +301,7 @@ Every key under `terminal:` has an env-var override of the form `TERMINAL_ **Multiplexing caveat:** forwarded credentials are not profile-isolated under the multiplexing gateway's shared terminal cache — two profiles served by one gateway process can reuse the same live sandbox. Avoid forwarding sensitive credentials (especially the control-plane token) into sandboxes when running multiple profiles from a single multiplexed gateway. + +**Fully remote supervisor pattern:** To make Hermes itself live remotely, run the Hermes process inside a long-lived Tenki supervisor sandbox and configure that process with `terminal.backend: tenki`. The supervisor owns `~/.hermes`, model credentials, sessions, memory, and gateway/dashboard processes. Terminal, file, `execute_code`, and delegated subagent execution then create child Tenki sandboxes on demand. Give the supervisor Tenki credentials with `tenki login`, `TENKI_AUTH_TOKEN`, or `TENKI_API_KEY`; child sandboxes do not need host sudo passwords. + ### Singularity/Apptainer Backend Runs commands in a [Singularity/Apptainer](https://apptainer.org) container. Designed for HPC clusters and shared machines where Docker isn't available. @@ -396,13 +443,14 @@ If terminal commands fail immediately or the terminal tool is reported as disabl - **SSH** — Both `TERMINAL_SSH_HOST` and `TERMINAL_SSH_USER` must be set. Hermes logs a clear error if either is missing. - **Modal** — Needs `MODAL_TOKEN_ID` env var or `~/.modal.toml`. Run `hermes doctor` to check. - **Daytona** — Needs `DAYTONA_API_KEY`. The Daytona SDK handles server URL configuration. +- **Tenki** — Needs Tenki CLI login or `TENKI_AUTH_TOKEN`/`TENKI_API_KEY`. Workspace/project can come from the Tenki CLI config or `terminal.tenki_workspace_id` / `terminal.tenki_project_id`. - **Singularity** — Needs `apptainer` or `singularity` in `$PATH`. Common on HPC clusters. When in doubt, set `terminal.backend` back to `local` and verify that commands run there first. ### Remote-to-Host File Sync on Teardown -For the **SSH**, **Modal**, and **Daytona** backends (anywhere the agent's working tree lives on a different machine than the host running Hermes), Hermes tracks files the agent touched inside the remote sandbox and, on session teardown / sandbox cleanup, **syncs the modified files back to the host** under `~/.hermes/cache/remote-syncs//`. +For the **SSH**, **Modal**, **Daytona**, and **Tenki** backends (anywhere the agent's working tree lives on a different machine than the host running Hermes), Hermes tracks files the agent touched inside the remote sandbox and, on session teardown / sandbox cleanup, **syncs the modified files back to the host** under `~/.hermes/cache/remote-syncs//`. Tenki also supports opt-in selected `.hermes` credential/skill/cache sync with `terminal.tenki_sync_hermes_home: true`; it is disabled by default. - Triggers on: session close, `/new`, `/reset`, gateway message timeout, `delegate_task` subagent completion when the child used a remote backend. - Covers the whole tree the agent modified, not just files it explicitly opened. Additions, edits, and deletions are all captured. @@ -819,16 +867,11 @@ Plugin engines are **never auto-activated** — you must explicitly set `context See [Memory Providers](/user-guide/features/memory-providers) for the analogous single-select system for memory plugins. -## Iteration Budget Pressure - -When the agent is working on a complex task with many tool calls, it can burn through its iteration budget (default: 90 turns) without realizing it's running low. Budget pressure automatically warns the model as it approaches the limit: +## Iteration Budget -| Threshold | Level | What the model sees | -|-----------|-------|---------------------| -| **70%** | Caution | `[BUDGET: 63/90. 27 iterations left. Start consolidating.]` | -| **90%** | Warning | `[BUDGET WARNING: 81/90. Only 9 left. Respond NOW.]` | +When the agent is working on a complex task with many tool calls, it can burn through its iteration budget (default: 90 turns). Hermes does **not** inject mid-task pressure warnings — earlier builds warned the model at 70%/90% budget, which caused models to abandon complex tasks prematurely and was removed in April 2026. -Warnings are injected into the last tool result's JSON (as a `_budget_warning` field) rather than as separate messages — this preserves prompt caching and doesn't disrupt the conversation structure. +Instead, when the budget is actually exhausted (90/90), Hermes injects one message asking the model to wrap up and allows a single **grace call** so it can deliver a final response. If that grace call still doesn't produce text, the agent is asked to summarise what it accomplished. ```yaml agent: @@ -836,9 +879,7 @@ agent: api_max_retries: 3 # Retries per provider before fallback engages (default: 3) ``` -Budget pressure is enabled by default. The agent sees warnings naturally as part of tool results, encouraging it to consolidate its work and deliver a response before running out of iterations. - -When the iteration budget is fully exhausted, the CLI shows a notification to the user: `⚠ Iteration budget reached (90/90) — response may be incomplete`. If the budget runs out during active work, the agent generates a summary of what was accomplished before stopping. +When the iteration budget is fully exhausted, the CLI shows a notification to the user: `⚠ Iteration budget reached (90/90) — response may be incomplete`. `agent.api_max_retries` controls how many times Hermes retries a provider API call on transient errors (rate limits, connection drops, 5xx) **before** fallback-provider switching engages. The default is `3` — four attempts total. If you have [fallback providers](/user-guide/features/fallback-providers) configured and want to fail over faster, drop this to `0` so the first transient error on your primary immediately hands off to the fallback instead of churning retries against the flaky endpoint. @@ -915,20 +956,17 @@ For Claude on **native Anthropic**, **OpenRouter**, and **Nous Portal**, Hermes The Qwen Cloud (Alibaba DashScope) upstream caps cache TTL at 5 minutes, so Hermes uses the 5-minute breakpoint TTL there instead. Other Claude-via-third-party paths (AWS Bedrock, Azure Foundry) fall back to the provider's own caching defaults. xAI Grok uses a separate session-pinned conversation-id mechanism — see [xAI prompt caching](/integrations/providers#xai-grok--responses-api--prompt-caching). -Caching is on by default and saves money even on single-turn conversations because the system prompt alone is a meaningful fraction of the input token count. It can be turned off entirely with the `enabled` knob below when a strict provider rejects `cache_control` markers. +No knob exists to disable this — caching is always-on and saves money even on single-turn conversations because the system prompt alone is a meaningful fraction of the input token count. -The explicit knobs are whether caching runs at all and the cache TTL tier Hermes requests on Anthropic-style breakpoints: +The one explicit knob is the cache TTL tier Hermes requests on Anthropic-style breakpoints: ```yaml prompt_caching: - enabled: true # set false to stop sending cache_control markers entirely cache_ttl: "5m" # "5m" or "1h" (Anthropic-supported tiers); other values are ignored ``` `cache_ttl` selects the breakpoint TTL Hermes attaches for Claude via the native Anthropic API, OpenRouter, and Nous Portal. Only the two Anthropic-supported tiers (`"5m"`, `"1h"`) are honored — any other value is ignored. Providers with their own caps (e.g. Qwen Cloud, which maxes at 5 minutes) still clamp to what the upstream allows. -`enabled` defaults to `true`. Set it to `false` as an escape hatch for strict Anthropic-compatible proxies that inject their own `cache_control` markers server-side — stacking those on top of Hermes' breakpoints can exceed Anthropic's 4-breakpoint limit and return HTTP 400 `"A maximum of 4 blocks with cache_control may be provided"`. Disabling caching on that setup passes requests through without client-side markers so the proxy manages its own. - ## Auxiliary Models Hermes uses "auxiliary" models for side tasks like image analysis, web page summarization, browser screenshot analysis, session-title generation, and context compression. By default (`auxiliary.*.provider: "auto"`), Hermes routes every auxiliary task to your **main chat model** — the same provider/model you picked in `hermes model`. You don't need to configure anything to get started, but be aware that on expensive reasoning models (Opus, MiniMax M2.7, etc.) auxiliary tasks add meaningful cost. If you want cheap-and-fast side tasks regardless of your main model, set `auxiliary..provider` and `auxiliary..model` explicitly (for example, Gemini Flash on OpenRouter for vision and web extraction). @@ -1176,7 +1214,7 @@ These options apply to **auxiliary task configs** (`auxiliary:`, `compression:`) | `"xai-oauth"` | Force xAI Grok OAuth (browser login for SuperGrok or X Premium+ subscribers, no API key). Same OAuth token covers chat, TTS, image, video, and transcription. | `hermes model` → xAI Grok OAuth (SuperGrok / Premium+) | | `"main"` | Use your active custom/main endpoint. This can come from `OPENAI_BASE_URL` + `OPENAI_API_KEY` or from a custom endpoint saved via `hermes model` / `config.yaml`. Works with OpenAI, local models, or any OpenAI-compatible API. **Auxiliary tasks only — not valid for `model.provider`.** | Custom endpoint credentials + base URL | -Direct API-key providers from the main provider catalog also work here when you want side tasks to bypass your default router. `gmi` is valid once `GMI_API_KEY` is configured: +Direct API-key providers from the main provider catalog also work here when you want side tasks to bypass your default router. For example, `gmi` is valid once `GMI_API_KEY` is configured, and `fireworks` is valid once `FIREWORKS_API_KEY` is configured: ```yaml auxiliary: @@ -1185,7 +1223,7 @@ auxiliary: model: "anthropic/claude-opus-4.6" ``` -For GMI auxiliary routing, use the exact model ID returned by GMI's `/v1/models` endpoint. +For GMI auxiliary routing, use the exact model ID returned by GMI's `/v1/models` endpoint. Fireworks model IDs use the provider's native slash form, for example `accounts/fireworks/models/glm-5p2`. ### Common Setups @@ -1282,7 +1320,7 @@ Control how much "thinking" the model does before responding: ```yaml agent: - reasoning_effort: "" # empty = medium (default). Options: none, minimal, low, medium, high, xhigh (max) + reasoning_effort: "" # empty = medium. Options: none, minimal, low, medium, high, xhigh, max, ultra ``` When unset (default), reasoning effort defaults to "medium" — a balanced level that works well for most tasks. Setting a value overrides it — higher reasoning effort gives better results on complex tasks at the cost of more tokens and latency. @@ -1291,10 +1329,9 @@ When unset (default), reasoning effort defaults to "medium" — a balanced level These models use *adaptive* thinking and don't accept the usual `reasoning.effort` field — OpenRouter ignores it for them. Hermes transparently routes your `reasoning_effort` to OpenRouter's `verbosity` parameter instead (which maps to -Anthropic's `output_config.effort`), so the same `low`/`medium`/`high`/`xhigh` -knob keeps working — no extra configuration needed. `none` (or unset) leaves the -model on its own adaptive default. (`max` is accepted on the wire but is not a -selectable `reasoning_effort` value; `xhigh` is the configurable ceiling.) The +Anthropic's `output_config.effort`), so the same effort knob keeps working with +the levels supported by the selected model. `none` (or unset) leaves the model +on its own adaptive default. The native Anthropic provider already controls effort directly and is unaffected. ::: @@ -1546,6 +1583,8 @@ Hashes are deterministic — the same user always maps to the same hash, so the ```yaml stt: + enabled: true # Auto-transcribe inbound voice messages (default: true) + echo_transcripts: true # Post raw transcripts back to the chat as 🎙️ "..." (default: true) provider: "local" # "local" | "groq" | "openai" | "mistral" local: model: "base" # tiny, base, small, medium, large-v3 @@ -1554,6 +1593,8 @@ stt: # model: "whisper-1" # Legacy fallback key still respected ``` +Set `stt.echo_transcripts: false` when the gateway should transcribe voice notes for the agent but must not post the raw transcript back to the chat (for example, customer-facing WhatsApp bots). + Provider behavior: - `local` uses `faster-whisper` running on your machine. Install it separately with `pip install faster-whisper`. @@ -1881,13 +1922,13 @@ Control how Hermes handles potentially dangerous commands: ```yaml approvals: - mode: manual # manual | smart | off + mode: smart # smart | manual | off ``` | Mode | Behavior | |------|----------| -| `manual` (default) | Prompt the user before executing any flagged command. In the CLI, shows an interactive approval dialog. In messaging, queues a pending approval request. | -| `smart` | Use an auxiliary LLM to assess whether a flagged command is actually dangerous. Low-risk commands are auto-approved with session-level persistence. Genuinely risky commands are escalated to the user. | +| `smart` (default) | Use an auxiliary LLM to assess whether a flagged command is actually dangerous. Low-risk commands are auto-approved for that command only. Genuinely risky commands are denied; uncertain decisions escalate to the user. | +| `manual` | Prompt the user before executing any flagged command. In the CLI, shows an interactive approval dialog. In messaging, queues a pending approval request. | | `off` | Skip all approval checks. Equivalent to `HERMES_YOLO_MODE=true`. **Use with caution.** | Smart mode is particularly useful for reducing approval fatigue — it lets the agent work more autonomously on safe operations while still catching genuinely destructive commands. @@ -1896,6 +1937,19 @@ Smart mode is particularly useful for reducing approval fatigue — it lets the Setting `approvals.mode: off` disables all safety checks for terminal commands. Only use this in trusted, sandboxed environments. ::: +### Deny rules + +`approvals.deny` is a list of glob patterns that block matching terminal commands unconditionally — even under `--yolo`, `/yolo`, or `mode: off`. It's the user-editable counterpart to the built-in hardline blocklist: + +```yaml +approvals: + deny: + - "git push --force*" + - "*curl*|*sh*" +``` + +Patterns are case-insensitive fnmatch globs and must be quoted in YAML (a bare leading `*` is a parse error). See [Security — User-Defined Deny Rules](/user-guide/security#user-defined-deny-rules-approvalsdeny) for details. + ## Checkpoints Automatic filesystem snapshots before destructive file operations. See the [Checkpoints & Rollback](/user-guide/checkpoints-and-rollback) for details. diff --git a/website/docs/user-guide/security.md b/website/docs/user-guide/security.md index 59b460719503f..6848ac159912c 100644 --- a/website/docs/user-guide/security.md +++ b/website/docs/user-guide/security.md @@ -30,7 +30,7 @@ The approval system supports three modes, configured via `approvals.mode` in `~/ ```yaml approvals: - mode: manual # manual | smart | off + mode: smart # smart | manual | off timeout: 60 # seconds to wait for user response (default: 60) cron_mode: deny # deny | approve — what cron jobs do when they hit a dangerous command mcp_reload_confirm: true # /reload-mcp asks before invalidating the MCP tool cache @@ -41,7 +41,7 @@ The full set of keys: | Key | Default | What it controls | |---|---|---| -| `mode` | `manual` | Approval policy for dangerous shell commands — see the table below. | +| `mode` | `smart` | Approval policy for dangerous shell commands — see the table below. | | `timeout` | `60` | Seconds Hermes waits for an approval reply before timing out. | | `cron_mode` | `deny` | How [cron jobs](./features/cron.md) behave headlessly when they trigger a dangerous-command prompt. `deny` blocks the command (the agent must find another path); `approve` auto-approves everything in cron context. | | `mcp_reload_confirm` | `true` | When true, `/reload-mcp` asks before rebuilding the MCP tool set. Rebuilding invalidates the provider prompt cache (tool schemas live in the system prompt), so the next message re-sends full input tokens. Users who click **Always Approve** flip this key to `false`. | @@ -49,8 +49,8 @@ The full set of keys: | Mode | Behavior | |------|----------| -| **manual** (default) | Always prompt the user for approval on dangerous commands | -| **smart** | Use an auxiliary LLM to assess risk. Low-risk commands (e.g., `python -c "print('hello')"`) are auto-approved. Genuinely dangerous commands are auto-denied. Uncertain cases escalate to a manual prompt. | +| **smart** (default) | Use an auxiliary LLM to assess risk. Low-risk commands (e.g., `python -c "print('hello')"`) are auto-approved for that command only. Genuinely dangerous commands are auto-denied. Uncertain cases escalate to a manual prompt. | +| **manual** | Always prompt the user for approval on dangerous commands. | | **off** | Disable all approval checks — equivalent to running with `--yolo`. All commands execute without prompts. | :::warning @@ -110,6 +110,32 @@ The blocklist is the floor below `--yolo`. It trips **before** the approval laye If you hit the blocklist, the tool call returns an explanatory error to the agent and nothing runs. If a legitimate workflow needs one of these commands (you're the operator of a wipe-and-reinstall pipeline, for example), run it outside the agent. +### User-Defined Deny Rules (`approvals.deny`) + +The hardline blocklist is fixed and code-shipped. `approvals.deny` is its user-editable counterpart: a list of glob patterns that block matching terminal commands unconditionally — **before** `--yolo`, `/yolo`, and `approvals.mode: off` are consulted. Use it to run yolo-with-exceptions: "let the agent do everything, except these specific things, ever." + +```yaml +approvals: + deny: + - "git push --force*" + - "*curl*|*sh*" + - "dd if=* of=/dev/*" +``` + +Details: + +- Patterns are [fnmatch](https://docs.python.org/3/library/fnmatch.html) globs (`*`, `?`, `[...]`) matched **case-insensitively** against the whole command text. `git push --force*` matches `git push --force origin main` but not `git push origin main`. +- Matching runs over the same normalized/deobfuscated command variants the dangerous-pattern detector uses, so simple quoting tricks (`git pu""sh --force`) don't slip past a rule. +- **YAML quoting:** always quote patterns. A bare leading `*` is a YAML alias and fails to parse; `{`, `!`, and `: ` have their own YAML meanings. Single quotes are safest for shell-ish content. +- Deny rules apply to host-reaching backends (local, SSH, host-mounted Docker). Isolated container backends skip the guard stack entirely, as they always have — nothing they run can touch the host. +- A denied command returns a BLOCKED error to the agent telling it not to retry or rephrase. Nothing runs. + +Like the rest of the approval config, changes take effect immediately (the config cache is mtime-keyed) — no session restart needed. + +:::note Threat model +Deny rules are a guardrail against an honest-but-wrong agent, the same threat model as the dangerous-pattern detector. They are not a sandbox against a deliberately adversarial process — for that, use an isolated backend (Docker, Modal) or an egress-restricted environment. +::: + ### Approval Timeout When a dangerous command prompt appears, the user has a configurable amount of time to respond. If no response is given within the timeout, the command is **denied** by default (fail-closed). @@ -306,6 +332,24 @@ hermes pairing revoke telegram 123456789 hermes pairing clear-pending ``` +:::tip Docker users: run pairing commands as the `hermes` user +The official Docker image runs the gateway as the unprivileged `hermes` user +(uid 10000) via `gosu`, but `docker exec` defaults to root. Approval files +created by root are written with mode `0600 root:root` and the gateway +cannot read them — the approval is silently ignored ([#10270][i10270]). + +Always pass `-u hermes`: + +```bash +docker exec -u hermes hermes-agent hermes pairing approve telegram ABC12DEF +``` + +If you already ran the command as root and the user is still unauthorized, +restart the container — the entrypoint will fix ownership on the next start. + +[i10270]: https://github.com/NousResearch/hermes-agent/issues/10270 +::: + **Storage:** Pairing data is stored in `~/.hermes/pairing/` with per-platform JSON files: - `{platform}-pending.json` — pending pairing requests - `{platform}-approved.json` — approved users @@ -359,7 +403,7 @@ For production gateway deployments, use `docker`, `modal`, `daytona`, or `tenki` ::: :::warning -If you add names to `terminal.docker_forward_env`, those variables are intentionally injected into the container for terminal commands. This is useful for task-specific credentials like `GITHUB_TOKEN`, but it also means code running in the container can read and exfiltrate them. +If you add names to `terminal.docker_forward_env` or `terminal.tenki_forward_env`, those variables are intentionally injected into the sandbox for terminal commands. This is useful for task-specific credentials like `GITHUB_TOKEN`, but it also means code running in the sandbox can read and exfiltrate them. ::: ## Terminal Backend Security Comparison @@ -448,6 +492,7 @@ Paths are relative to `~/.hermes/`. Files are mounted to `/root/.hermes/` inside | **terminal** (local) | Blocks explicit Hermes infrastructure vars (provider keys, gateway tokens, tool API keys) | ✅ Passthrough vars bypass the blocklist | | **terminal** (Docker) | No host env vars by default | ✅ Passthrough vars + `docker_forward_env` forwarded via `-e` | | **terminal** (Modal) | No host env/files by default | ✅ Credential files mounted; env passthrough via sync | +| **terminal** (Tenki) | No arbitrary host env vars by default | ✅ Passthrough vars + `tenki_forward_env` forwarded via sandbox env | | **MCP** | Blocks everything except safe system vars + explicitly configured `env` | ❌ Not affected by passthrough (use MCP `env` config instead) | ### Security Considerations diff --git a/website/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-hermes-agent.md b/website/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-hermes-agent.md index caa66b64e7a9a..8978978d6d76b 100644 --- a/website/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-hermes-agent.md +++ b/website/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-hermes-agent.md @@ -286,7 +286,7 @@ The registry of record is `hermes_cli/commands.py` — every consumer /config Show config (CLI) /model [name] Show or change model /personality [name] Set personality -/reasoning [level] Set reasoning (none|minimal|low|medium|high|xhigh|show|hide) +/reasoning [level] Set reasoning (none|minimal|low|medium|high|xhigh|max|ultra|show|hide) /verbose Cycle: off → new → all → verbose /voice [on|off|tts] Voice mode /yolo Toggle approval bypass @@ -492,10 +492,10 @@ hermes config set privacy.redact_pii false # disable (default) ### Command approval prompts -By default (`approvals.mode: manual`), Hermes prompts the user before running shell commands flagged as destructive (`rm -rf`, `git reset --hard`, etc.). The modes are: +By default (`approvals.mode: smart`), Hermes asks an auxiliary LLM to assess shell commands flagged as destructive (`rm -rf`, `git reset --hard`, etc.). The modes are: -- `manual` — always prompt (default) -- `smart` — use an auxiliary LLM to auto-approve low-risk commands, prompt on high-risk +- `smart` — auto-approve a low-risk command once, deny high-risk commands, and prompt when uncertain (default) +- `manual` — always prompt - `off` — skip all approval prompts (equivalent to `--yolo`) ```bash @@ -1034,7 +1034,7 @@ See `tests/agent/test_prompt_builder.py::TestEnvironmentHints` for a worked exam Factual guidance about the host OS, user home, cwd, terminal backend, and shell (bash vs. PowerShell on Windows) is emitted from `agent/prompt_builder.py::build_environment_hints()`. This is also where the WSL hint and per-backend probe logic live. The convention: - **Local terminal backend** → emit host info (OS, `$HOME`, cwd) + Windows-specific notes (hostname ≠ username, `terminal` uses bash not PowerShell). -- **Remote terminal backend** (anything in `_REMOTE_TERMINAL_BACKENDS`: `docker, singularity, modal, daytona, ssh, managed_modal`) → **suppress** host info entirely and describe only the backend. A live `uname`/`whoami`/`pwd` probe runs inside the backend via `tools.environments.get_environment(...).execute(...)`, cached per process in `_BACKEND_PROBE_CACHE`, with a static fallback if the probe times out. +- **Remote terminal backend** (anything in `_REMOTE_TERMINAL_BACKENDS`: `docker, singularity, modal, daytona, tenki, ssh, managed_modal`) → **suppress** host info entirely and describe only the backend. A live `uname`/`whoami`/`pwd` probe runs inside the backend via `tools.environments.get_environment(...).execute(...)`, cached per process in `_BACKEND_PROBE_CACHE`, with a static fallback if the probe times out. - **Key fact for prompt authoring:** when `TERMINAL_ENV != "local"`, *every* file tool (`read_file`, `write_file`, `patch`, `search_files`) runs inside the backend container, not on the host. The system prompt must never describe the host in that case — the agent can't touch it. Full design notes, the exact emitted strings, and testing pitfalls: