Skip to content

The agent that grows with you

refactor(tools): tool_result_storage/backend_helpers — collapse guard ladders and single-use locals, join lazy-import blank lines, compact docstrings

Teknium71c96e6762c4
diff --git a/tools/tool_backend_helpers.py b/tools/tool_backend_helpers.py
index fc3cdb7cf8c..4bcb3ff543f 100644
--- a/tools/tool_backend_helpers.py
+++ b/tools/tool_backend_helpers.py
@@ -23,7 +23,6 @@ def managed_nous_tools_enabled(*, force_fresh: bool = False) -> bool:
via ``tool_gateway_entitled_for``; ``force_fresh`` is for flows needing a just-bought grant."""
try:
from hermes_cli.nous_account import get_nous_portal_account_info
-
account_info = (get_nous_portal_account_info(force_fresh=True) if force_fresh
else get_nous_portal_account_info())
return bool(account_info.logged_in) and account_info.tool_gateway_entitled
@@ -36,19 +35,15 @@ def nous_tool_gateway_unavailable_message(
"""Return account-aware guidance for an unavailable Nous Tool Gateway path."""
try:
from hermes_cli.nous_account import (
- format_nous_portal_entitlement_message,
- get_nous_portal_account_info,
- )
-
- account_info = get_nous_portal_account_info(force_fresh=force_fresh)
- message = format_nous_portal_entitlement_message(account_info, capability=capability)
+ format_nous_portal_entitlement_message, get_nous_portal_account_info)
+ message = format_nous_portal_entitlement_message(
+ get_nous_portal_account_info(force_fresh=force_fresh), capability=capability)
if message:
return message
except Exception:
pass
- return (
- f"{capability} is unavailable. Run `hermes model` to refresh your "
- "Nous Portal login and billing status.")
+ return (f"{capability} is unavailable. Run `hermes model` to refresh your "
+ "Nous Portal login and billing status.")
def normalize_browser_cloud_provider(value: object | None) -> str:
@@ -68,12 +63,12 @@ normalize_modal_mode = coerce_modal_mode
def has_direct_modal_credentials() -> bool:
"""Return True when direct Modal credentials/config are available."""
+ if os.getenv("MODAL_TOKEN_ID") and os.getenv("MODAL_TOKEN_SECRET"):
+ return True
try:
- modal_file_exists = (Path.home() / ".modal.toml").exists()
- except (PermissionError, OSError):
- modal_file_exists = False
- return bool(
- (os.getenv("MODAL_TOKEN_ID") and os.getenv("MODAL_TOKEN_SECRET")) or modal_file_exists)
+ return (Path.home() / ".modal.toml").exists()
+ except OSError: # includes PermissionError on Path.home()
+ return False
def resolve_modal_backend_state(
@@ -82,8 +77,8 @@ def resolve_modal_backend_state(
has_direct: bool,
managed_ready: bool,
managed_enabled: bool | None = None) -> Dict[str, Any]:
- """Resolve direct vs managed Modal backend: ``direct``/``managed`` are
- exclusive; ``auto`` prefers managed when available, else direct."""
+ """Resolve direct vs managed Modal backend: ``direct``/``managed`` are exclusive; ``auto``
+ prefers managed when available, else direct."""
requested_mode = coerce_modal_mode(modal_mode)
if managed_enabled is None:
managed_enabled = managed_nous_tools_enabled()
@@ -104,12 +99,10 @@ def resolve_modal_backend_state(
def _scoped_credential(name: str) -> str:
- """Read a credential env var under the active profile secret scope. Raw env
- fallback only if ``agent.secret_scope`` cannot import — a packaging edge must
- never leave the caller without a key."""
+ """Read a credential env var under the active profile secret scope; raw env fallback only
+ if ``agent.secret_scope`` cannot import (a packaging edge must never lose the key)."""
try:
from agent.secret_scope import get_secret
-
return (get_secret(name, "") or "").strip()
except Exception: # pragma: no cover — secret_scope is in-repo
return (os.getenv(name, "") or "").strip()
@@ -119,7 +112,6 @@ def _dotenv_value(env_var: str) -> str:
"""``.env`` value via ``hermes_cli.config.get_env_value`` (``""`` when unavailable)."""
try:
from hermes_cli.config import get_env_value
-
return str(get_env_value(env_var) or "").strip()
except Exception: # pragma: no cover — config is in-repo
return ""
@@ -127,23 +119,16 @@ def _dotenv_value(env_var: str) -> str:
def resolve_provider_secret(
env_var: str, provider_id: str, config_value: str = "", env_getter=None) -> str:
- """Resolve a voice-provider API key (single owner for STT/TTS lookup).
-
- Order: explicit ``config_value`` -> profile secret scope / env -> ``.env``
- via ``env_getter`` (or ``hermes_cli.config.get_env_value``) -> credential
- pool for ``provider_id``. Under an active multiplex turn the profile scope
- is authoritative: a miss returns ``""`` rather than borrowing another
- profile's env or pool. Never raises.
- """
- value = str(config_value or "").strip()
- if value:
- return value
- key = _scoped_credential(env_var)
+ """Resolve a voice-provider API key (single owner for STT/TTS lookup). Order: explicit
+ ``config_value`` -> profile secret scope / env -> ``.env`` via ``env_getter`` (or
+ ``hermes_cli.config.get_env_value``) -> credential pool for ``provider_id``. Under an
+ active multiplex turn the profile scope is authoritative: a miss returns ``""`` rather
+ than borrowing another profile's env or pool. Never raises."""
+ key = str(config_value or "").strip() or _scoped_credential(env_var)
if key:
return key
try:
from agent.secret_scope import is_multiplex_active
-
if is_multiplex_active():
return ""
except Exception: # pragma: no cover — secret_scope is in-repo
@@ -154,18 +139,12 @@ def resolve_provider_secret(
return key
try:
from agent.credential_pool import load_pool
-
# config.yaml ``providers.<name>`` entries are pooled under ``custom:<name>``.
for pool_key in (provider_id, f"custom:{provider_id}"):
pool = load_pool(pool_key)
- if pool is None or not pool.has_credentials():
- continue
- entry = pool.peek()
- if entry is None:
- continue
- key = str(
- getattr(entry, "runtime_api_key", "") or getattr(entry, "access_token", "") or ""
- ).strip()
+ entry = pool.peek() if pool is not None and pool.has_credentials() else None
+ key = str(getattr(entry, "runtime_api_key", "") or getattr(entry, "access_token", "")
+ or "").strip()
if key:
return key
except Exception as exc:
@@ -174,12 +153,11 @@ def resolve_provider_secret(
def resolve_openai_audio_api_key() -> str:
- """Prefer VOICE_TOOLS_OPENAI_KEY, else OPENAI_API_KEY (scope-aware, with
- credential-pool fallback for the latter). Must go through the secret scope:
- a raw ``os.environ`` read could bill another profile's account under multiplex."""
- return (
- resolve_provider_secret("VOICE_TOOLS_OPENAI_KEY", "")
- or resolve_provider_secret("OPENAI_API_KEY", "openai-api"))
+ """Prefer VOICE_TOOLS_OPENAI_KEY, else OPENAI_API_KEY (scope-aware, pool fallback for the
+ latter). Must go through the secret scope: a raw ``os.environ`` read could bill another
+ profile's account under multiplex."""
+ return (resolve_provider_secret("VOICE_TOOLS_OPENAI_KEY", "")
+ or resolve_provider_secret("OPENAI_API_KEY", "openai-api"))
def prefers_gateway(config_section: str) -> bool:
@@ -194,15 +172,13 @@ def prefers_gateway(config_section: str) -> bool:
return False
-# Provider value the managed "Nous Subscription" picker rows write for every
-# category; any other name = that vendor direct; no key = legacy autodetect.
+# Provider value the managed "Nous Subscription" picker rows write for every category;
+# any other name = that vendor direct; no key = legacy autodetect.
NOUS_MANAGED_PROVIDER = "nous"
-
# Per-capability keys that also count as "this category has been configured".
_EXTRA_SELECTION_KEYS = {"web": ("search_backend", "extract_backend")}
-
-# Key(s) carrying the category's provider selection. ``browser.backend`` is the
-# DRIVER choice (browser-use CLI vs built-in), not the cloud provider — excluded.
+# Key(s) carrying the category's provider selection. ``browser.backend`` is the DRIVER
+# choice (browser-use CLI vs built-in), not the cloud provider — excluded.
_SELECTION_NAME_KEYS = {"browser": ("cloud_provider",), "web": ("backend",)}
_DEFAULT_NAME_KEYS = ("provider", "backend", "cloud_provider")
@@ -211,7 +187,6 @@ def _raw_section(section: str) -> Dict[str, Any] | None:
"""The RAW (unmerged) config.yaml mapping for ``section``, or None."""
try:
from hermes_cli.config import read_raw_config_readonly
-
cfg = read_raw_config_readonly() or {}
raw = cfg.get(section) if isinstance(cfg, dict) else None
except Exception:
@@ -220,15 +195,12 @@ def _raw_section(section: str) -> Dict[str, Any] | None:
def read_selection(section: str) -> str | None:
- """THE single runtime read of the persisted `hermes tools` selection.
-
- Returns ``"nous"`` (managed gateway row), a vendor name (direct, own
- credentials), or ``None`` (never configured -> legacy autodetect allowed).
- Reads the RAW config.yaml so key presence means "actually written", not
- "schema default"; a raw ``local`` is therefore a real user selection.
- Legacy shim: ``use_gateway: true`` was only ever written by the managed
- row, so it maps to ``"nous"`` regardless of the name key. Never raises.
- """
+ """THE single runtime read of the persisted `hermes tools` selection: ``"nous"`` (managed
+ gateway row), a vendor name (direct, own credentials), or ``None`` (never configured ->
+ legacy autodetect allowed). Reads the RAW config.yaml so key presence means "actually
+ written", not "schema default"; a raw ``local`` is therefore a real user selection.
+ Legacy shim: ``use_gateway: true`` was only ever written by the managed row, so it maps
+ to ``"nous"`` regardless of the name key. Never raises."""
raw = _raw_section(section)
if raw is None:
return None
@@ -236,52 +208,44 @@ def read_selection(section: str) -> str | None:
return NOUS_MANAGED_PROVIDER
for key in _SELECTION_NAME_KEYS.get(section, _DEFAULT_NAME_KEYS):
value = raw.get(key)
- if value is not None:
- text = str(value).strip().lower()
- if text:
- return text
+ if value is not None and str(value).strip():
+ return str(value).strip().lower()
# use_gateway: false with no name key is not a usable selection shape;
# per-capability web keys still count as configured via selection_exists().
return None
def selection_exists(section: str) -> bool:
- """True when ANY selection signal was ever written for the section
- (wider than read_selection: per-capability web keys count too)."""
+ """True when ANY selection signal was ever written for the section (wider than
+ read_selection: per-capability web keys count too)."""
if read_selection(section) is not None:
return True
extra = _EXTRA_SELECTION_KEYS.get(section, ())
raw = _raw_section(section) if extra else None
- if raw is None:
- return False
- return any(str(raw.get(key) or "").strip() for key in extra)
+ return raw is not None and any(str(raw.get(key) or "").strip() for key in extra)
-# Backends that once shipped in-tree but were removed. A config still pointing at
-# one would otherwise fail silently at the FIRST tool call with a generic "no
-# registered provider has that name". Consulted by the startup config check and
-# selection_error(). Add removals here, never as one-off string checks, e.g.
-# "web": {"<name>": "the <Name> backend was removed in vX.Y.Z (...)"},
+# Backends that once shipped in-tree but were removed; a config still pointing at one would
+# otherwise fail silently at the FIRST tool call with a generic "no registered provider has
+# that name". Consulted by the startup config check and selection_error(). Add removals
+# here, never as one-off string checks: "web": {"<name>": "the <Name> backend was removed"}
REMOVED_BACKENDS: Dict[str, Dict[str, str]] = {}
def removed_backend_note(section: str, name: str) -> Optional[str]:
- """Explanation for a backend that used to ship in-tree, or None.
- ``name`` tolerates the quoted form callers pass to selection_error()."""
- normalized = (name or "").strip().strip("'\"").lower()
- return REMOVED_BACKENDS.get(section, {}).get(normalized)
+ """Explanation for a backend that used to ship in-tree, or None. ``name`` tolerates the
+ quoted form callers pass to selection_error()."""
+ return REMOVED_BACKENDS.get(section, {}).get((name or "").strip().strip("'\"").lower())
def selection_error(section: str, selection_name: str, failure: str) -> str:
"""The uniform honest-error contract for a selected-but-broken provider."""
failure = removed_backend_note(section, selection_name) or failure
- return (
- f"{section} is configured to use {selection_name} (set via hermes "
- f"tools), but {failure}. Run 'hermes tools' to change it.")
+ return (f"{section} is configured to use {selection_name} (set via hermes "
+ f"tools), but {failure}. Run 'hermes tools' to change it.")
def fal_key_is_configured() -> bool:
- """True when FAL_KEY is set (scope/env, else ``.env`` for CLI paths that
- run before dotenv loads) to a non-whitespace value — so tool-side and CLI
- setup-time checks agree; whitespace-only counts as unset everywhere."""
+ """True when FAL_KEY is set (scope/env, else ``.env`` for CLI paths that run before dotenv
+ loads) to a non-whitespace value, so tool-side and CLI setup-time checks agree."""
return bool(_scoped_credential("FAL_KEY") or _dotenv_value("FAL_KEY"))
diff --git a/tools/tool_result_storage.py b/tools/tool_result_storage.py
index c3d714946da..d2bb5ba7c28 100644
--- a/tools/tool_result_storage.py
+++ b/tools/tool_result_storage.py
@@ -1,11 +1,10 @@
"""Tool result persistence -- preserves large outputs instead of truncating.
-
Layers against context overflow: (1) per-tool caps inside each tool; (2)
-``maybe_persist_tool_result`` — output over the tool's threshold is persisted and
-replaced by a preview + path. Canonical home is ALWAYS host-side
-``$HERMES_HOME/cache/spillover/{id}.txt`` (works for sessions that never ran a
-terminal); remote backends get the translated in-sandbox path (probed for
-readability) else a copy in the sandbox temp dir. (3) ``enforce_turn_budget``."""
+``maybe_persist_tool_result`` — output over the tool's threshold is persisted and replaced
+by a preview + path. Canonical home is ALWAYS host-side ``$HERMES_HOME/cache/spillover/
+{id}.txt`` (works for sessions that never ran a terminal); remote backends get the
+translated in-sandbox path (probed for readability) else a copy in the sandbox temp dir.
+(3) ``enforce_turn_budget``."""
import hashlib
import logging
@@ -34,13 +33,12 @@ _spillover_pruned_once = False
def get_spillover_dir():
"""Return $HERMES_HOME/cache/spillover as a Path (not created)."""
from hermes_constants import get_hermes_home
-
return get_hermes_home() / SPILLOVER_SUBDIR
def cleanup_spillover_cache(max_age_hours: int = SPILLOVER_MAX_AGE_HOURS) -> int:
- """Delete spillover files older than *max_age_hours*; returns count removed.
- Same contract as the ``cleanup_*_cache`` helpers the gateway housekeeping loop prunes hourly."""
+ """Delete spillover files older than *max_age_hours*; returns count removed (same
+ contract as the ``cleanup_*_cache`` helpers the gateway housekeeping loop runs hourly)."""
cutoff = time.time() - (max_age_hours * 3600)
removed = 0
try:
@@ -73,14 +71,12 @@ def _prune_spillover_once() -> None:
def _is_host_side_env(env) -> bool:
- """True when this process should write the spill file directly: ``env=None``
- (no sandbox yet) or the local backend. Remote backends resolve ``read_file``
- inside the sandbox, so the spill must be written there."""
+ """True when this process should write the spill file directly: ``env=None`` (no sandbox
+ yet) or the local backend. Remote backends resolve ``read_file`` inside the sandbox."""
if env is None:
return True
try:
from tools.environments.local import LocalEnvironment
-
return isinstance(env, LocalEnvironment)
except Exception:
return False
@@ -101,13 +97,12 @@ def _write_to_spillover(content: str, filename: str):
def _sandbox_visible_spillover_path(host_path: str, env) -> str | None:
- """Path where a remote backend can read *host_path*, or None. Translates via
- the image tools' helper, forces a sync for synced backends, then PROBES
- readability — a persistent container created before spillover joined the
- mount list lacks the bind mount and must fall back to the in-sandbox write."""
+ """Path where a remote backend can read *host_path*, or None. Translates via the image
+ tools' helper, forces a sync for synced backends, then PROBES readability — a persistent
+ container created before spillover joined the mount list lacks the bind mount and must
+ fall back to the in-sandbox write."""
try:
from tools.credential_files import to_agent_visible_cache_path
-
visible = to_agent_visible_cache_path(host_path)
except Exception as exc:
logger.debug("Spillover path translation failed: %s", exc)
@@ -119,8 +114,7 @@ def _sandbox_visible_spillover_path(host_path: str, env) -> str | None:
except Exception as exc:
logger.debug("Spillover sync failed: %s", exc)
try:
- result = env.execute(f"test -r {shlex.quote(visible)}", timeout=15)
- if result.get("returncode", 1) == 0:
+ if env.execute(f"test -r {shlex.quote(visible)}", timeout=15).get("returncode", 1) == 0:
return visible
except Exception as exc:
logger.debug("Spillover readability probe failed: %s", exc)
@@ -130,15 +124,13 @@ def _sandbox_visible_spillover_path(host_path: str, env) -> str | None:
def _resolve_storage_dir(env) -> str:
"""Return the best temp-backed storage dir for this environment."""
get_temp_dir = getattr(env, "get_temp_dir", None)
+ temp_dir = None
if callable(get_temp_dir):
try:
temp_dir = get_temp_dir()
except Exception as exc:
logger.debug("Could not resolve env temp dir: %s", exc)
- else:
- if temp_dir:
- return f"{temp_dir.rstrip('/') or '/'}/hermes-results"
- return STORAGE_DIR
+ return f"{temp_dir.rstrip('/') or '/'}/hermes-results" if temp_dir else STORAGE_DIR
def _safe_result_filename(tool_use_id: str) -> str:
@@ -146,9 +138,7 @@ def _safe_result_filename(tool_use_id: str) -> str:
raw_id = str(tool_use_id or "tool_result")
safe_stem = _UNSAFE_RESULT_FILENAME_CHARS.sub("_", raw_id).strip("._-")
changed = safe_stem != raw_id
- if not safe_stem:
- safe_stem = "tool_result"
- changed = True
+ safe_stem = safe_stem or "tool_result"
if changed or len(safe_stem) > _MAX_RESULT_FILENAME_STEM:
digest = hashlib.sha256(raw_id.encode("utf-8")).hexdigest()[:12]
safe_stem = safe_stem[:_MAX_RESULT_FILENAME_STEM].rstrip("._-") or "tool_result"
@@ -168,14 +158,12 @@ def generate_preview(content: str, max_chars: int = DEFAULT_PREVIEW_SIZE_CHARS)
def _write_to_sandbox(content: str, remote_path: str, env) -> bool:
- """Write content into the sandbox via env.execute(). Returns True on success.
- Content goes through stdin, not the command string: Linux ``MAX_ARG_STRLEN``
- caps one argv element at 128 KB, so a heredoc-in-command silently failed
- for exactly the oversized results persistence exists to handle."""
+ """Write content into the sandbox via env.execute(); True on success. Content goes through
+ stdin, not the command string: Linux ``MAX_ARG_STRLEN`` caps one argv element at 128 KB,
+ so a heredoc-in-command silently failed for exactly the oversized results this handles."""
storage_dir = os.path.dirname(remote_path)
cmd = f"mkdir -p {shlex.quote(storage_dir)} && cat > {shlex.quote(remote_path)}"
- result = env.execute(cmd, timeout=30, stdin_data=content)
- return result.get("returncode", 1) == 0
+ return env.execute(cmd, timeout=30, stdin_data=content).get("returncode", 1) == 0
def _build_persisted_message(
@@ -200,9 +188,8 @@ _PERSISTED_PATH_RE = re.compile(r"^Full output saved to: (.+)$", re.MULTILINE)
def extract_persisted_path(content: str) -> str | None:
- """Return the file path from a <persisted-output> block, or None. Lets the
- result-reference stubbing guard (agent/tool_guardrails.py) carry the
- spillover path in a stub instead of leaving it dangling."""
+ """File path from a <persisted-output> block, or None (lets the result-reference stubbing
+ guard in agent/tool_guardrails.py carry the spillover path instead of leaving it dangling)."""
if not isinstance(content, str) or PERSISTED_OUTPUT_TAG not in content:
return None
match = _PERSISTED_PATH_RE.search(content)
@@ -216,13 +203,13 @@ def maybe_persist_tool_result(
env=None,
config: BudgetConfig = DEFAULT_BUDGET,
threshold: int | float | None = None) -> str:
- """Layer 2: persist an oversized result, return preview + path.
- ``threshold`` overrides ``config.resolve_threshold(tool_name)``. Falls back
- to inline truncation when no write location succeeds."""
- effective_threshold = threshold if threshold is not None else config.resolve_threshold(tool_name)
- if effective_threshold == float("inf") or len(content) <= effective_threshold:
+ """Layer 2: persist an oversized result, return preview + path. ``threshold`` overrides
+ ``config.resolve_threshold(tool_name)``; falls back to inline truncation when no write
+ location succeeds."""
+ if threshold is None:
+ threshold = config.resolve_threshold(tool_name)
+ if threshold == float("inf") or len(content) <= threshold:
return content
-
filename = _safe_result_filename(tool_use_id)
preview, has_more = generate_preview(content, max_chars=config.preview_size)
@@ -238,9 +225,8 @@ def maybe_persist_tool_result(
if host_path is not None:
return _persisted(host_path)
else:
- # Remote backend: reference the mounted/synced path when the sandbox can
- # actually read it, else write into the sandbox temp dir (pre-existing
- # containers without the spillover mount, translation/probe failures).
+ # Remote backend: reference the mounted/synced path when the sandbox can actually read
+ # it, else write into the sandbox temp dir (containers without the spillover mount).
if host_path is not None:
visible = _sandbox_visible_spillover_path(host_path, env)
if visible is not None:
@@ -252,19 +238,16 @@ def maybe_persist_tool_result(
except Exception as exc:
logger.warning("Sandbox write failed for %s: %s", tool_use_id, exc)
- logger.info(
- "Inline-truncating large tool result: %s (%d chars, no sandbox write)",
- tool_name, len(content))
- return (
- f"{preview}\n\n"
- f"[Truncated: tool response was {len(content):,} chars. "
- f"Full output could not be saved to sandbox.]")
+ logger.info("Inline-truncating large tool result: %s (%d chars, no sandbox write)",
+ tool_name, len(content))
+ return (f"{preview}\n\n[Truncated: tool response was {len(content):,} chars. "
+ "Full output could not be saved to sandbox.]")
def enforce_turn_budget(
tool_messages: list[dict], env=None, config: BudgetConfig = DEFAULT_BUDGET) -> list[dict]:
- """Layer 3: persist the largest non-persisted results first until the turn's
- aggregate is under budget. Mutates the list in-place and returns it."""
+ """Layer 3: persist the largest non-persisted results first until the turn's aggregate is
+ under budget. Mutates the list in-place and returns it."""
candidates = []
total_size = 0
for i, msg in enumerate(tool_messages):
@@ -274,7 +257,6 @@ def enforce_turn_budget(
candidates.append((i, size))
if total_size <= config.turn_budget:
return tool_messages
-
candidates.sort(key=lambda x: x[1], reverse=True)
for idx, size in candidates:
if total_size <= config.turn_budget: