Skip to content

The agent that grows with you

refactor(tools): group H — pack multi-line signatures, config-default one-liners, exact-match score fold

Teknium0994c01d1d5e
diff --git a/tools/tool_backend_helpers.py b/tools/tool_backend_helpers.py
index 14cd2c3c8e2..24249aa6be6 100644
--- a/tools/tool_backend_helpers.py
+++ b/tools/tool_backend_helpers.py
@@ -28,8 +28,8 @@ def managed_nous_tools_enabled(*, force_fresh: bool = False) -> bool:
return False
-def nous_tool_gateway_unavailable_message(
- capability: str = "the Nous Tool Gateway", *, force_fresh: bool = False) -> str:
+def nous_tool_gateway_unavailable_message(capability: str = "the Nous Tool Gateway", *,
+ force_fresh: bool = False) -> str:
"""Return account-aware guidance for an unavailable Nous Tool Gateway path."""
try:
from hermes_cli.nous_account import (
@@ -69,12 +69,9 @@ def has_direct_modal_credentials() -> bool:
return False
-def resolve_modal_backend_state(
- modal_mode: object | None,
- *,
- has_direct: bool,
- managed_ready: bool,
- managed_enabled: bool | None = None) -> Dict[str, Any]:
+def resolve_modal_backend_state(modal_mode: object | None, *, 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."""
requested_mode = coerce_modal_mode(modal_mode)
@@ -110,8 +107,8 @@ def _dotenv_value(env_var: str) -> str:
return ""
-def resolve_provider_secret(
- env_var: str, provider_id: str, config_value: str = "", env_getter=None) -> 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
diff --git a/tools/tool_result_storage.py b/tools/tool_result_storage.py
index 4cd2c069caa..3fc19e209cd 100644
--- a/tools/tool_result_storage.py
+++ b/tools/tool_result_storage.py
@@ -166,8 +166,8 @@ def _write_to_sandbox(content: str, remote_path: str, env) -> bool:
return env.execute(cmd, timeout=30, stdin_data=content).get("returncode", 1) == 0
-def _build_persisted_message(
- preview: str, has_more: bool, original_size: int, file_path: str) -> str:
+def _build_persisted_message(preview: str, has_more: bool, original_size: int,
+ file_path: str) -> str:
"""Build the <persisted-output> replacement block."""
size_kb = original_size / 1024
size_str = f"{size_kb / 1024:.1f} MB" if size_kb >= 1024 else f"{size_kb:.1f} KB"
@@ -196,13 +196,9 @@ def extract_persisted_path(content: str) -> str | None:
return match.group(1).strip() if match else None
-def maybe_persist_tool_result(
- content: str,
- tool_name: str,
- tool_use_id: str,
- env=None,
- config: BudgetConfig = DEFAULT_BUDGET,
- threshold: int | float | None = None) -> str:
+def maybe_persist_tool_result(content: str, tool_name: str, tool_use_id: str, env=None,
+ config: BudgetConfig = DEFAULT_BUDGET,
+ threshold: int | float | None = None) -> str:
"""Layer 2: persist an oversized result, return preview + path. ``threshold`` overrides
``config.resolve_threshold(tool_name)``; falls back to inline truncation when no write
location succeeds."""
@@ -243,8 +239,8 @@ def maybe_persist_tool_result(
"Full output could not be saved to sandbox.]")
-def enforce_turn_budget(
- tool_messages: list[dict], env=None, config: BudgetConfig = DEFAULT_BUDGET) -> list[dict]:
+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."""
candidates = []
diff --git a/tools/tool_search.py b/tools/tool_search.py
index c5e493681bc..6279e1edcbe 100644
--- a/tools/tool_search.py
+++ b/tools/tool_search.py
@@ -161,9 +161,8 @@ def _tool_def_names(tool_defs: Iterable[Dict[str, Any]]) -> Iterable[str]:
return (_fn(td).get("name", "") for td in tool_defs)
-def classify_tools(
- tool_defs: List[Dict[str, Any]],
- defer_tools: Optional[frozenset] = None) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
+def classify_tools(tool_defs: List[Dict[str, Any]], defer_tools: Optional[frozenset] = None,
+ ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
"""Split a tool-defs list into (visible, deferrable); bridge tools are dropped (re-added
after classification)."""
visible: List[Dict[str, Any]] = []
@@ -190,10 +189,8 @@ def estimate_tokens_from_schemas(tool_defs: Iterable[Dict[str, Any]]) -> int:
return int(math.ceil(total_chars / CHARS_PER_TOKEN))
-def should_activate(
- config: ToolSearchConfig,
- deferrable_tokens: int,
- context_length: Optional[int]) -> bool:
+def should_activate(config: ToolSearchConfig, deferrable_tokens: int,
+ context_length: Optional[int]) -> bool:
"""``"off"`` never activates; ``"on"``/``"auto"`` activate whenever any deferrable tool
exists ("auto" is reserved for a future budget-gated mode — do not distinguish them
without that design). ``context_length`` is kept for caller compatibility."""
@@ -249,10 +246,8 @@ def _search_description(deferred_count: int, listing: Optional[str], listing_for
return desc + "\n\n" + listing
-def bridge_tool_schemas(
- deferred_count: int,
- listing: Optional[str] = None,
- listing_form: str = "") -> List[Dict[str, Any]]:
+def bridge_tool_schemas(deferred_count: int, listing: Optional[str] = None,
+ listing_form: str = "") -> List[Dict[str, Any]]:
"""Bridge tool schemas injected in place of deferred tools. Kept short — every byte is
paid on every turn. ``listing`` is embedded in the tool_search description; per-tool
``listing_form``s say "skip search when you see the exact name", "groups" says which
@@ -318,15 +313,11 @@ class AssemblyResult:
listing_form: str = "none" # "full" | "names" | "mixed" | "groups" | "none"
-def assemble_tool_defs(
- tool_defs: List[Dict[str, Any]],
- *,
- context_length: Optional[int] = None,
- config: Optional[ToolSearchConfig] = None) -> AssemblyResult:
+def assemble_tool_defs(tool_defs: List[Dict[str, Any]], *, context_length: Optional[int] = None,
+ config: Optional[ToolSearchConfig] = None) -> AssemblyResult:
"""Tool-defs the model should see: passthrough when inactive, else deferrable tools
replaced by the three bridge tools. Idempotent — existing bridge tools are stripped first."""
- if config is None:
- config = load_config()
+ config = config or load_config()
incoming = [td for td, name in zip(tool_defs, _tool_def_names(tool_defs))
if name not in BRIDGE_TOOL_NAMES]
visible, deferrable = classify_tools(incoming, config.effective_defer_tools)
@@ -379,9 +370,8 @@ def _available_source_summary(catalog: List[CatalogEntry]) -> List[Dict[str, Any
return [{"name": name, "tool_count": counts[name]} for name in sorted(counts)]
-def _string_list_arg(
- args: Dict[str, Any], key: str, *, dedupe: bool, max_items: int, retry_hint: str,
-) -> Tuple[Optional[List[str]], Optional[str]]:
+def _string_list_arg(args: Dict[str, Any], key: str, *, dedupe: bool, max_items: int,
+ retry_hint: str) -> Tuple[Optional[List[str]], Optional[str]]:
"""Read a list-of-strings bridge argument -> ``(items, error_json)``. A bare string (a
common model slip) is a one-item list; rejects non-lists, all-blank lists, > ``max_items``."""
raw = args.get(key)
@@ -407,8 +397,7 @@ def dispatch_tool_search(args: Dict[str, Any], *, current_tool_defs: List[Dict[s
results: [{query, matches: [names]}], tools: {name: {source, source_name, description,
required}}}``. ``limit`` applies PER QUERY; empty groups get ``available_sources`` +
``hint`` so a lexical miss is not mistaken for a missing capability."""
- if config is None:
- config = load_config()
+ config = config or load_config()
queries, err = _string_list_arg(
args, "queries", dedupe=False, max_items=_MAX_QUERIES_PER_CALL,
retry_hint="Retry with fewer, more targeted queries.")
@@ -444,8 +433,7 @@ def dispatch_tool_describe(args: Dict[str, Any], *, current_tool_defs: List[Dict
"""Execute the ``tool_describe`` bridge tool -> JSON ``{tools: {name: {description,
parameters}}, not_found: [...] (unknown / not in this assembly; never fails the call),
errors: {name: msg} (registered but non-deferrable)}``. Duplicates dedupe silently."""
- if config is None:
- config = load_config_readonly()
+ config = config or load_config_readonly()
names, err = _string_list_arg(
args, "names", dedupe=True, max_items=_MAX_DESCRIBE_NAMES_PER_CALL,
retry_hint="Retry with fewer names per call.")
diff --git a/tools/tool_search_catalog.py b/tools/tool_search_catalog.py
index e08603a2b57..67d68af9c3e 100644
--- a/tools/tool_search_catalog.py
+++ b/tools/tool_search_catalog.py
@@ -116,10 +116,9 @@ def build_catalog(tool_defs: List[Dict[str, Any]]) -> List[CatalogEntry]:
return catalog
-def _bm25_score(query_tokens: List[str], doc_tokens: List[str],
- doc_lengths: List[int], avg_dl: float,
- doc_freq: Dict[str, int], n_docs: int,
- k1: float = 1.5, b: float = 0.75) -> float:
+def _bm25_score(query_tokens: List[str], doc_tokens: List[str], doc_lengths: List[int],
+ avg_dl: float, doc_freq: Dict[str, int], n_docs: int, k1: float = 1.5,
+ b: float = 0.75) -> float:
"""Standard BM25 for one query against one document (inlined; the catalog is bounded —
typically < 500 tools — so a dependency is not worth it)."""
if not doc_tokens:
@@ -150,12 +149,8 @@ def _corpus_stats(catalog: List[CatalogEntry]) -> _CorpusStats:
return doc_lengths, avg_dl, dict(doc_freq), len(catalog)
-def search_catalog(
- catalog: List[CatalogEntry],
- query: str,
- limit: int = 5,
- *,
- corpus_stats: Optional[_CorpusStats] = None) -> List[CatalogEntry]:
+def search_catalog(catalog: List[CatalogEntry], query: str, limit: int = 5, *,
+ corpus_stats: Optional[_CorpusStats] = None) -> List[CatalogEntry]:
"""Top-``limit`` catalog entries for ``query`` by BM25 (exact name match ranks first).
Falls back to a name-substring match only when NO query token appears in any document
(e.g. "hub" vs ``github_*``); the IDF variant is strictly positive, so a hit anywhere
@@ -168,10 +163,8 @@ def search_catalog(
scored: List[Tuple[float, CatalogEntry]] = []
exact_name = query.strip().lower()
for entry in catalog:
- if entry.name.lower() == exact_name:
- scored.append((float("inf"), entry))
- continue
- s = _bm25_score(query_tokens, entry._tokens, *corpus_stats)
+ s = (float("inf") if entry.name.lower() == exact_name
+ else _bm25_score(query_tokens, entry._tokens, *corpus_stats))
if s > 0:
scored.append((s, entry))
if not scored: